text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { applyMixins } from '@nativescript-community/ui-material-core'; import { AndroidActivityBackPressedEventData, Application, Utils, View, fromObject } from '@nativescript/core'; import { BottomSheetOptions, StateBottomSheet, ViewWithBottomSheetBase } from './bottomsheet-common'; export { ViewWithBottomSheetBase } from './bottomsheet-common'; interface BottomSheetDataOptions { owner: View; options: BottomSheetOptions; shownCallback: () => void; dismissCallback: () => void; } function getId(id: string) { const context: android.content.Context = Application.android.context; return context.getResources().getIdentifier(id, 'id', context.getPackageName()); } @NativeClass class ChangeStateBottomSheet extends com.google.android.material.bottomsheet.BottomSheetBehavior.BottomSheetCallback { private owner: ViewWithBottomSheet; constructor(owner: ViewWithBottomSheet) { super(); this.owner = owner; return global.__native(this); } onSlide(bottomSheet: android.view.View, slideOffset: number) { if (this.checkActiveCallback()) { this.owner._onChangeStateBottomSheetCallback(StateBottomSheet.DRAGGING, slideOffset); } } onStateChanged(bottomSheet: android.view.View, newState: number) { if (this.checkActiveCallback()) { const status = this.getStateBottomSheetFromBottomSheetBehavior(newState); if (status !== undefined) { this.owner._onChangeStateBottomSheetCallback(status); } } } private checkActiveCallback() { return this.owner && this.owner._onChangeStateBottomSheetCallback; } public getStateBottomSheetFromBottomSheetBehavior(state: number): StateBottomSheet | undefined { switch (state) { case com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_HIDDEN: return StateBottomSheet.CLOSED; case com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_EXPANDED: return StateBottomSheet.EXPANDED; case com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_COLLAPSED: return StateBottomSheet.COLLAPSED; case com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_DRAGGING: return StateBottomSheet.DRAGGING; default: // @ts-ignore return; } } } export class ViewWithBottomSheet extends ViewWithBottomSheetBase { _bottomSheetFragment: com.nativescript.material.bottomsheet.BottomSheetDialogFragment; protected _hideNativeBottomSheet(parent: View, whenClosedCallback: () => void) { // call whenClosedCallback first because dismiss will call another one (without result) whenClosedCallback(); const manager = this._bottomSheetFragment.getFragmentManager(); if (manager) { this._bottomSheetFragment.dismissAllowingStateLoss(); } this._bottomSheetFragment = null; } protected _showNativeBottomSheet(parent: View, options: BottomSheetOptions) { this._commonShowNativeBottomSheet(parent, options); const owner = this; const domId = this._domId; const bottomSheetOptions: BottomSheetDataOptions = { owner: this, options, shownCallback: () => { this.bindingContext = fromObject(options.context); this._raiseShownBottomSheetEvent(); }, dismissCallback: () => this._onDismissBottomSheetCallback() }; const dfListener = new com.nativescript.material.bottomsheet.BottomSheetDialogFragment.BottomSheetDialogFragmentListener({ onCreateDialog(fragment: com.nativescript.material.bottomsheet.BottomSheetDialogFragment, savedInstanceState: android.os.Bundle): android.app.Dialog { const theme = fragment.getTheme(); const dialogListener = new com.nativescript.material.bottomsheet.BottomSheetDialog.BottomSheetDialogListener({ onDetachedFromWindow(dialog: com.nativescript.material.bottomsheet.BottomSheetDialog) { (dialog as any).nListener = null; }, onBackPressed(dialog: com.nativescript.material.bottomsheet.BottomSheetDialog) { if (bottomSheetOptions.options && bottomSheetOptions.options.dismissOnBackButton === false) { return true; } if (!owner) { return false; } const args = { eventName: 'activityBackPressed', object: owner, activity: owner._context, cancel: false } as AndroidActivityBackPressedEventData; // Fist fire application.android global event Application.android.notify(args); if (args.cancel) { return true; } owner.notify(args); if (!args.cancel) { args.cancel = owner.onBackPressed(); } return args.cancel; } }); const dialog = new com.nativescript.material.bottomsheet.BottomSheetDialog(fragment.getActivity(), theme); dialog.setListener(dialogListener); (dialog as any).nListener = dialogListener; if (bottomSheetOptions.options) { const creationOptions = bottomSheetOptions.options; if (creationOptions.dismissOnBackgroundTap !== undefined) { dialog.setCanceledOnTouchOutside(creationOptions.dismissOnBackgroundTap); } if (creationOptions.disableDimBackground === true) { dialog.getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_DIM_BEHIND); } } return dialog; }, onCreateView( fragment: com.nativescript.material.bottomsheet.BottomSheetDialogFragment, inflater: android.view.LayoutInflater, container: android.view.ViewGroup, savedInstanceState: android.os.Bundle ): android.view.View { owner._setupAsRootView(fragment.getActivity()); owner._isAddedToNativeVisualTree = true; return owner.nativeViewProtected; }, onStart(fragment: com.nativescript.material.bottomsheet.BottomSheetDialogFragment): void { const color = owner.backgroundColor; const contentViewId = getId('design_bottom_sheet'); const view = fragment.getDialog().findViewById(contentViewId); const transparent = bottomSheetOptions.options && bottomSheetOptions.options.transparent; if (transparent === true) { // we need delay it just a bit or it wont work setTimeout(() => { view.setBackground(null); }, 0); } const behavior = com.google.android.material.bottomsheet.BottomSheetBehavior.from(view); // prevent hiding the bottom sheet by const dismissOnDraggingDownSheet = !bottomSheetOptions.options || bottomSheetOptions.options.dismissOnDraggingDownSheet !== false; behavior.setHideable(dismissOnDraggingDownSheet); if (!dismissOnDraggingDownSheet) { // directly expand the bottom sheet after start behavior.setState(com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_EXPANDED); // set to maximum possible value to prevent dragging the sheet between peek and expanded height behavior.setPeekHeight(java.lang.Integer.MAX_VALUE); } const skipCollapsedState = !bottomSheetOptions.options || bottomSheetOptions.options.skipCollapsedState === true; if (skipCollapsedState) { // directly expand the bottom sheet after start behavior.setState(com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_EXPANDED); // disable peek/collapsed state behavior.setSkipCollapsed(true); } const peekHeight = bottomSheetOptions.options?.peekHeight; if (peekHeight) { behavior.setState(com.google.android.material.bottomsheet.BottomSheetBehavior.STATE_COLLAPSED); behavior.setPeekHeight(Utils.layout.toDevicePixels(peekHeight)); } const onChangeState = bottomSheetOptions.options?.onChangeState; if (onChangeState) { const changeStateBottomSheet = new ChangeStateBottomSheet(owner); behavior.addBottomSheetCallback(changeStateBottomSheet); owner._onChangeStateBottomSheetCallback(changeStateBottomSheet.getStateBottomSheetFromBottomSheetBehavior(behavior.getState())); } if (owner && !owner.isLoaded) { owner.callLoaded(); } bottomSheetOptions.shownCallback(); }, onDismiss(fragment: com.nativescript.material.bottomsheet.BottomSheetDialogFragment, dialog: android.content.DialogInterface): void { const manager = fragment.getFragmentManager(); if (manager) { bottomSheetOptions.dismissCallback(); } if (owner && owner.isLoaded) { owner.callUnloaded(); } }, onDestroy(fragment: com.nativescript.material.bottomsheet.BottomSheetDialogFragment): void { (df as any).nListener = null; if (owner) { // Android calls onDestroy before onDismiss. // Make sure we unload first and then call _tearDownUI. if (owner.isLoaded) { owner.callUnloaded(); } owner._isAddedToNativeVisualTree = false; owner._tearDownUI(true); } } }); const df = new com.nativescript.material.bottomsheet.BottomSheetDialogFragment(); df.setListener(dfListener); (df as any).nListener = dfListener; this._bottomSheetFragment = df; this._raiseShowingBottomSheetEvent(); //@ts-ignore df.show(parent._getRootFragmentManager(), domId.toString()); } } let mixinInstalled = false; export function overrideBottomSheet() { applyMixins(View, [ViewWithBottomSheetBase, ViewWithBottomSheet]); } export function install() { if (!mixinInstalled) { mixinInstalled = true; // overridePage(); overrideBottomSheet(); } }
the_stack
import { WITHDRAW_STATE_TIMEOUT } from "@connext/apps"; import { AppInstanceJson, CoinTransfer, MinimalTransaction, PublicParams, WithdrawAppAction, WithdrawAppName, WithdrawAppState, SingleAssetTwoPartyCoinTransferInterpreterParamsJson, EventNames, EventPayloads, } from "@connext/types"; import { getSignerAddressFromPublicIdentifier, stringify } from "@connext/utils"; import { Injectable } from "@nestjs/common"; import { BigNumber, constants, utils, providers } from "ethers"; import { CFCoreService } from "../cfCore/cfCore.service"; import { Channel } from "../channel/channel.entity"; import { ChannelRepository } from "../channel/channel.repository"; import { ConfigService } from "../config/config.service"; import { LoggerService } from "../logger/logger.service"; import { OnchainTransaction, TransactionReason, } from "../onchainTransactions/onchainTransaction.entity"; import { OnchainTransactionRepository } from "../onchainTransactions/onchainTransaction.repository"; import { OnchainTransactionService, OnchainTransactionResponse, } from "../onchainTransactions/onchainTransaction.service"; import { WithdrawRepository } from "./withdraw.repository"; import { Withdraw } from "./withdraw.entity"; const { HashZero, Zero, AddressZero } = constants; const { hexlify, randomBytes } = utils; @Injectable() export class WithdrawService { constructor( private readonly configService: ConfigService, private readonly log: LoggerService, private readonly cfCoreService: CFCoreService, private readonly onchainTransactionService: OnchainTransactionService, private readonly onchainTransactionRepository: OnchainTransactionRepository, private readonly withdrawRepository: WithdrawRepository, private readonly channelRepository: ChannelRepository, ) { this.log.setContext("WithdrawService"); } /* Called in the case that node wants to withdraw funds from channel */ async withdraw( channel: Channel, amount: BigNumber, assetId: string = AddressZero, ): Promise<providers.TransactionResponse> { // first try to deploy multisig. if this fails, cancel the withdrawal try { await this.deployMultisig(channel); } catch (e) { this.log.error(`Error deploying multisig: ${e.message}`); this.log.warn(`Aborting node reclaim`); throw e; } const { appIdentityHash, withdrawTracker } = await this.proposeWithdrawApp( amount, assetId, channel, ); let uninstallData: EventPayloads.Uninstall; try { uninstallData = await this.cfCoreService.emitter.waitFor( EventNames.UNINSTALL_EVENT, 20_000, (data) => data.appIdentityHash === appIdentityHash, ); } catch (e) { this.log.error(`Error waiting for withdrawal app to be uninstalled: ${e.message}`); // TODO: should we uninstall ourselves here? throw e; } if (!uninstallData.uninstalledApp.latestState.finalized) { throw new Error(`Error, cannot reclaim on withdraw app that is not finalized. AppId: ${appIdentityHash}`); } const action = uninstallData!.action as WithdrawAppAction; await this.withdrawRepository.addCounterpartySignatureAndFinalize( withdrawTracker, action.signature, ); const state = uninstallData!.uninstalledApp.latestState; const appInstance = uninstallData!.uninstalledApp; const commitment = await this.cfCoreService.createWithdrawCommitment( { amount: state.transfers[0].amount, // eslint-disable-next-line max-len assetId: (appInstance.outcomeInterpreterParameters as SingleAssetTwoPartyCoinTransferInterpreterParamsJson) .tokenAddress, recipient: this.cfCoreService.cfCore.signerAddress, nonce: state.nonce, }, channel, ); await commitment.addSignatures(state.signatures[0], state.signatures[1]); const tx = await commitment.getSignedTransaction(); const updatedChannel = await this.channelRepository.findByMultisigAddressOrThrow( appInstance.multisigAddress, ); return this.submitWithdrawToChain( updatedChannel, tx, appInstance.identityHash, TransactionReason.NODE_WITHDRAWAL, ); } /* Primary response method to user withdrawal. Called from appRegistry service. */ async handleUserWithdraw(appInstance: AppInstanceJson): Promise<void> { let state = appInstance.latestState as WithdrawAppState; const channel = await this.channelRepository.findByAppIdentityHashOrThrow( appInstance.identityHash, ); // first try to deploy multisig. if this fails, cancel the withdrawal try { await this.deployMultisig(channel); } catch (e) { this.log.error(`Error deploying multisig: ${e.message}`); this.log.warn( `Cancelling user ${appInstance.initiatorIdentifier} withdrawal by uninstalling withdrawal app ${appInstance.identityHash}`, ); await this.cfCoreService.uninstallApp(appInstance.identityHash, channel); this.log.warn(`User ${appInstance.initiatorIdentifier} withdrawal canceled`); } // Create the same commitment from scratch const generatedCommitment = await this.cfCoreService.createWithdrawCommitment( { amount: state.transfers[0].amount, // eslint-disable-next-line max-len assetId: (appInstance.outcomeInterpreterParameters as SingleAssetTwoPartyCoinTransferInterpreterParamsJson) .tokenAddress, recipient: state.transfers[0].to, nonce: state.nonce, } as PublicParams.Withdraw, channel, ); const signer = this.configService.getSigner( (await this.channelRepository.getChainIdByMultisigAddress(appInstance.multisigAddress))!, ); // Sign commitment const hash = generatedCommitment.hashToSign(); const counterpartySignatureOnWithdrawCommitment = await signer.signMessage(hash); // take action _before_ sending tx so that there is no double spend risk await this.cfCoreService.takeAction(appInstance.identityHash, channel, { signature: counterpartySignatureOnWithdrawCommitment, } as WithdrawAppAction); state = appInstance.latestState as WithdrawAppState; // Update the db entity with signature let withdraw = await this.withdrawRepository.findByAppIdentityHash(appInstance.identityHash); if (!withdraw) { this.log.error( `Unable to find withdraw entity that we just took action upon. AppId ${appInstance.identityHash}`, ); } else { await this.withdrawRepository.addCounterpartySignatureAndFinalize( withdraw, counterpartySignatureOnWithdrawCommitment, ); } await generatedCommitment.addSignatures( counterpartySignatureOnWithdrawCommitment, // our sig state.signatures[0], // user sig ); const signedWithdrawalCommitment = await generatedCommitment.getSignedTransaction(); // try to submit the user's withdrawal tx onchain // uninstall withdrawal app with tx hash if it's available, otherwise do not provide let txRes: OnchainTransactionResponse | undefined; try { txRes = await this.submitWithdrawToChain( channel, signedWithdrawalCommitment, appInstance.identityHash, TransactionReason.USER_WITHDRAWAL, ); if (!txRes) { throw new Error(`No tx response available after submitting to chain!`); } } catch (e) { this.log.error(`Unable to submit withdrawal tx: ${e.message}`); } await this.cfCoreService.uninstallApp( appInstance.identityHash, channel, undefined, { withdrawTx: txRes?.hash }, ); // Update db entry again withdraw = await this.withdrawRepository.findByAppIdentityHash(appInstance.identityHash); if (!withdraw) { this.log.error( `Unable to find withdraw entity that we just uninstalled. AppId ${appInstance.identityHash}`, ); return; } const onchainTransaction = await this.onchainTransactionRepository.findByHash(txRes!.hash); await this.withdrawRepository.addUserOnchainTransaction(withdraw, onchainTransaction!); this.log.info(`Node responded with transaction: ${onchainTransaction!.hash}`); this.log.debug(`Transaction details: ${stringify(onchainTransaction)}`); return; } async deployMultisig(channel: Channel) { this.log.info(`deployMultisig for ${channel.multisigAddress}`); const { transactionHash: deployTx } = await this.cfCoreService.deployMultisig( channel.multisigAddress, ); this.log.info(`Deploy multisig tx: ${deployTx}`); const wallet = this.configService.getSigner(channel.chainId); if (deployTx !== HashZero) { this.log.info(`Waiting for deployment transaction...`); wallet.provider!.waitForTransaction(deployTx); this.log.info(`Deployment transaction complete!`); } else { this.log.info(`Multisig already deployed`); } } async submitWithdrawToChain( channel: Channel, tx: MinimalTransaction, appIdentityHash: string, withdrawReason: TransactionReason.NODE_WITHDRAWAL | TransactionReason.USER_WITHDRAWAL, ): Promise<OnchainTransactionResponse> { this.log.info(`submitWithdrawToChain for ${channel.multisigAddress}`); let txRes: OnchainTransactionResponse; if (withdrawReason === TransactionReason.NODE_WITHDRAWAL) { txRes = await this.onchainTransactionService.sendWithdrawal(channel, tx, appIdentityHash); } else { txRes = await this.onchainTransactionService.sendUserWithdrawal(channel, tx, appIdentityHash); } this.log.info(`Withdrawal tx sent! Hash: ${txRes.hash}`); return txRes; } async saveWithdrawal( appIdentityHash: string, amount: BigNumber, assetId: string, recipient: string, data: string, withdrawerSignature: string, counterpartySignature: string, multisigAddress: string, ): Promise<Withdraw> { const channel = await this.channelRepository.findByMultisigAddressOrThrow(multisigAddress); const withdraw = new Withdraw(); withdraw.appIdentityHash = appIdentityHash; withdraw.amount = amount; withdraw.assetId = assetId; withdraw.recipient = recipient; withdraw.data = data; withdraw.withdrawerSignature = withdrawerSignature; withdraw.counterpartySignature = counterpartySignature; withdraw.finalized = false; withdraw.channel = channel; return this.withdrawRepository.save(withdraw); } async getLatestWithdrawal( userIdentifier: string, chainId: number, ): Promise<OnchainTransaction | undefined> { await this.channelRepository.findByUserPublicIdentifierAndChainOrThrow(userIdentifier, chainId); return this.onchainTransactionRepository.findLatestWithdrawalByUserPublicIdentifierAndChain( userIdentifier, chainId, ); } private async proposeWithdrawApp( amount: BigNumber, assetId: string, channel: Channel, ): Promise<{ appIdentityHash: string; withdrawTracker: Withdraw }> { this.log.debug(`Creating proposal for node withdraw`); const nonce = hexlify(randomBytes(32)); const commitment = await this.cfCoreService.createWithdrawCommitment( { amount, assetId, recipient: this.cfCoreService.cfCore.signerAddress, nonce, } as PublicParams.Withdraw, channel, ); const signer = this.configService.getSigner(channel.chainId); const hash = commitment.hashToSign(); const withdrawerSignatureOnCommitment = await signer.signMessage(hash); const transfers: CoinTransfer[] = [ { amount, to: this.cfCoreService.cfCore.signerAddress }, { amount: Zero, to: getSignerAddressFromPublicIdentifier(channel.userIdentifier) }, ]; const initialState: WithdrawAppState = { transfers: [transfers[0], transfers[1]], signatures: [withdrawerSignatureOnCommitment, HashZero], signers: [ this.cfCoreService.cfCore.signerAddress, getSignerAddressFromPublicIdentifier(channel.userIdentifier), ], data: hash, nonce, finalized: false, }; // propose install + wait for client confirmation const { appIdentityHash } = (await this.cfCoreService.proposeAndWaitForInstallApp( channel, initialState, amount, assetId, Zero, assetId, this.cfCoreService.getAppInfoByNameAndChain(WithdrawAppName, channel.chainId), { reason: "Node withdrawal" }, WITHDRAW_STATE_TIMEOUT, ))!; const withdrawTracker = await this.saveWithdrawal( appIdentityHash, BigNumber.from(amount), assetId, initialState.transfers[0].to, initialState.data, initialState.signatures[0], initialState.signatures[1], channel.multisigAddress, ); return { appIdentityHash, withdrawTracker }; } }
the_stack
import * as React from 'react'; import {render, fireEvent} from '@testing-library/react'; import {renderHook} from '@testing-library/react-hooks'; import {InformationIcon} from '@twilio-paste/icons/esm/InformationIcon'; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore import axe from '../../../../../.jest/axe-helper'; import {Badge} from '../src'; import type {NamedChild} from '../src/types'; import {isFocusableElement, getBadgeSpanProps} from '../src/utils'; import {useResizeChildIcons} from '../src/hooks'; describe('Badge', () => { describe('Utils', () => { describe('isFocusableElement', () => { it('should return true for a button', () => { expect(isFocusableElement({as: 'button'})).toBeTruthy(); }); it('should return true for an anchor', () => { expect(isFocusableElement({as: 'a'})).toBeTruthy(); }); it('should return false for a span', () => { expect(isFocusableElement({as: 'span'})).toBeFalsy(); }); }); describe('getBadgeSpanProps', () => { it('should return safe props to spread on the badge span when it is a span element', () => { expect( // @ts-expect-error can't pass style props in typescript but you can in JS and we need to prove they get removed getBadgeSpanProps({as: 'span', 'aria-labelledby': 'some-id', backgroundColor: 'colorBackgroundSuccess'}) ).toEqual({ 'aria-labelledby': 'some-id', as: 'span', }); }); it('should return no props to spread on the badge span when it is a button or anchor element as they should be spread on the parent', () => { expect( // @ts-expect-error can't pass style props in typescript but you can in JS and we need to prove they get removed getBadgeSpanProps({as: 'button', 'aria-labelledby': 'some-id', backgroundColor: 'colorBackgroundSuccess'}) ).toEqual({}); expect( // @ts-expect-error can't pass style props in typescript but you can in JS and we need to prove they get removed getBadgeSpanProps({as: 'a', 'aria-labelledby': 'some-id', backgroundColor: 'colorBackgroundSuccess'}) ).toEqual({}); }); }); }); describe('Hooks', () => { describe('useResizeChildIcons', () => { it('should return return no modifications when child icon size is default', () => { const {result} = renderHook(() => useResizeChildIcons(['test', <InformationIcon decorative />])); const icon = (result.current as ArrayLike<NamedChild>)[1]; expect(icon.type.displayName).toEqual('InformationIcon'); expect(icon.props.size).toEqual('sizeIcon10'); }); it('should return the correct modifications when child icon size is not the default', () => { const {result} = renderHook(() => useResizeChildIcons(['test', <InformationIcon size="sizeIcon40" decorative />]) ); const icon = (result.current as ArrayLike<NamedChild>)[1]; expect(icon.type.displayName).toEqual('InformationIcon'); expect(icon.props.size).toEqual('sizeIcon10'); }); }); }); describe('Refs', () => { it('should set ref to a span element when rendered as a "span"', () => { const badgeRef = React.createRef<HTMLElement>(); render( <Badge as="span" variant="default" ref={badgeRef}> Default </Badge> ); expect(badgeRef?.current?.tagName).toEqual('SPAN'); }); it('should set ref to a button element when rendered as a "button"', () => { const badgeRef = React.createRef<HTMLElement>(); render( <Badge as="button" onClick={() => {}} variant="default" ref={badgeRef}> Default </Badge> ); expect(badgeRef?.current?.tagName).toEqual('BUTTON'); }); it('should set ref to an anchor element when rendered as a "a"', () => { const badgeRef = React.createRef<HTMLElement>(); render( <Badge as="a" href="#" variant="default" ref={badgeRef}> Default </Badge> ); expect(badgeRef?.current?.tagName).toEqual('A'); }); }); describe('Badge as button', () => { describe('Event handlers', () => { it('should handle onclick event', () => { const onClickMock: jest.Mock = jest.fn(); const {getByRole} = render( <Badge as="button" onClick={onClickMock} variant="success"> Button </Badge> ); const button = getByRole('button'); fireEvent.click(button); expect(onClickMock).toBeCalledTimes(1); }); it('should handle onmouseup event', () => { const onMouseUpMock: jest.Mock = jest.fn(); const {getByRole} = render( <Badge as="button" onClick={() => null} onMouseUp={onMouseUpMock} variant="success"> Button </Badge> ); const button = getByRole('button'); fireEvent.mouseUp(button); expect(onMouseUpMock).toBeCalledTimes(1); }); it('should handle onmouseenter event', () => { const onMouseEnterMock: jest.Mock = jest.fn(); const {getByRole} = render( <Badge as="button" onClick={() => null} onMouseEnter={onMouseEnterMock} variant="success"> Button </Badge> ); const button = getByRole('button'); fireEvent.mouseEnter(button); expect(onMouseEnterMock).toBeCalledTimes(1); }); it('should handle onmouseleave event', () => { const onMouseLeaveMock: jest.Mock = jest.fn(); const {getByRole} = render( <Badge as="button" onClick={() => null} onMouseLeave={onMouseLeaveMock} variant="success"> Button </Badge> ); const button = getByRole('button'); fireEvent.mouseLeave(button); expect(onMouseLeaveMock).toBeCalledTimes(1); }); it('should handle onfocus event', () => { const onFocusMock: jest.Mock = jest.fn(); const {getByRole} = render( <Badge as="button" onClick={() => null} onFocus={onFocusMock} variant="success"> Button </Badge> ); const button = getByRole('button'); fireEvent.focus(button); expect(onFocusMock).toBeCalledTimes(1); }); it('should handle onblur event', () => { const onBlurMock: jest.Mock = jest.fn(); const {getByRole} = render( <Badge as="button" onClick={() => null} onBlur={onBlurMock} variant="success"> Button </Badge> ); const button = getByRole('button'); fireEvent.blur(button); expect(onBlurMock).toBeCalledTimes(1); }); it('should handle onmousedown event', () => { const onMouseDownMock: jest.Mock = jest.fn(); const {getByRole} = render( <Badge as="button" onClick={() => null} onMouseDown={onMouseDownMock} variant="success"> Button </Badge> ); const button = getByRole('button'); fireEvent.mouseDown(button); expect(onMouseDownMock).toBeCalledTimes(1); }); }); describe('Render', () => { it('should render badge as button if "as" is "button"', () => { const {getByRole} = render( <Badge as="button" onClick={() => null} variant="success"> Button </Badge> ); expect(getByRole('button')).toBeInTheDocument(); }); it('should render badge as button with correct styles', () => { const {container} = render( <Badge as="button" onClick={() => null} variant="success"> Button </Badge> ); const badgeElement = container.querySelector(':nth-child(1) > span > span'); // @TODO make sure all the style rules are accounted for here. expect(badgeElement).toHaveStyleRule('color', 'colorTextSuccess'); expect(badgeElement).toHaveStyleRule('background-color', 'colorBackgroundSuccessWeakest'); expect(badgeElement).toHaveStyleRule('text-decoration', 'underline'); expect(badgeElement).toHaveStyleRule('text-decoration', 'none', {target: ':hover'}); expect(badgeElement).toHaveStyleRule('box-shadow', 'shadowFocus', {target: ':focus'}); expect(badgeElement).toHaveStyleRule('text-decoration', 'none', {target: ':focus'}); }); }); }); describe('Badge as anchor', () => { describe('Event handlers', () => { it('should handle mouseup event', () => { const onMouseUpMock: jest.Mock = jest.fn(); const {getByRole} = render( <Badge as="a" href="#" onMouseUp={onMouseUpMock} variant="success"> Anchor </Badge> ); const anchor = getByRole('link'); fireEvent.mouseUp(anchor); expect(onMouseUpMock).toBeCalledTimes(1); }); it('should handle mouseenter event', () => { const onMouseEnterMock: jest.Mock = jest.fn(); const {getByRole} = render( <Badge as="a" href="#" onMouseEnter={onMouseEnterMock} variant="success"> Anchor </Badge> ); const anchor = getByRole('link'); fireEvent.mouseEnter(anchor); expect(onMouseEnterMock).toBeCalledTimes(1); }); it('should mouseleave event', () => { const onMouseLeaveMock: jest.Mock = jest.fn(); const {getByRole} = render( <Badge as="a" href="#" onMouseLeave={onMouseLeaveMock} variant="success"> Anchor </Badge> ); const anchor = getByRole('link'); fireEvent.mouseLeave(anchor); expect(onMouseLeaveMock).toBeCalledTimes(1); }); it('should handle onblur event', () => { const onBlurMock: jest.Mock = jest.fn(); const {getByRole} = render( <Badge as="a" href="#" onBlur={onBlurMock} variant="success"> Anchor </Badge> ); const anchor = getByRole('link'); fireEvent.blur(anchor); expect(onBlurMock).toBeCalledTimes(1); }); it('should handle onmousedown event', () => { const onMouseDownMock: jest.Mock = jest.fn(); const {getByRole} = render( <Badge as="a" href="#" onMouseDown={onMouseDownMock} variant="success"> Anchor </Badge> ); const anchor = getByRole('link'); fireEvent.mouseDown(anchor); expect(onMouseDownMock).toBeCalledTimes(1); }); }); describe('Render', () => { it('should render badge as anchor if "as" is "anchor"', () => { const {getByRole} = render( <Badge as="a" href="#test" variant="success"> Anchor </Badge> ); expect(getByRole('link')).toBeInTheDocument(); }); it('should render badge as anchor with correct styles', () => { const {container} = render( <Badge href="#test" as="a" variant="success"> Not anchor </Badge> ); const badgeElement = container.querySelector(':nth-child(1) > span > span'); expect(badgeElement).toHaveStyleRule('color', 'colorTextSuccess'); expect(badgeElement).toHaveStyleRule('background-color', 'colorBackgroundSuccessWeakest'); expect(badgeElement).toHaveStyleRule('text-decoration', 'underline'); expect(badgeElement).toHaveStyleRule('text-decoration', 'none', {target: ':hover'}); expect(badgeElement).toHaveStyleRule('box-shadow', 'shadowFocus', {target: ':focus'}); expect(badgeElement).toHaveStyleRule('text-decoration', 'none', {target: ':focus'}); }); }); }); describe('Badge as span', () => { describe('Render', () => { it('should render as a span element if as is "span"', () => { const {getByTestId} = render( <Badge as="span" variant="default" data-testid="badge-6"> test </Badge> ); const badgeElement = getByTestId('badge-6'); expect(badgeElement.tagName).toEqual('SPAN'); }); }); }); describe('Accessibility', () => { it('Should have no accessibility violations', async () => { const {container} = render( <> <Badge as="span" data-testid="badge-1" variant="default"> test </Badge> <Badge as="span" data-testid="badge-1" variant="success"> test </Badge> <Badge as="span" data-testid="badge-1" variant="warning"> test </Badge> <Badge as="span" data-testid="badge-1" variant="error"> test </Badge> <Badge as="span" data-testid="badge-1" variant="info"> test </Badge> <Badge as="span" data-testid="badge-1" variant="new"> test </Badge> <Badge as="a" href="#" data-testid="badge-1" variant="default"> test </Badge> <Badge as="a" href="#" data-testid="badge-1" variant="success"> test </Badge> <Badge as="a" href="#" data-testid="badge-1" variant="warning"> test </Badge> <Badge as="a" href="#" data-testid="badge-1" variant="error"> test </Badge> <Badge as="a" href="#" data-testid="badge-1" variant="info"> test </Badge> <Badge as="a" href="#" data-testid="badge-1" variant="new"> test </Badge> <Badge as="button" onClick={() => null} data-testid="badge-1" variant="default"> test </Badge> <Badge as="button" onClick={() => null} data-testid="badge-1" variant="success"> test </Badge> <Badge as="button" onClick={() => null} data-testid="badge-1" variant="warning"> test </Badge> <Badge as="button" onClick={() => null} data-testid="badge-1" variant="error"> test </Badge> <Badge as="button" onClick={() => null} data-testid="badge-1" variant="info"> test </Badge> <Badge as="button" onClick={() => null} data-testid="badge-1" variant="new"> test </Badge> </> ); const results = await axe(container); expect(results).toHaveNoViolations(); }); }); });
the_stack
import ava, {TestInterface} from 'ava'; import {DialogflowConversation} from '../conv'; import * as ApiV1 from '../api/v1'; import {clone} from '../../../common'; import {Permission, SimpleResponse, Image, List} from '../../actionssdk'; interface AvaContext { conv: DialogflowConversation; } const test = ava as TestInterface<AvaContext>; test.beforeEach(t => { t.context.conv = new DialogflowConversation({ body: { result: {}, originalRequest: { data: {}, }, } as ApiV1.DialogflowV1WebhookRequest, headers: {}, }); }); test('conv can be instantiated', t => { t.true(t.context.conv instanceof DialogflowConversation); }); test('conv.serialize returns the raw json when set with conv.json', t => { const json = { a: '1', b: '2', c: { d: '3', e: '4', }, }; t.context.conv.json(json); t.deepEqual(t.context.conv.serialize() as typeof json, json); }); test('conv.serialize returns the correct response with simple response string', t => { const response = 'abc123'; const conv = t.context.conv; conv.add(response); t.deepEqual(clone(conv.serialize()), { data: { google: { expectUserResponse: true, richResponse: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, }, }); }); const simulatorConv = () => new DialogflowConversation({ body: { id: 'idRandom', timestamp: 'timestampRandom', lang: 'en', result: { source: 'agent', resolvedQuery: 'test', speech: '', action: 'input.unknown', actionIncomplete: false, parameters: {}, contexts: [], metadata: { intentId: 'intentIdRandom', webhookUsed: 'true', webhookForSlotFillingUsed: 'false', isFallbackIntent: 'true', intentName: 'Default Fallback Intent', }, fulfillment: { speech: "Sorry, I didn't get that.", messages: [ { type: 0, speech: 'What was that?', }, ], }, score: 1, }, status: { code: 200, errorType: 'success', }, sessionId: 'sessionIdRandom', } as ApiV1.DialogflowV1WebhookRequest, headers: {}, }); test('conv.serialize w/ simple response has fulfillmentText when from simulator', t => { const response = 'abc123'; const conv = simulatorConv(); conv.add(response); t.deepEqual(clone(conv.serialize()), { data: { google: { expectUserResponse: true, richResponse: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, }, speech: response, }); }); test('conv.serialize w/ simple response text has fulfillmentText when from simulator', t => { const speech = 'abc123'; const text = 'abcd1234'; const conv = simulatorConv(); conv.add( new SimpleResponse({ speech, text, }) ); t.deepEqual(clone(conv.serialize()), { data: { google: { expectUserResponse: true, richResponse: { items: [ { simpleResponse: { textToSpeech: speech, displayText: text, }, }, ], }, }, }, speech: text, }); }); test('conv.serialize w/ two simple responses has fulfillmentText warning for simulator', t => { const response = 'abc123'; const response2 = 'abcd1234'; const conv = simulatorConv(); conv.add(response); conv.add(response2); t.deepEqual(clone(conv.serialize()), { data: { google: { expectUserResponse: true, richResponse: { items: [ { simpleResponse: { textToSpeech: response, }, }, { simpleResponse: { textToSpeech: response2, }, }, ], }, }, }, speech: 'Cannot display response in Dialogflow simulator. ' + 'Please test on the Google Assistant simulator instead.', }); }); test('conv.serialize w/ solo helper has fulfillmentText warning for simulator', t => { const permission: 'NAME' = 'NAME'; const context = 'To read your mind'; const conv = simulatorConv(); conv.ask( new Permission({ permissions: permission, context, }) ); t.deepEqual(clone(conv.serialize()), { data: { google: { expectUserResponse: true, systemIntent: { data: { '@type': 'type.googleapis.com/google.actions.v2.PermissionValueSpec', optContext: context, permissions: [permission], }, intent: 'actions.intent.PERMISSION', }, }, }, speech: 'Cannot display response in Dialogflow simulator. ' + 'Please test on the Google Assistant simulator instead.', }); }); test('conv.serialize w/ non solo helper has fulfillmentText warning for simulator', t => { const response = 'abc123'; const conv = simulatorConv(); conv.ask(response); conv.ask( new List({ items: { one: { title: 'one1', synonyms: ['one11', 'one12'], }, two: { title: 'two1', synonyms: ['two11', 'two12'], }, }, }) ); t.deepEqual(clone(conv.serialize()), { data: { google: { expectUserResponse: true, richResponse: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, systemIntent: { data: { '@type': 'type.googleapis.com/google.actions.v2.OptionValueSpec', listSelect: { items: [ { optionInfo: { key: 'one', synonyms: ['one11', 'one12'], }, title: 'one1', }, { optionInfo: { key: 'two', synonyms: ['two11', 'two12'], }, title: 'two1', }, ], }, }, intent: 'actions.intent.OPTION', }, }, }, speech: 'Cannot display response in Dialogflow simulator. ' + 'Please test on the Google Assistant simulator instead.', }); }); test('conv.serialize w/ image has fulfillmentText warning for simulator', t => { const response = 'abc123'; const image = 'abcd1234'; const alt = 'abcde12345'; const conv = simulatorConv(); conv.add(response); conv.add( new Image({ url: image, alt, }) ); t.deepEqual(clone(conv.serialize()), { data: { google: { expectUserResponse: true, richResponse: { items: [ { simpleResponse: { textToSpeech: response, }, }, { basicCard: { image: { accessibilityText: alt, url: image, }, }, }, ], }, }, }, speech: 'Cannot display response in Dialogflow simulator. ' + 'Please test on the Google Assistant simulator instead.', }); }); test('conv.data is parsed correctly', t => { const data = { a: '1', b: '2', c: { d: '3', e: '4', }, }; const conv = new DialogflowConversation({ body: { result: { contexts: [ { name: '_actions_on_google', parameters: { data: JSON.stringify(data), }, }, ], }, } as ApiV1.DialogflowV1WebhookRequest, }); t.deepEqual(conv.data, data); }); test('conv generates no contexts from empty conv.data', t => { const response = "What's up?"; const conv = new DialogflowConversation({ body: { result: {}, originalRequest: { data: {}, }, } as ApiV1.DialogflowV1WebhookRequest, }); t.deepEqual(conv.data, {}); conv.ask(response); t.deepEqual(clone(conv.serialize()), { data: { google: { expectUserResponse: true, richResponse: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, }, }); }); test('conv generates first conv.data replaced correctly', t => { const response = "What's up?"; const data = { a: '1', b: '2', c: { d: '3', e: '4', }, }; const conv = new DialogflowConversation({ body: { result: {}, originalRequest: { data: {}, }, } as ApiV1.DialogflowV1WebhookRequest, }); t.deepEqual(conv.data, {}); conv.ask(response); conv.data = data; t.deepEqual(clone(conv.serialize()), { data: { google: { expectUserResponse: true, richResponse: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, }, contextOut: [ { name: '_actions_on_google', lifespan: 99, parameters: { data: JSON.stringify(data), }, }, ], }); }); test('conv generates first conv.data mutated correctly', t => { const response = "What's up?"; const a = '7'; const conv = new DialogflowConversation<{a?: string}>({ body: { result: {}, originalRequest: { data: {}, }, } as ApiV1.DialogflowV1WebhookRequest, }); t.deepEqual(conv.data, {}); conv.ask(response); conv.data.a = a; t.deepEqual(clone(conv.serialize()), { data: { google: { expectUserResponse: true, richResponse: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, }, contextOut: [ { name: '_actions_on_google', lifespan: 99, parameters: { data: JSON.stringify({a}), }, }, ], }); }); test('conv generates different conv.data correctly', t => { const response = "What's up?"; const data = { a: '1', b: '2', c: { d: '3', e: '4', }, }; const e = '6'; const conv = new DialogflowConversation<typeof data>({ body: { result: { contexts: [ { name: '_actions_on_google', parameters: { data: JSON.stringify(data), }, }, ], }, originalRequest: { data: {}, }, } as ApiV1.DialogflowV1WebhookRequest, }); t.deepEqual(conv.data, data); conv.ask(response); conv.data.c.e = e; t.deepEqual(clone(conv.serialize()), { data: { google: { expectUserResponse: true, richResponse: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, }, contextOut: [ { name: '_actions_on_google', lifespan: 99, parameters: { data: JSON.stringify({ a: '1', b: '2', c: { d: '3', e, }, }), }, }, ], }); }); test('conv generates same conv.data as no output contexts', t => { const response = "What's up?"; const data = { a: '1', b: '2', c: { d: '3', e: '4', }, }; const conv = new DialogflowConversation<typeof data>({ body: { result: { contexts: [ { name: '_actions_on_google', parameters: { data: JSON.stringify(data), }, }, ], }, originalRequest: { data: {}, }, } as ApiV1.DialogflowV1WebhookRequest, }); t.deepEqual(conv.data, data); conv.ask(response); t.deepEqual(clone(conv.serialize()), { data: { google: { expectUserResponse: true, richResponse: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, }, }); }); test('conv sends userStorage when it is not empty', t => { const response = "What's up?"; const data = { a: '1', b: '2', c: { d: '3', e: '4', }, }; const conv = new DialogflowConversation({ body: { result: {}, originalRequest: { data: {}, }, } as ApiV1.DialogflowV1WebhookRequest, }); t.deepEqual(conv.data, {}); conv.user.storage = data; conv.ask(response); t.deepEqual(clone(conv.serialize()), { data: { google: { expectUserResponse: true, richResponse: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, userStorage: JSON.stringify({data}), }, }, }); }); test('conv does not send userStorage when it is empty', t => { const response = "What's up?"; const conv = new DialogflowConversation({ body: { result: {}, originalRequest: { data: {}, }, } as ApiV1.DialogflowV1WebhookRequest, }); t.deepEqual(conv.user.storage, {}); conv.ask(response); t.deepEqual(clone(conv.serialize()), { data: { google: { expectUserResponse: true, richResponse: { items: [ { simpleResponse: { textToSpeech: response, }, }, ], }, }, }, }); }); test('conv does not error out when simple response is after image', t => { const response = 'How are you?'; const conv = new DialogflowConversation({ body: { result: {}, originalRequest: { data: {}, }, } as ApiV1.DialogflowV1WebhookRequest, }); conv.ask(new Image({url: '', alt: ''})); conv.ask(response); t.deepEqual(clone(conv.serialize()), { data: { google: { expectUserResponse: true, richResponse: { items: [ { basicCard: { image: { url: '', accessibilityText: '', }, }, }, { simpleResponse: { textToSpeech: response, }, }, ], }, }, }, }); }); test('conv w/ simple response after image has fulfillmentText warning for simulator', t => { const response = 'abc123'; const image = 'abcd1234'; const alt = 'abcde12345'; const conv = simulatorConv(); conv.add( new Image({ url: image, alt, }) ); conv.add(response); t.deepEqual(clone(conv.serialize()), { data: { google: { expectUserResponse: true, richResponse: { items: [ { basicCard: { image: { accessibilityText: alt, url: image, }, }, }, { simpleResponse: { textToSpeech: response, }, }, ], }, }, }, speech: 'Cannot display response in Dialogflow simulator. ' + 'Please test on the Google Assistant simulator instead.', }); });
the_stack
import * as promiseLimit from 'promise-limit'; import config from '../../../config'; import Resolver from '../resolver'; import post from '../../../services/note/create'; import { resolvePerson, updatePerson } from './person'; import { resolveImage } from './image'; import { IRemoteUser, User } from '../../../models/entities/user'; import { fromHtml } from '../../../mfm/fromHtml'; import { ITag, extractHashtags } from './tag'; import { unique, concat, difference } from '../../../prelude/array'; import { extractPollFromQuestion } from './question'; import vote from '../../../services/note/polls/vote'; import { apLogger } from '../logger'; import { DriveFile } from '../../../models/entities/drive-file'; import { deliverQuestionUpdate } from '../../../services/note/polls/update'; import { extractDbHost, toPuny } from '../../../misc/convert-host'; import { Notes, Emojis, Polls } from '../../../models'; import { Note } from '../../../models/entities/note'; import { IObject, INote } from '../type'; import { Emoji } from '../../../models/entities/emoji'; import { genId } from '../../../misc/gen-id'; import { fetchMeta } from '../../../misc/fetch-meta'; import { ensure } from '../../../prelude/ensure'; const logger = apLogger; export function validateNote(object: any, uri: string) { const expectHost = extractDbHost(uri); if (object == null) { return new Error('invalid Note: object is null'); } if (!['Note', 'Question', 'Article'].includes(object.type)) { return new Error(`invalid Note: invalied object type ${object.type}`); } if (object.id && extractDbHost(object.id) !== expectHost) { return new Error(`invalid Note: id has different host. expected: ${expectHost}, actual: ${extractDbHost(object.id)}`); } if (object.attributedTo && extractDbHost(object.attributedTo) !== expectHost) { return new Error(`invalid Note: attributedTo has different host. expected: ${expectHost}, actual: ${extractDbHost(object.attributedTo)}`); } return null; } /** * Noteをフェッチします。 * */ export async function fetchNote(value: string | IObject, resolver?: Resolver): Promise<Note | null> { const uri = typeof value == 'string' ? value : value.id; if (uri == null) throw new Error('missing uri'); // URIがこのサーバーを指しているならデータベースからフェッチ if (uri.startsWith(config.url + '/')) { const id = uri.split('/').pop(); return await Notes.findOne(id).then(x => x || null); } //#region このサーバーに既に登録されていたらそれを返す const exist = await Notes.findOne({ uri }); if (exist) { return exist; } //#endregion return null; } /** * Noteを作成します。 */ export async function createNote(value: any, resolver?: Resolver, silent = false): Promise<Note | null> { if (resolver == null) resolver = new Resolver(); const object: any = await resolver.resolve(value); const entryUri = value.id || value; const err = validateNote(object, entryUri); if (err) { logger.error(`${err.message}`, { resolver: { history: resolver.getHistory() }, value: value, object: object }); throw new Error('invalid note'); } const note: INote = object; logger.debug(`Note fetched: ${JSON.stringify(note, null, 2)}`); logger.info(`Creating the Note: ${note.id}`); // 投稿者をフェッチ const actor = await resolvePerson(note.attributedTo, resolver) as IRemoteUser; // 投稿者が凍結されていたらスキップ if (actor.isSuspended) { throw new Error('actor has been suspended'); } //#region Visibility note.to = note.to == null ? [] : typeof note.to == 'string' ? [note.to] : note.to; note.cc = note.cc == null ? [] : typeof note.cc == 'string' ? [note.cc] : note.cc; let visibility = 'public'; let visibleUsers: User[] = []; if (!note.to.includes('https://www.w3.org/ns/activitystreams#Public')) { if (note.cc.includes('https://www.w3.org/ns/activitystreams#Public')) { visibility = 'home'; } else if (note.to.includes(`${actor.uri}/followers`)) { // TODO: person.followerと照合するべき? visibility = 'followers'; } else { visibility = 'specified'; visibleUsers = await Promise.all(note.to.map(uri => resolvePerson(uri, resolver))); } } //#endergion const apMentions = await extractMentionedUsers(actor, note.to, note.cc, resolver); const apHashtags = await extractHashtags(note.tag); // 添付ファイル // TODO: attachmentは必ずしもImageではない // TODO: attachmentは必ずしも配列ではない // Noteがsensitiveなら添付もsensitiveにする const limit = promiseLimit(2); note.attachment = Array.isArray(note.attachment) ? note.attachment : note.attachment ? [note.attachment] : []; const files = note.attachment .map(attach => attach.sensitive = note.sensitive) ? (await Promise.all(note.attachment.map(x => limit(() => resolveImage(actor, x)) as Promise<DriveFile>))) .filter(image => image != null) : []; // リプライ const reply: Note | null = note.inReplyTo ? await resolveNote(note.inReplyTo, resolver).then(x => { if (x == null) { logger.warn(`Specified inReplyTo, but nout found`); throw new Error('inReplyTo not found'); } else { return x; } }).catch(e => { logger.warn(`Error in inReplyTo ${note.inReplyTo} - ${e.statusCode || e}`); throw e; }) : null; // 引用 let quote: Note | undefined | null; if (note._misskey_quote && typeof note._misskey_quote == 'string') { quote = await resolveNote(note._misskey_quote).catch(e => { // 4xxの場合は引用してないことにする if (e.statusCode >= 400 && e.statusCode < 500) { logger.warn(`Ignored quote target ${note.inReplyTo} - ${e.statusCode} `); return null; } logger.warn(`Error in quote target ${note.inReplyTo} - ${e.statusCode || e}`); throw e; }); } const cw = note.summary === '' ? null : note.summary; // テキストのパース const text = note._misskey_content || (note.content ? fromHtml(note.content) : null); // vote if (reply && reply.hasPoll) { const poll = await Polls.findOne(reply.id).then(ensure); const tryCreateVote = async (name: string, index: number): Promise<null> => { if (poll.expiresAt && Date.now() > new Date(poll.expiresAt).getTime()) { logger.warn(`vote to expired poll from AP: actor=${actor.username}@${actor.host}, note=${note.id}, choice=${name}`); } else if (index >= 0) { logger.info(`vote from AP: actor=${actor.username}@${actor.host}, note=${note.id}, choice=${name}`); await vote(actor, reply, index); // リモートフォロワーにUpdate配信 deliverQuestionUpdate(reply.id); } return null; }; if (note.name) { return await tryCreateVote(note.name, poll.choices.findIndex(x => x === note.name)); } // 後方互換性のため if (text) { const m = text.match(/(\d+)$/); if (m) { return await tryCreateVote(m[0], Number(m[1])); } } } const emojis = await extractEmojis(note.tag || [], actor.host).catch(e => { logger.info(`extractEmojis: ${e}`); return [] as Emoji[]; }); const apEmojis = emojis.map(emoji => emoji.name); const questionUri = note._misskey_question; const poll = await extractPollFromQuestion(note._misskey_question || note).catch(() => undefined); // ユーザーの情報が古かったらついでに更新しておく if (actor.lastFetchedAt == null || Date.now() - actor.lastFetchedAt.getTime() > 1000 * 60 * 60 * 24) { updatePerson(note.attributedTo); } return await post(actor, { createdAt: note.published ? new Date(note.published) : null, files, reply, renote: quote, name: note.name, cw, text, viaMobile: false, localOnly: false, geo: undefined, visibility, visibleUsers, apMentions, apHashtags, apEmojis, questionUri, poll, uri: note.id }, silent); } /** * Noteを解決します。 */ export async function resolveNote(value: string | IObject, resolver?: Resolver): Promise<Note | null> { const uri = typeof value == 'string' ? value : value.id; if (uri == null) throw new Error('missing uri'); // ブロックしてたら中断 const meta = await fetchMeta(); if (meta.blockedHosts.includes(extractDbHost(uri))) throw { statusCode: 451 }; //#region このサーバーに既に登録されていたらそれを返す const exist = await fetchNote(uri); if (exist) { return exist; } //#endregion // リモートサーバーからフェッチしてきて登録 // ここでuriの代わりに添付されてきたNote Objectが指定されていると、サーバーフェッチを経ずにノートが生成されるが // 添付されてきたNote Objectは偽装されている可能性があるため、常にuriを指定してサーバーフェッチを行う。 return await createNote(uri, resolver, true).catch(e => { if (e.name === 'duplicated') { return fetchNote(uri).then(note => { if (note == null) { throw new Error('something happened'); } else { return note; } }); } else { throw e; } }); } export async function extractEmojis(tags: ITag[], host: string): Promise<Emoji[]> { host = toPuny(host); if (!tags) return []; const eomjiTags = tags.filter(tag => tag.type === 'Emoji' && tag.icon && tag.icon.url && tag.name); return await Promise.all(eomjiTags.map(async tag => { const name = tag.name!.replace(/^:/, '').replace(/:$/, ''); const exists = await Emojis.findOne({ host, name }); if (exists) { if ((tag.updated != null && exists.updatedAt == null) || (tag.id != null && exists.uri == null) || (tag.updated != null && exists.updatedAt != null && new Date(tag.updated) > exists.updatedAt) ) { await Emojis.update({ host, name, }, { uri: tag.id, url: tag.icon!.url, updatedAt: new Date(tag.updated!), }); return await Emojis.findOne({ host, name }) as Emoji; } return exists; } logger.info(`register emoji host=${host}, name=${name}`); return await Emojis.save({ id: genId(), host, name, uri: tag.id, url: tag.icon!.url, updatedAt: tag.updated ? new Date(tag.updated) : undefined, aliases: [] } as Partial<Emoji>); })); } async function extractMentionedUsers(actor: IRemoteUser, to: string[], cc: string[], resolver: Resolver) { const ignoreUris = ['https://www.w3.org/ns/activitystreams#Public', `${actor.uri}/followers`]; const uris = difference(unique(concat([to || [], cc || []])), ignoreUris); const limit = promiseLimit<User | null>(2); const users = await Promise.all( uris.map(uri => limit(() => resolvePerson(uri, resolver).catch(() => null)) as Promise<User | null>) ); return users.filter(x => x != null) as User[]; }
the_stack
import { NgZone } from '@angular/core'; import { createStore, Reducer, Action, AnyAction, Store } from 'redux'; import { Observable } from 'rxjs'; import { combineLatest, filter } from 'rxjs/operators'; import { NgRedux } from './ng-redux'; import { RootStore } from './root-store'; import { select } from '../decorators/select'; class MockNgZone extends NgZone { run<T>(fn: (...args: any[]) => T): T { return fn() as T; } } type PayloadAction = Action & { payload?: string | number }; describe('NgRedux Observable Store', () => { interface IAppState { foo: string; bar: string; baz: number; } let defaultState: IAppState; let rootReducer: Reducer<IAppState, AnyAction>; let store: Store<IAppState>; let ngRedux: NgRedux<IAppState>; const mockNgZone = new MockNgZone({ enableLongStackTrace: false }) as NgZone; beforeEach(() => { defaultState = { foo: 'bar', bar: 'foo', baz: -1, }; rootReducer = (state = defaultState, action: PayloadAction) => { switch (action.type) { case 'UPDATE_FOO': return Object.assign({}, state, { foo: action.payload }); case 'UPDATE_BAZ': return Object.assign({}, state, { baz: action.payload }); case 'UPDATE_BAR': return Object.assign({}, state, { bar: action.payload }); default: return state; } }; store = createStore(rootReducer); ngRedux = new RootStore<IAppState>(mockNgZone); ngRedux.configureStore(rootReducer, defaultState); }); it('should throw when the store is configured twice', () => { // Configured once in beforeEach, now we try to configure // it a second time. expect( ngRedux.configureStore.bind(ngRedux, rootReducer, defaultState) ).toThrowError(Error); }); it('should get the initial state', done => ngRedux.select<any>().subscribe((state: IAppState) => { expect(state.foo).toEqual('bar'); expect(state.baz).toEqual(-1); done(); })); it('should accept a keyname for a selector', done => ngRedux.select<any>('foo').subscribe(stateSlice => { expect(stateSlice).toEqual('bar'); done(); })); it('should not trigger selector if that slice of state wasnt changed', () => { let fooData = ''; const spy = jasmine.createSpy('spy').and.callFake((foo: string) => { fooData = foo; }); const foo$ = ngRedux.select<any>('foo').subscribe(spy); expect(spy.calls.count()).toEqual(1); ngRedux.dispatch({ type: 'UPDATE_BAR', payload: 0 }); expect(spy.calls.count()).toEqual(1); expect(fooData).toEqual('bar'); ngRedux.dispatch({ type: 'UPDATE_FOO', payload: 'changeFoo' }); expect(spy.calls.count()).toEqual(2); expect(fooData).toEqual('changeFoo'); foo$.unsubscribe(); }); it('should not trigger a selector if the action payload is the same', () => { let fooData = ''; const spy = jasmine.createSpy('spy').and.callFake((foo: string) => { fooData = foo; }); const foo$ = ngRedux.select('foo').subscribe(spy); expect(spy.calls.count()).toEqual(1); expect(fooData).toEqual('bar'); ngRedux.dispatch({ type: 'UPDATE_FOO', payload: 'bar' }); expect(spy.calls.count()).toEqual(1); expect(fooData).toEqual('bar'); foo$.unsubscribe(); }); it('should not call sub if the result of the function is the same', () => { let fooData = ''; const spy = jasmine.createSpy('spy').and.callFake((foo: string) => { fooData = foo; }); ngRedux.select(state => `${state.foo}-${state.baz}`).subscribe(spy); expect(spy.calls.count()).toEqual(1); expect(fooData).toEqual('bar--1'); expect(spy.calls.count()).toEqual(1); expect(fooData).toEqual('bar--1'); ngRedux.dispatch({ type: 'UPDATE_BAR', payload: 'bar' }); expect(spy.calls.count()).toEqual(1); expect(fooData).toEqual('bar--1'); ngRedux.dispatch({ type: 'UPDATE_FOO', payload: 'update' }); expect(fooData).toEqual('update--1'); expect(spy.calls.count()).toEqual(2); ngRedux.dispatch({ type: 'UPDATE_BAZ', payload: 2 }); expect(fooData).toEqual('update-2'); expect(spy.calls.count()).toEqual(3); }); it(`should accept a custom compare function`, () => { interface IRecord { data?: string; } let fooData: IRecord = {}; const spy = jasmine .createSpy('spy') .and.callFake((data: IRecord) => (fooData = data)); const cmp = (a: IRecord, b: IRecord) => a.data === b.data; ngRedux .select(state => ({ data: `${state.foo}-${state.baz}` }), cmp) .subscribe(spy); expect(spy.calls.count()).toEqual(1); expect(fooData.data).toEqual('bar--1'); ngRedux.dispatch({ type: 'UPDATE_BAR', payload: 'bar' }); expect(spy.calls.count()).toEqual(1); expect(fooData.data).toEqual('bar--1'); ngRedux.dispatch({ type: 'UPDATE_FOO', payload: 'update' }); expect(fooData.data).toEqual('update--1'); expect(spy.calls.count()).toEqual(2); ngRedux.dispatch({ type: 'UPDATE_BAZ', payload: 2 }); expect(fooData.data).toEqual('update-2'); expect(spy.calls.count()).toEqual(3); }); it(`should only call provided select function if state changed`, () => { const selectSpy = jasmine .createSpy('selectSpy') .and.callFake((state: IAppState) => state.foo); ngRedux.select().subscribe(selectSpy); // called once to get the initial value expect(selectSpy.calls.count()).toEqual(1); // not called since no state was updated ngRedux.dispatch({ type: 'NOT_A_STATE_CHANGE' }); expect(selectSpy.calls.count()).toEqual(1); ngRedux.dispatch({ type: 'UPDATE_FOO', payload: 'update' }); expect(selectSpy.calls.count()).toEqual(2); ngRedux.dispatch({ type: 'NOT_A_STATE_CHANGE' }); expect(selectSpy.calls.count()).toEqual(2); }); it('should throw if store is provided after it has been configured', () => { // Configured once in beforeEach, now we try to provide a store when // we already have configured one. expect(ngRedux.provideStore.bind(store)).toThrowError(); }); it('should wait until store is configured before emitting values', () => { class SomeService { foo: string; bar: string; baz: number; constructor(_ngRedux: NgRedux<any>) { _ngRedux.select(n => n.foo).subscribe(foo => (this.foo = foo)); _ngRedux.select(n => n.bar).subscribe(bar => (this.bar = bar)); _ngRedux.select(n => n.baz).subscribe(baz => (this.baz = baz)); } } ngRedux = new RootStore<IAppState>(mockNgZone); const someService = new SomeService(ngRedux); ngRedux.configureStore(rootReducer, defaultState); expect(someService.foo).toEqual('bar'); expect(someService.bar).toEqual('foo'); expect(someService.baz).toEqual(-1); }); it('should have select decorators work before store is configured', done => { class SomeService { @select() foo$: Observable<string>; @select() bar$: Observable<string>; @select() baz$: Observable<number>; } ngRedux = new RootStore<IAppState>(mockNgZone); const someService = new SomeService(); someService.foo$ .pipe(combineLatest(someService.bar$, someService.baz$)) .subscribe(([foo, bar, baz]) => { expect(foo).toEqual('bar'); expect(bar).toEqual('foo'); expect(baz).toEqual(-1); done(); }); ngRedux.configureStore(rootReducer, defaultState); }); }); describe('Chained actions in subscriptions', () => { interface IAppState { keyword: string; keywordLength: number; } let defaultState: IAppState; let rootReducer: Reducer<IAppState, AnyAction>; let ngRedux: NgRedux<IAppState>; const mockNgZone = new MockNgZone({ enableLongStackTrace: false }) as NgZone; const doSearch = (word: string) => ngRedux.dispatch({ type: 'SEARCH', payload: word }); const doFetch = (word: string) => ngRedux.dispatch({ type: 'SEARCH_RESULT', payload: word.length }); beforeEach(() => { defaultState = { keyword: '', keywordLength: -1, }; rootReducer = (state = defaultState, action: PayloadAction) => { switch (action.type) { case 'SEARCH': return Object.assign({}, state, { keyword: action.payload }); case 'SEARCH_RESULT': return Object.assign({}, state, { keywordLength: action.payload }); default: return state; } }; ngRedux = new RootStore<IAppState>(mockNgZone); ngRedux.configureStore(rootReducer, defaultState); }); describe('dispatching an action in a keyword$ before length$ happens', () => { it(`length sub should be called twice`, () => { const keyword$ = ngRedux.select(n => n.keyword); let keyword = ''; let length = 0; const length$ = ngRedux.select(n => n.keywordLength); const lengthSpy = jasmine .createSpy('lengthSpy') .and.callFake((n: number) => (length = n)); let lenSub; let keywordSub; keywordSub = keyword$.pipe(filter(n => n !== '')).subscribe(n => { keyword = n; doFetch(n); }); lenSub = length$.subscribe(lengthSpy); expect(keyword).toEqual(''); expect(length).toEqual(-1); expect(lengthSpy.calls.count()).toEqual(1); doSearch('test'); expect(lengthSpy.calls.count()).toEqual(2); expect(keyword).toEqual('test'); expect(length).toEqual(4); keywordSub.unsubscribe(); lenSub.unsubscribe(); }); it(`second sub should get most current state value`, () => { const keyword$ = ngRedux.select(n => n.keyword); let keyword = ''; let length = 0; const length$ = ngRedux.select(n => n.keywordLength); const lengthSpy = jasmine .createSpy('lengthSpy') .and.callFake((n: number) => (length = n)); let lenSub; let keywordSub; keywordSub = keyword$.pipe(filter(n => n !== '')).subscribe(n => { keyword = n; doFetch(n); }); lenSub = length$.subscribe(lengthSpy); expect(keyword).toEqual(''); expect(length).toEqual(-1); expect(lengthSpy.calls.count()).toEqual(1); doSearch('test'); expect(keyword).toEqual('test'); expect(length).toEqual(4); keywordSub.unsubscribe(); lenSub.unsubscribe(); }); }); describe('dispatching an action in a keyword$ after length$ happens', () => { it(`length sub should be called twice`, () => { const keyword$ = ngRedux.select(n => n.keyword); let keyword = ''; let length = 0; const length$ = ngRedux.select(n => n.keywordLength); const lengthSpy = jasmine .createSpy('lengthSpy') .and.callFake((n: number) => (length = n)); let lenSub; let keywordSub; lenSub = length$.subscribe(lengthSpy); keywordSub = keyword$.pipe(filter(n => n !== '')).subscribe(n => { keyword = n; doFetch(n); }); expect(keyword).toEqual(''); expect(length).toEqual(-1); expect(lengthSpy.calls.count()).toEqual(1); doSearch('test'); expect(lengthSpy.calls.count()).toEqual(2); expect(keyword).toEqual('test'); expect(length).toEqual(4); keywordSub.unsubscribe(); lenSub.unsubscribe(); }); it(`first sub should get most current state value`, () => { const keyword$ = ngRedux.select(n => n.keyword); let keyword = ''; let length = 0; const length$ = ngRedux.select(n => n.keywordLength); const lengthSpy = jasmine .createSpy('lengthSpy') .and.callFake((n: number) => (length = n)); let lenSub; let keywordSub; lenSub = length$.subscribe(lengthSpy); keywordSub = keyword$.pipe(filter(n => n !== '')).subscribe(n => { keyword = n; doFetch(n); }); expect(keyword).toEqual(''); expect(length).toEqual(-1); expect(lengthSpy.calls.count()).toEqual(1); doSearch('test'); expect(keyword).toEqual('test'); expect(length).toEqual(4); keywordSub.unsubscribe(); lenSub.unsubscribe(); }); }); });
the_stack
import { FlatTheme, SolidLineStyle, StyleSet, Theme } from "@here/harp-datasource-protocol"; import { getTestResourceUrl } from "@here/harp-test-utils"; import { cloneDeep, ContextLogger, getAppBaseUrl, resolveReferenceUri, UriResolver } from "@here/harp-utils"; import { assert } from "chai"; import { ThemeLoader } from "../lib/ThemeLoader"; describe("ThemeLoader", function () { describe("#isThemeLoaded", function () { it("checks for external dependencies", function () { assert.isFalse( ThemeLoader.isThemeLoaded({ extends: ["base_theme.json"] }) ); assert.isFalse( ThemeLoader.isThemeLoaded({ extends: "base_theme.json" }) ); assert.isTrue(ThemeLoader.isThemeLoaded({})); }); }); describe("#load url handling", function () { const appBaseUrl = getAppBaseUrl(); const sampleThemeUrl = getTestResourceUrl( "@here/harp-mapview", "test/resources/baseTheme.json" ); it("resolves absolute url of theme passed as object", async function () { const result = await ThemeLoader.load({}); assert.equal(result.url, appBaseUrl); }); it("resolves absolute theme url of theme loaded from relative url", async function () { const result = await ThemeLoader.load(sampleThemeUrl); assert.equal(result.url, sampleThemeUrl); }); it("resolves urls of resources embedded in theme", async function () { const absoluteSampleThemeUrl = resolveReferenceUri(appBaseUrl, sampleThemeUrl); const result = await ThemeLoader.load(absoluteSampleThemeUrl); assert.equal(result.url, absoluteSampleThemeUrl); const expectedFontCatalogUrl = resolveReferenceUri( absoluteSampleThemeUrl, "fonts/Default_FontCatalog.json" ); assert.exists(result.fontCatalogs); assert.exists(result.fontCatalogs![0]); assert.equal(result.fontCatalogs![0].url, expectedFontCatalogUrl); }); it("doesn't break if called on already #load-ed theme", async function () { const firstLoadResult = await ThemeLoader.load(sampleThemeUrl); const firstResultCopy = cloneDeep(firstLoadResult); const secondLoadResult = await ThemeLoader.load(firstLoadResult); assert.deepEqual(firstResultCopy, secondLoadResult); }); it("obeys `uriResolver` option", async function () { // new PrefixMapUriResolver({ // "fonts://fira": "ACTUAL_FONT_LOCATION", // "icons://": "ACTUAL_ICONS_LOCATION" // }); const uriResolver: UriResolver = { resolveUri(uri) { return uri.replace("://", "://resolved!"); } }; const r = await ThemeLoader.load( { fontCatalogs: [ { url: "fonts://fira", name: "fira" } ], images: { icons_day_maki: { url: "icons://maki_icons.png", preload: true, atlas: "icons://icons/maki_icons.json" } } }, { uriResolver } ); assert.equal(r.fontCatalogs![0].url, "fonts://resolved!fira"); assert.equal(r.images!.icons_day_maki.url, "icons://resolved!maki_icons.png"); assert.equal(r.images!.icons_day_maki.atlas, "icons://resolved!icons/maki_icons.json"); }); }); describe("#resolveStyleSet", function () { it("resolves ref expression in technique attr values", async function () { const theme: Theme = { definitions: { roadColor: { value: "#f00" }, roadWidth: { type: "number", value: 123 }, roadOutlineWidth: { value: 33 } }, styles: { tilezen: [ { description: "roads", when: "kind == 'road", technique: "solid-line", attr: { lineColor: ["ref", "roadColor"], lineWidth: ["ref", "roadWidth"], outlineWidth: ["ref", "roadOutlineWidth"] } } ] } }; const contextLogger = new ContextLogger(console, "theme"); // Hack to access private members with type safety const r = ThemeLoader["resolveStyleSet"]( theme.styles!.tilezen, theme.definitions, contextLogger ); const roadStyle = r.find(s => s.description === "roads")!; assert.exists(roadStyle); assert.equal(roadStyle.technique, "solid-line"); const roadStyleCasted = (roadStyle as any) as SolidLineStyle; assert.equal(roadStyleCasted.attr?.lineColor, "#f00"); assert.equal(roadStyleCasted.attr?.lineWidth, 123); assert.equal(roadStyleCasted.attr?.outlineWidth, 33); }); it("resolves ref expressions in Style", async function () { const theme: Theme = { definitions: { roadColor: { type: "color", value: "#f00" }, roadCondition: { type: "selector", value: "kind == 'road'" } }, styles: { tilezen: [ { description: "roads", when: ["ref", "roadCondition"], technique: "solid-line", attr: { lineColor: ["ref", "roadColor"] } } ] } }; const contextLogger = new ContextLogger(console, "test theme: "); // Hack to access private members with type safety const r = ThemeLoader["resolveStyleSet"]( theme.styles!.tilezen, theme.definitions, contextLogger ); const roadStyle = r.find(s => s.description === "roads")!; assert.exists(roadStyle); assert.equal(roadStyle.technique, "solid-line"); const roadStyleCasted = (roadStyle as any) as SolidLineStyle; assert.equal(roadStyleCasted.description, "roads"); assert.deepEqual(roadStyleCasted.when!, theme.definitions!.roadCondition.value); assert.equal(roadStyleCasted.attr!.lineColor, "#f00"); }); it("resolves refs embedded in expressions", async function () { const theme: Theme = { definitions: { roadColor: { type: "color", value: "#f00" }, roadCondition: { type: "selector", value: ["==", ["get", "kind"], "road"] } }, styles: { tilezen: [ { description: "custom-roads", when: ["all", ["ref", "roadCondition"], ["has", "color"]], technique: "solid-line", final: true, attr: { lineColor: ["ref", "roadColor"] } } ] } }; const contextLogger = new ContextLogger(console, "test theme: "); // Hack to access private members with type safety const r = ThemeLoader["resolveStyleSet"]( theme.styles!.tilezen, theme.definitions, contextLogger ); const roadStyle = r.find(s => s.description === "custom-roads")!; assert.exists(roadStyle); assert.equal(roadStyle.technique, "solid-line"); const roadStyleCasted = (roadStyle as any) as SolidLineStyle; assert.deepEqual(roadStyleCasted.when, [ "all", ["==", ["get", "kind"], "road"], ["has", "color"] ]); assert.deepEqual(roadStyleCasted.attr!.lineColor, "#f00"); }); }); describe("#resolveBaseTheme", function () { const baseThemeRoads: Theme = { definitions: { roadColor: { type: "color", value: "#f00" }, primaryRoadFillLineWidth: { type: "number", value: { interpolation: "Linear", zoomLevels: [8, 9, 10, 11, 12, 13, 14, 16, 18], values: [650, 400, 220, 120, 65, 35, 27, 9, 7] } } }, styles: { tilezen: [ { description: "roads", technique: "solid-line", when: "foo", lineWidth: ["ref", "primaryRoadFillLineWidth"], lineColor: ["ref", "roadColor"] } ] } }; const baseThemeWater: Theme = { definitions: { waterColor: { type: "color", value: "#44f" } } }; it("supports single inheritance", async function () { const inheritedTheme: Theme = { extends: baseThemeRoads, definitions: { roadColor: { type: "color", value: "#fff" } } }; // Hack to access private members with type safety const result = await ThemeLoader["resolveBaseThemes"](inheritedTheme); assert.exists(result.definitions); assert.exists(result.definitions!.roadColor); assert.deepEqual(result.definitions!.roadColor, { type: "color", value: "#fff" }); }); it("supports multiple inheritance", async function () { const inheritedTheme: Theme = { extends: [ baseThemeRoads, baseThemeWater, { definitions: { waterColor: { type: "color", value: "#0f0" } } } ], definitions: { roadColor: { type: "color", value: "#fff" } } }; // Hack to access private members with type safety const result = await ThemeLoader["resolveBaseThemes"](inheritedTheme); assert.exists(result.definitions); assert.exists(result.definitions!.roadColor); assert.deepEqual(result.definitions!.roadColor, { type: "color", value: "#fff" }); assert.deepEqual(result.definitions!.waterColor, { type: "color", value: "#0f0" }); }); it("supports multiple inheritance with textures", async function () { const inheritedTheme: Theme = { extends: [ { images: { foo: { url: "icons://maki_icons.png", preload: true }, baz: { url: "icons://maki_icons.png", preload: true } }, imageTextures: [ { name: "foo", image: "foo" }, { name: "baz", image: "baz" } ] }, { images: { bar: { url: "icons://maki_icons.png", preload: true }, baz: { url: "icons://override.png", atlas: "icons://icons/maki_icons.json", preload: true } }, imageTextures: [ { name: "bar", image: "bar" }, { name: "baz", image: "baz" } ] } ] }; const result = await ThemeLoader.load(inheritedTheme); assert.exists(result.images?.foo); assert.exists(result.images?.bar); assert.exists(result.images?.baz); assert.equal(result.images?.baz.url, "icons://override.png"); assert.exists(result.images?.baz.atlas); assert.deepEqual(result.imageTextures?.map(imageTexture => imageTexture.name).sort(), [ "bar", "baz", "foo" ]); }); }); describe("#load support for inheritance and optional reference resolving", function () { const baseThemeUrl = getTestResourceUrl( "@here/harp-mapview", "test/resources/baseTheme.json" ); const expectedBaseStyleSet: StyleSet = [ { description: "roads", when: "kind == 'road", technique: "solid-line", attr: { lineWidth: { interpolation: "Linear", zoomLevels: [8, 9, 10, 11, 12, 13, 14, 16, 18], values: [650, 400, 220, 120, 65, 35, 27, 9, 7] }, lineColor: "#f00" } } ]; const expectedOverridenStyleSet: StyleSet = [ { description: "roads", when: "kind == 'road", technique: "solid-line", attr: { lineWidth: { interpolation: "Linear", zoomLevels: [8, 9, 10, 11, 12, 13, 14, 16, 18], values: [650, 400, 220, 120, 65, 35, 27, 9, 7] }, lineColor: "#fff" } } ]; it("loads theme from actual URL and resolves definitions", async function () { const result = await ThemeLoader.load(baseThemeUrl, { resolveDefinitions: true }); assert.exists(result); assert.exists(result.styles!.tilezen); assert.deepEqual(result.styles!.tilezen, expectedBaseStyleSet); }); it("supports definitions override with actual files", async function () { const inheritedThemeUrl = getTestResourceUrl( "@here/harp-mapview", "test/resources/inheritedStyleBasic.json" ); const result = await ThemeLoader.load(inheritedThemeUrl, { resolveDefinitions: true }); assert.exists(result); assert.exists(result.styles!.tilezen); assert.deepEqual(result.styles!.tilezen, expectedOverridenStyleSet); }); it("empty inherited theme just loads base", async function () { const result = await ThemeLoader.load( { extends: baseThemeUrl }, { resolveDefinitions: true } ); assert.exists(result); assert.exists(result.styles!.tilezen); assert.deepEqual(result.styles!.tilezen, expectedBaseStyleSet); }); it("supports local definitions override", async function () { const result = await ThemeLoader.load( { extends: baseThemeUrl, definitions: { roadColor: { type: "color", value: "#fff" } } }, { resolveDefinitions: true } ); assert.exists(result); assert.exists(result.styles!.tilezen); assert.deepEqual(result.styles!.tilezen, expectedOverridenStyleSet); }); }); describe("flat themes", function () { it("load flat theme", async () => { const flatTheme: FlatTheme = { styles: [ { styleSet: "tilezen", when: ["boolean", true], technique: "none" }, { styleSet: "terrain", when: ["boolean", false], technique: "none" }, { styleSet: "tilezen", when: ["boolean", false], technique: "solid-line", attr: { lineWidth: 2 } } ] }; const theme = await ThemeLoader.load(flatTheme); assert.isDefined(theme.styles); assert.isArray(theme.styles!.tilezen); const tilezen = theme.styles!.tilezen; assert.strictEqual(tilezen.length, 2); assert.strictEqual(tilezen[0].technique, "none"); assert.strictEqual(tilezen[1].technique, "solid-line"); assert.isArray(theme.styles!.terrain); const terrain = theme.styles!.terrain; assert.strictEqual(terrain.length, 1); assert.strictEqual(terrain[0].technique, "none"); }); }); describe("merge style sets", function () { it("merge themes", async () => { const baseTheme: Theme = { styles: { tilezen: [ { when: ["boolean", true], technique: "none" } ], terrain: [ { when: ["boolean", false], technique: "none" } ] } }; const source: Theme = { extends: [baseTheme], styles: { tilezen: [ { when: ["boolean", false], technique: "solid-line", attr: { lineWidth: 2 } } ] } }; const theme = await ThemeLoader.load(source); assert.isDefined(theme.styles); assert.isArray(theme.styles!.tilezen); const tilezen = theme.styles!.tilezen; assert.strictEqual(tilezen.length, 2); assert.strictEqual(tilezen[0].technique, "none"); assert.strictEqual(tilezen[1].technique, "solid-line"); assert.isArray(theme.styles!.terrain); const terrain = theme.styles!.terrain; assert.strictEqual(terrain.length, 1); assert.strictEqual(terrain[0].technique, "none"); }); it("merge flat themes", async () => { const baseTheme: FlatTheme = { styles: [ { styleSet: "tilezen", when: ["boolean", true], technique: "none" }, { styleSet: "terrain", when: ["boolean", false], technique: "none" } ] }; const source: FlatTheme = { extends: [(baseTheme as unknown) as Theme], styles: [ { styleSet: "tilezen", when: ["boolean", false], technique: "solid-line", attr: { lineWidth: 2 } } ] }; const theme = await ThemeLoader.load(source); assert.isDefined(theme.styles); assert.isArray(theme.styles!.tilezen); const tilezen = theme.styles!.tilezen; assert.strictEqual(tilezen.length, 2); assert.strictEqual(tilezen[0].technique, "none"); assert.strictEqual(tilezen[1].technique, "solid-line"); assert.isArray(theme.styles!.terrain); const terrain = theme.styles!.terrain; assert.strictEqual(terrain.length, 1); assert.strictEqual(terrain[0].technique, "none"); }); it("extends existing style", async () => { const baseTheme: FlatTheme = { styles: [ { styleSet: "tilezen", id: "buildings", layer: "buildings", when: ["==", ["geometry-type"], "Polygon"], technique: "extruded-polygon", color: "#f00" }, { styleSet: "terrain", when: ["boolean", false], technique: "none" } ] }; const source: FlatTheme = { extends: [(baseTheme as unknown) as Theme], styles: [ { styleSet: "tilezen", // extends the extisting style with this id extends: "buildings", technique: "extruded-polygon", color: "#0f0", lineColor: "#00f" } ] }; const theme = await ThemeLoader.load(source); assert.isDefined(theme.styles); assert.isArray(theme.styles!.tilezen); const tilezen = theme.styles!.tilezen; assert.strictEqual(tilezen.length, 1); assert.strictEqual(tilezen[0].technique, "extruded-polygon"); assert.deepEqual(tilezen[0], { styleSet: "tilezen", id: "buildings", extends: undefined, layer: "buildings", when: ["==", ["geometry-type"], "Polygon"], technique: "extruded-polygon", color: "#0f0", lineColor: "#00f" }); assert.isArray(theme.styles!.terrain); const terrain = theme.styles!.terrain; assert.strictEqual(terrain.length, 1); assert.strictEqual(terrain[0].technique, "none"); }); it("overrides property of an existing sytle", async () => { const baseTheme: FlatTheme = { styles: [ { styleSet: "tilezen", id: "buildings", layer: "buildings", when: ["==", ["geometry-type"], "Polygon"], technique: "extruded-polygon", color: "#f00" }, { styleSet: "terrain", when: ["boolean", false], technique: "none" } ] }; const source: FlatTheme = { extends: [(baseTheme as unknown) as Theme], styles: [ { styleSet: "tilezen", // overrides the extisting style with this id id: "buildings", layer: "buildings", when: ["==", ["geometry-type"], "Polygon"], technique: "fill" } ] }; const theme = await ThemeLoader.load(source); assert.isDefined(theme.styles); assert.isArray(theme.styles!.tilezen); const tilezen = theme.styles!.tilezen; assert.strictEqual(tilezen.length, 1); assert.deepEqual(tilezen[0], { styleSet: "tilezen", id: "buildings", layer: "buildings", when: ["==", ["geometry-type"], "Polygon"], technique: "fill" }); assert.isArray(theme.styles!.terrain); const terrain = theme.styles!.terrain; assert.strictEqual(terrain.length, 1); assert.strictEqual(terrain[0].technique, "none"); }); it("verify the scope of ids", async () => { // the two style sets have a rule with the same id. const baseTheme: FlatTheme = { styles: [ { styleSet: "tilezen", id: "rule-id", layer: "buildings", when: ["==", ["geometry-type"], "Polygon"], technique: "extruded-polygon", color: "#f00" }, { styleSet: "terrain", id: "rule-id", when: ["boolean", false], technique: "none" } ] }; // the extension overrides only the rule from the // referenced id of the styleset `tilezen`, and leaves // the styleset `terrain` unmodified. const source: FlatTheme = { extends: [(baseTheme as unknown) as Theme], styles: [ { styleSet: "tilezen", // extends the extisting style with this id extends: "rule-id", technique: "extruded-polygon", color: "#0f0", lineColor: "#00f" } ] }; const theme = await ThemeLoader.load(source); assert.isDefined(theme.styles); assert.isArray(theme.styles!.tilezen); const tilezen = theme.styles!.tilezen; assert.strictEqual(tilezen.length, 1); assert.deepEqual(tilezen[0], { styleSet: "tilezen", id: "rule-id", extends: undefined, layer: "buildings", when: ["==", ["geometry-type"], "Polygon"], technique: "extruded-polygon", color: "#0f0", lineColor: "#00f" }); const terrain = theme.styles!.terrain; assert.strictEqual(terrain.length, 1); assert.deepEqual(terrain[0], { styleSet: "terrain", id: "rule-id", when: ["boolean", false], technique: "none" }); }); }); });
the_stack
import { Component, OnDestroy, OnInit } from '@angular/core'; import { FormBuilder } from '@angular/forms'; import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { BehaviorSubject, combineLatest, Observable, Subscription } from 'rxjs'; import { map, switchMap, take } from 'rxjs/operators'; import { buildPaginatedList, PaginatedList } from '../../core/data/paginated-list.model'; import { RemoteData } from '../../core/data/remote-data'; import { EPersonDataService } from '../../core/eperson/eperson-data.service'; import { EPerson } from '../../core/eperson/models/eperson.model'; import { hasValue } from '../../shared/empty.util'; import { NotificationsService } from '../../shared/notifications/notifications.service'; import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model'; import { EpersonDtoModel } from '../../core/eperson/models/eperson-dto.model'; import { FeatureID } from '../../core/data/feature-authorization/feature-id'; import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service'; import { getAllSucceededRemoteData, getFirstCompletedRemoteData } from '../../core/shared/operators'; import { ConfirmationModalComponent } from '../../shared/confirmation-modal/confirmation-modal.component'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { RequestService } from '../../core/data/request.service'; import { PageInfo } from '../../core/shared/page-info.model'; import { NoContent } from '../../core/shared/NoContent.model'; import { PaginationService } from '../../core/pagination/pagination.service'; @Component({ selector: 'ds-epeople-registry', templateUrl: './epeople-registry.component.html', }) /** * A component used for managing all existing epeople within the repository. * The admin can create, edit or delete epeople here. */ export class EPeopleRegistryComponent implements OnInit, OnDestroy { labelPrefix = 'admin.access-control.epeople.'; /** * A list of all the current EPeople within the repository or the result of the search */ ePeople$: BehaviorSubject<PaginatedList<EPerson>> = new BehaviorSubject(buildPaginatedList<EPerson>(new PageInfo(), [])); /** * A BehaviorSubject with the list of EpersonDtoModel objects made from the EPeople in the repository or * as the result of the search */ ePeopleDto$: BehaviorSubject<PaginatedList<EpersonDtoModel>> = new BehaviorSubject<PaginatedList<EpersonDtoModel>>({} as any); /** * An observable for the pageInfo, needed to pass to the pagination component */ pageInfoState$: BehaviorSubject<PageInfo> = new BehaviorSubject<PageInfo>(undefined); /** * A boolean representing if a search is pending */ searching$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false); /** * Pagination config used to display the list of epeople */ config: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), { id: 'elp', pageSize: 5, currentPage: 1 }); /** * Whether or not to show the EPerson form */ isEPersonFormShown: boolean; // The search form searchForm; // Current search in epersons registry currentSearchQuery: string; currentSearchScope: string; /** * FindListOptions */ findListOptionsSub: Subscription; /** * List of subscriptions */ subs: Subscription[] = []; constructor(private epersonService: EPersonDataService, private translateService: TranslateService, private notificationsService: NotificationsService, private authorizationService: AuthorizationDataService, private formBuilder: FormBuilder, private router: Router, private modalService: NgbModal, private paginationService: PaginationService, public requestService: RequestService) { this.currentSearchQuery = ''; this.currentSearchScope = 'metadata'; this.searchForm = this.formBuilder.group(({ scope: 'metadata', query: '', })); } ngOnInit() { this.initialisePage(); } /** * This method will initialise the page */ initialisePage() { this.searching$.next(true); this.isEPersonFormShown = false; this.search({scope: this.currentSearchScope, query: this.currentSearchQuery}); this.subs.push(this.epersonService.getActiveEPerson().subscribe((eperson: EPerson) => { if (eperson != null && eperson.id) { this.isEPersonFormShown = true; } })); this.subs.push(this.ePeople$.pipe( switchMap((epeople: PaginatedList<EPerson>) => { if (epeople.pageInfo.totalElements > 0) { return combineLatest(...epeople.page.map((eperson) => { return this.authorizationService.isAuthorized(FeatureID.CanDelete, hasValue(eperson) ? eperson.self : undefined).pipe( map((authorized) => { const epersonDtoModel: EpersonDtoModel = new EpersonDtoModel(); epersonDtoModel.ableToDelete = authorized; epersonDtoModel.eperson = eperson; return epersonDtoModel; }) ); })).pipe(map((dtos: EpersonDtoModel[]) => { return buildPaginatedList(epeople.pageInfo, dtos); })); } else { // if it's empty, simply forward the empty list return [epeople]; } })).subscribe((value: PaginatedList<EpersonDtoModel>) => { this.searching$.next(false);this.ePeopleDto$.next(value); this.pageInfoState$.next(value.pageInfo); })); } /** * Search in the EPeople by metadata (default) or email * @param data Contains scope and query param */ search(data: any) { this.searching$.next(true); if (hasValue(this.findListOptionsSub)) { this.findListOptionsSub.unsubscribe(); } this.findListOptionsSub = this.paginationService.getCurrentPagination(this.config.id, this.config).pipe( switchMap((findListOptions) => { const query: string = data.query; const scope: string = data.scope; if (query != null && this.currentSearchQuery !== query) { this.router.navigate([this.epersonService.getEPeoplePageRouterLink()], { queryParamsHandling: 'merge' }); this.currentSearchQuery = query; this.paginationService.resetPage(this.config.id); } if (scope != null && this.currentSearchScope !== scope) { this.router.navigate([this.epersonService.getEPeoplePageRouterLink()], { queryParamsHandling: 'merge' }); this.currentSearchScope = scope; this.paginationService.resetPage(this.config.id); } return this.epersonService.searchByScope(this.currentSearchScope, this.currentSearchQuery, { currentPage: findListOptions.currentPage, elementsPerPage: findListOptions.pageSize }); } ), getAllSucceededRemoteData(), ).subscribe((peopleRD) => { this.ePeople$.next(peopleRD.payload); this.pageInfoState$.next(peopleRD.payload.pageInfo); } ); } /** * Checks whether the given EPerson is active (being edited) * @param eperson */ isActive(eperson: EPerson): Observable<boolean> { return this.getActiveEPerson().pipe( map((activeEPerson) => eperson === activeEPerson) ); } /** * Gets the active eperson (being edited) */ getActiveEPerson(): Observable<EPerson> { return this.epersonService.getActiveEPerson(); } /** * Start editing the selected EPerson * @param ePerson */ toggleEditEPerson(ePerson: EPerson) { this.getActiveEPerson().pipe(take(1)).subscribe((activeEPerson: EPerson) => { if (ePerson === activeEPerson) { this.epersonService.cancelEditEPerson(); this.isEPersonFormShown = false; } else { this.epersonService.editEPerson(ePerson); this.isEPersonFormShown = true; } }); this.scrollToTop(); } /** * Deletes EPerson, show notification on success/failure & updates EPeople list */ deleteEPerson(ePerson: EPerson) { if (hasValue(ePerson.id)) { const modalRef = this.modalService.open(ConfirmationModalComponent); modalRef.componentInstance.dso = ePerson; modalRef.componentInstance.headerLabel = 'confirmation-modal.delete-eperson.header'; modalRef.componentInstance.infoLabel = 'confirmation-modal.delete-eperson.info'; modalRef.componentInstance.cancelLabel = 'confirmation-modal.delete-eperson.cancel'; modalRef.componentInstance.confirmLabel = 'confirmation-modal.delete-eperson.confirm'; modalRef.componentInstance.brandColor = 'danger'; modalRef.componentInstance.confirmIcon = 'fas fa-trash'; modalRef.componentInstance.response.pipe(take(1)).subscribe((confirm: boolean) => { if (confirm) { if (hasValue(ePerson.id)) { this.epersonService.deleteEPerson(ePerson).pipe(getFirstCompletedRemoteData()).subscribe((restResponse: RemoteData<NoContent>) => { if (restResponse.hasSucceeded) { this.notificationsService.success(this.translateService.get(this.labelPrefix + 'notification.deleted.success', {name: ePerson.name})); this.reset(); } else { this.notificationsService.error('Error occured when trying to delete EPerson with id: ' + ePerson.id + ' with code: ' + restResponse.statusCode + ' and message: ' + restResponse.errorMessage); } }); } } }); } } /** * Unsub all subscriptions */ ngOnDestroy(): void { this.cleanupSubscribes(); this.paginationService.clearPagination(this.config.id); } cleanupSubscribes() { this.subs.filter((sub) => hasValue(sub)).forEach((sub) => sub.unsubscribe()); } scrollToTop() { (function smoothscroll() { const currentScroll = document.documentElement.scrollTop || document.body.scrollTop; if (currentScroll > 0) { window.requestAnimationFrame(smoothscroll); window.scrollTo(0, currentScroll - (currentScroll / 8)); } })(); } /** * Reset all input-fields to be empty and search all search */ clearFormAndResetResult() { this.searchForm.patchValue({ query: '', }); this.search({query: ''}); } /** * This method will set everything to stale, which will cause the lists on this page to update. */ reset() { this.epersonService.getBrowseEndpoint().pipe( take(1) ).subscribe((href: string) => { this.requestService.setStaleByHrefSubstring(href).pipe(take(1)).subscribe(() => { this.epersonService.cancelEditEPerson(); this.isEPersonFormShown = false; }); }); } }
the_stack
import { inject, injectable } from "inversify"; import { TYPES } from "../types"; import { ILogger } from "../../utils/logging"; import { EMPTY_ROOT, IModelFactory } from "../model/smodel-factory"; import { SModelRoot } from "../model/smodel"; import { AnimationFrameSyncer } from "../animations/animation-frame-syncer"; import { IViewer, IViewerProvider } from "../views/viewer"; import { CommandStackOptions } from './command-stack-options'; import { HiddenCommand, ICommand, CommandExecutionContext, CommandResult, SystemCommand, MergeableCommand, PopupCommand } from './command'; /** * The component that holds the current model and applies the commands * to change it. * * The command stack is called by the ActionDispatcher and forwards the * changed model to the Viewer that renders it. */ export interface ICommandStack { /** * Executes the given command on the current model and returns a * Promise for the new result. * * Unless it is a special command, it is pushed to the undo stack * such that it can be rolled back later and the redo stack is * cleared. */ execute(command: ICommand): Promise<SModelRoot> /** * Executes all of the given commands. As opposed to calling * execute() multiple times, the Viewer is only updated once after * the last command has been executed. */ executeAll(commands: ICommand[]): Promise<SModelRoot> /** * Takes the topmost command from the undo stack, undoes its * changes and pushes it ot the redo stack. Returns a Promise for * the changed model. */ undo(): Promise<SModelRoot> /** * Takes the topmost command from the redo stack, redoes its * changes and pushes it ot the undo stack. Returns a Promise for * the changed model. */ redo(): Promise<SModelRoot> } /** * As part of the event cylce, the ICommandStack should be injected * using a provider to avoid cyclic injection dependencies. */ export type CommandStackProvider = () => Promise<ICommandStack>; /** * The implementation of the ICommandStack. Clients should not use this * class directly. * * The command stack holds the current model as the result of the current * promise. When a new command is executed/undone/redone, its execution is * chained using <code>Promise#then()</code> to the current Promise. This * way we can handle long running commands without blocking the current * thread. * * The command stack also does the special handling for special commands: * * System commands should be transparent to the user and as such be * automatically undone/redone with the next plain command. Additional care * must be taken that system commands that are executed after undo don't * break the correspondence between the topmost commands on the undo and * redo stacks. * * Hidden commands only tell the viewer to render a hidden model such that * its bounds can be extracted from the DOM and forwarded as separate actions. * Hidden commands should not leave any trace on the undo/redo/off stacks. * * Mergeable commands should be merged with their predecessor if possible, * such that e.g. multiple subsequent moves of the smae element can be undone * in one single step. */ @injectable() export class CommandStack implements ICommandStack { protected currentPromise: Promise<CommandStackState>; protected viewer?: IViewer; protected undoStack: ICommand[] = []; protected redoStack: ICommand[] = []; /** * System commands should be transparent to the user in undo/redo * operations. When a system command is executed when the redo * stack is not empty, it is pushed to offStack instead. * * On redo, all commands form this stack are undone such that the * redo operation gets the exact same model as when it was executed * first. * * On undo, all commands form this stack are undone as well as * system ommands should be transparent to the user. */ protected offStack: SystemCommand[] = []; constructor(@inject(TYPES.IModelFactory) protected modelFactory: IModelFactory, @inject(TYPES.IViewerProvider) protected viewerProvider: IViewerProvider, @inject(TYPES.ILogger) protected logger: ILogger, @inject(TYPES.AnimationFrameSyncer) protected syncer: AnimationFrameSyncer, @inject(TYPES.CommandStackOptions) protected options: CommandStackOptions) { this.currentPromise = Promise.resolve({ root: modelFactory.createRoot(EMPTY_ROOT), hiddenRoot: undefined, popupRoot: undefined, rootChanged: false, hiddenRootChanged: false, popupChanged: false }); } protected get currentModel(): Promise<SModelRoot> { return this.currentPromise.then( state => state.root ); } executeAll(commands: ICommand[]): Promise<SModelRoot> { commands.forEach( command => { this.logger.log(this, 'Executing', command); this.handleCommand(command, command.execute, this.mergeOrPush); } ); return this.thenUpdate(); } execute(command: ICommand): Promise<SModelRoot> { this.logger.log(this, 'Executing', command); this.handleCommand(command, command.execute, this.mergeOrPush); return this.thenUpdate(); } undo(): Promise<SModelRoot> { this.undoOffStackSystemCommands(); this.undoPreceedingSystemCommands(); const command = this.undoStack.pop(); if (command !== undefined) { this.logger.log(this, 'Undoing', command); this.handleCommand(command, command.undo, (c: ICommand, context: CommandExecutionContext) => { this.redoStack.push(c); }); } return this.thenUpdate(); } redo(): Promise<SModelRoot> { this.undoOffStackSystemCommands(); const command = this.redoStack.pop(); if (command !== undefined) { this.logger.log(this, 'Redoing', command); this.handleCommand(command, command.redo, (c: ICommand, context: CommandExecutionContext) => { this.pushToUndoStack(c); }); } this.redoFollowingSystemCommands(); return this.thenUpdate(); } /** * Chains the current promise with another Promise that performs the * given operation on the given command. * * @param beforeResolve a function that is called directly before * resolving the Promise to return the new model. Usually puts the * command on the appropriate stack. */ protected handleCommand(command: ICommand, operation: (context: CommandExecutionContext) => CommandResult, beforeResolve: (command: ICommand, context: CommandExecutionContext) => void) { this.currentPromise = this.currentPromise.then(state => new Promise((resolve: (result: CommandStackState) => void, reject: (reason?: any) => void) => { const context = this.createContext(state.root); let newResult: CommandResult; try { newResult = operation.call(command, context); } catch (error) { this.logger.error(this, "Failed to execute command:", error); newResult = state.root; } if (command instanceof HiddenCommand) { resolve({ ...state, ...{ hiddenRoot: newResult as SModelRoot, hiddenRootChanged: true } }); } else if (command instanceof PopupCommand) { resolve({ ...state, ...{ popupRoot: newResult as SModelRoot, popupChanged: true } }); } else if (newResult instanceof Promise) { newResult.then( (newModel: SModelRoot) => { beforeResolve.call(this, command, context); resolve({ ...state, ...{ root: newModel, rootChanged: true } }); } ); } else { beforeResolve.call(this, command, context); resolve({ ...state, ...{ root: newResult, rootChanged: true } }); } }) ); } protected pushToUndoStack(command: ICommand) { this.undoStack.push(command); if (this.options.undoHistoryLimit >= 0 && this.undoStack.length > this.options.undoHistoryLimit) this.undoStack.splice(0, this.undoStack.length - this.options.undoHistoryLimit); } /** * Notifies the Viewer to render the new model and/or the new hidden model * and returns a Promise for the new model. */ protected thenUpdate(): Promise<SModelRoot> { this.currentPromise = this.currentPromise.then(async state => { if (state.hiddenRootChanged && state.hiddenRoot !== undefined) await this.updateHidden(state.hiddenRoot); if (state.rootChanged) await this.update(state.root); if (state.popupChanged && state.popupRoot !== undefined) await this.updatePopup(state.popupRoot); return { root: state.root, hiddenRoot: undefined, popupRoot: undefined, rootChanged: false, hiddenRootChanged: false, popupChanged: false }; }); return this.currentModel; } /** * Notify the <code>Viewer</code> that the model has changed. */ async update(model: SModelRoot): Promise<void> { if (this.viewer === undefined) this.viewer = await this.viewerProvider(); this.viewer.update(model); } /** * Notify the <code>Viewer</code> that the hidden model has changed. */ async updateHidden(model: SModelRoot): Promise<void> { if (this.viewer === undefined) this.viewer = await this.viewerProvider(); this.viewer.updateHidden(model); } /** * Notify the <code>Viewer</code> that the model has changed. */ async updatePopup(model: SModelRoot): Promise<void> { if (this.viewer === undefined) this.viewer = await this.viewerProvider(); this.viewer.updatePopup(model); } /** * Handling of commands after their execution. * * Hidden commands are not pushed to any stack. * * System commands are pushed to the <code>offStack</code> when the redo * stack is not empty, allowing to undo the before a redo to keep the chain * of commands consistent. * * Mergable commands are merged if possible. */ protected mergeOrPush(command: ICommand, context: CommandExecutionContext): void { if (command instanceof HiddenCommand) return; if (command instanceof SystemCommand && this.redoStack.length > 0) { this.offStack.push(command); } else { this.offStack.forEach(c => this.undoStack.push(c)); this.offStack = []; this.redoStack = []; if (this.undoStack.length > 0) { const lastCommand = this.undoStack[this.undoStack.length - 1]; if (lastCommand instanceof MergeableCommand && lastCommand.merge(command, context)) return; } this.pushToUndoStack(command); } } /** * Reverts all system commands on the offStack. */ protected undoOffStackSystemCommands(): void { let command = this.offStack.pop(); while (command !== undefined) { this.logger.log(this, 'Undoing off-stack', command); this.handleCommand(command, command.undo, () => {}); command = this.offStack.pop(); } } /** * System commands should be transparent to the user, so this method * is called from <code>undo()</code> to revert all system commands * at the top of the undoStack. */ protected undoPreceedingSystemCommands(): void { let command = this.undoStack[this.undoStack.length - 1]; while (command !== undefined && command instanceof SystemCommand) { this.undoStack.pop(); this.logger.log(this, 'Undoing', command); this.handleCommand(command, command.undo, (c: ICommand, context: CommandExecutionContext) => { this.redoStack.push(c); }); command = this.undoStack[this.undoStack.length - 1]; } } /** * System commands should be transparent to the user, so this method * is called from <code>redo()</code> to re-execute all system commands * at the top of the redoStack. */ protected redoFollowingSystemCommands(): void { let command = this.redoStack[this.redoStack.length - 1]; while (command !== undefined && command instanceof SystemCommand) { this.redoStack.pop(); this.logger.log(this, 'Redoing ', command); this.handleCommand(command, command.redo, (c: ICommand, context: CommandExecutionContext) => { this.pushToUndoStack(c); }); command = this.redoStack[this.redoStack.length - 1]; } } /** * Assembles the context object that is passed to the commands execution method. */ protected createContext(currentModel: SModelRoot): CommandExecutionContext { return { root: currentModel, modelChanged: this, modelFactory: this.modelFactory, duration: this.options.defaultDuration, logger: this.logger, syncer: this.syncer }; } } /** * Internal type to pass the results between the <code>Promises</code> in the * <code>ICommandStack</code>. */ export interface CommandStackState { root: SModelRoot hiddenRoot: SModelRoot | undefined popupRoot: SModelRoot | undefined rootChanged: boolean hiddenRootChanged: boolean popupChanged: boolean }
the_stack
import * as path from 'path'; import * as vscode from 'vscode'; import WebSocket from 'ws'; import TelemetryReporter from './telemetry'; import QuickPickItem = vscode.QuickPickItem; import * as utils from './utils'; import packageJson from "../package.json"; interface IPackageInfo { name: string; version: string; aiKey: string; } const debuggerType: string = 'devtools-for-chrome'; const defaultUrl: string = 'about:blank'; let telemetryReporter: TelemetryReporter; export function activate(context: vscode.ExtensionContext) { const packageInfo = getPackageInfo(context); if (packageInfo && vscode.env.machineId !== 'someValue.machineId') { // Use the real telemetry reporter telemetryReporter = new TelemetryReporter(packageInfo.name, packageInfo.version, packageInfo.aiKey); } else { // Fallback to a fake telemetry reporter telemetryReporter = new DebugTelemetryReporter(); } context.subscriptions.push(telemetryReporter); context.subscriptions.push(vscode.commands.registerCommand('devtools-for-chrome.launch', async () => { launch(context); })); context.subscriptions.push(vscode.commands.registerCommand('devtools-for-chrome.attach', async () => { attach(context, /* viaConfig= */ false, defaultUrl); })); vscode.debug.registerDebugConfigurationProvider(debuggerType, { provideDebugConfigurations(folder: vscode.WorkspaceFolder | undefined, token?: vscode.CancellationToken): vscode.ProviderResult<vscode.DebugConfiguration[]> { return Promise.resolve([{ type: debuggerType, name: 'Launch Chrome against localhost', request: 'launch', url: 'http://localhost:8080' }]); }, resolveDebugConfiguration(folder: vscode.WorkspaceFolder | undefined, config: vscode.DebugConfiguration, token?: vscode.CancellationToken): vscode.ProviderResult<vscode.DebugConfiguration> { if (config && config.type === debuggerType) { const targetUri: string = utils.getUrlFromConfig(folder, config); if (config.request && config.request.localeCompare('attach', 'en', { sensitivity: 'base' }) === 0) { attach(context, /* viaConfig= */ true, targetUri); telemetryReporter.sendTelemetryEvent('launch/command/attach'); } else if (config.request && config.request.localeCompare('launch', 'en', { sensitivity: 'base' }) === 0) { launch(context, targetUri, config.chromePath); telemetryReporter.sendTelemetryEvent('launch/command/launch'); } } else { vscode.window.showErrorMessage('No supported launch config was found.'); telemetryReporter.sendTelemetryEvent('launch/error/config_not_found'); } return; } }); } async function launch(context: vscode.ExtensionContext, launchUrl?: string, chromePathFromLaunchConfig?: string) { const viaConfig = !!(launchUrl || chromePathFromLaunchConfig); const telemetryProps = { viaConfig: `${viaConfig}` }; telemetryReporter.sendTelemetryEvent('launch', telemetryProps); const { hostname, port } = getSettings(); const portFree = await utils.isPortFree(hostname, port); if (portFree) { const settings = vscode.workspace.getConfiguration('vscode-devtools-for-chrome'); const pathToChrome = settings.get('chromePath') as string || chromePathFromLaunchConfig || utils.getPathToChrome(); if (!pathToChrome || !utils.existsSync(pathToChrome)) { vscode.window.showErrorMessage('Chrome was not found. Chrome must be installed for this extension to function. If you have Chrome installed at a custom location you can specify it in the \'chromePath\' setting.'); telemetryReporter.sendTelemetryEvent('launch/error/chrome_not_found', telemetryProps); return; } utils.launchLocalChrome(pathToChrome, port, defaultUrl); } const target = JSON.parse(await utils.getURL(`http://${hostname}:${port}/json/new?${launchUrl}`)); if (!target || !target.webSocketDebuggerUrl || target.webSocketDebuggerUrl === '') { vscode.window.showErrorMessage(`Could not find the launched Chrome tab: (${launchUrl}).`); telemetryReporter.sendTelemetryEvent('launch/error/tab_not_found', telemetryProps); attach(context, viaConfig, defaultUrl); } else { DevToolsPanel.createOrShow(context, target.webSocketDebuggerUrl); } } async function attach(context: vscode.ExtensionContext, viaConfig: boolean, targetUrl: string) { const telemetryProps = { viaConfig: `${viaConfig}` }; telemetryReporter.sendTelemetryEvent('attach', telemetryProps); const { hostname, port } = getSettings(); const responseArray = await getListOfTargets(hostname, port); if (Array.isArray(responseArray)) { telemetryReporter.sendTelemetryEvent('attach/list', telemetryProps, { targetCount: responseArray.length }); if (responseArray.length === 0) { vscode.window.showErrorMessage(`Could not find any targets for attaching.\nDid you remember to run Chrome with '--remote-debugging-port=9222'?`); return; } const items: QuickPickItem[] = []; responseArray.forEach(i => { i = utils.fixRemoteUrl(hostname, port, i); items.push({ label: i.title, description: i.url, detail: i.webSocketDebuggerUrl }); }); let targetWebsocketUrl = ''; if (typeof targetUrl === 'string' && targetUrl.length > 0 && targetUrl !== defaultUrl) { const matches = items.filter(i => i.description && targetUrl.localeCompare(i.description, 'en', { sensitivity: 'base' }) === 0); if (matches && matches.length > 0 ) { targetWebsocketUrl = matches[0].detail || ''; } else { vscode.window.showErrorMessage(`Couldn't attach to ${targetUrl}.`); } } if (targetWebsocketUrl && targetWebsocketUrl.length > 0) { DevToolsPanel.createOrShow(context, targetWebsocketUrl as string); } else { vscode.window.showQuickPick(items).then((selection) => { if (selection) { DevToolsPanel.createOrShow(context, selection.detail as string); } }); } } else { telemetryReporter.sendTelemetryEvent('attach/error/no_json_array', telemetryProps); } } function getSettings(): { hostname: string, port: number } { const settings = vscode.workspace.getConfiguration('vscode-devtools-for-chrome'); const hostname = settings.get('hostname') as string || 'localhost'; const port = settings.get('port') as number || 9222; return { hostname, port }; } function getPackageInfo(context: vscode.ExtensionContext): IPackageInfo { if (packageJson) { return { name: packageJson.name, version: packageJson.version, aiKey: packageJson.aiKey }; } return undefined as any as IPackageInfo; } async function getListOfTargets(hostname: string, port: number, useHttps: boolean = false): Promise<Array<any>> { const checkDiscoveryEndpoint = (uri: string) => { return utils.getURL(uri, { headers: { Host: "localhost" } }); }; const protocol = (useHttps ? "https" : "http"); let jsonResponse = ""; for (const endpoint of ["/json/list", "/json"]) { try { jsonResponse = await checkDiscoveryEndpoint(`${protocol}://${hostname}:${port}${endpoint}`); if (jsonResponse) { break; } } catch { // Do nothing } } let result: any[]; try { result = JSON.parse(jsonResponse); } catch { result = []; } return result; } class DevToolsPanel { private static currentPanel: DevToolsPanel | undefined; private readonly _panel: vscode.WebviewPanel; private readonly _context: vscode.ExtensionContext; private readonly _extensionPath: string; private readonly _targetUrl: string; private _socket: WebSocket | undefined = undefined; private _isConnected: boolean = false; private _messages: any[] = []; private _disposables: vscode.Disposable[] = []; public static createOrShow(context: vscode.ExtensionContext, targetUrl: string) { const column = vscode.ViewColumn.Beside; if (DevToolsPanel.currentPanel) { DevToolsPanel.currentPanel._panel.reveal(column); } else { const panel = vscode.window.createWebviewPanel('devtools-for-chrome', 'DevTools', column, { enableScripts: true, enableCommandUris: true, retainContextWhenHidden: true }); DevToolsPanel.currentPanel = new DevToolsPanel(panel, context, targetUrl); } } public static revive(panel: vscode.WebviewPanel, context: vscode.ExtensionContext, targetUrl: string) { DevToolsPanel.currentPanel = new DevToolsPanel(panel, context, targetUrl); } private constructor(panel: vscode.WebviewPanel, context: vscode.ExtensionContext, targetUrl: string) { this._panel = panel; this._context = context; this._extensionPath = context.extensionPath; this._targetUrl = targetUrl; this._update(); // Handle closing this._panel.onDidDispose(() => { this.dispose(); }, undefined, this._disposables); // Handle view change this._panel.onDidChangeViewState(e => { if (this._panel.visible) { this._update(); } }, undefined, this._disposables); // Handle messages from the webview this._panel.webview.onDidReceiveMessage(message => { this._onMessageFromWebview(message); }, undefined, this._disposables); } public dispose() { DevToolsPanel.currentPanel = undefined; this._panel.dispose(); this._disposeSocket(); while (this._disposables.length) { const x = this._disposables.pop(); if (x) { x.dispose(); } } } private _disposeSocket() { if (this._socket) { // Reset the socket since the devtools have been reloaded telemetryReporter.sendTelemetryEvent('websocket/dispose'); const s = this._socket as any; s.onopen = undefined; s.onmessage = undefined; s.onerror = undefined; s.onclose = undefined; this._socket.close(); this._socket = undefined; } } private _onMessageFromWebview(message: string) { if (message === 'ready') { if (this._socket) { telemetryReporter.sendTelemetryEvent('websocket/reconnect'); } this._disposeSocket(); } else if (message.substr(0, 10) === 'telemetry:') { return this._sendTelemetryMessage(message.substr(10)); } else if (message.substr(0, 9) === 'getState:') { return this._getDevtoolsState(); } else if (message.substr(0, 9) === 'setState:') { return this._setDevtoolsState(message.substr(9)); } else if (message.substr(0, 7) === 'getUrl:') { return this._getDevtoolsUrl(message.substr(7)); } else if (message.substr(0, 7) === 'copyText:') { return this._copyText(message.substr(9)); } if (!this._socket) { // First message, so connect a real websocket to the target this._connectToTarget(); } else if (!this._isConnected) { // DevTools are sending a message before the real websocket has finished opening so cache it this._messages.push(message); } else { // Websocket ready so send the message directly this._socket.send(message); } } private _connectToTarget() { const url = this._targetUrl; // Create the websocket this._socket = new WebSocket(url); this._socket.onopen = this._onOpen.bind(this); this._socket.onmessage = this._onMessage.bind(this); this._socket.onerror = this._onError.bind(this); this._socket.onclose = this._onClose.bind(this); } private _onOpen() { this._isConnected = true; // Tell the devtools that the real websocket was opened telemetryReporter.sendTelemetryEvent('websocket/open'); this._panel.webview.postMessage('open'); if (this._socket) { // Forward any cached messages onto the real websocket for (const message of this._messages) { this._socket.send(message); } this._messages = []; } } private _onMessage(message: any) { if (this._isConnected) { // Forward the message onto the devtools this._panel.webview.postMessage(message.data); } } private _onError() { if (this._isConnected) { // Tell the devtools that there was a connection error telemetryReporter.sendTelemetryEvent('websocket/error'); this._panel.webview.postMessage('error'); } } private _onClose() { if (this._isConnected) { // Tell the devtools that the real websocket was closed telemetryReporter.sendTelemetryEvent('websocket/close'); this._panel.webview.postMessage('close'); } this._isConnected = false; } private _sendTelemetryMessage(message: string) { const telemetry = JSON.parse(message); telemetryReporter.sendTelemetryEvent(telemetry.name, telemetry.properties, telemetry.metrics); } private _getDevtoolsState() { const allPrefsKey = 'devtools-preferences'; const allPrefs: any = this._context.workspaceState.get(allPrefsKey) || { uiTheme: '"dark"', screencastEnabled: false }; this._panel.webview.postMessage(`preferences:${JSON.stringify(allPrefs)}`); } private _setDevtoolsState(message: string) { // Parse the preference from the message and store it const pref = JSON.parse(message) as { name: string, value: string }; const allPrefsKey = 'devtools-preferences'; const allPrefs: any = this._context.workspaceState.get(allPrefsKey) || {}; allPrefs[pref.name] = pref.value; this._context.workspaceState.update(allPrefsKey, allPrefs); } private async _getDevtoolsUrl(message: string) { // Parse the request from the message and store it const request = JSON.parse(message) as { id: number, url: string }; let content = ''; try { content = await utils.getURL(request.url); } catch (ex) { content = ''; } this._panel.webview.postMessage(`setUrl:${JSON.stringify({ id: request.id, content })}`); } private async _copyText(message: string) { // Parse the request from the message and store it const request = JSON.parse(message) as { text: string }; vscode.env.clipboard.writeText(request.text); } private _update() { this._panel.webview.html = this._getHtmlForWebview(); } private _getHtmlForWebview() { const htmlPath = vscode.Uri.file(path.join(this._extensionPath, 'out/tools/front_end', 'inspector.html')); const htmlUri = htmlPath.with({ scheme: 'vscode-resource' }); const scriptPath = vscode.Uri.file(path.join(this._extensionPath, 'out', 'host', 'messaging.bundle.js')); const scriptUri = scriptPath.with({ scheme: 'vscode-resource' }); const stylesPath = vscode.Uri.file(path.join(this._extensionPath, 'out', 'common', 'styles.css')); const stylesUri = stylesPath.with({ scheme: 'vscode-resource' }); return ` <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="Content-Security-Policy" content="default-src 'none'; frame-src vscode-resource:; script-src vscode-resource:; style-src vscode-resource:;"> <link href="${stylesUri}" rel="stylesheet"/> <script src="${scriptUri}"></script> </head> <body> <iframe id="host" frameBorder="0" src="${htmlUri}?ws=trueD&experiments=true&edgeThemes=true"></iframe> </body> </html> `; } } class DebugTelemetryReporter extends TelemetryReporter { constructor() { super('extensionId', 'extensionVersion', 'key'); } public sendTelemetryEvent(name: string, properties?: any, measurements?: any) { console.log(`${name}: ${JSON.stringify(properties)}, ${JSON.stringify(properties)}`); } public dispose(): Promise<any> { return Promise.resolve(); } }
the_stack
namespace annie { declare let require: any; import Shape = annie.Shape; import Bitmap = annie.Bitmap; //打包swf用 export let _isReleased = false; export let suffixName = ".swf"; export let classPool: any = {}; //打包swf用 export let _shareSceneList: any = []; //存储加载资源的总对象 export let res: any = {}; // 加载器是否正在加载中 let _isLoading: boolean; // 加载中的场景名列表 let _loadSceneNames: any; //加载地址的域名地址或前缀 let _domain: string; //当前加载到哪一个资源 let _loadIndex: number; // 当前加载的总资源数 let _totalLoadRes: number; //当前已经加载的资源数 let _loadedLoadRes: number; //加载资源的完成回调 let _completeCallback: Function; //加载资源时的进度回调 let _progressCallback: Function; // 当前加载的资源配置文件内容 let _currentConfig: any; // 加载资源数和总资源数的比 let _loadPer: number; //单个资源占总资源数的比 let _loadSinglePer: number; /** * <h4><font color="red">注意:小程序 小游戏里这个方法是同步方法</font></h4> * 加载一个flash2x转换的文件内容,如果未加载完成继续调用此方法将会刷新加载器,中断未被加载完成的资源 * @method annie.loadScene * @public * @static * @since 1.0.0 * @param {string} sceneName fla通过flash2x转换时设置的包名 * @param {Function} progressFun 加载进度回调,回调参数为当前的进度值1-100 * @param {Function} completeFun 加载完成回调,回调参数为当前加载的场景信息 * @param {string} domain 加载时要设置的url前缀,默认则不更改加载路径 */ export let loadScene = function (sceneName: any, progressFun: Function, completeFun: Function, domain: string = ""): void { //加载资源配置文件 if (_isLoading) { console.log("当前加载未完成"); return; } _loadSceneNames = []; _domain = domain; if (typeof (sceneName) == "string") { if (!isLoadedScene(sceneName)) { res[sceneName] = {}; _loadSceneNames.push(sceneName); } else { let info: any = {}; info.sceneName = sceneName; info.sceneId = 1; info.sceneTotal = 1; completeFun(info); } } else { let len = sceneName.length; let index = 0; for (let i = 0; i < len; i++) { if (!isLoadedScene(sceneName[i])) { res[sceneName[i]] = {}; _loadSceneNames.push(sceneName[i]); } else { let info: any = {}; info.sceneName = sceneName[i]; info.sceneId = ++index; info.sceneTotal = len; completeFun(info); } } } if (_loadSceneNames.length == 0) { return; } _loadPer = 0; _loadIndex = 0; _totalLoadRes = 0; _loadedLoadRes = 0; _isLoading = true; _completeCallback = completeFun; _progressCallback = progressFun; _currentConfig = []; _loadConfig(); }; /** * 加载分包场景的方法 * @param sceneName 分包名字 * @param {Function} progressFun * @param {Function} completeFun * @param {string} domain */ export function loadSubScene(subName: string, progressFun: Function, completeFun: Function) { if (isLoadedScene(subName)) { completeFun({status: 1, name: subName}); } else { //分包加载 let loadTask = annie.app.loadSubpackage({ name: subName, success: function (res: any) { //分包加载成功后通过 success 回调 completeFun({status: 1, name: subName}); }, fail: function (res: any) { //分包加载失败通过 fail 回调 completeFun({status: 0, name: subName}); } }); loadTask.onProgressUpdate(progressFun); } } //加载配置文件,打包成released线上版时才会用到这个方法。 //打包released后,所有资源都被base64了,所以线上版不会调用这个方法。 function _loadConfig(): void { if (_domain.indexOf("http") != 0) { //本地 let sourceUrl = "../resource/"; if (_domain != "") { sourceUrl = "../" + _domain + "/resource/"; } let result: any = require(sourceUrl + _loadSceneNames[_loadIndex] + "/" + _loadSceneNames[_loadIndex] + ".res.js"); _onCFGComplete(result) } else { let downloadTask: any = app.downloadFile({ url: _domain + "resource/" + _loadSceneNames[_loadIndex] + "/" + _loadSceneNames[_loadIndex] + ".res.json", success(result: any) { if (result.statusCode == 200) { let resultData: string = app.getFileSystemManager().readFileSync(result.tempFilePath, "utf8"); _onCFGComplete(JSON.parse(resultData)); } } }); downloadTask.onProgressUpdate(function (res: any) { //远程资源的进度条根据每个加载文件K数才计算 if (_progressCallback) { _progressCallback((res.progress + 100 * _loadIndex) / _loadSceneNames.length >> 0); } }) } } function _onCFGComplete(data: any) { _currentConfig.push(data); _totalLoadRes += data.length; _loadIndex++; if (_loadSceneNames[_loadIndex]) { _loadConfig(); } else { //所有配置文件加载完成,那就开始加载资源 _loadIndex = 0; _loadSinglePer = 1 / _totalLoadRes; _loadRes(); } } //解析加载后的json资源数据 function _parseContent(loadContent: any) { //在加载完成之后解析并调整json数据文件,_a2x_con应该是con.json文件里最后一个被加载的,这个一定在fla生成json文件时注意 //主要工作就是遍历时间轴并调整成方便js读取的方式 let mc: any; for (let item in loadContent) { mc = loadContent[item]; if (mc.t == 1) { if (!(mc.f instanceof Object)) { mc.f = []; continue; } if (mc.tf > 1) { let frameList = mc.f; let count = frameList.length; let frameCon: any = null; let lastFrameCon: any = null; let ol: any = []; for (let i = 0; i < count; i++) { frameCon = frameList[i].c; //这帧是否为空 if (frameCon instanceof Object) { for (let j in frameCon) { let at = frameCon[j].at; if (at != undefined && at != -1) { if (at == 0) { ol.push(j); } else { for (let l = 0; l < ol.length; l++) { if (ol[l] == at) { ol.splice(l, 0, j); break; } } } delete frameCon[j].at; } } //上一帧是否为空 if (lastFrameCon instanceof Object) { for (let j in lastFrameCon) { //上一帧有,这一帧没有,加进来 if (!(frameCon[j] instanceof Object)) { frameCon[j] = lastFrameCon[j]; } else { //上一帧有,这一帧也有那么at就只有-1一种可能 if (frameCon[j].at != -1) { //如果不为空,则更新元素 for (let m in lastFrameCon[j]) { //这个地方一定要用undefined。因为有些元素可能为0.当然不是所有的元素都要补,比如滤镜,为空就不需要补 if (frameCon[j][m] == void 0 && m != "fi") { frameCon[j][m] = lastFrameCon[j][m]; } } } else { //如果为-1,删除元素 delete frameCon[j]; } } } } } lastFrameCon = frameCon; } mc.ol = ol; } } } } //检查所有资源是否全加载完成 function _checkComplete(): void { _currentConfig[_loadIndex].shift(); if (_domain.indexOf("http") != 0) { //本地的进度条根据加个的总文件数才计算 _loadedLoadRes++; _loadPer = _loadedLoadRes / _totalLoadRes; if (_progressCallback) { _progressCallback(_loadPer * 100 >> 0); } } if (_currentConfig[_loadIndex].length > 0) { _loadRes(); } else { res[_loadSceneNames[_loadIndex]]._f2x_had_loaded_scene = true; let info: any = {}; info.sceneName = _loadSceneNames[_loadIndex]; _loadIndex++; info.sceneId = _loadIndex; info.sceneTotal = _loadSceneNames.length; if (_loadIndex == _loadSceneNames.length) { //全部资源加载完成 _isLoading = false; if (_completeCallback) { _completeCallback(info); } } else { if (_completeCallback) { _completeCallback || _completeCallback(info); } _loadRes(); } } } //加载场景资源 function _loadRes(): void { let scene = _loadSceneNames[_loadIndex]; let type = _currentConfig[_loadIndex][0].type; if (type != "javascript") { let loadContent: any; if (_currentConfig[_loadIndex][0].id == "_a2x_con") { if (_domain.indexOf("http") != 0) { //本地 let sourceUrl = "../"; if (_domain != "") { sourceUrl = "../" + _domain + "/"; } loadContent = require(sourceUrl + _currentConfig[_loadIndex][0].src); } else { loadContent = _currentConfig[_loadIndex][0].src; } res[scene][_currentConfig[_loadIndex][0].id] = loadContent; _parseContent(loadContent); } else { if (type == "image") { //图片 loadContent = app.createImage(); if (_domain.indexOf("http") != 0) { let sourceUrl = ""; if (_domain != "") { sourceUrl = _domain + "/"; } loadContent.src = sourceUrl + _currentConfig[_loadIndex][0].src; } else { loadContent.src = _currentConfig[_loadIndex][0].src; } annie.res[scene][_currentConfig[_loadIndex][0].id] = loadContent; } else if (type == "sound") { //声音 loadContent = app.createInnerAudioContext(); if (_domain.indexOf("http") != 0) { let sourceUrl = ""; if (_domain != "") { sourceUrl = _domain + "/"; } loadContent.src = sourceUrl + _currentConfig[_loadIndex][0].src; } else { loadContent.src = _currentConfig[_loadIndex][0].src; } annie.res[scene][_currentConfig[_loadIndex][0].id] = loadContent; } } } else { //本地 let sourceUrl = "../"; if (_domain != "" && _domain.indexOf("http") != 0) { sourceUrl = "../" + _domain + "/"; } require(sourceUrl + _currentConfig[_loadIndex][0].src); } _checkComplete(); } /** * 判断一个场景是否已经被加载 * @method annie.isLoadedScene * @public * @static * @since 1.0.0 * @param {string} sceneName * @return {boolean} */ export function isLoadedScene(sceneName: string): Boolean { if (res[sceneName] != undefined && res[sceneName] != null && res[sceneName]._f2x_had_loaded_scene) { return true; } else { return false; } } /** * 删除一个场景资源,以方便系统垃圾回收 * @method annie.unLoadScene * @public * @static * @since 1.0.2 * @param {string} sceneName */ export function unLoadScene(sceneName: string): void { delete res[sceneName]; let w: any = window; let scene: any = w[sceneName]; for (let i in scene) { delete scene[i]; } delete w[sceneName]; scene = null; } /** * 获取已经加载到场景中的资源 * @method annie.getResource * @public * @static * @since 2.0.0 * @param {string} sceneName * @param {string} resName * @return {any} */ export function getResource(sceneName: string, resName: string): any { return res[sceneName][resName]; } /** * 新建一个已经加载到场景中的类生成的对象 * @method annie.getDisplay * @public * @static * @since 3.2.1 * @param {string} sceneName * @param {string} className * @return {any} */ export function getDisplay(sceneName: string, className: string): any { return new annie.classPool[sceneName][className](); } // 通过已经加载场景中的图片资源创建Bitmap对象实例,此方法一般给Annie2x工具自动调用 function b(sceneName: string, resName: string): Bitmap { return new annie.Bitmap(res[sceneName][resName]); } //用一个对象批量设置另一个对象的属性值,此方法一般给Annie2x工具自动调用 export function d(target: any, info: any, isMc: boolean = false): void { if (target._a2x_res_obj == info) { return; } else { //信息设置的时候看看是不是文本,如果有文本的话还需要设置宽和高 if (info.tr == undefined || info.tr.length == 1) { info.tr = [0, 0, 1, 1, 0, 0]; } let lastInfo = target._a2x_res_obj; if (info.al == void 0) { info.al = 1; } if (isMc) { let isUmChange: boolean = target.a2x_um; if (!target._changeTransformInfo[0] && target._x != info.tr[0]) { target._x = info.tr[0]; isUmChange = true; } if (!target._changeTransformInfo[1] && target._y != info.tr[1]) { target._y = info.tr[1]; isUmChange = true; } if (!target._changeTransformInfo[2] && target._scaleX != info.tr[2]) { target._scaleX = info.tr[2]; isUmChange = true; } if (!target._changeTransformInfo[3] && target._scaleY != info.tr[3]) { target._scaleY = info.tr[3]; isUmChange = true; } if (!target._changeTransformInfo[4]) { if (target._skewX != info.tr[4]) { target._skewX = info.tr[4]; target._rotation = 0; isUmChange = true; } if (target._skewY != info.tr[5]) { target._skewY = info.tr[5]; target._rotation = 0; isUmChange = true; } } target.a2x_um = isUmChange; if (!target._changeTransformInfo[5] && target._alpha != info.al) { target._alpha = info.al; target.a2x_ua = true; } } else { if (lastInfo.tr != info.tr) { [target._x, target._y, target._scaleX, target._scaleY, target._skewX, target._skewY] = info.tr; target.a2x_um = true; } if (target._alpha != info.al) { target._alpha = info.al; target.a2x_ua = true; } } if (info.w != undefined) { target.textWidth = info.w; target.textHeight = info.h; } //动画播放模式 图形 按钮 动画 if (info.t != undefined) { if (info.t == -1) { //initButton if (target.initButton) { target.initButton(); } } target._a2x_mode = info.t; } target._a2x_res_obj = info; } } // 解析数据里需要确定的文本类型 let _textLineType: Array<string> = ["single", "multiline"]; //解析数据里需要确定的文本对齐方式 let _textAlign: Array<string> = ["left", "center", "right"]; //创建一个动态文本或输入文本,此方法一般给Annie2x工具自动调用 function t(sceneName: string, resName: string): any { let textDate = res[sceneName]._a2x_con[resName]; let textObj: any; let text = decodeURIComponent(textDate[9]); let font = decodeURIComponent(textDate[4]).replace(/\s(Regular|Medium)/, ""); let size = textDate[5]; let textAlign = _textAlign[textDate[3]]; let lineType = _textLineType[textDate[2]]; let italic = textDate[11]; let bold = textDate[10]; let color = textDate[6]; let textAlpha = textDate[7]; let border = textDate[12]; let lineHeight = textDate[8]; // if (textDate[1] == 0 || textDate[1] == 1) { textObj = new annie.TextField(); textObj.text = text; textObj.font = font; textObj.size = size; textObj.textAlign = textAlign; textObj.lineType = lineType; textObj.italic = italic; textObj.bold = bold; textObj.color = color; textObj.textAlpha = textAlpha; textObj.border = border; textObj.lineHeight = lineHeight; // } else { /*textObj = new annie.InputText(textDate[2]); textObj.initInfo(text, color, textAlign, size, font, border, lineHeight); textObj.italic = italic; textObj.bold = bold;*/ // } return textObj; } //创建一个Shape矢量对象,此方法一般给Annie2x工具自动调用 function g(sceneName: string, resName: string): Shape { let shapeDate = res[sceneName]._a2x_con[resName][1]; let shape: annie.Shape = new annie.Shape(); for (let i = 0; i < shapeDate.length; i++) { if (shapeDate[i][0] == 1) { if (shapeDate[i][1] == 0) { shape.beginFill(annie.Shape.getRGBA(shapeDate[i][2][0], shapeDate[i][2][1])); } else if (shapeDate[i][1] == 1) { shape.beginLinearGradientFill(shapeDate[i][2][0], shapeDate[i][2][1]); } else if (shapeDate[i][1] == 2) { shape.beginRadialGradientFill(shapeDate[i][2][0], shapeDate[i][2][1]); } else { shape.beginBitmapFill(getResource(sceneName, shapeDate[i][2][0]), shapeDate[i][2][1]); } shape.decodePath(shapeDate[i][3]); shape.endFill(); } else { if (shapeDate[i][1] == 0) { shape.beginStroke(annie.Shape.getRGBA(shapeDate[i][2][0], shapeDate[i][2][1]), shapeDate[i][4], shapeDate[i][5], shapeDate[i][6], shapeDate[i][7]); } else if (shapeDate[i][1] == 1) { shape.beginLinearGradientStroke(shapeDate[i][2][0], shapeDate[i][2][1], shapeDate[i][4], shapeDate[i][5], shapeDate[i][6], shapeDate[i][7]); } else if (shapeDate[i][1] == 2) { shape.beginRadialGradientStroke(shapeDate[i][2][0], shapeDate[i][2][1], shapeDate[i][4], shapeDate[i][5], shapeDate[i][6], shapeDate[i][7]); } else { shape.beginBitmapStroke(getResource(sceneName, shapeDate[i][2][0]), shapeDate[i][2][1], shapeDate[i][4], shapeDate[i][5], shapeDate[i][6], shapeDate[i][7]); } shape.decodePath(shapeDate[i][3]); shape.endStroke(); } } return shape; } // 获取声音实例 function s(sceneName: string, resName: string): annie.Sound { return new annie.Sound(res[sceneName][resName]); } /** * <h4><font color="red">注意:小程序 小游戏不支持</font></h4> * 获取url地址中的get参数 * @method annie.getQueryString * @static * @param name * @return {any} * @since 1.0.9 * @public * @example * //如果当前网页的地址为http://xxx.xxx.com?id=1&username=anlun * //通过此方法获取id和username的值 * var id=annie.getQueryString("id"); * var userName=annie.getQueryString("username"); * console.log(id,userName); */ export function getQueryString(name: string) { let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); let r = window.location.search.substr(1).match(reg); if (r != null) return decodeURIComponent(r[2]); return null; } /** * 引擎自调用.初始化 sprite和movieClip用 * @method annie.initRes * @param target * @param {string} sceneName * @param {string} resName * @public * @static */ export function initRes(target: any, sceneName: string, resName: string) { let Root: any = annie.classPool; //资源树最顶层 let resRoot: any = res[sceneName]; //资源树里类对象json数据 let classRoot: any = resRoot._a2x_con; //资源树里类对象json数据里非资源类数据 let resClass: any = classRoot[resName]; //时间轴 target._a2x_res_class = resClass; let isMc: boolean = false; let i: number; if (resClass.tf > 1) { isMc = true; if (resClass.timeLine == void 0) { //将时间轴丰满,抽出脚本,抽出标签 let keyFrameCount = resClass.f.length; let timeLine: Array<number> = []; let curKeyFrame: number = keyFrameCount > 0 ? resClass.f[0].i : resClass.tf; let nextFrame: number = 0; if (curKeyFrame > 0) { let frameValue: number = -1; for (let j = 0; j < curKeyFrame; j++) { timeLine[timeLine.length] = frameValue; } } if (keyFrameCount > 0) { for (i = 0; i < keyFrameCount; i++) { if (i + 1 < keyFrameCount) { nextFrame = resClass.f[i + 1].i } else { nextFrame = resClass.tf; } curKeyFrame = resClass.f[i].i; //将时间线补齐 for (let j = 0; j < nextFrame - curKeyFrame; j++) { timeLine[timeLine.length] = i; } } } resClass.timeLine = timeLine; //初始化标签对象方便gotoAndStop gotoAndPlay if (!(resClass.f instanceof Object)) resClass.f = []; if (!(resClass.a instanceof Object)) resClass.a = {}; if (!(resClass.s instanceof Object)) resClass.s = {}; if (!(resClass.e instanceof Object)) resClass.e = {}; let label: any = {}; if (!(resClass.l instanceof Object)) { resClass.l = []; } else { for (let index in resClass.l) { for (let n = 0; n < resClass.l[index].length; n++) { label[resClass.l[index][n]] = parseInt(index) + 1; } } } resClass.label = label; } } let children = resClass.c; if (children instanceof Object) { let allChildren: any = []; let objCount = children.length; let obj: any = null; let objType: number = 0; let maskObj: any = null; let maskTillId = 0; for (i = 0; i < objCount; i++) { //if (children[i].indexOf("_$") == 0) { if (classRoot[children[i]] instanceof Array) { objType = classRoot[children[i]][0]; } else { objType = classRoot[children[i]].t; } switch (objType) { case 1: case 4: //text 和 Sprite //检查是否有名字,并且已经初始化过了 if (resClass.n && resClass.n[i] && target[resClass.n[i]]) { obj = target[resClass.n[i]]; } else { if (objType == 4) { obj = t(sceneName, children[i]); } else { //displayObject if (children[i].indexOf("_$") == 0) { if (classRoot[children[i]].tf > 1) { obj = new annie.MovieClip(); } else { obj = new annie.Sprite(); } initRes(obj, sceneName, children[i]); } else { obj = new Root[sceneName][children[i]](); } } if (resClass.n && resClass.n[i]) { target[resClass.n[i]] = obj; obj.name = resClass.n[i]; } } break; case 2: //bitmap obj = b(sceneName, children[i]); break; case 3: //shape obj = g(sceneName, children[i]); break; case 5: //sound obj = s(sceneName, children[i]); obj.name = children[i]; target.addSound(obj); } if (!isMc) { let index: number = i + 1; if (objType == 5) { obj._loop = obj._repeate = resClass.s[0][index]; } else { d(obj, resClass.f[0].c[index]); // 检查是否有遮罩 if (resClass.f[0].c[index].ma != void 0) { maskObj = obj; maskTillId = resClass.f[0].c[index].ma - 1; } else { if (maskObj instanceof Object && i <= maskTillId) { obj.mask = maskObj; if (i == maskTillId) { maskObj = null; } } } target.addChildAt(obj, 0); } } else { //这里一定把要声音添加到里面,以保证objectId与数组下标对应 allChildren[allChildren.length] = obj; //如果是声音,还要把i这个顺序保存下来 if (objType == 5) { obj.isPlaying = false; if (!(target._a2x_sounds instanceof Object)) { target._a2x_sounds = {}; } target._a2x_sounds[i] = obj; } } } if (isMc) { //将mc里面的实例按照时间轴上的图层排序 let ol = resClass.ol; if (ol instanceof Object) { for (let o = 0; o < ol.length; o++) { target._a2x_res_children[o] = [ol[o], allChildren[ol[o] - 1]]; } } } } } console.log("https://github.com/flash2x/AnnieJS"); }
the_stack
import { assert } from 'chai'; import { groupBy } from 'lodash'; import * as moment from 'moment'; import { Article, Category, Comment, CommentScore, CommentScoreRequest, CommentSummaryScore, Decision, MODERATION_ACTION_ACCEPT, MODERATION_ACTION_REJECT, Tag, } from '../../models'; import { compileScoresData, compileSummaryScoresData, completeMachineScoring, findOrCreateTagsByKey, getCommentsToResendForScoring, processMachineScore, recordDecision, } from '../../pipeline'; import { IScores, ISummaryScores } from '../../pipeline/shim'; import { getIsDoneScoring } from '../../pipeline/state'; import { createArticle, createCategory, createComment, createCommentScoreRequest, createCommentSummaryScore, createModerationRule, createModeratorUser, createTag, createUser, } from '../domain/comments/fixture'; describe('Pipeline Tests', () => { beforeEach(async () => { await CommentSummaryScore.destroy({where: {}}); await CommentScore.destroy({where: {}}); await CommentScoreRequest.destroy({where: {}}); await Decision.destroy({where: {}}); await Comment.destroy({where: {}}); await Article.destroy({where: {}}); await Category.destroy({where: {}}); await Tag.destroy({where: {}}); }); describe('getCommentsToResendForScoring', () => { it('should fetch comments that need to be resent for scoring', async () => { const [ comment, notQuiteStaleComment, staleComment, acceptedComment, rejectedComment, scoredComment, scoredStaleComment, ] = await Promise.all([ // Standard comment createComment(), // Not quite re-sendable createComment({ isAccepted: null, sentForScoring: moment().subtract(5, 'minutes').add(10, 'seconds'), }), // Freshly re-sendable createComment({ isAccepted: null, sentForScoring: moment().subtract(5, 'minutes').subtract(10, 'seconds'), }), // Accepted comments should be ignored createComment({ isAccepted: true, }), // Rejected comments should be ignored createComment({ isAccepted: false, }), // Scored comments should be ignored createComment({ isScored: true, }), // Scored, stale comments should be ignored createComment({ isScored: true, sentForScoring: moment().subtract(5, 'minutes').subtract(10, 'seconds'), }), ]); const comments = await getCommentsToResendForScoring(); const ids = comments.map((c) => c.id); assert.notInclude(ids, comment.id); assert.notInclude(ids, notQuiteStaleComment.id); assert.include(ids, staleComment.id); assert.notInclude(ids, acceptedComment.id); assert.notInclude(ids, rejectedComment.id); assert.notInclude(ids, scoredComment.id); assert.notInclude(ids, scoredStaleComment.id); }); }); describe('processMachineScore', () => { it('should process the passed in score data, updating the request record and adding score records', async () => { // Create test data const fakeScoreData: any = { scores: { ATTACK_ON_COMMENTER: [ { score: 0.2, begin: 0, end: 62, }, ], INFLAMMATORY: [ { score: 0.4, begin: 0, end: 62, }, { score: 0.7, begin: 63, end: 66, }, ], }, summaryScores: { ATTACK_ON_COMMENTER: 0.2, INFLAMMATORY: 0.55, }, error: '', }; // Put a series of fixture data into the database const [comment, serviceUser] = await Promise.all([ createComment(), createModeratorUser(), ]); const commentScoreRequest = await createCommentScoreRequest({ commentId: comment.id, userId: serviceUser.id, }); // Call processMachineScore and start making assertions await processMachineScore(comment.id, serviceUser.id, fakeScoreData); // This is the only score in the queue, so it should be complete (true). assert.isTrue(await getIsDoneScoring(comment.id)); await completeMachineScoring(comment.id); // Get scores and score requests from the database const scores = await CommentScore.findAll({ where: { commentId: comment.id }, include: [Tag], }); const request = await CommentScoreRequest.findOne({ where: { id: commentScoreRequest.id }, include: [Comment], }); const summaryScores = await CommentSummaryScore.findAll({ where: { commentId: comment.id }, include: [Tag], }); // Scores assertions assert.lengthOf(scores, 3); // Summary scores assertions assert.lengthOf(summaryScores, 2); // Assertions against test data for (const score of scores) { assert.equal(score.sourceType, 'Machine'); assert.equal(score.userId, serviceUser.id); if (score.score === 0.2) { assert.equal(score.annotationStart, 0); assert.equal(score.annotationEnd, 62); assert.equal((await score.getTag())!.key, 'ATTACK_ON_COMMENTER'); } if (score.score === 0.4) { assert.equal(score.annotationStart, 0); assert.equal(score.annotationEnd, 62); assert.equal((await score.getTag())!.key, 'INFLAMMATORY'); } if (score.score === 0.7) { assert.equal(score.annotationStart, 63); assert.equal(score.annotationEnd, 66); assert.equal((await score.getTag())!.key, 'INFLAMMATORY'); } } for (const score of summaryScores) { if (score.score === 0.2) { assert.equal((await score.getTag())!.key, 'ATTACK_ON_COMMENTER'); } if (score.score === 0.55) { assert.equal((await score.getTag())!.key, 'INFLAMMATORY'); } } // Request assertions assert.isNotNull(request); assert.isOk(request!.doneAt); assert.equal(request!.commentId, comment.id); assert.isTrue((await request!.getComment())!.isScored); }); it('should short-circuit if error key is present and not falsy in the scoreData', async () => { const fakeScoreData: any = { scores: { SPAM: [ { score: 0.2, begin: 0, end: 15, }, ], }, summaryScores: { SPAM: 0.2, }, error: 'Some error message', }; try { await processMachineScore(1, 1, fakeScoreData); throw new Error('`processMachineScore` successfully resolved when it should have been rejected'); } catch (err) { assert.instanceOf(err, Error); } }); it('should fail for any missed queries', async () => { // Create test data const fakeScoreData: any = { scores: { ATTACK_ON_COMMENTER: [ { score: 0.2, begin: 0, end: 62, }, ], INFLAMMATORY: [ { score: 0.4, begin: 0, end: 62, }, { score: 0.7, begin: 63, end: 66, }, ], }, summaryScores: { ATTACK_ON_COMMENTER: 0.2, INFLAMMATORY: 0.55, }, error: '', }; // Create similar fixture data as to previous test case, but leave out the score request creation const [comment, serviceUser] = await Promise.all([ createComment(), createModeratorUser(), ]); try { await processMachineScore(comment.id, serviceUser.id, fakeScoreData); throw new Error('`processMachineScore` unexpectedly resolved successfully'); } catch (err) { assert.instanceOf(err, Error); } }); it('should not mark the comment as `isScored` when not all score requests have come back', async () => { // Test data const fakeScoreData: any = { scores: { ATTACK_ON_COMMENTER: [ { score: 0.2, begin: 0, end: 62, }, ], INFLAMMATORY: [ { score: 0.4, begin: 0, end: 62, }, { score: 0.7, begin: 63, end: 66, }, ], }, summaryScores: { ATTACK_ON_COMMENTER: 0.2, INFLAMMATORY: 0.55, }, error: '', }; // Create similar fixture data as to previous test case, but leave out the score request const [comment, serviceUser1, serviceUser2] = await Promise.all([ createComment(), createModeratorUser(), createModeratorUser(), ]); // Make one request for each scorer const [commentScoreRequest1] = await Promise.all([ createCommentScoreRequest({ commentId: comment.id, userId: serviceUser1.id, }), createCommentScoreRequest({ commentId: comment.id, userId: serviceUser2.id, }), ]); // Receive a score for the first scorer await processMachineScore(comment.id, serviceUser1.id, fakeScoreData); const commentScoreRequests = await CommentScoreRequest.findAll({ where: { commentId: comment.id }, include: [Comment], order: [['id', 'ASC']], }); assert.lengthOf(commentScoreRequests, 2); commentScoreRequests.forEach((request: CommentScoreRequest) => { if (request.id === commentScoreRequest1.id) { assert.isOk(request.doneAt); } else { assert.isNull(request.doneAt); } }); assert.isFalse((await commentScoreRequests[0].getComment())!.isScored); }); }); describe('completeMachineScoring', () => { it('should denormalize', async () => { const category = await createCategory(); const article = await createArticle({ categoryId: category.id }); const comment = await createComment({ isScored: true, articleId: article.id }); const tag = await createTag(); await createCommentSummaryScore({ commentId: comment.id, tagId: tag.id, score: 0.5, }); await createModerationRule({ action: MODERATION_ACTION_REJECT, tagId: tag.id, lowerThreshold: 0.0, upperThreshold: 1.0, }); await completeMachineScoring(comment.id); const updatedCategory = (await Category.findByPk(category.id))!; const updatedArticle = (await Article.findByPk(article.id))!; const updatedComment = (await Comment.findByPk(comment.id))!; assert.isTrue(updatedComment.isAutoResolved, 'comment isAutoResolved'); assert.equal(updatedComment.unresolvedFlagsCount, 0, 'comment unresolvedFlagsCount'); assert.equal(updatedCategory.moderatedCount, 1, 'category moderatedCount'); assert.equal(updatedCategory.rejectedCount, 1, 'category rejectedCount'); assert.equal(updatedArticle.moderatedCount, 1, 'article moderatedCount'); assert.equal(updatedArticle.rejectedCount, 1, 'article rejectedCount'); assert.isNull(updatedArticle.lastModeratedAt); // last moderated doesn't get updated by machine ops }); it('should record the Reject decision from a rule', async () => { const category = await createCategory(); const article = await createArticle({ categoryId: category.id }); const comment = await createComment({ articleId: article.id }); const tag = await createTag(); await createCommentSummaryScore({ commentId: comment.id, tagId: tag.id, score: 0.5, }); const rule = await createModerationRule({ action: MODERATION_ACTION_REJECT, tagId: tag.id, lowerThreshold: 0.0, upperThreshold: 1.0, }); await completeMachineScoring(comment.id); const decision = (await Decision.findOne({ where: { commentId: comment.id }, }))!; assert.equal(decision.status, MODERATION_ACTION_REJECT); assert.equal(decision.source, 'Rule'); assert.equal(decision.moderationRuleId, rule.id); }); }); describe('compileScoresData', () => { it('should compile raw score and model data into an array for CommentScore bulk creation', async () => { const scoreData: IScores = { ATTACK_ON_COMMENTER: [ { score: 0.2, begin: 0, end: 62, }, ], INFLAMMATORY: [ { score: 0.4, begin: 0, end: 62, }, { score: 0.7, begin: 63, end: 66, }, ], }; const tags = await findOrCreateTagsByKey(Object.keys(scoreData)); const tagsByKey = groupBy(tags, (tag: Tag) => { return tag.key; }); const [comment, serviceUser] = await Promise.all([ createComment(), createModeratorUser(), ]); const commentScoreRequest = await createCommentScoreRequest({ commentId: comment.id, userId: serviceUser.id, }); const sourceType = 'Machine'; const expected = [ { sourceType, userId: serviceUser.id, commentId: comment.id, commentScoreRequestId: commentScoreRequest.id, tagId: tagsByKey.ATTACK_ON_COMMENTER[0].id, score: 0.2, annotationStart: 0, annotationEnd: 62, }, { sourceType, userId: serviceUser.id, commentId: comment.id, commentScoreRequestId: commentScoreRequest.id, tagId: tagsByKey.INFLAMMATORY[0].id, score: 0.4, annotationStart: 0, annotationEnd: 62, }, { sourceType, userId: serviceUser.id, commentId: comment.id, commentScoreRequestId: commentScoreRequest.id, tagId: tagsByKey.INFLAMMATORY[0].id, score: 0.7, annotationStart: 63, annotationEnd: 66, }, ]; const compiled = compileScoresData(sourceType, serviceUser.id, scoreData, { comment, commentScoreRequest, tags, }); assert.deepEqual(compiled, expected); }); }); describe('compileSummaryScoresData', () => { it('should compile raw score and model data into an array for CommentSummaryScore bulk creation', async () => { const summarScoreData: ISummaryScores = { ATTACK_ON_COMMENTER: 0.2, INFLAMMATORY: 0.55, }; const tags = await findOrCreateTagsByKey(Object.keys(summarScoreData)); const tagsByKey = groupBy(tags, (tag: Tag) => { return tag.key; }); const comment = await createComment(); const expected = [ { commentId: comment.id, tagId: tagsByKey.ATTACK_ON_COMMENTER[0].id, score: 0.2, }, { commentId: comment.id, tagId: tagsByKey.INFLAMMATORY[0].id, score: 0.55, }, ]; const compiled = compileSummaryScoresData(summarScoreData, comment, tags); assert.deepEqual(compiled, expected); }); }); describe('findOrCreateTagsByKey', () => { it('should create tags not present in the database and resolve their data', async () => { const keys = ['ATTACK_ON_AUTHOR']; const results = await findOrCreateTagsByKey(keys); assert.lengthOf(results, 1); const tag = results[0]; assert.equal(tag.key, keys[0]); assert.equal(tag.label, 'Attack On Author'); const instance = (await Tag.findOne({ where: { key: keys[0] }, }))!; assert.equal(tag.id, instance.id); assert.equal(tag.key, instance.key); assert.equal(tag.label, instance.label); }); it('should find existing tags and resolve their data', async () => { const key = 'SPAM'; const dbTag = await Tag.create({ key, label: 'Spam', }); const results = await findOrCreateTagsByKey([key]); assert.lengthOf(results, 1); const tag = results[0]; assert.equal(tag.id, dbTag.id); assert.equal(tag.key, key); assert.equal(tag.label, 'Spam'); }); it('should resolve a mix of existing and new tags', async () => { const keys = ['INCOHERENT', 'OFF_TOPIC']; const dbTag = await Tag.create({ key: 'INCOHERENT', label: 'Incoherent', }); const results = await findOrCreateTagsByKey(keys); assert.lengthOf(results, keys.length); results.forEach((tag) => { if (tag.key === 'INCOHERENT') { assert.equal(tag.id, dbTag.id); } else { assert.isNumber(tag.id); assert.equal(tag.key, 'OFF_TOPIC'); assert.equal(tag.label, 'Off Topic'); } }); }); }); describe('recordDecision', () => { it('should record the descision to accept', async () => { const comment = await createComment(); const user = await createUser(); await recordDecision(comment, MODERATION_ACTION_ACCEPT, user); const foundDecisions = await Decision.findAll({ where: { commentId: comment.id }, }); assert.lengthOf(foundDecisions, 1); const firstDecision = foundDecisions[0]; assert.equal(firstDecision.commentId, comment.id); assert.equal(firstDecision.source, 'User'); assert.equal(firstDecision.userId, user.id); assert.equal(firstDecision.status, MODERATION_ACTION_ACCEPT); assert.isTrue(firstDecision.isCurrentDecision); }); it('should clear old decisions', async () => { const user = await createUser(); const tag = await createTag(); const rule = await createModerationRule({ action: MODERATION_ACTION_REJECT, tagId: tag.id, lowerThreshold: 0.0, upperThreshold: 1.0, }); const comment = await createComment(); await recordDecision(comment, MODERATION_ACTION_ACCEPT, user); await recordDecision(comment, MODERATION_ACTION_REJECT, rule); const foundDecisions = await Decision.findAll({ where: { commentId: comment.id }, }); assert.lengthOf(foundDecisions, 2); const currentDecisions = await Decision.findAll({ where: { commentId: comment.id, isCurrentDecision: true, }, }); assert.lengthOf(currentDecisions, 1); const firstDecision = currentDecisions[0]; assert.equal(firstDecision.commentId, comment.id); assert.equal(firstDecision.source, 'Rule'); assert.equal(firstDecision.moderationRuleId, rule.id); assert.equal(firstDecision.status, MODERATION_ACTION_REJECT); assert.isTrue(firstDecision.isCurrentDecision); }); }); });
the_stack
import { Endpoint } from "butlerd"; import { Cave, CleanDownloadsEntry, Download, DownloadProgress, Game, GameUpdate, GameUpdateChoice, Profile, InstallLocationSummary, } from "common/butlerd/messages"; import { LogEntry } from "common/logger"; import { TypedModal, TypedModalUpdate } from "common/modals"; import { Action, CommonsState, Dispatch, EvolveTabPayload, GenerosityLevel, I18nResources, I18nResourceSet, ItchAppTabs, LocalizedString, MenuTemplate, ModalAction, NavigatePayload, NavigateTabPayload, OpenAtLoginError, OpenContextMenuBase, OpenTabPayload, PackageState, PreferencesState, ProgressInfo, ProxySource, SystemState, SystemTasksState, TabPage, TaskName, WindRole, } from "common/types"; export interface ActionCreator<PayloadType> { payload: PayloadType; (payload: PayloadType): Action<PayloadType>; } function action<PayloadType>(): ActionCreator<PayloadType> { const ret = (type: string) => (payload: PayloadType): Action<PayloadType> => { return { type, payload, }; }; // bending typing rules a bit, forgive me return ret as any; } export function dispatcher<T, U>( dispatch: Dispatch, actionCreator: (payload: T) => Action<U> ) { return (payload: T) => { const action = actionCreator(payload); dispatch(action); return action; }; } interface MirrorInput { [key: string]: ActionCreator<any>; } type MirrorOutput<T> = { [key in keyof T]: T[key] }; function wireActions<T extends MirrorInput>(input: T): MirrorOutput<T> { const res = {} as any; for (const k of Object.keys(input)) { res[k] = input[k](k); } return res as MirrorOutput<T>; } export const actions = wireActions({ // system preboot: action<{}>(), prebootDone: action<{}>(), rootWindowReady: action<{}>(), boot: action<{}>(), tick: action<{}>(), log: action<{ entry: LogEntry; }>(), scheduleSystemTask: action<Partial<SystemTasksState>>(), systemAssessed: action<{ system: SystemState; }>(), languageChanged: action<{ lang: string; }>(), processUrlArguments: action<{ /** these are command-line arguments */ args: string[]; }>(), handleItchioURI: action<{ /** example: itchio:///games/3 */ uri: string; }>(), pushItchioURI: action<{ uri: string; }>(), clearItchioURIs: action<{}>(), proxySettingsDetected: action<{ /** a valid HTTP(S) proxy string (that could be in $HTTP_PROXY) */ proxy: string; source: ProxySource; }>(), commonsUpdated: action<Partial<CommonsState>>(), // modals openModal: action<TypedModal<any, any>>(), updateModalWidgetParams: action<TypedModalUpdate<any>>(), closeModal: action<{ wind: string; /** id of the modal to close - if unspecified, close frontmost */ id?: string; /** action that should be dispatched once the modal's been closed */ action?: ModalAction; }>(), modalClosed: action<{ wind: string; /** id of the modal that was just closed */ id: string; /** if there was a response, it's here */ response: any; }>(), modalResponse: action<any>(), openWind: action<{ initialURL: string; role: WindRole; }>(), closeWind: action<{ wind: string; }>(), windClosed: action<{ wind: string; }>(), windOpened: action<{ wind: string; nativeId: number; initialURL: string; role: WindRole; }>(), // setup packagesListed: action<{ packageNames: string[]; }>(), packageGotVersionPrefix: action<{ name: string; version: string; versionPrefix: string; }>(), packageStage: action<{ name: string; stage: PackageState["stage"]; }>(), packageNeedRestart: action<{ name: string; availableVersion: string; }>(), packageProgress: action<{ name: string; progressInfo: ProgressInfo; }>(), relaunchRequest: action<{}>(), relaunch: action<{}>(), spinningUpButlerd: action<{ startedAt: number; }>(), gotButlerdEndpoint: action<{ endpoint: Endpoint; }>(), setupStatus: action<{ icon: string; message: LocalizedString; rawError?: Error; log?: string; }>(), setupOperationProgress: action<{ progress: ProgressInfo; }>(), setupDone: action<{}>(), silentlyScanInstallLocations: action<{}>(), locationScanProgress: action<{ progress: number; }>(), locationScanDone: action<{}>(), retrySetup: action<{}>(), // login attemptLogin: action<{}>(), loginWithPassword: action<{ /** the username or e-mail for the itch.io account to log in as */ username: string; /** the password for the itch.io account to log in as */ password: string; /** the 2FA totp code entered by user */ totpCode?: string; }>(), useSavedLogin: action<{ profile: Profile; }>(), loginFailed: action<{ /** the username we couldn't log in as (useful to prefill login form for retry) */ username: string; /** an error that occured while logging in */ error: Error; }>(), loginCancelled: action<{}>(), loginSucceeded: action<{ /** Profile we just logged in as */ profile: Profile; }>(), forgetProfileRequest: action<{ /** Profile to forget */ profile: Profile; }>(), forgetProfile: action<{ /** Profile to forget */ profile: Profile; }>(), profilesUpdated: action<{}>(), changeUser: action<{}>(), requestLogout: action<{}>(), loggedOut: action<{}>(), // onboarding startOnboarding: action<{}>(), exitOnboarding: action<{}>(), // window events windDestroyed: action<{ wind: string; }>(), windFocusChanged: action<{ wind: string; /** current state of focusedness */ focused: boolean; }>(), windFullscreenChanged: action<{ wind: string; /** current state of fullscreenedness */ fullscreen: boolean; }>(), windHtmlFullscreenChanged: action<{ wind: string; /** current state of html-fullscreenedness */ htmlFullscreen: boolean; }>(), windMaximizedChanged: action<{ wind: string; /** current state of fullscreenedness */ maximized: boolean; }>(), windBoundsChanged: action<{ wind: string; bounds: { /** left border, in pixels */ x: number; /** top border, in pixels */ y: number; /** in pixels */ width: number; /** in pixels */ height: number; }; }>(), focusWind: action<{ wind: string; /** if set to true, toggle focus instead of always focusing */ toggle?: boolean; }>(), hideWind: action<{ wind: string; }>(), minimizeWind: action<{ wind: string; }>(), toggleMaximizeWind: action<{ wind: string; }>(), // navigation tabOpened: action<OpenTabPayload>(), newTab: action<{ wind: string; }>(), navigate: action<NavigatePayload>(), tabFocused: action<{ wind: string; /** the id of the new tab */ tab: string; }>(), focusNthTab: action<{ wind: string; /** the index of the constant tab to focus (0-based) */ index: number; }>(), moveTab: action<{ wind: string; /** old tab index */ before: number; /** new tab index */ after: number; }>(), showNextTab: action<{ wind: string; }>(), showPreviousTab: action<{ wind: string; }>(), closeTab: action<{ wind: string; /** id of tab to close */ tab: string; }>(), closeCurrentTab: action<{ wind: string; }>(), closeTabOrAuxWindow: action<{ wind: string; }>(), closeAllTabs: action<{ wind: string; }>(), closeOtherTabs: action<{ wind: string; /** the only transient tab that'll be left */ tab: string; }>(), closeTabsBelow: action<{ wind: string; /** the tab after which all tabs will be closed */ tab: string; }>(), tabsClosed: action<{ wind: string; tabs: string[]; andFocus?: string; }>(), navigateTab: action<NavigateTabPayload>(), evolveTab: action<EvolveTabPayload>(), tabReloaded: action<{ wind: string; /** the tab that just reloaded */ tab: string; }>(), tabChanged: action<{ wind: string; /** the newly active tab */ tab: string; }>(), tabsChanged: action<{ wind: string; }>(), tabsRestored: action<{ wind: string; snapshot: ItchAppTabs; }>(), tabPageUpdate: action<{ wind: string; /** tab for which we fetched data */ tab: string; /** the data we fetched */ page: Partial<TabPage>; }>(), tabLoadingStateChanged: action<{ wind: string; tab: string; loading: boolean; }>(), analyzePage: action<{ wind: string; /** Which tab we're analyzing the page for */ tab: string; /** The url we're supposed to analyze */ url: string; }>(), tabGotWebContents: action<{ wind: string; /** id of tab that just got a webcontents */ tab: string; webContentsId: number; }>(), tabLosingWebContents: action<{ wind: string; /** id of tab that just lost a webcontents */ tab: string; }>(), openTabBackHistory: action< OpenContextMenuBase & { tab: string; } >(), openTabForwardHistory: action< OpenContextMenuBase & { tab: string; } >(), openGameContextMenu: action< OpenContextMenuBase & { /** game to open the context menu of */ game: Game; } >(), openUserMenu: action<OpenContextMenuBase>(), viewCreatorProfile: action<{}>(), viewCommunityProfile: action<{}>(), // menu menuChanged: action<{ /** new menu template */ template: MenuTemplate; }>(), // context menus popupContextMenu: action< OpenContextMenuBase & { /** contents of the context menu */ template: MenuTemplate; } >(), closeContextMenu: action<{ wind: string; }>(), checkForComponentUpdates: action<{}>(), beforeQuit: action<{}>(), cancelQuit: action<{}>(), quit: action<{}>(), performQuit: action<{}>(), quitWhenMain: action<{}>(), // locales localesConfigLoaded: action<{ /** initial set of i18n strings */ strings: I18nResourceSet; }>(), queueLocaleDownload: action<{ /** language to download */ lang: string; /** true if not triggered manually */ implicit?: boolean; }>(), localeDownloadStarted: action<{ /** which language just started downloading */ lang: string; }>(), localeDownloadEnded: action<{ /** which language just finished downloading */ lang: string; /** i18n strings */ resources: I18nResources; }>(), reloadLocales: action<{}>(), // install locations browseInstallLocation: action<{ /** id of install location to browse */ id: string; }>(), addInstallLocation: action<{ wind: string; }>(), removeInstallLocation: action<{ /** id of the install location to remove */ id: string; }>(), makeInstallLocationDefault: action<{ /** id of install location to make the default */ id: string; }>(), scanInstallLocations: action<{}>(), newItemsImported: action<{}>(), installLocationsChanged: action<{}>(), ownedKeysFetched: action<{}>(), // tasks taskStarted: action<{ /** name of task that just started */ name: TaskName; /** identifier of the task that just started */ id: string; /** timestamp for the task's start */ startedAt: number; /** identifier of the game the task is tied to */ gameId: number; /** identifier of the cave the task is tied to */ caveId: string; }>(), taskProgress: action< ProgressInfo & { /** the task this progress info is for */ id: string; } >(), taskEnded: action<{ /** the task that just ended */ id: string; /** an error, if any */ err: string; }>(), abortTask: action<{ /** id of the task to abort */ id: string; }>(), // downloads downloadQueued: action<{}>(), downloadsListed: action<{ downloads: Download[]; }>(), refreshDownloads: action<{}>(), downloadProgress: action<{ download: Download; progress: DownloadProgress; speedHistory: number[]; }>(), downloadEnded: action<{ download: Download; }>(), clearFinishedDownloads: action<{}>(), prioritizeDownload: action<{ /** the download for which we want to show an error dialog */ id: string; }>(), showDownloadError: action<{ /** the download for which we want to show an error dialog */ id: string; }>(), discardDownload: action<{ /** id of download to discard */ id: string; }>(), downloadDiscarded: action<{ /** id of download that was just discarded */ id: string; }>(), setDownloadsPaused: action<{ paused: boolean; }>(), retryDownload: action<{ /** id of download to retry */ id: string; }>(), clearGameDownloads: action<{ /** id of game for which to clear downloads */ gameId: number; }>(), downloadsRestored: action<{}>(), cleanDownloadsSearch: action<{}>(), cleanDownloadsFoundEntries: action<{ /** download subfolders we could remove */ entries: CleanDownloadsEntry[]; }>(), cleanDownloadsApply: action<{ /** download subfolders we will remove */ entries: CleanDownloadsEntry[]; }>(), // game management queueGame: action<{ /** the game we want to download */ game: Game; /** which cave to launch */ caveId?: string; }>(), queueGameInstall: action<{ /** the game we want to install */ game: Game; /** the upload we picked */ uploadId?: number; }>(), queueLaunch: action<{ cave: Cave }>(), launchEnded: action<{}>(), manageGame: action<{ /** which game to manage */ game: Game; }>(), manageCave: action<{ /** which cave to manage */ caveId: string; }>(), requestCaveUninstall: action<{ /** id of the cave to uninstall */ caveId: string; }>(), queueCaveUninstall: action<{ /** id of the cave to uninstall */ caveId: string; }>(), queueCaveReinstall: action<{ /** id of the cave to reinstall */ caveId: string; }>(), uninstallEnded: action<{}>(), exploreCave: action<{ /** id of the cave to explore */ caveId: string; }>(), recordGameInteraction: action<{}>(), forceCloseLastGame: action<{}>(), forceCloseGameRequest: action<{ /** the game we want to force-quit */ game: Game; }>(), forceCloseGame: action<{ /** the id of the game we want to force-quit */ gameId: number; }>(), checkForGameUpdates: action<{}>(), checkForGameUpdate: action<{ /** which cave to check for an update */ caveId: string; }>(), gameUpdateCheckStatus: action<{ /** whether we're currently checking */ checking: boolean; /** how far along we are */ progress: number; }>(), gameUpdateAvailable: action<{ /** the actual update info */ update: GameUpdate; }>(), showGameUpdate: action<{ /** the actual update info */ update: GameUpdate; }>(), queueGameUpdate: action<{ /** the actual update info */ update: GameUpdate; /** the choice we made */ choice: GameUpdateChoice; }>(), queueAllGameUpdates: action<{}>(), snoozeCave: action<{ caveId: string; }>(), switchVersionCaveRequest: action<{ /** the cave to revert to a different build */ cave: Cave; }>(), viewCaveDetails: action<{ /** the cave to view details of */ caveId: string; }>(), // purchase initiatePurchase: action<{ /** the game that might be purchased */ game: Game; }>(), purchaseCompleted: action<{ /** the game that was just purchased */ game: Game; }>(), encourageGenerosity: action<{ /** for which game should we encourage generosity? */ gameId: number; /** how hard should we encourage generosity? */ level: GenerosityLevel; }>(), // search focusInPageSearch: action<{ wind: string; }>(), searchFetched: action<{}>(), focusSearch: action<{}>(), closeSearch: action<{}>(), focusLocationBar: action<{ wind: string; tab: string; }>(), blurLocationBar: action<{}>(), searchVisibilityChanged: action<{ open: boolean; }>(), // preferences updatePreferences: action<Partial<PreferencesState>>(), preferencesLoaded: action<PreferencesState>(), clearBrowsingDataRequest: action<{ wind: string; }>(), clearBrowsingData: action<{ /** Whether to wipe cached images & files */ cache: boolean; /** Whether to wipe cookies (will log out user) */ cookies: boolean; }>(), openAtLoginError: action<OpenAtLoginError>(), // internal setReduxLoggingEnabled: action<{ /** true if should show in the chrome console */ enabled: boolean; }>(), // misc. gcDatabase: action<{}>(), /** macOS-only, bounce dock */ bounce: action<{}>(), /** cross-platform, notification bubble */ notify: action<{ /** title of the notification, defaults to `itch` */ title?: string; /** main text of the notification */ body: string; /** path to the icon (on fs, can be relative to `app/`), defaults to itch icon */ icon?: string; /** action to dispatch if notification is clicked */ onClick?: Action<any>; }>(), statusMessage: action<{ /** the message we want to show in the status bar */ message: LocalizedString; }>(), dismissStatusMessage: action<{}>(), commandMain: action<{ wind: string; }>(), commandOk: action<{ wind: string; }>(), commandBack: action<{ wind: string; }>(), commandGoBack: action<{ wind: string; }>(), commandGoForward: action<{ wind: string; }>(), commandLocation: action<{ wind: string; }>(), commandReload: action<{ wind: string; }>(), commandStop: action<{ wind: string; }>(), tabGoBack: action<{ wind: string; tab: string; }>(), tabGoForward: action<{ wind: string; tab: string; }>(), tabGoToIndex: action<{ wind: string; tab: string; index: number; }>(), tabWentToIndex: action<{ wind: string; tab: string; oldIndex: number; index: number; fromWebContents?: boolean; }>(), tabStop: action<{ wind: string; tab: string; }>(), openInExternalBrowser: action<{ /** the URL to open in an external web browser */ url: string; }>(), openAppLog: action<{}>(), openLogFileRequest: action<{}>(), openDevTools: action<{ wind: string; /** if specified, opens devTools for a tab, not the app */ tab?: string; }>(), inspect: action<{ webContentsId: number; x: number; y: number; }>(), sendFeedback: action<{ /** error log that should be included in the issue report */ log?: string; }>(), viewChangelog: action<{}>(), copyToClipboard: action<{ /** text to copy to clipboard */ text: string; }>(), });
the_stack
import * as chai from "chai"; import "url-search-params-polyfill"; import { MindSphereSdk } from "../src"; import { decrypt, loadAuth } from "../src/api/utils"; import { setupDeviceTestStructure, tearDownDeviceTestStructure } from "./test-device-setup-utils"; import { getPasskeyForUnitTest } from "./test-utils"; chai.should(); const timeOffset = new Date().getTime(); describe("[SDK] DeviceManagementClient.EdgeAppDeployment", () => { const auth = loadAuth(); const sdk = new MindSphereSdk({ ...auth, basicAuth: decrypt(auth, getPasskeyForUnitTest()), }); const appDeploymentClient = sdk.GetEdgeDeploymentClient(); const edgeAppInstanceClient = sdk.GetEdgeAppInstanceManagementClient(); const tenant = sdk.GetTenant(); const testAppInstance = { name: `testAppInst_${tenant}_${timeOffset}`, appInstanceId: `testAppInst_${tenant}_${timeOffset}`, deviceId: "string", releaseId: "string", applicationId: `testApp_${tenant}_${timeOffset}` }; const testConfigurations = { deviceId: `${tenant}.UnitTestDeviceType`, appId: "718ca5ad0...", appReleaseId: "718ca5ad0...", appInstanceId: "718ca5ad0...", configuration: { sampleKey1: "sampleValue1", sampleKey2: "sampleValue2" } }; const taskTemplate = { deviceId: "7d018c...", softwareId: "7d018c...", softwareReleaseId: "7d018c...", customData: { sampleKey1: "sampleValue1", sampleKey2: "sampleValue2" } }; const workflowInstance = { deviceId: "", model: { key: `${tenant}_fwupdate`, customTransitions: [] }, data: { userDefined: {} } }; let deviceTypeId = "aee2e37f-f562-4ed6-b90a-c43208dc054a"; let assetTypeId = `${tenant}.UnitTestDeviceAssetType`; let assetId = ""; let gFolderid = ""; let deviceId = ""; let appId = ""; let appReleaseId = ""; let appInstanceId = ""; // let installationTaskId = ""; // let removalTaskId = ""; before(async () => { // tear Down test infrastructure await tearDownDeviceTestStructure(sdk); // Setup the testing architecture const {device, deviceAsset, deviceType, deviceAssetType, folderid } = await setupDeviceTestStructure(sdk); assetTypeId = `${(deviceAssetType as any).id}`; deviceTypeId = `${(deviceType as any).id}`; assetId = `${(deviceAsset as any).assetId}`; deviceId = `${(device as any).id}`; gFolderid = `${folderid}`; // Create a new app testAppInstance.deviceId = `${deviceId}`; testAppInstance.releaseId = `V001${timeOffset}`; const appInstRes = await edgeAppInstanceClient.PostAppInstance(testAppInstance); appInstanceId = (appInstRes as any).id; appId = (appInstRes as any).applicationId; appReleaseId = (appInstRes as any).releaseId; // Create a new app instance configuration testConfigurations.deviceId = `${deviceId}`; testConfigurations.appId = `${appId}`; testConfigurations.appInstanceId = `${appInstanceId}`; testConfigurations.appReleaseId = `${appReleaseId}`; const instConfRes = await edgeAppInstanceClient.PostAppInstanceConfigurations(testConfigurations); // Set the task template taskTemplate.deviceId = `${deviceId}`; taskTemplate.softwareId = `${appId}`; taskTemplate.softwareReleaseId = `${appInstanceId}`; }); after(async () => { // delete App configuration await edgeAppInstanceClient.DeleteAppInstanceConfiguration(appInstanceId); // Delete the app await edgeAppInstanceClient.DeleteAppInstance(appInstanceId); // tear Down test infrastructure await tearDownDeviceTestStructure(sdk); }); it("SDK should not be undefined", async () => { sdk.should.not.be.undefined; }); it("standard properties shoud be defined", async () => { appDeploymentClient.should.not.be.undefined; appDeploymentClient.GetGateway().should.be.equal(auth.gateway); (await appDeploymentClient.GetToken()).length.should.be.greaterThan(200); (await appDeploymentClient.GetToken()).length.should.be.greaterThan(200); }); it("should POST accepted term and conditions", async () => { appDeploymentClient.should.not.be.undefined; // Prepare a new workflow instance const acceptedTermsAndConditions = await appDeploymentClient.PostAcceptTermsAndConditions({ deviceId: deviceId, releaseId: appReleaseId }); acceptedTermsAndConditions.should.not.be.undefined; acceptedTermsAndConditions.should.not.be.null; (acceptedTermsAndConditions as any).firstAccepted.should.not.be.undefined; (acceptedTermsAndConditions as any).firstAccepted.should.not.be.null; }); it("should GET terms and conditions", async () => { appDeploymentClient.should.not.be.undefined; // Get terms and conditions const appTermAndConditions = await appDeploymentClient.GetTermsAndConditions(deviceId, appReleaseId); appTermAndConditions.should.not.be.undefined; appTermAndConditions.should.not.be.null; (appTermAndConditions as any).firstAccepted.should.not.be.null; }); /* TODO: 27-06-2021 Not supported in yet it("should POST a new deployment task", async () => { appDeploymentClient.should.not.be.undefined; // Set the task template taskTemplate.deviceId = `${deviceId}`; taskTemplate.softwareId = `${appId}`; taskTemplate.softwareReleaseId = `${appInstanceId}`; const installationTask = await appDeploymentClient.PostInstallationTask(taskTemplate); (installationTask as any).should.not.be.undefined; (installationTask as any).should.not.be.null; (installationTask as any).id.should.not.be.undefined; (installationTask as any).id.should.not.be.null; (installationTask as any).currentState.should.not.be.undefined; (installationTask as any).currentState.should.not.be.null; installationTaskId = `${(installationTask as any).id}`; });*/ it("should GET list of installation tasks.", async () => { appDeploymentClient.should.not.be.undefined; const taks = await appDeploymentClient.GetInstallationTasks(deviceId); (taks as any).should.not.be.undefined; (taks as any).should.not.be.null; (taks as any).page.number.should.equal(0); (taks as any).page.size.should.be.gte(10); (taks as any).content.length.should.be.gte(0); }); /* TODO: 27-06-2021 Not supported in yet it("should GET specific installation task", async () => { appDeploymentClient.should.not.be.undefined; const task = await appDeploymentClient.GetInstallationTask(installationTaskId); (task as any).should.not.be.undefined; (task as any).should.not.be.null; (task as any).id.should.not.be.undefined; (task as any).id.should.not.be.null; });*/ /* TODO: 27-06-2021 Not supported in yet it("should PATCH installation Status as downloading", async () => { appDeploymentClient.should.not.be.undefined; // Set the task template const status = { state: EdgeAppDeploymentModels.TaskStatus.StateEnum.DOWNLOAD, progress: 0.9, message: "Task status updated as DOWNLOAD", details: { sampleKey1: "sampleValue1", sampleKey2: "sampleValue2" } }; const installationTAsk = await appDeploymentClient.PatchInstallationTask(installationTaskId, status); (installationTAsk as any).should.not.be.undefined; (installationTAsk as any).should.not.be.null; (installationTAsk as any).currentState.should.not.be.undefined; (installationTAsk as any).currentState.should.not.be.null; }); */ /* TODO: 27-06-2021 Not supported in yet it("should PATCH installation Status as activate", async () => { appDeploymentClient.should.not.be.undefined; // Set the task template const status = { state: EdgeAppDeploymentModels.TaskStatus.StateEnum.ACTIVATE, progress: 1.0, message: "Task status updated as ACTIVATE", details: { sampleKey1: "sampleValue1", sampleKey2: "sampleValue2" } }; const installationTAsk = await appDeploymentClient.PatchInstallationTask(installationTaskId, status); (installationTAsk as any).should.not.be.undefined; (installationTAsk as any).should.not.be.null; (installationTAsk as any).currentState.should.not.be.undefined; (installationTAsk as any).currentState.should.not.be.null; }); */ /* TODO: 27-06-2021 Not supported in yet it("should POST to create a removal task", async () => { appDeploymentClient.should.not.be.undefined; // Set the task template taskTemplate.deviceId = `${deviceId}`; taskTemplate.softwareId = `${appId}`; taskTemplate.softwareReleaseId = `${appInstanceId}`; const installationTask = await appDeploymentClient.PostRemovalTask(taskTemplate); (installationTask as any).should.not.be.undefined; (installationTask as any).should.not.be.null; (installationTask as any).id.should.not.be.undefined; (installationTask as any).id.should.not.be.null; (installationTask as any).currentState.should.not.be.undefined; (installationTask as any).currentState.should.not.be.null; removalTaskId = `${(installationTask as any).id}`; });*/ it("should GET list of removal tasks.", async () => { appDeploymentClient.should.not.be.undefined; const taks = await appDeploymentClient.GetRemovalTasks(deviceId); (taks as any).should.not.be.undefined; (taks as any).should.not.be.null; (taks as any).page.number.should.equal(0); (taks as any).page.size.should.be.gte(10); (taks as any).content.length.should.be.gte(0); }); });
the_stack
import * as vscode from 'vscode'; interface ExpressionInfo { functionName: string; parameterPosition: number; } interface RelativeExpressionInfo { startPosition: number; parameterPosition: number; } const CLJ_TEXT_DELIMITER = `"`; const CLJ_TEXT_ESCAPE = `\\`; const CLJ_COMMENT_DELIMITER = `;`; const R_CLJ_WHITE_SPACE = /\s|,/; const R_CLJ_OPERATOR_DELIMITERS = /\s|,|\(|{|\[/; const OPEN_CLJ_BLOCK_BRACKET = `(`; const CLOSE_CLJ_BLOCK_BRACKET = `)`; /** { close_char open_char } */ const CLJ_EXPRESSION_DELIMITERS: Map<string, string> = new Map<string, string>([ [`}`, `{`], [CLOSE_CLJ_BLOCK_BRACKET, OPEN_CLJ_BLOCK_BRACKET], [`]`, `[`], [CLJ_TEXT_DELIMITER, CLJ_TEXT_DELIMITER], ]); const getExpressionInfo = (text: string): ExpressionInfo | undefined => { text = removeCljComments(text); const relativeExpressionInfo = getRelativeExpressionInfo(text); if (!relativeExpressionInfo) return; let functionName = text.substring(relativeExpressionInfo.startPosition + 1); // expression openning ignored functionName = functionName.substring(functionName.search(/[^,\s]/)); // trim left functionName = functionName.substring(0, functionName.search(R_CLJ_OPERATOR_DELIMITERS)); // trim right according to operator delimiter if (!functionName.length) return; return { functionName, parameterPosition: relativeExpressionInfo.parameterPosition, }; }; const removeCljComments = (text: string): string => { const lines = text.match(/[^\r\n]+/g) || [] // split string by line if (lines.length > 1) { return lines.map(line => removeCljComments(line)).join(`\n`); // remove comments from each line and concat them again after } const line = lines[0]; let uncommentedIndex = line.length; let insideString = false; for (let i = 0; i < line.length; i++) { if (line[i] === CLJ_TEXT_DELIMITER) { insideString = !insideString || line[i - 1] === CLJ_TEXT_ESCAPE; continue; } if (line[i] === CLJ_COMMENT_DELIMITER && !insideString) { // ignore comment delimiter inside a string uncommentedIndex = i; break; } } return line.substring(0, uncommentedIndex); }; const getRelativeExpressionInfo = (text: string, openChar: string = `(`): RelativeExpressionInfo | undefined => { const relativeExpressionInfo: RelativeExpressionInfo = { startPosition: text.length - 1, parameterPosition: -1, }; let newParameterFound = false; while (relativeExpressionInfo.startPosition >= 0) { const char = text[relativeExpressionInfo.startPosition]; // check if found the beginning of the expression (string escape taken care of) if (char === openChar && (openChar !== CLJ_TEXT_DELIMITER || (text[relativeExpressionInfo.startPosition - 1] !== CLJ_TEXT_ESCAPE))) { if (newParameterFound) // ignore one parameter found if it's actually the function we're looking for relativeExpressionInfo.parameterPosition--; return relativeExpressionInfo; } // ignore everything if searching inside a string if (openChar === CLJ_TEXT_DELIMITER) { relativeExpressionInfo.startPosition--; continue; } // invalid code if a beginning of an expression is found without being searched for if (char !== CLJ_TEXT_DELIMITER && containsValue(CLJ_EXPRESSION_DELIMITERS, char)) return; // keep searching if it's white space if (R_CLJ_WHITE_SPACE.test(char)) { if (!newParameterFound) { relativeExpressionInfo.parameterPosition++; newParameterFound = true; } relativeExpressionInfo.startPosition--; continue; } // check for new expressions const expressionDelimiter = CLJ_EXPRESSION_DELIMITERS.get(char); if (!!expressionDelimiter) { const innerExpressionInfo = getRelativeExpressionInfo(text.substring(0, relativeExpressionInfo.startPosition), expressionDelimiter); if (!innerExpressionInfo) return; relativeExpressionInfo.startPosition = innerExpressionInfo.startPosition - 1; relativeExpressionInfo.parameterPosition++; newParameterFound = true; continue; } newParameterFound = false; relativeExpressionInfo.startPosition--; } return; // reached the beginning of the text without finding the start of the expression }; const containsValue = (map: Map<any, any>, checkValue: any): boolean => { for (let value of map.values()) { if (value === checkValue) return true; } return false; }; const getNamespace = (text: string): string => { const m = text.match(/^[;\s\t\n]*\((?:[\s\t\n]*(?:in-){0,1}ns)[\s\t\n]+'?([\w\-.]+)[\s\S]*\)[\s\S]*/); return m ? m[1] : 'user'; }; /** A range of numbers between `start` and `end`. * The `end` index is not included and `end` could be before `start`. * Whereas default `vscode.Range` requires that `start` should be * before or equal than `end`. */ const range = (start: number, end: number): Array<number> => { if (start < end) { const length = end - start; return Array.from(Array(length), (_, i) => start + i); } else { const length = start - end; return Array.from(Array(length), (_, i) => start - i); } } const findNearestBracket = ( editor: vscode.TextEditor, current: vscode.Position, bracket: string): vscode.Position | undefined => { const isBackward = bracket == OPEN_CLJ_BLOCK_BRACKET; // "open" and "close" brackets as keys related to search direction let openBracket = OPEN_CLJ_BLOCK_BRACKET, closeBracket = CLOSE_CLJ_BLOCK_BRACKET; if (isBackward) { [closeBracket, openBracket] = [openBracket, closeBracket] }; let bracketStack: string[] = [], // get begin of text if we are searching `(` and end of text otherwise lastLine = isBackward ? -1 : editor.document.lineCount, lineRange = range(current.line, lastLine); for (var line of lineRange) { const textLine = editor.document.lineAt(line); if (textLine.isEmptyOrWhitespace) continue; // get line and strip clj comments const firstChar = textLine.firstNonWhitespaceCharacterIndex, strippedLine = removeCljComments(textLine.text); let startColumn = firstChar, endColumn = strippedLine.length; if (isBackward) { // dec both as `range` doesn't include an end edge [startColumn, endColumn] = [endColumn - 1, startColumn - 1]; } // select block if cursor right after the closed bracket or right before opening if (current.line == line) { // get current current char index if it is first iteration of loop let currentColumn = current.character; // set current position as start if (isBackward) { if (currentColumn <= endColumn) continue; startColumn = currentColumn; if (strippedLine[startColumn - 1] == CLOSE_CLJ_BLOCK_BRACKET) { startColumn = startColumn - 2; } else if (strippedLine[startColumn] == CLOSE_CLJ_BLOCK_BRACKET) { startColumn--; }; } else if (currentColumn <= endColumn) { // forward direction startColumn = currentColumn; if (strippedLine[startColumn - 1] == CLOSE_CLJ_BLOCK_BRACKET) { return new vscode.Position(line, startColumn); } else if (strippedLine[startColumn] == OPEN_CLJ_BLOCK_BRACKET) { startColumn++; }; } } // search nearest bracket for (var column of range(startColumn, endColumn)) { const char = strippedLine[column]; if (!bracketStack.length && char == bracket) { // inc column if `char` is a `)` to get correct selection if (!isBackward) column++; return new vscode.Position(line, column); } else if (char == openBracket) { bracketStack.push(char); // check if inner block is closing } else if (char == closeBracket && bracketStack.length > 0) { bracketStack.pop(); }; }; } }; const getCurrentBlock = ( editor: vscode.TextEditor, left?: vscode.Position, right?: vscode.Position): vscode.Selection | undefined => { if (!left || !right) { left = right = editor.selection.active; }; const prevBracket = findNearestBracket(editor, left, OPEN_CLJ_BLOCK_BRACKET); if (!prevBracket) return; const nextBracket = findNearestBracket(editor, right, CLOSE_CLJ_BLOCK_BRACKET); if (nextBracket) { return new vscode.Selection(prevBracket, nextBracket); } }; const getOuterBlock = ( editor: vscode.TextEditor, left?: vscode.Position, right?: vscode.Position, prevBlock?: vscode.Selection): vscode.Selection | undefined => { if (!left || !right) { left = right = editor.selection.active; }; const nextBlock = getCurrentBlock(editor, left, right); if (nextBlock) { // calculate left position one step before if (nextBlock.anchor.character > 0) { left = new vscode.Position(nextBlock.anchor.line, nextBlock.anchor.character - 1); } else if (nextBlock.anchor.line > 0) { const line = nextBlock.anchor.line - 1; left = editor.document.lineAt(line).range.end; } else { return new vscode.Selection(nextBlock.anchor, nextBlock.active); } // calculate right position one step after const lineLength = editor.document.lineAt(nextBlock.active.line).text.length; if (nextBlock.active.character < lineLength) { right = new vscode.Position(nextBlock.active.line, nextBlock.active.character + 1); } else if (nextBlock.active.line < editor.document.lineCount - 1) { right = new vscode.Position(nextBlock.active.line + 1, 0); } else { return new vscode.Selection(nextBlock.anchor, nextBlock.active); }; // try to find next outer block return getOuterBlock(editor, left, right, nextBlock); } else if (right != left) { return prevBlock; }; } export const cljParser = { R_CLJ_WHITE_SPACE, getExpressionInfo, getNamespace, getCurrentBlock, getOuterBlock, };
the_stack
import {Animation} from './animation'; import {AnimationManager, AnimationResult} from './animationmanager'; import {ModelData} from '../render/program/animatedentityprogram'; import {Vec3} from '../math/vec3'; import {Mat4} from '../math/mat4'; import {Quaternion} from '../math/quaternion'; // Size of primitives const UINT_SIZE = 4; const FLOAT_SIZE = 4; const MAT4_SIZE = 16 * FLOAT_SIZE; const STATIC_BONE_SIZE = 2 * UINT_SIZE + MAT4_SIZE; const VEC3_SIZE = 3 * FLOAT_SIZE; const QUAT_SIZE = 4 * FLOAT_SIZE; const ANIMATED_BONE_SIZE = UINT_SIZE * 7; const POSITION_KEYFRAME_SIZE = FLOAT_SIZE + VEC3_SIZE; const ROTATION_KEYFRAME_SIZE = FLOAT_SIZE + QUAT_SIZE; const SCALING_KEYFRAME_SIZE = FLOAT_SIZE + VEC3_SIZE; const errCodes: Map<number, string> = new Map(); errCodes.set(0, 'Nullptr'); errCodes.set(1, 'DebugMsg'); errCodes.set(2, 'ValueNotFound'); /** * Follow the same logic as the NaiveJSAnimationManager, but in a WASM module. * Notice: Resting memory here will not be zero, because the structs (ModelData, AnimationData) will be * copied to the WASM heap. This is to prevent expensive copies from happening every frame - I want to * simulate a self-contained module here, not just a workhorse for math operations. * If I copy memory over every frame, I suspect (haven't actually checked) that the memory cost will swallow * up any benefits of using WASM. */ export class NaiveWASMAnimationManager extends AnimationManager { private wasmModule: WASMModule|null = null; private exports: any = null; private memory: WebAssembly.Memory|null = null; // Keep a pointer to the next available heap memory // In compilation C++ -> WASM, I noticed that what would be expected to be stack allocations // were being treated as such - e.g.: // // int a; // int b; // &b = &a + sizeof(int) // // However, when memory was then written, it was being written to the same heap memory // contained in this.memory. To mitigate this problem, I've given the WASM code a 1MB "stack". // of heap memory that will not be addressed with this JS malloc implementation. // This is not a general purpose solution, and will NOT fail gracefully in the case of a stack overflow! // Fun fact: googling "webassembly stack overflow" is exceptionally not helpful. private nextMemoryOpen: number = 1024 * 1024; // Where is the next available memory chunk? Notice my paranoia at not starting at 0 ;-) constructor() { super(); this.boneIds.set('RootNode', 0); this.nextBoneId = 1; } private nextBoneId: number = 0; private boneIds: Map<string, number> = new Map(); private animationAddresses: Map<Animation, number> = new Map(); private modelAddresses: Map<ModelData, number> = new Map(); public load() { return fetch('naive.wasm') .then((response) => response.arrayBuffer()) .then((bytes) => WebAssembly.compile(bytes)) .then((wasmModule: WASMModule) => { this.memory = new WebAssembly.Memory({ initial: 512 }); const imports = { env: { memoryBase: 0, tableBase: 0, memory: this.memory, table: new WebAssembly.Table({ initial: 0, element: 'anyfunc' }), _acosf: Math.acos, _sinf: Math.sin, _fmodf: (a: number, b: number) => { return a % b; }, _alertError: (code: number, line: number, extra: number) => { console.error(errCodes.get(code) || '', ' ON LINE ', line, ' EXTRA:: ', extra); } } }; return WebAssembly.instantiate(wasmModule, imports); }) .then((wasmModule) => { this.wasmModule = wasmModule; this.exports = this.wasmModule.exports; (<any>window).wasm = this.wasmModule.exports; return true; }) .catch((err) => { console.error('Failed to load naive WASM module!', err); return false; }); } public registerAnimation(animation: Animation): void { if (!this.memory) { console.error('Could not register animation with naive WASM system, because system is not loaded yet!'); return; } this.registerBones(animation); var pAnimationAddress = this.createAnimationData(animation); this.animationAddresses.set(animation, pAnimationAddress); } public registerModel(model: ModelData): void { if (!this.memory) { console.error('Could not register animation with naive WASM system, because system is not loaded yet!'); return; } if (this.modelAddresses.has(model)) { console.warn('Model already registered in system, will not duplicate'); return; } var pModelAddress = this.createModelData(model); this.modelAddresses.set(model, pModelAddress); } public associateModelAndAnimation(animation: Animation, model: ModelData): boolean { // Since this is initialization-time, we can do this in JavaScript exclusively for (var i = 0; i < model.boneNames.length; i++) { var name = model.boneNames[i]; // TODO SESS: Is it necessary to check both? All of them _should_ be in the static bones... if (!(animation.staticBones.has(name) || animation.animatedBones.has(name))) { console.warn('ASSOCIATION FALIED: Bone', name, 'in model', model, 'missing from animation', animation); return false; } } return true; } public getSingleAnimation(animation: Animation, model: ModelData, animationTime: number): AnimationResult { if (!this.memory || !this.exports) { console.error('Could not register animation with naive WASM system, because system is not loaded yet!'); return new AnimationResult(new Float32Array([]), 0); } if (!this.animationAddresses.has(animation)) { console.error('Unregistered animation'); return new AnimationResult(new Float32Array([]), 0); } if (!this.modelAddresses.has(model)) { console.error('Unregistered model'); return new AnimationResult(new Float32Array([]), 0); } var rsl = new Float32Array(this.memory.buffer, this.nextMemoryOpen, MAT4_SIZE * model.boneNames.length / FLOAT_SIZE); this.exports._getSingleAnimation(this.nextMemoryOpen, this.animationAddresses.get(animation), this.modelAddresses.get(model), animationTime); return new AnimationResult( rsl, 0 // TODO SESS: What actually is the extra memory usage? ); } public getBlendedAnimation(animations: [Animation, Animation], model: ModelData, animationTimes: [number, number], blendFactor: number): AnimationResult { if (!this.memory) return new AnimationResult(new Float32Array([]), 0); this.exports._getBlendedAnimation( this.nextMemoryOpen, this.animationAddresses.get(animations[0]), this.animationAddresses.get(animations[1]), this.modelAddresses.get(model), animationTimes[0], animationTimes[1], blendFactor ); return new AnimationResult(new Float32Array(this.memory.buffer, this.nextMemoryOpen, MAT4_SIZE * model.boneNames.length / FLOAT_SIZE), 0); } public getRestingMemoryUsage(): number { return this.nextMemoryOpen; // How much extra memory for copying everything over to c structures? } // // Helpers // protected malloc(length: number): number { var ptr = this.nextMemoryOpen; this.nextMemoryOpen += length; return ptr; } private createModelData(model: ModelData): number { if (!this.memory) { console.error('Could not serialize model data, WASM module not initialized'); return 0; } var pModelData = this.malloc(UINT_SIZE * 3); var uintView = new Uint32Array(this.memory.buffer, pModelData, UINT_SIZE * 3); uintView[0] = model.boneNames.length; // set boneIds array var pBoneIds = this.malloc(model.boneNames.length * UINT_SIZE); var boneView = new Uint32Array(this.memory.buffer, pBoneIds, model.boneNames.length * UINT_SIZE); for (var idx = 0; idx < model.boneNames.length; idx++) { if (!this.boneIds.has(model.boneNames[idx])) { throw new Error(`ERROR - Tried to serialize model data, could not get bone for ${model.boneNames[idx]}`); } boneView[idx] = this.boneIds.get(model.boneNames[idx]) || 0; } uintView[1] = pBoneIds; // set boneOffsets var pBoneOffsets = this.malloc(model.boneNames.length * MAT4_SIZE); var offsetsView = new Float32Array(this.memory.buffer, pBoneOffsets, model.boneNames.length * MAT4_SIZE); for (var idx = 0; idx < model.boneNames.length; idx++) { offsetsView.set(this.serializeMat4(model.boneOffsets[idx]), idx * 16); } uintView[2] = pBoneOffsets; // set final object return pModelData; } private serializeMat4(mat4: Mat4): Float32Array { return mat4.data; } private serializeQuat(quat: Quaternion): Float32Array { return quat.data; } private registerBones(animation: Animation) { animation.staticBones.forEach((_, key) => { if (!this.boneIds.has(key)) { this.boneIds.set(key, this.nextBoneId++); } }); } private createAnimationData(animation: Animation): number { if (!this.memory) { console.error('Cannot create animation data, WASM module not initialized'); return 0; } animation.staticBones.forEach((_, key) => { if (!this.boneIds.has(key)) { console.error(`Could not serialize animation - static bone key ${key} missing from bone registry`); } }); animation.animatedBones.forEach((_, key) => { if (!this.boneIds.has(key)) { console.error(`Could not serialize animation - animated bone key ${key} missing from bone registry`); } }); var pAnimationData = this.malloc(FLOAT_SIZE + UINT_SIZE * 4); var animationFloatView = new Float32Array(this.memory.buffer, pAnimationData, 1); animationFloatView[0] = animation.duration; var animationUintView = new Uint32Array(this.memory.buffer, pAnimationData + FLOAT_SIZE, 4); animationUintView[0] = animation.staticBones.size; animationUintView[2] = animation.animatedBones.size; // set staticBones var pStaticBones = this.malloc(animation.staticBones.size * STATIC_BONE_SIZE); var idx = 0; animation.staticBones.forEach((bone, name) => { if (!this.memory) return; // For TS type safety, grumble grumble... if (!this.boneIds.has(name)) { console.error('Bone IDs array does not have bone', name, 'in create static bones'); } if (!this.boneIds.has(bone.parent || 'RootNode')) { console.error('Bone IDs array does not have parent node', bone.parent); }; var uintView = new Uint32Array(this.memory.buffer, pStaticBones + idx * STATIC_BONE_SIZE, UINT_SIZE * 2); var floatView = new Float32Array(this.memory.buffer, pStaticBones + idx * STATIC_BONE_SIZE + UINT_SIZE * 2, MAT4_SIZE); uintView[0] = this.boneIds.get(name) || 0; uintView[1] = this.boneIds.get(bone.parent || 'RootNode') || 0; floatView.set(this.serializeMat4(bone.transform)); idx++; }); animationUintView[1] = pStaticBones; // set animatedBones var pAnimatedBones = this.malloc(animation.animatedBones.size * ANIMATED_BONE_SIZE); idx = 0; animation.animatedBones.forEach((bone, name) => { if (!this.memory) return; // For TS type safety, grumble grumble... var uintView = new Uint32Array(this.memory.buffer, pAnimatedBones + idx * ANIMATED_BONE_SIZE, ANIMATED_BONE_SIZE / UINT_SIZE); uintView[0] = this.boneIds.get(name) || 0; uintView[1] = bone.positionChannel.length; uintView[3] = bone.rotationChannel.length; uintView[5] = bone.scalingChannel.length; // set positionChannel var pPositionChannel = this.malloc(bone.positionChannel.length * POSITION_KEYFRAME_SIZE); for (var pidx = 0; pidx < bone.positionChannel.length; pidx++) { var view = new Float32Array(this.memory.buffer, pPositionChannel + pidx * POSITION_KEYFRAME_SIZE, POSITION_KEYFRAME_SIZE / FLOAT_SIZE); view[0] = bone.positionChannel[pidx].time; view.set(bone.positionChannel[pidx].position.data, 1); } // set rotationChannel var pRotationChannel = this.malloc(bone.rotationChannel.length * ROTATION_KEYFRAME_SIZE); for (var ridx = 0; ridx < bone.rotationChannel.length; ridx++) { var view = new Float32Array(this.memory.buffer, pRotationChannel + ridx * ROTATION_KEYFRAME_SIZE, ROTATION_KEYFRAME_SIZE / FLOAT_SIZE); view[0] = bone.rotationChannel[ridx].time; view.set(this.serializeQuat(bone.rotationChannel[ridx].rotation), 1); } // set scaleChannel var pScaleChannel = this.malloc(bone.scalingChannel.length * SCALING_KEYFRAME_SIZE); for (var sidx = 0; sidx < bone.scalingChannel.length; sidx++) { var view = new Float32Array(this.memory.buffer, pScaleChannel + sidx * SCALING_KEYFRAME_SIZE, SCALING_KEYFRAME_SIZE / FLOAT_SIZE); view[0] = bone.scalingChannel[sidx].time; view.set(bone.scalingChannel[sidx].scale.data, 1); } uintView[2] = pPositionChannel; uintView[4] = pRotationChannel; uintView[6] = pScaleChannel; idx++; }); animationUintView[3] = pAnimatedBones; return pAnimationData; } }
the_stack
import { Timezone } from "chronoshift"; import memoizeOne from "memoize-one"; import { $ } from "plywood"; import * as React from "react"; import { CSSTransition } from "react-transition-group"; import { ClientAppSettings } from "../../../common/models/app-settings/app-settings"; import { Clicker } from "../../../common/models/clicker/clicker"; import { ClientCustomization } from "../../../common/models/customization/customization"; import { ClientDataCube } from "../../../common/models/data-cube/data-cube"; import { Device, DeviceSize } from "../../../common/models/device/device"; import { Dimension } from "../../../common/models/dimension/dimension"; import { DragPosition } from "../../../common/models/drag-position/drag-position"; import { Essence, VisStrategy } from "../../../common/models/essence/essence"; import { Filter } from "../../../common/models/filter/filter"; import { SeriesList } from "../../../common/models/series-list/series-list"; import { Series } from "../../../common/models/series/series"; import { Split } from "../../../common/models/split/split"; import { Splits } from "../../../common/models/splits/splits"; import { Stage } from "../../../common/models/stage/stage"; import { TimeShift } from "../../../common/models/time-shift/time-shift"; import { Timekeeper } from "../../../common/models/timekeeper/timekeeper"; import { VisualizationManifest } from "../../../common/models/visualization-manifest/visualization-manifest"; import { VisualizationSettings } from "../../../common/models/visualization-settings/visualization-settings"; import { Binary, Ternary } from "../../../common/utils/functional/functional"; import { Fn } from "../../../common/utils/general/general"; import { maxTimeQuery } from "../../../common/utils/query/max-time-query"; import { datesEqual } from "../../../common/utils/time/time"; import { DimensionMeasurePanel } from "../../components/dimension-measure-panel/dimension-measure-panel"; import { GlobalEventListener } from "../../components/global-event-listener/global-event-listener"; import { PinboardPanel } from "../../components/pinboard-panel/pinboard-panel"; import { Direction, DragHandle, ResizeHandle } from "../../components/resize-handle/resize-handle"; import { SideDrawer } from "../../components/side-drawer/side-drawer"; import { SvgIcon } from "../../components/svg-icon/svg-icon"; import { DruidQueryModal } from "../../modals/druid-query-modal/druid-query-modal"; import { RawDataModal } from "../../modals/raw-data-modal/raw-data-modal"; import { UrlShortenerModal } from "../../modals/url-shortener-modal/url-shortener-modal"; import { ViewDefinitionModal } from "../../modals/view-definition-modal/view-definition-modal"; import { DragManager } from "../../utils/drag-manager/drag-manager"; import * as localStorage from "../../utils/local-storage/local-storage"; import { getVisualizationComponent } from "../../visualizations"; import { CubeContext, CubeContextValue } from "./cube-context"; import { CubeHeaderBar } from "./cube-header-bar/cube-header-bar"; import "./cube-view.scss"; import { DownloadableDatasetProvider } from "./downloadable-dataset-context"; import { PartialTilesProvider } from "./partial-tiles-provider"; const ToggleArrow: React.SFC<{ right: boolean }> = ({ right }) => right ? <SvgIcon svg={require("../../icons/full-caret-small-right.svg")}/> : <SvgIcon svg={require("../../icons/full-caret-small-left.svg")}/>; export interface CubeViewLayout { factPanel: { width: number; hidden?: boolean; }; pinboard: { width: number; hidden?: boolean; }; } const defaultLayout: CubeViewLayout = { factPanel: { width: 240 }, pinboard: { width: 240 } }; export interface CubeViewProps { initTimekeeper?: Timekeeper; maxFilters?: number; hash: string; changeCubeAndEssence: Ternary<ClientDataCube, Essence, boolean, void>; urlForCubeAndEssence: Binary<ClientDataCube, Essence, string>; getEssenceFromHash: Binary<string, ClientDataCube, Essence>; dataCube: ClientDataCube; dataCubes: ClientDataCube[]; openAboutModal: Fn; customization?: ClientCustomization; appSettings: ClientAppSettings; } export interface CubeViewState { essence?: Essence; timekeeper?: Timekeeper; menuStage?: Stage; dragOver?: boolean; showSideBar?: boolean; showRawDataModal?: boolean; showViewDefinitionModal?: boolean; showDruidQueryModal?: boolean; urlShortenerModalProps?: { url: string, title: string }; layout?: CubeViewLayout; deviceSize?: DeviceSize; updatingMaxTime?: boolean; lastRefreshRequestTimestamp: number; } const MIN_PANEL_WIDTH = 240; const MAX_PANEL_WIDTH = 400; const CONTROL_PANEL_HEIGHT = 115; // redefined in .center-top-bar in cube-view.scss export class CubeView extends React.Component<CubeViewProps, CubeViewState> { static defaultProps: Partial<CubeViewProps> = { maxFilters: 20 }; private static canDrop(): boolean { return DragManager.draggingDimension() !== null; } public mounted: boolean; private readonly clicker: Clicker; private container = React.createRef<HTMLDivElement>(); private centerPanel = React.createRef<HTMLDivElement>(); constructor(props: CubeViewProps) { super(props); this.state = { essence: null, dragOver: false, layout: this.getStoredLayout(), lastRefreshRequestTimestamp: 0, updatingMaxTime: false }; this.clicker = { changeFilter: (filter: Filter) => { this.setState(state => { let { essence } = state; essence = essence.changeFilter(filter); return { ...state, essence }; }); }, changeComparisonShift: (timeShift: TimeShift) => { this.setState(state => ({ ...state, essence: state.essence.changeComparisonShift(timeShift) })); }, changeSplits: (splits: Splits, strategy: VisStrategy) => { const { essence } = this.state; this.setState({ essence: essence.changeSplits(splits, strategy) }); }, changeSplit: (split: Split, strategy: VisStrategy) => { const { essence } = this.state; this.setState({ essence: essence.changeSplit(split, strategy) }); }, addSplit: (split: Split, strategy: VisStrategy) => { const { essence } = this.state; this.setState({ essence: essence.addSplit(split, strategy) }); }, removeSplit: (split: Split, strategy: VisStrategy) => { const { essence } = this.state; this.setState({ essence: essence.removeSplit(split, strategy) }); }, changeSeriesList: (seriesList: SeriesList) => { const { essence } = this.state; this.setState({ essence: essence.changeSeriesList(seriesList) }); }, addSeries: (series: Series) => { const { essence } = this.state; this.setState({ essence: essence.addSeries(series) }); }, removeSeries: (series: Series) => { const { essence } = this.state; this.setState({ essence: essence.removeSeries(series) }); }, changeVisualization: (visualization: VisualizationManifest, settings: VisualizationSettings) => { const { essence } = this.state; this.setState({ essence: essence.changeVisualization(visualization, settings) }); }, pin: (dimension: Dimension) => { const { essence } = this.state; this.setState({ essence: essence.pin(dimension) }); }, unpin: (dimension: Dimension) => { const { essence } = this.state; this.setState({ essence: essence.unpin(dimension) }); }, changePinnedSortSeries: (series: Series) => { const { essence } = this.state; this.setState({ essence: essence.changePinnedSortSeries(series) }); } }; } refreshMaxTime = () => { const { essence, timekeeper } = this.state; const { dataCube: { name, executor, timeAttribute, refreshRule } } = essence; this.setState({ updatingMaxTime: true }); maxTimeQuery($(timeAttribute), executor) .then(maxTime => { if (!this.mounted) return; const timeName = name; const isBatchCube = !refreshRule.isRealtime(); const isCubeUpToDate = datesEqual(maxTime, timekeeper.getTime(timeName)); if (isBatchCube && isCubeUpToDate) { this.setState({ updatingMaxTime: false }); return; } this.setState({ timekeeper: timekeeper.updateTime(timeName, maxTime), updatingMaxTime: false, lastRefreshRequestTimestamp: (new Date()).getTime() }); }); }; componentWillMount() { const { hash, dataCube, initTimekeeper } = this.props; if (!dataCube) { throw new Error("Data cube is required."); } this.setState({ timekeeper: initTimekeeper || Timekeeper.EMPTY }); this.updateEssenceFromHashOrDataCube(hash, dataCube); } componentDidMount() { this.mounted = true; DragManager.init(); this.globalResizeListener(); } componentWillReceiveProps(nextProps: CubeViewProps) { const { hash, dataCube } = this.props; if (!nextProps.dataCube) { throw new Error("Data cube is required."); } if (dataCube.name !== nextProps.dataCube.name || hash !== nextProps.hash) { this.updateEssenceFromHashOrDataCube(nextProps.hash, nextProps.dataCube); } } componentWillUpdate(nextProps: CubeViewProps, nextState: CubeViewState): void { const { changeCubeAndEssence, dataCube } = this.props; const { essence } = this.state; if (!nextState.essence.equals(essence)) { changeCubeAndEssence(dataCube, nextState.essence, false); } } componentDidUpdate(prevProps: CubeViewProps, { layout: { pinboard: prevPinboard, factPanel: prevFactPanel } }: CubeViewState) { const { layout: { pinboard, factPanel } } = this.state; if (pinboard.hidden !== prevPinboard.hidden || factPanel.hidden !== prevFactPanel.hidden) { this.globalResizeListener(); } } componentWillUnmount() { this.mounted = false; } updateEssenceFromHashOrDataCube(hash: string, dataCube: ClientDataCube) { let essence: Essence; try { essence = this.getEssenceFromHash(hash, dataCube); } catch (e) { const { changeCubeAndEssence } = this.props; essence = this.getEssenceFromDataCube(dataCube); changeCubeAndEssence(dataCube, essence, true); } this.setState({ essence }); } getEssenceFromDataCube(dataCube: ClientDataCube): Essence { return Essence.fromDataCube(dataCube); } getEssenceFromHash(hash: string, dataCube: ClientDataCube): Essence { if (!dataCube) { throw new Error("Data cube is required."); } if (!hash) { throw new Error("Hash is required."); } const { getEssenceFromHash } = this.props; return getEssenceFromHash(hash, dataCube); } globalResizeListener = () => { this.setState({ deviceSize: Device.getSize(), menuStage: this.container.current && Stage.fromClientRect(this.container.current.getBoundingClientRect()) }); }; private isSmallDevice(): boolean { return this.state.deviceSize === DeviceSize.SMALL; } dragEnter = (e: React.DragEvent<HTMLElement>) => { if (!CubeView.canDrop()) return; e.preventDefault(); this.setState({ dragOver: true }); }; dragOver = (e: React.DragEvent<HTMLElement>) => { if (!CubeView.canDrop()) return; e.preventDefault(); }; dragLeave = () => { this.setState({ dragOver: false }); }; drop = (e: React.DragEvent<HTMLElement>) => { if (!CubeView.canDrop()) return; e.preventDefault(); const dimension = DragManager.draggingDimension(); if (dimension) { this.clicker.changeSplit(Split.fromDimension(dimension), VisStrategy.FairGame); } this.setState({ dragOver: false }); }; openRawDataModal = () => { this.setState({ showRawDataModal: true }); }; onRawDataModalClose = () => { this.setState({ showRawDataModal: false }); }; renderRawDataModal() { const { showRawDataModal, essence, timekeeper } = this.state; const { customization } = this.props; if (!showRawDataModal) return null; return <RawDataModal essence={essence} timekeeper={timekeeper} locale={customization.locale} onClose={this.onRawDataModalClose} />; } openViewDefinitionModal = () => { this.setState({ showViewDefinitionModal: true }); }; onViewDefinitionModalClose = () => { this.setState({ showViewDefinitionModal: false }); }; renderViewDefinitionModal() { const { showViewDefinitionModal, essence } = this.state; if (!showViewDefinitionModal) return null; return <ViewDefinitionModal onClose={this.onViewDefinitionModalClose} essence={essence} />; } openDruidQueryModal = () => { this.setState({ showDruidQueryModal: true }); }; closeDruidQueryModal = () => { this.setState({ showDruidQueryModal: false }); }; renderDruidQueryModal() { const { showDruidQueryModal, essence, timekeeper } = this.state; if (!showDruidQueryModal) return null; return <DruidQueryModal timekeeper={timekeeper} essence={essence} onClose={this.closeDruidQueryModal}/>; } openUrlShortenerModal = (url: string, title: string) => { this.setState({ urlShortenerModalProps: { url, title } }); }; closeUrlShortenerModal = () => { this.setState({ urlShortenerModalProps: null }); }; renderUrlShortenerModal() { const { urlShortenerModalProps } = this.state; if (!urlShortenerModalProps) return null; return <UrlShortenerModal title={urlShortenerModalProps.title} url={urlShortenerModalProps.url} onClose={this.closeUrlShortenerModal}/>; } changeTimezone = (newTimezone: Timezone) => { const { essence } = this.state; const newEssence = essence.changeTimezone(newTimezone); this.setState({ essence: newEssence }); }; getStoredLayout(): CubeViewLayout { return localStorage.get("cube-view-layout-v2") || defaultLayout; } storeLayout(layout: CubeViewLayout) { localStorage.set("cube-view-layout-v2", layout); } private updateLayout(layout: CubeViewLayout) { this.setState({ layout }); this.storeLayout(layout); } toggleFactPanel = () => { const { layout: { factPanel }, layout } = this.state; this.updateLayout({ ...layout, factPanel: { ...factPanel, hidden: !factPanel.hidden } }); }; togglePinboard = () => { const { layout: { pinboard }, layout } = this.state; this.updateLayout({ ...layout, pinboard: { ...pinboard, hidden: !pinboard.hidden } }); }; onFactPanelResize = (width: number) => { const { layout: { factPanel }, layout } = this.state; this.updateLayout({ ...layout, factPanel: { ...factPanel, width } }); }; onPinboardPanelResize = (width: number) => { const { layout: { pinboard }, layout } = this.state; this.updateLayout({ ...layout, pinboard: { ...pinboard, width } }); }; onPanelResizeEnd = () => { this.globalResizeListener(); }; // TODO: Refactor via https://github.com/allegro/turnilo/issues/799 private chartStage(): Stage | null { const { menuStage } = this.state; const { centerPanel: { left, right } } = this.calculateStyles(); if (!menuStage) return null; return menuStage.within({ left, right, top: CONTROL_PANEL_HEIGHT }); } private getCubeContext(): CubeContextValue { const { essence } = this.state; /* React determine context value change using value reference. Because we're creating new object, reference would be different despite same values inside, hence memoization. More info: https://reactjs.org/docs/context.html#caveats */ return this.constructContext(essence, this.clicker); } private urlForEssence = (essence: Essence): string => { const { dataCube, urlForCubeAndEssence } = this.props; return urlForCubeAndEssence(dataCube, essence); } private constructContext = memoizeOne( (essence: Essence, clicker: Clicker) => ({ essence, clicker }), ([nextEssence, nextClicker]: [Essence, Clicker], [prevEssence, prevClicker]: [Essence, Clicker]) => nextEssence.equals(prevEssence) && nextClicker === prevClicker); render() { const clicker = this.clicker; const { customization } = this.props; const { layout, essence, timekeeper, menuStage, dragOver, updatingMaxTime, lastRefreshRequestTimestamp } = this.state; if (!essence) return null; const styles = this.calculateStyles(); const headerBar = <CubeHeaderBar clicker={clicker} essence={essence} timekeeper={timekeeper} onNavClick={this.sideDrawerOpen} urlForEssence={this.urlForEssence} refreshMaxTime={this.refreshMaxTime} openRawDataModal={this.openRawDataModal} openViewDefinitionModal={this.openViewDefinitionModal} openUrlShortenerModal={this.openUrlShortenerModal} openDruidQueryModal={this.openDruidQueryModal} customization={customization} changeTimezone={this.changeTimezone} updatingMaxTime={updatingMaxTime} />; const Visualization = getVisualizationComponent(essence.visualization); return <CubeContext.Provider value={this.getCubeContext()}> <DownloadableDatasetProvider> <div className="cube-view"> <GlobalEventListener resize={this.globalResizeListener}/> {headerBar} <div className="container" ref={this.container}> <PartialTilesProvider>{({ series, filter, addFilter, addSeries, removeTile }) => <React.Fragment> {!layout.factPanel.hidden && <DimensionMeasurePanel style={styles.dimensionMeasurePanel} clicker={clicker} essence={essence} menuStage={menuStage} addPartialFilter={dimension => addFilter(dimension, DragPosition.insertAt(essence.filter.length()))} addPartialSeries={series => addSeries(series, DragPosition.insertAt(essence.series.count()))} />} {!this.isSmallDevice() && !layout.factPanel.hidden && <ResizeHandle direction={Direction.LEFT} value={layout.factPanel.width} onResize={this.onFactPanelResize} onResizeEnd={this.onPanelResizeEnd} min={MIN_PANEL_WIDTH} max={MAX_PANEL_WIDTH} > <DragHandle/> </ResizeHandle>} <div className="center-panel" style={styles.centerPanel} ref={this.centerPanel}> <div className="dimension-panel-toggle" onClick={this.toggleFactPanel}> <ToggleArrow right={layout.factPanel.hidden}/> </div> <Visualization essence={essence} clicker={clicker} timekeeper={timekeeper} stage={this.chartStage()} customization={customization} addSeries={addSeries} addFilter={addFilter} lastRefreshRequestTimestamp={lastRefreshRequestTimestamp} partialFilter={filter} partialSeries={series} removeTile={removeTile} dragEnter={this.dragEnter} dragOver={this.dragOver} isDraggedOver={dragOver} dragLeave={this.dragLeave} drop={this.drop} /> <div className="pinboard-toggle" onClick={this.togglePinboard}> <ToggleArrow right={!layout.pinboard.hidden}/> </div> </div> {!this.isSmallDevice() && !layout.pinboard.hidden && <ResizeHandle direction={Direction.RIGHT} value={layout.pinboard.width} onResize={this.onPinboardPanelResize} onResizeEnd={this.onPanelResizeEnd} min={MIN_PANEL_WIDTH} max={MAX_PANEL_WIDTH} > <DragHandle/> </ResizeHandle>} {!layout.pinboard.hidden && <PinboardPanel style={styles.pinboardPanel} clicker={clicker} essence={essence} timekeeper={timekeeper} refreshRequestTimestamp={lastRefreshRequestTimestamp}/>} </React.Fragment>}</PartialTilesProvider> </div> {this.renderDruidQueryModal()} {this.renderRawDataModal()} {this.renderViewDefinitionModal()} {this.renderUrlShortenerModal()} </div> {this.renderSideDrawer()} </DownloadableDatasetProvider> </CubeContext.Provider>; } sideDrawerOpen = () => { this.setState({ showSideBar: true }); }; sideDrawerClose = () => { this.setState({ showSideBar: false }); }; renderSideDrawer() { const { dataCubes, changeCubeAndEssence, openAboutModal, appSettings } = this.props; const { showSideBar, essence } = this.state; const { customization } = appSettings; const transitionTimeout = { enter: 500, exit: 300 }; return <CSSTransition in={showSideBar} classNames="side-drawer" mountOnEnter={true} unmountOnExit={true} timeout={transitionTimeout} > <SideDrawer key="drawer" essence={essence} dataCubes={dataCubes} onOpenAbout={openAboutModal} onClose={this.sideDrawerClose} customization={customization} changeDataCubeAndEssence={changeCubeAndEssence} /> </CSSTransition>; } private calculateStyles() { const { layout } = this.state; const isDimensionPanelHidden = layout.factPanel.hidden; const isPinboardHidden = layout.pinboard.hidden; if (this.isSmallDevice()) { const dimensionsWidth = isDimensionPanelHidden ? 0 : 200; const pinboardWidth = isPinboardHidden ? 0 : 200; return { dimensionMeasurePanel: { width: dimensionsWidth }, centerPanel: { left: dimensionsWidth, right: pinboardWidth }, pinboardPanel: { width: pinboardWidth } }; } const nonSmallLayoutPadding = 10; return { dimensionMeasurePanel: { width: isDimensionPanelHidden ? 0 : layout.factPanel.width }, centerPanel: { left: isDimensionPanelHidden ? nonSmallLayoutPadding : layout.factPanel.width, right: isPinboardHidden ? nonSmallLayoutPadding : layout.pinboard.width }, pinboardPanel: { width: isPinboardHidden ? 0 : layout.pinboard.width } }; } }
the_stack
import { isFileModuleRef, isPackageModuleRef, parseModuleRef, } from "@rnx-kit/tools-node"; import path from "path"; import ts from "typescript"; import { ExtensionsJavaScript, ExtensionsJSON, ExtensionsTypeScript, } from "./extension"; import { changeModuleResolutionHostToLogFileSystemReads, logModuleBegin, logModuleEnd, ResolverLog, ResolverLogMode, } from "./log"; import { createReactNativePackageNameReplacer } from "./react-native-package-name"; import { resolveFileModule, resolvePackageModule } from "./resolve"; import type { ResolverContext, ModuleResolutionHostLike } from "./types"; /** * Change the TypeScript `CompilerHost` or `LanguageServiceHost` so it makes * use of react-native module resolution. * * This includes binding the `trace` method to a react-native trace logger. * The logger is active when the compiler option `traceResolution` is true, or * when react-native error tracing is enabled. All file and directory reads * are logged, making it easy to see what the resolver is doing. * * @param host Compiler host or language service host * @param options Compiler options * @param platform Target platform * @param platformExtensionNames Optional list of platform file extensions, from highest precedence (index 0) to lowest. Example: `["ios", "mobile", "native"]`. * @param disableReactNativePackageSubstitution Flag to prevent substituting the module name `react-native` with the target platform's out-of-tree NPM package implementation. For example, on Windows, devs expect `react-native` to implicitly refer to `react-native-windows`. * @param traceReactNativeModuleResolutionErrors Flag to enable trace logging when a resolver error occurs. All messages involved in the failed module resolution are aggregated and logged. * @param traceResolutionLog Optional file to use for logging trace message. When not present, log messages go to the console. */ export function changeHostToUseReactNativeResolver({ host, options, platform, platformExtensionNames, disableReactNativePackageSubstitution, traceReactNativeModuleResolutionErrors, traceResolutionLog, }: { host: ts.CompilerHost | ts.LanguageServiceHost; options: ts.ParsedCommandLine["options"]; platform: string; platformExtensionNames: string[] | undefined; disableReactNativePackageSubstitution: boolean; traceReactNativeModuleResolutionErrors: boolean; traceResolutionLog: string | undefined; }): void { // Ensure that optional methods have an implementation so they can be hooked // for logging, and so we can use them in the resolver. host.directoryExists = host.directoryExists ?? ts.sys.directoryExists; host.realpath = host.realpath ?? ts.sys.realpath; host.getDirectories = host.getDirectories ?? ts.sys.getDirectories; let mode = ResolverLogMode.Never; if (options.traceResolution) { mode = ResolverLogMode.Always; } else if (traceReactNativeModuleResolutionErrors) { mode = ResolverLogMode.OnFailure; } const log = new ResolverLog(mode, traceResolutionLog); if (mode !== ResolverLogMode.Never) { host.trace = log.log.bind(log); changeModuleResolutionHostToLogFileSystemReads( host as ModuleResolutionHostLike ); } const context: ResolverContext = { host: host as ModuleResolutionHostLike, options, disableReactNativePackageSubstitution, log, platform, platformExtensions: [platform, ...(platformExtensionNames || [])].map( (e) => `.${e}` // prepend a '.' to each name to make it a file extension ), replaceReactNativePackageName: createReactNativePackageNameReplacer( host.getCurrentDirectory(), platform, disableReactNativePackageSubstitution, log ), }; host.resolveModuleNames = resolveModuleNames.bind(undefined, context); host.resolveTypeReferenceDirectives = resolveTypeReferenceDirectives.bind( undefined, context ); } /** * Resolve a module for a TypeScript program. Prefer type (.d.ts) files and * TypeScript source (.ts[x]) files, as they usually carry more type * information than JavaScript source (.js[x]) files. * * @param context Resolver context * @param moduleName Module name, as listed in the require/import statement * @param containingFile File from which the module was required/imported * @param extensions List of allowed file extensions to use when resolving the module to a file * @returns Resolved module information, or `undefined` if resolution failed. */ export function resolveModuleName( context: ResolverContext, moduleName: string, containingFile: string, extensions: ts.Extension[] ): ts.ResolvedModuleFull | undefined { let module: ts.ResolvedModuleFull | undefined = undefined; const moduleRef = parseModuleRef(moduleName); const searchDir = path.dirname(containingFile); if (isPackageModuleRef(moduleRef)) { module = resolvePackageModule(context, moduleRef, searchDir, extensions); } else if (isFileModuleRef(moduleRef)) { module = resolveFileModule(context, moduleRef, searchDir, extensions); } if (module) { module.isExternalLibraryImport = /[/\\]node_modules[/\\]/.test( module.resolvedFileName ); const { host, options } = context; if (host.realpath && !options.preserveSymlinks) { const resolvedFileName = host.realpath(module.resolvedFileName); const originalPath = resolvedFileName === module.resolvedFileName ? undefined : module.resolvedFileName; Object.assign(module, { resolvedFileName, originalPath }); } } return module; } /** * Resolve a set of modules for a TypeScript program, all referenced from a * single containing file. Prefer type (.d.ts) files and TypeScript source * (.ts[x]) files, as they usually carry more type information than JavaScript * source (.js[x]) files. * * @param context Resolver context * @param moduleNames List of module names, as they appear in each require/import statement * @param containingFile File from which the modules were all required/imported * @returns Array of results. Each entry will have resolved module information, or will be `undefined` if resolution failed. The array will have one element for each entry in the module name list. */ export function resolveModuleNames( context: ResolverContext, moduleNames: string[], containingFile: string, _reusedNames: string[] | undefined, _redirectedReference?: ts.ResolvedProjectReference ): (ts.ResolvedModuleFull | undefined)[] { const { options, log, replaceReactNativePackageName } = context; const resolutions: (ts.ResolvedModuleFull | undefined)[] = []; for (const moduleName of moduleNames) { logModuleBegin(log, moduleName, containingFile); const finalModuleName = replaceReactNativePackageName(moduleName); // First, try to resolve the module to a TypeScript file. Then, fall back // to looking for a JavaScript file. Finally, if JSON modules are allowed, // try resolving to one of them. log.log( "Searching for module '%s' with target file type 'TypeScript'", finalModuleName ); let module = resolveModuleName( context, finalModuleName, containingFile, ExtensionsTypeScript ); if (!module) { log.log( "Searching for module '%s' with target file type 'JavaScript'", finalModuleName ); module = resolveModuleName( context, finalModuleName, containingFile, ExtensionsJavaScript ); if (!module && options.resolveJsonModule) { log.log( "Searching for module '%s' with target file type 'JSON'", finalModuleName ); module = resolveModuleName( context, finalModuleName, containingFile, ExtensionsJSON ); } } resolutions.push(module); logModuleEnd(log, options, moduleName, module); } return resolutions; } /** * Resolve a set of type references for a TypeScript program. * * A type reference typically originates from a triple-slash directive: * * `/// <reference path="...">` * `/// <reference types="...">` * `/// <reference lib="...">` * * Type references also come from the `compilerOptions.types` property in * `tsconfig.json`: * * `types: ["node", "jest"]` * * @param context Resolver context * @param typeDirectiveNames List of type names, as they appear in each type reference directive * @param containingFile File from which the type names were all referenced * @param redirectedReference Head node in the program's graph of type references * @returns Array of results. Each entry will have resolved type information, or will be `undefined` if resolution failed. The array will have one element for each entry in the type name list. */ export function resolveTypeReferenceDirectives( context: ResolverContext, typeDirectiveNames: string[], containingFile: string, redirectedReference?: ts.ResolvedProjectReference ): (ts.ResolvedTypeReferenceDirective | undefined)[] { const { host, options, log } = context; const resolutions: (ts.ResolvedTypeReferenceDirective | undefined)[] = []; for (const typeDirectiveName of typeDirectiveNames) { // TypeScript only emits trace messages when traceResolution is enabled. // Our code, however, can emit even when traceResolution is disabled. We // have the "emit only errors" mode. This includes the file-system reads // we hooked on the module-resolution host. // // We don't want to see those file-system read messages without the // larger context of TypeScript's trace messages. So, for type directives, // we can only log successes AND failures when traceResolution is enabled. // if (options.traceResolution) { log.begin(); } const { resolvedTypeReferenceDirective: directive } = ts.resolveTypeReferenceDirective( typeDirectiveName, containingFile, options, host, redirectedReference ); resolutions.push(directive); if (options.traceResolution) { if (directive) { log.endSuccess(); } else { log.endFailure(); } } } return resolutions; }
the_stack
import { parse } from 'pathington'; const O = Object; const { create, getOwnPropertySymbols, getPrototypeOf, keys, propertyIsEnumerable } = O; const { isArray } = Array; type ToString = (value: any) => string; const toStringFunction: ToString = Function.prototype.bind.call( Function.prototype.call, Function.prototype.toString, ); const toStringObject: ToString = Function.prototype.bind.call( Function.prototype.call, O.prototype.toString, ); /** * @constant HAS_SYMBOL_SUPPORT are Symbols supported */ const HAS_SYMBOL_SUPPORT = typeof Symbol === 'function' && typeof Symbol.for === 'function'; /** * @constant REACT_ELEMENT the symbol / number specific to react elements */ const REACT_ELEMENT: symbol | number = HAS_SYMBOL_SUPPORT ? Symbol.for('react.element') : 0xeac7; /** * @function cloneArray * * @description * clone an array to a new array * * @param array the array to clone * @returns the cloned array */ export const cloneArray = (array: any[]): any[] => { const Constructor = array.constructor as ArrayConstructor; const cloned = Constructor === Array ? [] : new Constructor(); for (let index = 0, length = array.length; index < length; index++) { cloned[index] = array[index]; } return cloned; }; /** * @function reduce * * @description * a targeted reduce method faster than the native * * @param array the array to reduce * @param fn the method to reduce each array value with * @param initialValue the initial value of the reduction * @returns the reduced value */ export const reduce = ( array: any[], fn: (accum: any, value: any) => any, initialValue: any, ): any => { let value = initialValue; for (let index = 0, length = array.length; index < length; index++) { value = fn(value, array[index]); } return value; }; /** * @function getOwnProperties * * @description * get the all properties (keys and symbols) of the object passed * * @param object the object to get the properties of * @returns the keys and symbols the object has */ export const getOwnProperties = (object: unchanged.Unchangeable): (string | symbol)[] => { if (!HAS_SYMBOL_SUPPORT) { return keys(object); } const ownSymbols: symbol[] = getOwnPropertySymbols(object); if (!ownSymbols.length) { return keys(object); } return keys(object).concat( reduce( ownSymbols, (enumerableSymbols: symbol[], symbol: symbol): symbol[] => { if (propertyIsEnumerable.call(object, symbol)) { enumerableSymbols.push(symbol); } return enumerableSymbols; }, [], ), ); }; /** * @function assignFallback * * @description * a targeted fallback if native Object.assign is unavailable * * @param target the object to shallowly merge into * @param source the object to shallowly merge into target * @returns the shallowly merged object */ export const assignFallback = ( target: unchanged.Unchangeable, source: unchanged.Unchangeable, ): unchanged.Unchangeable => { if (!source) { return target; } return reduce( getOwnProperties(source), (clonedObject: unchanged.Unchangeable, property: string) => { clonedObject[property] = source[property]; return clonedObject; }, Object(target), ); }; const assign = typeof O.assign === 'function' ? O.assign : assignFallback; /** * @function createWithProto * * @description * create a new object with the prototype of the object passed * * @param object object whose prototype will be the new object's prototype * @returns object with the prototype of the one passed */ export const createWithProto = (object: unchanged.Unchangeable): unchanged.Unchangeable => create(object.__proto__ || getPrototypeOf(object)); /** * @function isCloneable * * @description * is the object passed considered cloneable * * @param object the object that is being checked for cloneability * @returns whether the object can be cloned */ export const isCloneable = (object: any) => { if (!object || typeof object !== 'object' || object.$$typeof === REACT_ELEMENT) { return false; } const type = toStringObject(object); return type !== '[object Date]' && type !== '[object RegExp]'; }; /** * @function isEmptyPath * * @description * is the path passed an empty path * * @param path the path to check for emptiness * @returns whether the path passed is considered empty */ export const isEmptyPath = (path: any) => path == null || (isArray(path) && !path.length); /** * @function isGlobalConstructor * * @description * is the fn passed a global constructor * * @param fn the fn to check if a global constructor * @returns whether the fn passed is a global constructor */ export const isGlobalConstructor = (fn: any) => typeof fn === 'function' && !!~toStringFunction(fn).indexOf('[native code]'); /** * @function callIfFunction * * @description * if the object passed is a function, call it and return its return, else return undefined * * @param object the object to call if a function * @param context the context to call the function with * @param parameters the parameters to call the function with * @returns the result of the function call, or undefined */ export const callIfFunction = (object: any, context: any, parameters: any[]) => typeof object === 'function' ? object.apply(context, parameters) : void 0; /** * @function getNewEmptyChild * * @description * get a new empty child object based on the key passed * * @param key the key to base the empty child on * @returns the empty object the child is built from */ export const getNewEmptyChild = (key: any): unchanged.Unchangeable => typeof key === 'number' ? [] : {}; /** * @function getNewEmptyObject * * @description * get a new empty object based on the object passed * * @param object the object to base the empty object on * @returns an empty version of the object passed */ export const getNewEmptyObject = (object: unchanged.Unchangeable): unchanged.Unchangeable => isArray(object) ? [] : {}; /** * @function getShallowClone * * @description * create a shallow clone of the object passed, respecting its prototype * * @param object the object to clone * @returns a shallow clone of the object passed */ export const getShallowClone = (object: unchanged.Unchangeable): unchanged.Unchangeable => { if (object.constructor === O) { return assign({}, object); } if (isArray(object)) { return cloneArray(object); } return isGlobalConstructor(object.constructor) ? {} : assign(createWithProto(object), object); }; /** * @function isSameValueZero * * @description * are the values equal based on SameValueZero * * @param value1 the first value to test * @param value2 the second value to test * @returns are the two values passed equal based on SameValueZero */ export const isSameValueZero = (value1: any, value2: any) => value1 === value2 || (value1 !== value1 && value2 !== value2); /** * @function cloneIfPossible * * @description * clone the object if it can be cloned, otherwise return the object itself * * @param object the object to clone * @returns a cloned version of the object, or the object itself if not cloneable */ export const cloneIfPossible = (object: any) => isCloneable(object) ? getShallowClone(object) : object; /** * @function getCloneOrEmptyObject * * @description * if the object is cloneable, get a clone of the object, else get a new * empty child object based on the key * * @param object the object to clone * @param nextKey the key to base the empty child object on * @returns a clone of the object, or an empty child object */ export const getCloneOrEmptyObject = ( object: unchanged.Unchangeable, nextKey: any, ): unchanged.Unchangeable => isCloneable(object) ? getShallowClone(object) : getNewEmptyChild(nextKey); /** * @function getCoalescedValue * * @description * return the value if not undefined, otherwise return the fallback value * * @param value the value to coalesce if undefined * @param fallbackValue the value to coalesce to * @returns the coalesced value */ export const getCoalescedValue = (value: any, fallbackValue: any) => value === void 0 ? fallbackValue : value; /** * @function getParsedPath * * @description * parse the path passed into an array path * * @param path the path to parse * @returns the parsed path */ export const getParsedPath = (path: unchanged.Path): unchanged.ParsedPath => isArray(path) ? path : parse(path); /** * @function getCloneAtPath * * @description * get a new object, cloned at the path specified while leveraging * structural sharing for the rest of the properties * * @param path the path to clone at * @param object the object with cloned children at path * @param onMatch the method to call once the end of the path is reached * @param index the path index * @returns the object deeply cloned at the path specified */ export const getCloneAtPath = ( path: unchanged.ParsedPath, object: unchanged.Unchangeable, onMatch: (object: unchanged.Unchangeable, key: unchanged.PathItem) => any, index: number, ) => { const key = path[index]; const nextIndex = index + 1; if (nextIndex === path.length) { onMatch(object, key); } else { object[key] = getCloneAtPath( path, getCloneOrEmptyObject(object[key], path[nextIndex]), onMatch, nextIndex, ); } return object; }; /** * @function getDeepClone * * @description * get a clone of the object at the path specified * * @param path the path to clone at * @param object the object to clone at the path * @param onMatch once a patch match is found, the callback to fire * @returns the clone of the object at path specified */ export const getDeepClone = ( path: unchanged.Path, object: unchanged.Unchangeable, onMatch: (object: unchanged.Unchangeable, key: unchanged.PathItem) => any, ): unchanged.Unchangeable => { const parsedPath = getParsedPath(path); const topLevelClone = getCloneOrEmptyObject(object, parsedPath[0]); if (parsedPath.length === 1) { onMatch(topLevelClone, parsedPath[0]); return topLevelClone; } return getCloneAtPath(parsedPath, topLevelClone, onMatch, 0); }; /** * @function getMergedObject * * @description * merge the source into the target, either deeply or shallowly * * @param target the object to merge into * @param source the object being merged into the target * @param isDeep is the merge a deep merge * @returns the merged object */ export const getMergedObject = ( target: unchanged.Unchangeable, source: unchanged.Unchangeable, isDeep: boolean, ): unchanged.Unchangeable => { const isObject1Array: boolean = isArray(target); if (isObject1Array !== isArray(source) || !isCloneable(target)) { return cloneIfPossible(source); } if (isObject1Array) { return target.concat(source); } const targetClone: unchanged.Unchangeable = target.constructor === O || isGlobalConstructor(target.constructor) ? {} : createWithProto(target); return reduce( getOwnProperties(source), (clone: unchanged.Unchangeable, key: string): unchanged.Unchangeable => { clone[key] = isDeep && isCloneable(source[key]) ? getMergedObject(target[key], source[key], isDeep) : source[key]; return clone; }, assign(targetClone, target), ); }; /** * @function getValueAtPath * * @description * get the value at the nested property, or the fallback provided * * @param path the path to get the value from * @param object the object to get the value from at path * @param noMatchValue the value returned if no match is found * @returns the matching value, or the fallback provided */ export const getValueAtPath = ( path: unchanged.Path, object: unchanged.Unchangeable, noMatchValue?: any, ) => { const parsedPath = getParsedPath(path); if (parsedPath.length === 1) { return object ? getCoalescedValue(object[parsedPath[0]], noMatchValue) : noMatchValue; } let ref: any = object; let key: number | string = parsedPath[0]; for (let index: number = 0; index < parsedPath.length - 1; index++) { if (!ref || !ref[key]) { return noMatchValue; } ref = ref[key]; key = parsedPath[index + 1]; } return ref ? getCoalescedValue(ref[key], noMatchValue) : noMatchValue; }; /** * @function getFullPath * * @description * get the path to add to, based on the object and fn passed * * @param path the path to add to * @param object the object traversed by the path * @param fn the function to transform the retrieved value with * @returns the full path to add to */ export const getFullPath = ( path: unchanged.Path, object: unchanged.Unchangeable, fn?: (value: any) => any, ): unchanged.Path => { const isPathEmpty: boolean = isEmptyPath(path); const valueAtPath: any = isPathEmpty ? object : fn ? fn(getValueAtPath(path, object)) : getValueAtPath(path, object); return isArray(valueAtPath) ? isArray(path) ? path.concat([valueAtPath.length]) : `${isPathEmpty ? '' : path}[${valueAtPath.length}]` : path; }; /** * @function splice * * @description * a faster, more targeted version of the native splice * * @param array the array to remove the value from * @param splicedIndex the index of the value to remove */ export const splice = (array: any[], splicedIndex: number): void => { if (array.length) { const cutoff = array.length - 1; let index = splicedIndex; while (index < cutoff) { array[index] = array[index + 1]; ++index; } array.length = cutoff; } }; /** * @function throwInvalidFnError * * @description * throw the TypeError based on the invalid handler * * @throws */ export const throwInvalidFnError = (): never => { throw new TypeError('handler passed is not of type "function".'); };
the_stack
import React, {useState, useEffect} from "react"; import {Form, Input, Icon, Select} from "antd"; import styles from "./create-edit-load.module.scss"; import {srcOptions, tgtOptions, fieldSeparatorOptions} from "../../../config/formats.config"; import StepsConfig from "../../../config/steps.config"; import {NewLoadTooltips} from "../../../config/tooltips.config"; import {MLButton, MLTooltip} from "@marklogic/design-system"; interface Props { tabKey: string; openStepSettings: boolean; setOpenStepSettings: any; isEditing: boolean; canReadWrite: boolean; canReadOnly: boolean; createLoadArtifact: any; updateLoadArtifact: any; stepData: any; currentTab: string; setIsValid: any; resetTabs: any; setHasChanged: any; setPayload: any; onCancel: any; } const CreateEditLoad: React.FC<Props> = (props) => { const [stepName, setStepName] = useState(props.stepData && props.stepData !== {} ? props.stepData.name : ""); const [description, setDescription] = useState(props.stepData && props.stepData !== {} ? props.stepData.description : ""); const [srcFormat, setSrcFormat] = useState(props.stepData && props.stepData !== {} ? props.stepData.sourceFormat : StepsConfig.defaultSourceFormat); const [tgtFormat, setTgtFormat] = useState(props.stepData && props.stepData !== {} ? props.stepData.targetFormat : StepsConfig.defaultTargetFormat); const [sourceName, setSourceName] = useState(props.stepData && props.stepData !== {} ? props.stepData.sourceName : ""); const [sourceType, setSourceType] = useState(props.stepData && props.stepData !== {} ? props.stepData.sourceType : ""); const [outputUriPrefix, setOutputUriPrefix] = useState(props.stepData && props.stepData !== {} ? props.stepData.outputURIPrefix : ""); const [fieldSeparator, setFieldSeparator] = useState(props.stepData && props.stepData !== {} ? props.stepData.fieldSeparator : StepsConfig.defaultFieldSeparator); const [otherSeparator, setOtherSeparator] = useState(""); //To check submit validity const [isStepNameTouched, setStepNameTouched] = useState(false); const [isDescriptionTouched, setDescriptionTouched] = useState(false); const [isSrcFormatTouched, setSrcFormatTouched] = useState(false); const [isTgtFormatTouched, setTgtFormatTouched] = useState(false); const [isSourceNameTouched, setSourceNameTouched] = useState(false); const [isSourceTypeTouched, setSourceTypeTouched] = useState(false); const [isOutputUriPrefixTouched, setOutputUriPrefixTouched] = useState(false); const [isFieldSeparatorTouched, setFieldSeparatorTouched] = useState(false); const [isOtherSeparatorTouched, setOtherSeparatorTouched] = useState(false); const [isValid, setIsValid] = useState(false); // eslint-disable-line @typescript-eslint/no-unused-vars const [invalidChars, setInvalidChars] = useState(false); const [tobeDisabled, setTobeDisabled] = useState(false); const initStep = () => { setStepName(props.stepData.name); setDescription(props.stepData.description); setSrcFormat(props.stepData.sourceFormat); if (props.stepData.separator) { if ([",", "\\t", "|", ";"].includes(props.stepData.separator)) { setFieldSeparator(props.stepData.separator); } else { setFieldSeparator("Other"); setOtherSeparator(props.stepData.separator); } } setTgtFormat(props.stepData.targetFormat); setOutputUriPrefix(props.stepData.outputURIPrefix); setIsValid(true); props.setIsValid(true); setTobeDisabled(true); setDescriptionTouched(false); setSrcFormatTouched(false); setTgtFormatTouched(false); setSourceNameTouched(false); setSourceTypeTouched(false); setOutputUriPrefixTouched(false); }; useEffect(() => { // Edit step if (props.stepData && JSON.stringify(props.stepData) !== JSON.stringify({}) && props.isEditing) { initStep(); } else { // New step setStepName(""); setStepNameTouched(false); setDescription(""); setDescriptionTouched(false); setSrcFormat(StepsConfig.defaultSourceFormat); setSrcFormatTouched(false); setFieldSeparator(StepsConfig.defaultFieldSeparator); setFieldSeparatorTouched(false); setOtherSeparator(""); setOtherSeparatorTouched(false); setTgtFormat(StepsConfig.defaultTargetFormat); setTgtFormatTouched(false); setSourceName(""); setSourceNameTouched(false); setSourceType(""); setSourceTypeTouched(false); setOutputUriPrefix(""); setOutputUriPrefixTouched(false); setIsValid(false); props.setIsValid(false); } // Reset return (() => { setStepName(""); setStepNameTouched(false); setDescription(""); setDescriptionTouched(false); setSrcFormat(StepsConfig.defaultSourceFormat); setSrcFormatTouched(false); setFieldSeparator(StepsConfig.defaultFieldSeparator); setFieldSeparatorTouched(false); setOtherSeparator(""); setOtherSeparatorTouched(false); setTgtFormat(StepsConfig.defaultTargetFormat); setTgtFormatTouched(false); setSourceName(""); setSourceNameTouched(false); setSourceType(""); setSourceTypeTouched(false); setOutputUriPrefix(""); setOutputUriPrefixTouched(false); setTobeDisabled(false); }); }, [props.stepData, props.isEditing]); const onCancel = () => { // Parent checks changes across tabs props.onCancel(); }; /* sends payload to steps.tsx */ const sendPayload = () => { props.setHasChanged(hasFormChanged()); props.setPayload(getPayload()); }; const hasFormChanged = () => { if (!isStepNameTouched && !isDescriptionTouched && !isSrcFormatTouched && !isTgtFormatTouched && !isSourceNameTouched && !isSourceTypeTouched && !isOutputUriPrefixTouched && !isFieldSeparatorTouched && !isOtherSeparatorTouched ) { return false; } else { return true; } }; const getPayload = () => { let result; if (srcFormat === "csv") { result = { name: stepName, description: description, sourceFormat: srcFormat, separator: fieldSeparator === "Other"? otherSeparator : fieldSeparator, targetFormat: tgtFormat, sourceName: sourceName, sourceType: sourceType, outputURIPrefix: outputUriPrefix, }; } else { result = { name: stepName, description: description, sourceFormat: srcFormat, targetFormat: tgtFormat, sourceName: sourceName, sourceType: sourceType, outputURIPrefix: outputUriPrefix }; if (props.stepData.separator) { result.separator = null; } } return result; }; const handleSubmit = (event: { preventDefault: () => void; }) => { if (!stepName || invalidChars) { // missing name setStepNameTouched(true); event.preventDefault(); return; } // else: submit handle if (event) event.preventDefault(); setIsValid(true); props.setIsValid(true); if (!props.isEditing) { props.createLoadArtifact(getPayload()); } else { props.updateLoadArtifact(getPayload()); } props.setOpenStepSettings(false); props.resetTabs(); }; const handleChange = (event) => { if (event.target.id === "name") { let isSpecialChars = false; if (event.target.value === " ") { setStepNameTouched(false); } else { setStepNameTouched(true); setStepName(event.target.value); //check value does not contain special chars and leads with a letter if (event.target.value !== "" && !(/^[a-zA-Z][a-zA-Z0-9\-_]*$/g.test(event.target.value))) { setInvalidChars(true); isSpecialChars = true; } else { setInvalidChars(false); } if (event.target.value.length === 0 || isSpecialChars) { setIsValid(false); props.setIsValid(false); } else if (srcFormat && tgtFormat) { setIsValid(true); props.setIsValid(true); } } } if (event.target.id === "description") { if (event.target.value === " ") { setDescriptionTouched(false); } else { setDescriptionTouched(true); setDescription(event.target.value); if (props.stepData && props.stepData.description) { if (event.target.value === props.stepData.description) { setDescriptionTouched(false); } } if (!props.isEditing) { if (event.target.value === "") { setDescriptionTouched(false); } } } } if (event.target.id === "sourceName") { if (event.target.value === " ") { setSourceNameTouched(false); } else { setSourceNameTouched(true); setSourceName(event.target.value); if (props.stepData && props.stepData.sourceName) { if (event.target.value === props.stepData.sourceName) { setSourceNameTouched(false); } } if (!props.isEditing) { if (event.target.value === "") { setSourceNameTouched(false); } } } } if (event.target.id === "sourceType") { if (event.target.value === " ") { setSourceTypeTouched(false); } else { setSourceTypeTouched(true); setSourceType(event.target.value); if (props.stepData && props.stepData.sourceType) { if (event.target.value === props.stepData.sourceType) { setSourceTypeTouched(false); } } if (!props.isEditing) { if (event.target.value === "") { setSourceTypeTouched(false); } } } } }; const handleOutputUriPrefix = (event) => { if (event.target.id === "outputUriPrefix") { if (event.target.value === " ") { setOutputUriPrefixTouched(false); } else { setOutputUriPrefixTouched(true); setOutputUriPrefix(event.target.value); if (props.stepData && props.stepData.outputURIPrefix) { if (event.target.value === props.stepData.outputURIPrefix) { setOutputUriPrefixTouched(false); } } if (!props.isEditing) { if (event.target.value === "") { setOutputUriPrefixTouched(false); } } } } }; const handleSrcFormat = (value) => { if (value === " ") { setSrcFormatTouched(false); } else { setSrcFormatTouched(true); setSrcFormat(value); if (props.stepData && props.stepData.srcFormat) { if (value === props.stepData.srcFormat) { setSrcFormatTouched(false); } } if (!props.isEditing) { if (value === "") { setSrcFormatTouched(false); } } if (value === "csv") { setFieldSeparator(StepsConfig.defaultFieldSeparator); } } }; const handleFieldSeparator = (value) => { if (value === " ") { setFieldSeparatorTouched(false); } else { setFieldSeparatorTouched(true); setFieldSeparator(value); if (value === "Other") { setOtherSeparator(""); } if (props.stepData && props.stepData.fieldSeparator) { if (value === props.stepData.fieldSeparator) { setFieldSeparatorTouched(false); } } if (!props.isEditing) { if (value === StepsConfig.defaultFieldSeparator) { setFieldSeparatorTouched(false); } } } }; const handleOtherSeparator = (event) => { if (event.target.value === " ") { setOtherSeparatorTouched(false); } else { setOtherSeparatorTouched(true); setOtherSeparator(event.target.value); if (props.stepData && props.stepData.fieldSeparator) { if (event.target.value === props.stepData.fieldSeparator) { setOtherSeparatorTouched(false); } } if (!props.isEditing) { if (event.target.value === "") { setOtherSeparatorTouched(false); } } } }; const handleTgtFormat = (value) => { if (value === " ") { setTgtFormatTouched(false); } else { setTgtFormatTouched(true); setTgtFormat(value); if (props.stepData && props.stepData.tgtFormat) { if (value === props.stepData.tgtFormat) { setTgtFormatTouched(false); } } if (!props.isEditing) { if (value === "") { setTgtFormatTouched(false); } } if (value !== "json" && value !== "xml") { setSourceName(""); setSourceType(""); } } }; const formItemLayout = { labelCol: { xs: {span: 24}, sm: {span: 7}, }, wrapperCol: { xs: {span: 28}, sm: {span: 15}, }, }; const soptions = Object.keys(srcOptions).map(d => <Select.Option key={srcOptions[d]}>{d}</Select.Option>); const fsoptions = Object.keys(fieldSeparatorOptions).map(d => <Select.Option key={fieldSeparatorOptions[d]}>{d}</Select.Option>); const toptions = Object.keys(tgtOptions).map(d => <Select.Option key={tgtOptions[d]}>{d}</Select.Option>); return ( <div className={styles.newDataLoadForm}> <div className={styles.newLoadCardTitle} aria-label={"newLoadCardTitle"}>Configure the new Loading step. Then, add the new step to a flow and run it to load your data.</div> <Form {...formItemLayout} onSubmit={handleSubmit} colon={false}> <Form.Item label={<span> Name:&nbsp;<span className={styles.asterisk}>*</span>&nbsp; &nbsp; </span>} labelAlign="left" validateStatus={(stepName || !isStepNameTouched) ? (invalidChars ? "error" : "") : "error"} help={invalidChars ? "Names must start with a letter and can contain letters, numbers, hyphens, and underscores only." : (stepName || !isStepNameTouched) ? "" : "Name is required"} > { tobeDisabled?<MLTooltip title={NewLoadTooltips.nameField} placement={"bottom"}> <Input id="name" placeholder="Enter name" value={stepName} onChange={handleChange} disabled={tobeDisabled} className={styles.input} onBlur={sendPayload} /></MLTooltip>:<Input id="name" placeholder="Enter name" value={stepName} onChange={handleChange} disabled={tobeDisabled} className={styles.input} onBlur={sendPayload} />} &nbsp;&nbsp;<MLTooltip title={NewLoadTooltips.name} placement={"right"}> <Icon type="question-circle" className={styles.questionCircle} theme="filled" /> </MLTooltip> </Form.Item> <Form.Item label={<span> Description:&nbsp; </span>} labelAlign="left"> <Input id="description" placeholder="Enter description" value={description} onChange={handleChange} disabled={props.canReadOnly && !props.canReadWrite} className={styles.input} onBlur={sendPayload} />&nbsp;&nbsp;<MLTooltip title={NewLoadTooltips.description} placement={"right"}> <Icon type="question-circle" className={styles.questionCircle} theme="filled" /> </MLTooltip> </Form.Item> <Form.Item label={<span> Source Format:&nbsp;<span className={styles.asterisk}>*</span>&nbsp; </span>} labelAlign="left"> <Select id="sourceFormat" showSearch placeholder="Enter source format" optionFilterProp="children" value={srcFormat} onChange={handleSrcFormat} disabled={props.canReadOnly && !props.canReadWrite} style={{width: "95%"}} onBlur={sendPayload} > {soptions} </Select> &nbsp;&nbsp;<MLTooltip title={NewLoadTooltips.sourceFormat} placement={"right"}> <Icon type="question-circle" className={styles.questionCircle} theme="filled" /> </MLTooltip> </Form.Item> {srcFormat === "csv" ? <Form.Item label={<span> Field Separator:&nbsp;<span className={styles.asterisk}>*</span>&nbsp; </span>} labelAlign="left"> <span><Select id="fieldSeparator" showSearch placeholder="Choose Field Separator" optionFilterProp="children" value={fieldSeparator} onChange={handleFieldSeparator} style={{width: 120}} disabled={props.canReadOnly && !props.canReadWrite} onBlur={sendPayload} > {fsoptions} </Select></span> &nbsp;&nbsp; <span>{fieldSeparator === "Other" ? <span><Input id="otherSeparator" value={otherSeparator} onChange={handleOtherSeparator} style={{width: 75}} disabled={props.canReadOnly && !props.canReadWrite} onBlur={sendPayload} />&nbsp;&nbsp;<MLTooltip title={NewLoadTooltips.fieldSeparator}> <Icon type="question-circle" className={styles.questionCircle} theme="filled" /> </MLTooltip></span> : <span>&nbsp;&nbsp;<MLTooltip title={NewLoadTooltips.fieldSeparator} placement={"right"}> <Icon type="question-circle" className={styles.questionCircle} theme="filled" /> </MLTooltip></span>}</span> </Form.Item> : ""} <Form.Item label={<span> Target Format:&nbsp;<span className={styles.asterisk}>*</span>&nbsp; </span>} labelAlign="left"> <Select id="targetFormat" placeholder="Enter target format" value={tgtFormat} onChange={handleTgtFormat} disabled={props.canReadOnly && !props.canReadWrite} style={{width: "95%"}} onBlur={sendPayload}> {toptions} </Select>&nbsp;&nbsp; <MLTooltip title={NewLoadTooltips.targetFormat} placement={"right"}> <Icon type="question-circle" className={styles.questionCircle} theme="filled" /> </MLTooltip> </Form.Item> {(tgtFormat && (tgtFormat.toLowerCase() === "json" || tgtFormat.toLowerCase() === "xml")) && <Form.Item label={<span> Source Name:&nbsp; </span>} labelAlign="left"> <Input id="sourceName" placeholder="Enter Source Name" value={sourceName} onChange={handleChange} disabled={props.canReadOnly && !props.canReadWrite} className={styles.input} onBlur={sendPayload} />&nbsp;&nbsp;<MLTooltip title={NewLoadTooltips.sourceName} placement={"right"}> <Icon type="question-circle" className={styles.questionCircle} theme="filled" /> </MLTooltip> </Form.Item>} {(tgtFormat && (tgtFormat.toLowerCase() === "json" || tgtFormat.toLowerCase() === "xml")) && <Form.Item label={<span> Source Type:&nbsp; </span>} labelAlign="left"> <Input id="sourceType" placeholder="Enter Source Type" value={sourceType} onChange={handleChange} disabled={props.canReadOnly && !props.canReadWrite} className={styles.input} onBlur={sendPayload} />&nbsp;&nbsp;<MLTooltip title={NewLoadTooltips.sourceType} placement={"right"}> <Icon type="question-circle" className={styles.questionCircle} theme="filled" /> </MLTooltip> </Form.Item>} <Form.Item label={<span> Target URI Prefix:&nbsp; </span>} labelAlign="left"> <Input id="outputUriPrefix" placeholder="Enter URI Prefix" value={outputUriPrefix} onChange={handleOutputUriPrefix} disabled={props.canReadOnly && !props.canReadWrite} className={styles.input} onBlur={sendPayload} />&nbsp;&nbsp; <MLTooltip title={NewLoadTooltips.outputURIPrefix} placement={"right"}> <Icon type="question-circle" className={styles.questionCircle} theme="filled" /> </MLTooltip> </Form.Item> <Form.Item className={styles.submitButtonsForm}> <div className={styles.submitButtons}> <MLButton aria-label="Cancel" onClick={() => onCancel()}>Cancel</MLButton> &nbsp;&nbsp; {!props.canReadWrite?<MLTooltip title={NewLoadTooltips.missingPermission} placement={"bottomRight"}><span className={styles.disabledCursor}><MLButton className={styles.disabledSaveButton} aria-label="Save" type="primary" htmlType="submit" disabled={true} onClick={handleSubmit} >Save</MLButton></span></MLTooltip>: <MLButton aria-label="Save" type="primary" htmlType="submit" disabled={false} onClick={handleSubmit} onFocus={sendPayload} >Save</MLButton>} </div> </Form.Item> </Form> </div> ); }; export default CreateEditLoad;
the_stack
export type Browsers = typeof Browsers; /** * @internal */ export const Browsers = { chrome: { releases: { "1": { date: 1228953600000 }, "2": { date: 1242864000000 }, "3": { date: 1252972800000 }, "4": { date: 1264377600000 }, "5": { date: 1274745600000 }, "6": { date: 1283385600000 }, "7": { date: 1287446400000 }, "8": { date: 1291248000000 }, "9": { date: 1296691200000 }, "10": { date: 1299542400000 }, "11": { date: 1303862400000 }, "12": { date: 1307404800000 }, "13": { date: 1312243200000 }, "14": { date: 1316131200000 }, "15": { date: 1319500800000 }, "16": { date: 1323734400000 }, "17": { date: 1328659200000 }, "18": { date: 1332892800000 }, "19": { date: 1337040000000 }, "20": { date: 1340668800000 }, "21": { date: 1343692800000 }, "22": { date: 1348531200000 }, "23": { date: 1352160000000 }, "24": { date: 1357776000000 }, "25": { date: 1361404800000 }, "26": { date: 1364256000000 }, "27": { date: 1369094400000 }, "28": { date: 1373328000000 }, "29": { date: 1376956800000 }, "30": { date: 1380585600000 }, "31": { date: 1384214400000 }, "32": { date: 1389657600000 }, "33": { date: 1392854400000 }, "34": { date: 1396915200000 }, "35": { date: 1400544000000 }, "36": { date: 1405468800000 }, "37": { date: 1409011200000 }, "38": { date: 1412640000000 }, "39": { date: 1416268800000 }, "40": { date: 1421798400000 }, "41": { date: 1425340800000 }, "42": { date: 1428969600000 }, "43": { date: 1431993600000 }, "44": { date: 1437436800000 }, "45": { date: 1441065600000 }, "46": { date: 1444694400000 }, "47": { date: 1448928000000 }, "48": { date: 1453248000000 }, "49": { date: 1456876800000 }, "50": { date: 1460505600000 }, "51": { date: 1464134400000 }, "52": { date: 1468972800000 }, "53": { date: 1472601600000 }, "54": { date: 1476230400000 }, "55": { date: 1480550400000 }, "56": { date: 1485302400000 }, "57": { date: 1489017600000 }, "58": { date: 1492560000000 }, "59": { date: 1496620800000 }, "60": { date: 1500940800000 }, "61": { date: 1504569600000 }, "62": { date: 1508198400000 }, "63": { date: 1512518400000 }, "64": { date: 1516665600000 }, "65": { date: 1520294400000 }, "66": { date: 1523923200000 }, "67": { date: 1527552000000 }, "68": { date: 1532390400000 }, "69": { date: 1536019200000 }, "70": { date: 1539648000000 }, "71": { date: 1543881600000 }, "72": { date: 1548720000000 }, "73": { date: 1552348800000 }, "74": { date: 1555977600000 }, "75": { date: 1559606400000 }, "76": { date: 1564444800000 }, "77": { date: 1568073600000 }, "78": { date: 1571702400000 }, "79": { date: 1575936000000 }, "80": { date: 1580774400000 }, "81": { date: 1586217600000 }, "83": { date: 1589846400000 }, "84": { date: 1595808000000 }, "85": { date: 1598313600000 }, "86": { date: 1603152000000 }, "87": { date: 1605571200000 }, "88": { date: 1611014400000 }, "89": { date: 1614643200000 }, }, }, edge: { releases: { "12": { date: 1438041600000 }, "13": { date: 1447286400000 }, "14": { date: 1470096000000 }, "15": { date: 1491350400000 }, "16": { date: 1508198400000 }, "17": { date: 1525046400000 }, "18": { date: 1538438400000 }, "79": { date: 1579046400000 }, "80": { date: 1581033600000 }, "81": { date: 1586736000000 }, "83": { date: 1590019200000 }, "84": { date: 1594857600000 }, "85": { date: 1598486400000 }, "86": { date: 1602201600000 }, "87": { date: 1605744000000 }, "88": { date: 1611187200000 }, }, }, firefox: { releases: { "1": { date: 1099958400000 }, "1.5": { date: 1133222400000 }, "2": { date: 1161648000000 }, "3": { date: 1213660800000 }, "3.5": { date: 1246320000000 }, "3.6": { date: 1264032000000 }, "4": { date: 1300752000000 }, "5": { date: 1308614400000 }, "6": { date: 1313452800000 }, "7": { date: 1317081600000 }, "8": { date: 1320710400000 }, "9": { date: 1324339200000 }, "10": { date: 1327968000000 }, "11": { date: 1331596800000 }, "12": { date: 1335225600000 }, "13": { date: 1338854400000 }, "14": { date: 1342483200000 }, "15": { date: 1346112000000 }, "16": { date: 1349740800000 }, "17": { date: 1353369600000 }, "18": { date: 1357603200000 }, "19": { date: 1361232000000 }, "20": { date: 1364860800000 }, "21": { date: 1368489600000 }, "22": { date: 1372118400000 }, "23": { date: 1375747200000 }, "24": { date: 1379376000000 }, "25": { date: 1383004800000 }, "26": { date: 1386633600000 }, "27": { date: 1391472000000 }, "28": { date: 1395100800000 }, "29": { date: 1398729600000 }, "30": { date: 1402358400000 }, "31": { date: 1405987200000 }, "32": { date: 1409616000000 }, "33": { date: 1413244800000 }, "34": { date: 1417392000000 }, "35": { date: 1421107200000 }, "36": { date: 1424736000000 }, "37": { date: 1427760000000 }, "38": { date: 1431388800000 }, "39": { date: 1435795200000 }, "40": { date: 1439251200000 }, "41": { date: 1442880000000 }, "42": { date: 1446508800000 }, "43": { date: 1450137600000 }, "44": { date: 1453766400000 }, "45": { date: 1457395200000 }, "46": { date: 1461628800000 }, "47": { date: 1465257600000 }, "48": { date: 1470096000000 }, "49": { date: 1474329600000 }, "50": { date: 1479168000000 }, "51": { date: 1485216000000 }, "52": { date: 1488844800000 }, "53": { date: 1492560000000 }, "54": { date: 1497312000000 }, "55": { date: 1502150400000 }, "56": { date: 1506556800000 }, "57": { date: 1510617600000 }, "58": { date: 1516665600000 }, "59": { date: 1520899200000 }, "60": { date: 1525824000000 }, "61": { date: 1529971200000 }, "62": { date: 1536105600000 }, "63": { date: 1540252800000 }, "64": { date: 1544486400000 }, "65": { date: 1548720000000 }, "66": { date: 1552953600000 }, "67": { date: 1558396800000 }, "68": { date: 1562630400000 }, "69": { date: 1567468800000 }, "70": { date: 1571702400000 }, "71": { date: 1575936000000 }, "72": { date: 1578355200000 }, "73": { date: 1581379200000 }, "74": { date: 1583798400000 }, "75": { date: 1586217600000 }, "76": { date: 1588636800000 }, "77": { date: 1591056000000 }, "78": { date: 1593475200000 }, "79": { date: 1595894400000 }, "80": { date: 1598313600000 }, "81": { date: 1600732800000 }, "82": { date: 1603152000000 }, "83": { date: 1605571200000 }, "84": { date: 1607990400000 }, "85": { date: 1611619200000 }, "86": { date: 1614038400000 }, }, }, ie: { releases: { "1": { date: 808531200000 }, "2": { date: 816998400000 }, "3": { date: 839894400000 }, "4": { date: 875577600000 }, "5": { date: 921715200000 }, "5.5": { date: 962841600000 }, "6": { date: 998870400000 }, "7": { date: 1161129600000 }, "8": { date: 1237420800000 }, "9": { date: 1300060800000 }, "10": { date: 1351209600000 }, "11": { date: 1381968000000 }, }, }, opera: { releases: { "2": { date: 837302400000 }, "3": { date: 880934400000 }, "3.5": { date: 911347200000 }, "3.6": { date: 925948800000 }, "4": { date: 962150400000 }, "5": { date: 976060800000 }, "5.1": { date: 986860800000 }, "6": { date: 1008633600000 }, "7": { date: 1043712000000 }, "7.1": { date: 1050019200000 }, "7.2": { date: 1064275200000 }, "7.5": { date: 1084320000000 }, "8": { date: 1113868800000 }, "8.5": { date: 1127174400000 }, "9": { date: 1150761600000 }, "9.1": { date: 1166400000000 }, "9.2": { date: 1176249600000 }, "9.5": { date: 1213228800000 }, "9.6": { date: 1223424000000 }, "10": { date: 1251763200000 }, "10.1": { date: 1258934400000 }, "10.5": { date: 1267488000000 }, "10.6": { date: 1277942400000 }, "11": { date: 1292457600000 }, "11.1": { date: 1302566400000 }, "11.5": { date: 1309219200000 }, "11.6": { date: 1323129600000 }, "12": { date: 1339632000000 }, "12.1": { date: 1353369600000 }, "15": { date: 1372723200000 }, "16": { date: 1377561600000 }, "17": { date: 1381190400000 }, "18": { date: 1384819200000 }, "19": { date: 1390867200000 }, "20": { date: 1393891200000 }, "21": { date: 1399334400000 }, "22": { date: 1401753600000 }, "23": { date: 1405987200000 }, "24": { date: 1409616000000 }, "25": { date: 1413331200000 }, "26": { date: 1417564800000 }, "27": { date: 1422316800000 }, "28": { date: 1425945600000 }, "29": { date: 1430179200000 }, "30": { date: 1433808000000 }, "31": { date: 1438646400000 }, "32": { date: 1442275200000 }, "33": { date: 1445904000000 }, "34": { date: 1449532800000 }, "35": { date: 1454371200000 }, "36": { date: 1458000000000 }, "37": { date: 1462320000000 }, "38": { date: 1465344000000 }, "39": { date: 1470096000000 }, "40": { date: 1474329600000 }, "41": { date: 1477353600000 }, "42": { date: 1481587200000 }, "43": { date: 1486425600000 }, "44": { date: 1490054400000 }, "45": { date: 1494374400000 }, "46": { date: 1498089600000 }, "47": { date: 1502236800000 }, "48": { date: 1506470400000 }, "49": { date: 1510099200000 }, "50": { date: 1515024000000 }, "51": { date: 1517961600000 }, "52": { date: 1521676800000 }, "53": { date: 1525910400000 }, "54": { date: 1530144000000 }, "55": { date: 1534377600000 }, "56": { date: 1537833600000 }, "57": { date: 1543363200000 }, "58": { date: 1548201600000 }, "60": { date: 1554768000000 }, "62": { date: 1561593600000 }, "63": { date: 1566259200000 }, "64": { date: 1570406400000 }, "65": { date: 1573603200000 }, "66": { date: 1578355200000 }, "67": { date: 1583193600000 }, "68": { date: 1587513600000 }, "69": { date: 1592956800000 }, "70": { date: 1595808000000 }, "71": { date: 1600128000000 }, "72": { date: 1603238400000 }, "73": { date: 1607472000000 }, "74": { date: 1612224000000 }, }, }, safari: { releases: { "1": { date: 1056326400000 }, "1.1": { date: 1066953600000 }, "1.2": { date: 1075680000000 }, "1.3": { date: 1113523200000 }, "2": { date: 1114732800000 }, "3": { date: 1194998400000 }, "3.1": { date: 1205798400000 }, "3.2": { date: 1226534400000 }, "4": { date: 1244419200000 }, "5": { date: 1275868800000 }, "5.1": { date: 1311120000000 }, "6": { date: 1343174400000 }, "6.1": { date: 1370908800000 }, "7": { date: 1382400000000 }, "8": { date: 1413417600000 }, "9": { date: 1443571200000 }, "9.1": { date: 1458518400000 }, "10": { date: 1474329600000 }, "10.1": { date: 1490572800000 }, "11": { date: 1505779200000 }, "11.1": { date: 1523491200000 }, "12": { date: 1537747200000 }, "12.1": { date: 1553472000000 }, "13": { date: 1568851200000 }, "13.1": { date: 1585008000000 }, "14": { date: 1600214400000 }, }, }, };
the_stack
import BN from 'bn.js'; import BigNumber from 'bignumber.js'; import { PromiEvent, TransactionReceipt, EventResponse, EventData, Web3ContractContext, } from 'ethereum-abi-types-generator'; export interface CallOptions { from?: string; gasPrice?: string; gas?: number; } export interface SendOptions { from: string; value?: number | string | BN | BigNumber; gasPrice?: string; gas?: number; } export interface EstimateGasOptions { from?: string; value?: number | string | BN | BigNumber; gas?: number; } export interface MethodPayableReturnContext { send(options: SendOptions): PromiEvent<TransactionReceipt>; send( options: SendOptions, callback: (error: Error, result: any) => void ): PromiEvent<TransactionReceipt>; estimateGas(options: EstimateGasOptions): Promise<number>; estimateGas( options: EstimateGasOptions, callback: (error: Error, result: any) => void ): Promise<number>; encodeABI(): string; } export interface MethodConstantReturnContext<TCallReturn> { call(): Promise<TCallReturn>; call(options: CallOptions): Promise<TCallReturn>; call( options: CallOptions, callback: (error: Error, result: TCallReturn) => void ): Promise<TCallReturn>; encodeABI(): string; } export interface MethodReturnContext extends MethodPayableReturnContext {} export type ContractContext = Web3ContractContext< UniswapExchangeContract, UniswapExchangeContractMethodNames, UniswapExchangeContractEventsContext, UniswapExchangeContractEvents >; export type UniswapExchangeContractEvents = | 'TokenPurchase' | 'EthPurchase' | 'AddLiquidity' | 'RemoveLiquidity' | 'Transfer' | 'Approval'; export interface UniswapExchangeContractEventsContext { TokenPurchase( parameters: { filter?: { buyer?: string | string[]; eth_sold?: string | string[]; tokens_bought?: string | string[]; }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; EthPurchase( parameters: { filter?: { buyer?: string | string[]; tokens_sold?: string | string[]; eth_bought?: string | string[]; }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; AddLiquidity( parameters: { filter?: { provider?: string | string[]; eth_amount?: string | string[]; token_amount?: string | string[]; }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; RemoveLiquidity( parameters: { filter?: { provider?: string | string[]; eth_amount?: string | string[]; token_amount?: string | string[]; }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; Transfer( parameters: { filter?: { _from?: string | string[]; _to?: string | string[] }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; Approval( parameters: { filter?: { _owner?: string | string[]; _spender?: string | string[] }; fromBlock?: number; toBlock?: 'latest' | number; topics?: string[]; }, callback?: (error: Error, event: EventData) => void ): EventResponse; } export type UniswapExchangeContractMethodNames = | 'setup' | 'addLiquidity' | 'removeLiquidity' | '__default__' | 'ethToTokenSwapInput' | 'ethToTokenTransferInput' | 'ethToTokenSwapOutput' | 'ethToTokenTransferOutput' | 'tokenToEthSwapInput' | 'tokenToEthTransferInput' | 'tokenToEthSwapOutput' | 'tokenToEthTransferOutput' | 'tokenToTokenSwapInput' | 'tokenToTokenTransferInput' | 'tokenToTokenSwapOutput' | 'tokenToTokenTransferOutput' | 'tokenToExchangeSwapInput' | 'tokenToExchangeTransferInput' | 'tokenToExchangeSwapOutput' | 'tokenToExchangeTransferOutput' | 'getEthToTokenInputPrice' | 'getEthToTokenOutputPrice' | 'getTokenToEthInputPrice' | 'getTokenToEthOutputPrice' | 'tokenAddress' | 'factoryAddress' | 'balanceOf' | 'transfer' | 'transferFrom' | 'approve' | 'allowance' | 'name' | 'symbol' | 'decimals' | 'totalSupply'; export interface UniswapExchangeContract { /** * Payable: false * Constant: false * StateMutability: undefined * Type: function * @param token_addr Type: address, Indexed: false */ setup(token_addr: string): MethodReturnContext; /** * Payable: true * Constant: false * StateMutability: undefined * Type: function * @param min_liquidity Type: uint256, Indexed: false * @param max_tokens Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false */ addLiquidity( min_liquidity: string, max_tokens: string, deadline: string ): MethodPayableReturnContext; /** * Payable: false * Constant: false * StateMutability: undefined * Type: function * @param amount Type: uint256, Indexed: false * @param min_eth Type: uint256, Indexed: false * @param min_tokens Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false */ removeLiquidity( amount: string, min_eth: string, min_tokens: string, deadline: string ): MethodReturnContext; /** * Payable: true * Constant: false * StateMutability: undefined * Type: function */ __default__(): MethodPayableReturnContext; /** * Payable: true * Constant: false * StateMutability: undefined * Type: function * @param min_tokens Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false */ ethToTokenSwapInput( min_tokens: string, deadline: string ): MethodPayableReturnContext; /** * Payable: true * Constant: false * StateMutability: undefined * Type: function * @param min_tokens Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false * @param recipient Type: address, Indexed: false */ ethToTokenTransferInput( min_tokens: string, deadline: string, recipient: string ): MethodPayableReturnContext; /** * Payable: true * Constant: false * StateMutability: undefined * Type: function * @param tokens_bought Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false */ ethToTokenSwapOutput( tokens_bought: string, deadline: string ): MethodPayableReturnContext; /** * Payable: true * Constant: false * StateMutability: undefined * Type: function * @param tokens_bought Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false * @param recipient Type: address, Indexed: false */ ethToTokenTransferOutput( tokens_bought: string, deadline: string, recipient: string ): MethodPayableReturnContext; /** * Payable: false * Constant: false * StateMutability: undefined * Type: function * @param tokens_sold Type: uint256, Indexed: false * @param min_eth Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false */ tokenToEthSwapInput( tokens_sold: string, min_eth: string, deadline: string ): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: undefined * Type: function * @param tokens_sold Type: uint256, Indexed: false * @param min_eth Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false * @param recipient Type: address, Indexed: false */ tokenToEthTransferInput( tokens_sold: string, min_eth: string, deadline: string, recipient: string ): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: undefined * Type: function * @param eth_bought Type: uint256, Indexed: false * @param max_tokens Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false */ tokenToEthSwapOutput( eth_bought: string, max_tokens: string, deadline: string ): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: undefined * Type: function * @param eth_bought Type: uint256, Indexed: false * @param max_tokens Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false * @param recipient Type: address, Indexed: false */ tokenToEthTransferOutput( eth_bought: string, max_tokens: string, deadline: string, recipient: string ): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: undefined * Type: function * @param tokens_sold Type: uint256, Indexed: false * @param min_tokens_bought Type: uint256, Indexed: false * @param min_eth_bought Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false * @param token_addr Type: address, Indexed: false */ tokenToTokenSwapInput( tokens_sold: string, min_tokens_bought: string, min_eth_bought: string, deadline: string, token_addr: string ): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: undefined * Type: function * @param tokens_sold Type: uint256, Indexed: false * @param min_tokens_bought Type: uint256, Indexed: false * @param min_eth_bought Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false * @param recipient Type: address, Indexed: false * @param token_addr Type: address, Indexed: false */ tokenToTokenTransferInput( tokens_sold: string, min_tokens_bought: string, min_eth_bought: string, deadline: string, recipient: string, token_addr: string ): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: undefined * Type: function * @param tokens_bought Type: uint256, Indexed: false * @param max_tokens_sold Type: uint256, Indexed: false * @param max_eth_sold Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false * @param token_addr Type: address, Indexed: false */ tokenToTokenSwapOutput( tokens_bought: string, max_tokens_sold: string, max_eth_sold: string, deadline: string, token_addr: string ): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: undefined * Type: function * @param tokens_bought Type: uint256, Indexed: false * @param max_tokens_sold Type: uint256, Indexed: false * @param max_eth_sold Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false * @param recipient Type: address, Indexed: false * @param token_addr Type: address, Indexed: false */ tokenToTokenTransferOutput( tokens_bought: string, max_tokens_sold: string, max_eth_sold: string, deadline: string, recipient: string, token_addr: string ): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: undefined * Type: function * @param tokens_sold Type: uint256, Indexed: false * @param min_tokens_bought Type: uint256, Indexed: false * @param min_eth_bought Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false * @param exchange_addr Type: address, Indexed: false */ tokenToExchangeSwapInput( tokens_sold: string, min_tokens_bought: string, min_eth_bought: string, deadline: string, exchange_addr: string ): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: undefined * Type: function * @param tokens_sold Type: uint256, Indexed: false * @param min_tokens_bought Type: uint256, Indexed: false * @param min_eth_bought Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false * @param recipient Type: address, Indexed: false * @param exchange_addr Type: address, Indexed: false */ tokenToExchangeTransferInput( tokens_sold: string, min_tokens_bought: string, min_eth_bought: string, deadline: string, recipient: string, exchange_addr: string ): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: undefined * Type: function * @param tokens_bought Type: uint256, Indexed: false * @param max_tokens_sold Type: uint256, Indexed: false * @param max_eth_sold Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false * @param exchange_addr Type: address, Indexed: false */ tokenToExchangeSwapOutput( tokens_bought: string, max_tokens_sold: string, max_eth_sold: string, deadline: string, exchange_addr: string ): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: undefined * Type: function * @param tokens_bought Type: uint256, Indexed: false * @param max_tokens_sold Type: uint256, Indexed: false * @param max_eth_sold Type: uint256, Indexed: false * @param deadline Type: uint256, Indexed: false * @param recipient Type: address, Indexed: false * @param exchange_addr Type: address, Indexed: false */ tokenToExchangeTransferOutput( tokens_bought: string, max_tokens_sold: string, max_eth_sold: string, deadline: string, recipient: string, exchange_addr: string ): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: undefined * Type: function * @param eth_sold Type: uint256, Indexed: false */ getEthToTokenInputPrice( eth_sold: string ): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: undefined * Type: function * @param tokens_bought Type: uint256, Indexed: false */ getEthToTokenOutputPrice( tokens_bought: string ): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: undefined * Type: function * @param tokens_sold Type: uint256, Indexed: false */ getTokenToEthInputPrice( tokens_sold: string ): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: undefined * Type: function * @param eth_bought Type: uint256, Indexed: false */ getTokenToEthOutputPrice( eth_bought: string ): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: undefined * Type: function */ tokenAddress(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: undefined * Type: function */ factoryAddress(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: undefined * Type: function * @param _owner Type: address, Indexed: false */ balanceOf(_owner: string): MethodConstantReturnContext<string>; /** * Payable: false * Constant: false * StateMutability: undefined * Type: function * @param _to Type: address, Indexed: false * @param _value Type: uint256, Indexed: false */ transfer(_to: string, _value: string): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: undefined * Type: function * @param _from Type: address, Indexed: false * @param _to Type: address, Indexed: false * @param _value Type: uint256, Indexed: false */ transferFrom(_from: string, _to: string, _value: string): MethodReturnContext; /** * Payable: false * Constant: false * StateMutability: undefined * Type: function * @param _spender Type: address, Indexed: false * @param _value Type: uint256, Indexed: false */ approve(_spender: string, _value: string): MethodReturnContext; /** * Payable: false * Constant: true * StateMutability: undefined * Type: function * @param _owner Type: address, Indexed: false * @param _spender Type: address, Indexed: false */ allowance( _owner: string, _spender: string ): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: undefined * Type: function */ name(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: undefined * Type: function */ symbol(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: undefined * Type: function */ decimals(): MethodConstantReturnContext<string>; /** * Payable: false * Constant: true * StateMutability: undefined * Type: function */ totalSupply(): MethodConstantReturnContext<string>; }
the_stack
import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, Input, OnChanges, Output, SimpleChanges, TemplateRef, ViewEncapsulation, } from '@angular/core'; import { FormControl } from '@angular/forms'; import { coerceNumberProperty } from '@terminus/ngx-tools/coercion'; import { inputHasChanged } from '@terminus/ngx-tools/utilities'; import { TsSelectionListChange } from '@terminus/ui/selection-list'; import { TsStyleThemeTypes } from '@terminus/ui/utilities'; /** * Define the allowed keys and types for an item passed to the {@link TsMenuComponent} within a * {@link TsPaginatorComponent} */ export interface TsPaginatorMenuItem { /** * The menu item name */ name: string; /** * A value for the item */ value?: number; } /** * Define the default count of records per page */ const DEFAULT_RECORDS_PER_PAGE = 10; /** * Default max records before message is shown */ const DEFAULT_MAX_PREFERRED_RECORDS = 100; /** * Define the default options for the records per page select menu */ // eslint-disable-next-line @typescript-eslint/no-magic-numbers const DEFAULT_RECORDS_PER_PAGE_OPTIONS = [10, 20, 50]; /** * A paginator component * * @example * <ts-paginator * currentPageIndex="1" * firstPageTooltip="View first results" * [isSimpleMode]="true" * [isZeroBased]="true" * lastPageTooltip="View last results" * maxPreferredRecords="100" * menuLocation="below" * nextPageTooltip="View next results" * [paginatorMessageTemplate]="myTemplate" * previousPageTooltip="View previous results" * recordCountTooHighMessage="Please refine your filters." * recordsPerPageChoices="[10, 20, 50]" * [showRecordsPerPageSelector]="true" * totalRecords="1450" * (pageSelect)="myMethod($event)" * (recordsPerPageChange)="myMethod($event)" * ></ts-paginator> * * <ng-template #myTemplate let-message> * <strong>{{ message }}</strong> * <a href="/faq">Learn more</a> * </ng-template> * * <example-url>https://getterminus.github.io/ui-demos-release/components/paginator</example-url> */ @Component({ selector: 'ts-paginator', templateUrl: './paginator.component.html', styleUrls: ['./paginator.component.scss'], host: { class: 'ts-paginator' }, changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, exportAs: 'tsPaginator', }) export class TsPaginatorComponent implements OnChanges, AfterViewInit { /** * Define the default message to show when too many records are returned */ private DEFAULT_HIGH_RECORD_MESSAGE = `That's a lot of results! Try refining your filters for better results.`; /** * This does not allow user input in selection list */ public allowUserInput = false; /** * Define the icon for the 'first page' button */ public firstPageIcon = 'first_page'; /** * Set up a form control to pass to {@link TsSelectionListComponent} */ public pageControl = new FormControl(); /** * Define the icon for the 'previous page' button */ public previousPageIcon = 'keyboard_arrow_left'; /** * Define the icon for the 'next page' button */ public nextPageIcon = 'keyboard_arrow_right'; /** * Define the icon for the 'last page' button */ public lastPageIcon = 'last_page'; /** * Store the array of objects that represent pages of collections */ public pagesArray!: TsPaginatorMenuItem[]; /** * Store the label for the current page */ public currentPageLabel!: string; /** * Define the amount of records show per page * * @param value */ // public recordsPerPage: number = DEFAULT_RECORDS_PER_PAGE; public set recordsPerPage(value: number) { this._recordsPerPage = value; this.pageControl.setValue([value]); } public get recordsPerPage(): number { return this._recordsPerPage; } private _recordsPerPage = DEFAULT_RECORDS_PER_PAGE; /** * Define the template context for the record count message */ public templateContext = { $implicit: this.DEFAULT_HIGH_RECORD_MESSAGE }; /** * Getter to return the index of the first page */ public get firstPageIndex(): number { return this.isZeroBased ? 0 : 1; } /** * Getter to return the index of the next page */ public get nextPageIndex(): number { return this.currentPageIndex - this.firstPageIndex; } /** * Getter to return the index of the last page */ public get lastPageIndex(): number { return this.isZeroBased ? (this.pagesArray.length - 1) : this.pagesArray.length; } /** * Define if the paging is 0-based or 1-based */ @Input() public isZeroBased = true; /** * Define the tooltip message for the first page tooltip */ @Input() public firstPageTooltip = 'View the first results'; /** * Define the tooltip message for the previous page tooltip */ @Input() public previousPageTooltip = 'View the previous results'; /** * Define the tooltip message for the next page tooltip */ @Input() public nextPageTooltip = 'View the next results'; /** * Define the tooltip message for the last page tooltip */ @Input() public lastPageTooltip = 'View the last results'; /** * Define the current page * * @param page */ @Input() public set currentPageIndex(page: number) { this._currentPageIndex = coerceNumberProperty(page); } public get currentPageIndex(): number { return this._currentPageIndex; } private _currentPageIndex = 0; /** * Define how many pages exist to show a prompt about better filtering */ @Input() public maxPreferredRecords: number = DEFAULT_MAX_PREFERRED_RECORDS; /** * Define the menu location (open up or open down) */ @Input() public menuLocation: 'above' | 'below' = 'above'; /** * Allow a custom template to be used for the paginator message */ @Input() public paginatorMessageTemplate!: TemplateRef<ElementRef>; /** * Define the color theme */ @Input() public theme: TsStyleThemeTypes = 'accent'; /** * Define the total number of records * * @param records */ @Input() public set totalRecords(records: number) { this._totalRecords = coerceNumberProperty(records); } public get totalRecords(): number { return this._totalRecords; } private _totalRecords = 0; /** * Define the message to show when too many pages exist */ @Input() public recordCountTooHighMessage: string = this.DEFAULT_HIGH_RECORD_MESSAGE; /** * Define how many records are shown per page */ @Input() public recordsPerPageChoices: number[] = DEFAULT_RECORDS_PER_PAGE_OPTIONS; /** * Define the label for the records per page select */ @Input() public recordsSelectLabel = 'Per page'; /** * Define if the records per page select menu should be visible */ @Input() public showRecordsPerPageSelector = true; /** * Determine if the paginator should be in 'simple' mode * * Simple mode: Page jump dropdown is converted to plain text, jump to last page button removed. */ @Input() public isSimpleMode = false; /** * Override the disabling of the next button */ @Input() public isNextDisabled: boolean | undefined; /** * Emit a page selected event */ @Output() public readonly pageSelect = new EventEmitter<TsPaginatorMenuItem>(); /** * Emit a change event when the records per page changes */ @Output() public readonly recordsPerPageChange = new EventEmitter<number>(); constructor( private changeDetectorRef: ChangeDetectorRef, ) { this.pageControl.setValue([this.recordsPerPage]); } /** * Initialize after the view is initialized */ public ngAfterViewInit(): void { this.initialize(); } /** * Initialize on any changes * * @param changes - The object containing all changes since last cycle */ public ngOnChanges(changes: SimpleChanges): void { // If the record count changed, assign the new value to the template context // istanbul ignore else if (inputHasChanged(changes, 'recordCountTooHighMessage')) { this.templateContext.$implicit = this.recordCountTooHighMessage; } // If the zeroBased input changes, update the current page index if (inputHasChanged(changes, 'isZeroBased')) { this.currentPageIndex = changes.isZeroBased.currentValue ? 0 : 1; } this.initialize(); } /** * Set up initial resources */ private initialize(): void { this.pagesArray = this.createPagesArray(this.totalRecords, this.recordsPerPage, this.isZeroBased); this.currentPageLabel = this.createCurrentPageLabel(this.currentPageIndex, this.pagesArray, this.totalRecords); // Change to the current page // istanbul ignore else if (this.totalRecords > 0) { this.changePage(this.currentPageIndex, -1, this.pagesArray); } } /** * Perform tasks when the current page is changed * * @param page - The selected page */ public currentPageChanged(page: TsPaginatorMenuItem): void { // Set the current page this.currentPageIndex = coerceNumberProperty(page.value); // Create a new label for the menu this.currentPageLabel = this.createCurrentPageLabel(this.currentPageIndex, this.pagesArray, this.totalRecords); // Emit an event this.pageSelect.emit(page); this.changeDetectorRef.detectChanges(); } /** * Manually trigger a page change event from a number * * @param destinationPage - The selected page number * @param currentPage - The current page number * @param pages - The collection of pages */ public changePage( destinationPage: number, currentPage: number, pages: TsPaginatorMenuItem[], ): void { const destinationIsValid: boolean = destinationPage >= this.firstPageIndex && destinationPage <= pages.length; const notAlreadyOnPage: boolean = destinationPage !== currentPage; // istanbul ignore else if (destinationIsValid && notAlreadyOnPage) { const foundPage: TsPaginatorMenuItem | undefined = pages.find((page: TsPaginatorMenuItem): boolean => page.value === destinationPage); // istanbul ignore else if (foundPage) { this.currentPageChanged(foundPage); } } } /** * Check if a page is the first page * * @param page - The number of the current page * @returns A boolean representing if this is the first page */ public isFirstPage(page: number): boolean { return coerceNumberProperty(page) === this.firstPageIndex; } /** * Check if a page is the last page * * @param page - The number of the current page * @returns A boolean representing if this is the last page */ public isLastPage(page: number): boolean { if (this.pagesArray) { return page === (this.pagesArray.length - (this.isZeroBased ? 1 : 0)); } return false; } /** * Check if the next button is disabled * * @param page - The number of the current page * @returns A boolena representing if the button is disabled. */ public isNextButtonDisabled(page: number): boolean { if (this.isNextDisabled === undefined) { return this.isLastPage(page) || !this.pagesArray || !this.pagesArray.length; } return this.isNextDisabled; } /** * Determine if the string exists * * @param message - The help message when too many results are returned * @param max - The max number of records before the message should be shown * @param totalRecords - The number of records * @returns A boolean representing if the message should be shown */ public shouldShowRecordsMessage(message: string, max: number, totalRecords: number): boolean { if (totalRecords > max) { return !!((message && message.length > 0)); } return false; } /** * Re-initialize the paginator when records per page changes * * @param selection - The selected records-per-page count */ public recordsPerPageUpdated(selection: TsSelectionListChange<number>): void { this.recordsPerPage = selection.value; this.currentPageIndex = this.firstPageIndex; this.recordsPerPageChange.emit(selection.value); this.initialize(); } /** * Determine if the page select menu should be disabled * * @param pagesCount - The number of pages * @returns A boolean representing if the menu should be disabled */ public menuIsDisabled(pagesCount: number): boolean { const moreThanOne = 2; return coerceNumberProperty(pagesCount) < moreThanOne; } /** * Determine if the records-per-page menu should be disabled * * @param totalRecords - The total number of records * @param recordsPerPageChoices - The array of counts representing how many records may be show * per page * @returns A boolean representing if the records select should be disabled */ public disableRecordsPerPage(totalRecords: number, recordsPerPageChoices: number[]): boolean { const lowestPerPage: number = Math.min.apply(Math, recordsPerPageChoices); return totalRecords < lowestPerPage; } /** * Create a new label based on the current page * * @param currentPage - The current page * @param pages - The array of all pages * @param totalRecords - The number of total records * @returns The string to use as the current page label */ private createCurrentPageLabel( currentPage: number, pages: TsPaginatorMenuItem[], totalRecords: number, ): string { const findPage = (allPages: TsPaginatorMenuItem[], index: number) => pages.find((page: TsPaginatorMenuItem): boolean => page.value === index); let foundPage: TsPaginatorMenuItem | undefined = findPage(pages, currentPage); // If no found page, try the previous page if (!foundPage) { foundPage = findPage(pages, currentPage - 1); // istanbul ignore else if (foundPage) { // If we found the previous page, // save the current page change back to the primary variable this.currentPageIndex -= 1; } } // This may be the case if there are no records if (!foundPage || !foundPage.name) { return this.createDefaultPageLabel(currentPage, totalRecords); } // '1 - 10 of 243' return `${foundPage.name} of ${totalRecords}`; } /** * Create a default label based on the records per page and total records * * @param currentPage - The current page * @param totalRecords - The number of total records * @returns The string to use as the current page label */ private createDefaultPageLabel( currentPage: number, totalRecords: number, ): string { const start = this.isZeroBased ? (currentPage * this.recordsPerPage) : (currentPage - 1) * this.recordsPerPage; const end = start + this.recordsPerPage; // '1 - 10' if (this.isSimpleMode && !totalRecords) { return `${start + 1} - ${end}`; } // '1 - 10 of 243' return `${start + 1} - ${end} of ${totalRecords}`; } /** * Create an array containing objects that represent each available page of records * * @param total - The total records remaining * @param perPage - How many records are shown per page * @param zeroBased - If the pages are based on a `0` index rather than `1` * @returns The array representing all possible pages of records */ private createPagesArray(total: number, perPage: number, zeroBased: boolean): TsPaginatorMenuItem[] { const paginatorArray: TsPaginatorMenuItem[] = []; let recordsRemaining = total; let page = zeroBased ? 0 : 1; // If there are no records just return an empty array if (!recordsRemaining || recordsRemaining < 1) { return paginatorArray; } while (recordsRemaining >= perPage) { // We are creating the text for the range here so we are dealing with records based on 1 // (while the pages themselves may be based on 0 or 1) const pageNumber = (page < 1) ? 1 : page; const rangeStart = (pageNumber * perPage) - (perPage - 1); const rangeEnd = pageNumber * perPage; const pageValue: number = paginatorArray.length + 1; // Create a page object paginatorArray.push({ name: `${rangeStart} - ${rangeEnd}`, // The value is zero based value: (pageValue - (zeroBased ? 1 : 0)), }); // Update the remaining count recordsRemaining -= perPage; // Set up for next loop if enough records exist if (recordsRemaining >= perPage) { page = pageValue + 1; } } // If any records remain, add the partial group as the last page in the array if (recordsRemaining > 0) { let name; let value; const pageNumber = (page < 1) ? 1 : page; const pageValue: number = paginatorArray.length + 1; if (paginatorArray.length > 0) { name = `${(pageNumber * perPage) + 1} - ${(pageNumber * perPage) + recordsRemaining}`; value = (pageValue - (zeroBased ? 1 : 0)); } else { name = `${pageNumber} - ${recordsRemaining}`; value = (pageValue - (zeroBased ? 1 : 0)); } paginatorArray.push({ name, value, }); } return paginatorArray.sort((a: TsPaginatorMenuItem, b: TsPaginatorMenuItem): number => { const first: number = coerceNumberProperty(a.value); const second: number = coerceNumberProperty(b.value); return (first < second) ? -1 : 1; }); } /** * Tracking method for the pagesArray ngFor * * @param index - The current index * @param page - The page object * @returns The value to be used */ public trackPagesArray(index: number, page: TsPaginatorMenuItem): string | undefined { return page ? page.name : undefined; } }
the_stack
import {fakeAsync, TestBed, tick} from "@angular/core/testing"; import {HttpClientTestingModule, HttpTestingController} from "@angular/common/http/testing"; import * as Immutable from "immutable"; import {LoggerService} from "../../../../services/utils/logger.service"; import {AutoQueueService} from "../../../../services/autoqueue/autoqueue.service"; import {AutoQueuePattern} from "../../../../services/autoqueue/autoqueue-pattern"; import {StreamServiceRegistry} from "../../../../services/base/stream-service.registry"; import {MockStreamServiceRegistry} from "../../../mocks/mock-stream-service.registry"; import {RestService} from "../../../../services/utils/rest.service"; import {ConnectedService} from "../../../../services/utils/connected.service"; // noinspection JSUnusedLocalSymbols const DoNothing = {next: reaction => {}}; describe("Testing autoqueue service", () => { let mockRegistry: MockStreamServiceRegistry; let httpMock: HttpTestingController; let aqService: AutoQueueService; beforeEach(fakeAsync(() => { TestBed.configureTestingModule({ imports: [ HttpClientTestingModule ], providers: [ AutoQueueService, LoggerService, RestService, ConnectedService, {provide: StreamServiceRegistry, useClass: MockStreamServiceRegistry} ] }); mockRegistry = TestBed.get(StreamServiceRegistry); httpMock = TestBed.get(HttpTestingController); aqService = TestBed.get(AutoQueueService); // Connect the services mockRegistry.connect(); // Finish the init aqService.onInit(); })); it("should create an instance", () => { expect(aqService).toBeDefined(); }); it("should parse patterns json correctly", fakeAsync(() => { const patternsJson = [ {"pattern": "one"}, {"pattern": "tw o"}, {"pattern": "th'ree"}, {"pattern": "fo\"ur"}, {"pattern": "fi%ve"}, ]; httpMock.expectOne("/server/autoqueue/get").flush(patternsJson); const expectedPatterns = [ new AutoQueuePattern({pattern: "one"}), new AutoQueuePattern({pattern: "tw o"}), new AutoQueuePattern({pattern: "th'ree"}), new AutoQueuePattern({pattern: "fo\"ur"}), new AutoQueuePattern({pattern: "fi%ve"}) ]; let actualCount = 0; aqService.patterns.subscribe({ next: patterns => { expect(patterns.size).toBe(5); for (let i = 0; i < patterns.size; i++) { expect(Immutable.is(patterns.get(i), expectedPatterns[i])).toBe(true); } actualCount++; } }); tick(); expect(actualCount).toBe(1); httpMock.verify(); })); it("should get empty list on get error 404", fakeAsync(() => { httpMock.expectOne("/server/autoqueue/get").flush( "Not found", {status: 404, statusText: "Bad Request"} ); let actualCount = 0; aqService.patterns.subscribe({ next: patterns => { expect(patterns.size).toBe(0); actualCount++; } }); tick(); expect(actualCount).toBe(1); httpMock.verify(); })); it("should get empty list on get network error", fakeAsync(() => { httpMock.expectOne("/server/autoqueue/get").error(new ErrorEvent("mock error")); let actualCount = 0; aqService.patterns.subscribe({ next: patterns => { expect(patterns.size).toBe(0); actualCount++; } }); tick(); expect(actualCount).toBe(1); httpMock.verify(); })); it("should get empty list on disconnect", fakeAsync(() => { const patternsJson = [ {"pattern": "one"} ]; httpMock.expectOne("/server/autoqueue/get").flush(patternsJson); const expectedPatterns = [ Immutable.List([new AutoQueuePattern({pattern: "one"})]), Immutable.List([]) ]; let actualCount = 0; aqService.patterns.subscribe({ next: patterns => { expect(Immutable.is(patterns, expectedPatterns[actualCount++])).toBe(true); } }); tick(); // status disconnect mockRegistry.disconnect(); tick(); expect(actualCount).toBe(2); httpMock.verify(); })); it("should retry GET on disconnect", fakeAsync(() => { // first connect httpMock.expectOne("/server/autoqueue/get").flush("[]"); tick(); // status disconnect mockRegistry.disconnect(); tick(); // status reconnect mockRegistry.connect(); tick(); httpMock.expectOne("/server/autoqueue/get").flush("[]"); tick(); httpMock.verify(); })); it("should send a GET on add pattern", fakeAsync(() => { httpMock.expectOne("/server/autoqueue/get").flush([]); let actualCount = 0; aqService.add("one").subscribe({ next: reaction => { expect(reaction.success).toBe(true); actualCount++; } }); httpMock.expectOne("/server/autoqueue/add/one").flush("{}"); tick(); expect(actualCount).toBe(1); httpMock.verify(); })); it("should send correct GET requests on add pattern", fakeAsync(() => { httpMock.expectOne("/server/autoqueue/get").flush([]); aqService.add("test").subscribe(DoNothing); httpMock.expectOne("/server/autoqueue/add/test").flush("{}"); aqService.add("test space").subscribe(DoNothing); httpMock.expectOne("/server/autoqueue/add/test%2520space").flush("{}"); aqService.add("test/slash").subscribe(DoNothing); httpMock.expectOne("/server/autoqueue/add/test%252Fslash").flush("{}"); aqService.add("test\"doublequote").subscribe(DoNothing); httpMock.expectOne("/server/autoqueue/add/test%2522doublequote").flush("{}"); aqService.add("/test/leadingslash").subscribe(DoNothing); httpMock.expectOne("/server/autoqueue/add/%252Ftest%252Fleadingslash").flush("{}"); httpMock.verify(); })); it("should return error on adding existing pattern", fakeAsync(() => { httpMock.expectOne("/server/autoqueue/get").flush([ {"pattern": "one"} ]); let actualCount = 0; aqService.add("one").subscribe({ next: reaction => { expect(reaction.success).toBe(false); expect(reaction.errorMessage).toBe("Pattern 'one' already exists."); actualCount++; } }); httpMock.expectNone("/server/autoqueue/add/one"); tick(); expect(actualCount).toBe(1); httpMock.verify(); })); it("should return error on adding empty pattern", fakeAsync(() => { httpMock.expectOne("/server/autoqueue/get").flush([]); let actualCount = 0; aqService.add("").subscribe({ next: reaction => { expect(reaction.success).toBe(false); expect(reaction.errorMessage).toBe("Cannot add an empty autoqueue pattern."); actualCount++; } }); aqService.add(" ").subscribe({ next: reaction => { expect(reaction.success).toBe(false); expect(reaction.errorMessage).toBe("Cannot add an empty autoqueue pattern."); actualCount++; } }); aqService.add(null).subscribe({ next: reaction => { expect(reaction.success).toBe(false); expect(reaction.errorMessage).toBe("Cannot add an empty autoqueue pattern."); actualCount++; } }); httpMock.expectNone("/server/autoqueue/add/"); tick(); expect(actualCount).toBe(3); httpMock.verify(); })); it("should send updated patterns after an add pattern", fakeAsync(() => { httpMock.expectOne("/server/autoqueue/get").flush([]); const expectedPatterns = [ Immutable.List([]), Immutable.List([new AutoQueuePattern({pattern: "one"})]) ]; let actualCount = 0; aqService.patterns.subscribe({ next: patterns => { expect(Immutable.is(patterns, expectedPatterns[actualCount++])).toBe(true); } }); aqService.add("one").subscribe(DoNothing); httpMock.expectOne("/server/autoqueue/add/one").flush("{}"); tick(); expect(actualCount).toBe(2); httpMock.verify(); })); it("should NOT send updated patterns after a failed add", fakeAsync(() => { httpMock.expectOne("/server/autoqueue/get").flush([ new AutoQueuePattern({pattern: "one"}) ]); const expectedPatterns = [ Immutable.List([new AutoQueuePattern({pattern: "one"})]) ]; let actualCount = 0; aqService.patterns.subscribe({ next: patterns => { expect(Immutable.is(patterns, expectedPatterns[actualCount++])).toBe(true); } }); aqService.add("one").subscribe(DoNothing); httpMock.expectNone("/server/autoqueue/add/one"); tick(); expect(actualCount).toBe(1); httpMock.verify(); })); it("should send a GET on remove pattern", fakeAsync(() => { httpMock.expectOne("/server/autoqueue/get").flush([ new AutoQueuePattern({pattern: "one"}) ]); let actualCount = 0; aqService.remove("one").subscribe({ next: reaction => { expect(reaction.success).toBe(true); actualCount++; } }); httpMock.expectOne("/server/autoqueue/remove/one").flush("{}"); tick(); expect(actualCount).toBe(1); httpMock.verify(); })); it("should send correct GET requests on remove pattern", fakeAsync(() => { httpMock.expectOne("/server/autoqueue/get").flush([ new AutoQueuePattern({pattern: "test"}), new AutoQueuePattern({pattern: "test space"}), new AutoQueuePattern({pattern: "test/slash"}), new AutoQueuePattern({pattern: "test\"doublequote"}), new AutoQueuePattern({pattern: "/test/leadingslash"}) ]); aqService.remove("test").subscribe(DoNothing); httpMock.expectOne("/server/autoqueue/remove/test").flush("{}"); aqService.remove("test space").subscribe(DoNothing); httpMock.expectOne("/server/autoqueue/remove/test%2520space").flush("{}"); aqService.remove("test/slash").subscribe(DoNothing); httpMock.expectOne("/server/autoqueue/remove/test%252Fslash").flush("{}"); aqService.remove("test\"doublequote").subscribe(DoNothing); httpMock.expectOne("/server/autoqueue/remove/test%2522doublequote").flush("{}"); aqService.remove("/test/leadingslash").subscribe(DoNothing); httpMock.expectOne("/server/autoqueue/remove/%252Ftest%252Fleadingslash").flush("{}"); httpMock.verify(); })); it("should return error on removing non-existing pattern", fakeAsync(() => { httpMock.expectOne("/server/autoqueue/get").flush([ ]); let actualCount = 0; aqService.remove("one").subscribe({ next: reaction => { expect(reaction.success).toBe(false); expect(reaction.errorMessage).toBe("Pattern 'one' not found."); actualCount++; } }); httpMock.expectNone("/server/autoqueue/remove/one"); tick(); expect(actualCount).toBe(1); httpMock.verify(); })); it("should return error on removing empty pattern", fakeAsync(() => { httpMock.expectOne("/server/autoqueue/get").flush([ ]); let actualCount = 0; aqService.remove("").subscribe({ next: reaction => { expect(reaction.success).toBe(false); expect(reaction.errorMessage).toBe("Pattern '' not found."); actualCount++; } }); aqService.remove(" ").subscribe({ next: reaction => { expect(reaction.success).toBe(false); expect(reaction.errorMessage).toBe("Pattern ' ' not found."); actualCount++; } }); aqService.remove(null).subscribe({ next: reaction => { expect(reaction.success).toBe(false); expect(reaction.errorMessage).toBe("Pattern 'null' not found."); actualCount++; } }); httpMock.expectNone("/server/autoqueue/remove/"); tick(); expect(actualCount).toBe(3); httpMock.verify(); })); it("should send updated patterns after a remove pattern", fakeAsync(() => { httpMock.expectOne("/server/autoqueue/get").flush([ new AutoQueuePattern({pattern: "one"}), new AutoQueuePattern({pattern: "two"}) ]); const expectedPatterns = [ Immutable.List([ new AutoQueuePattern({pattern: "one"}), new AutoQueuePattern({pattern: "two"}) ]), Immutable.List([ new AutoQueuePattern({pattern: "two"}) ]) ]; let actualCount = 0; aqService.patterns.subscribe({ next: patterns => { expect(Immutable.is(patterns, expectedPatterns[actualCount++])).toBe(true); } }); aqService.remove("one").subscribe(DoNothing); httpMock.expectOne("/server/autoqueue/remove/one").flush("{}"); tick(); expect(actualCount).toBe(2); httpMock.verify(); })); it("should NOT send updated patterns after a failed remove", fakeAsync(() => { httpMock.expectOne("/server/autoqueue/get").flush([ new AutoQueuePattern({pattern: "one"}) ]); const expectedPatterns = [ Immutable.List([new AutoQueuePattern({pattern: "one"})]) ]; let actualCount = 0; aqService.patterns.subscribe({ next: patterns => { expect(Immutable.is(patterns, expectedPatterns[actualCount++])).toBe(true); } }); aqService.remove("two").subscribe(DoNothing); httpMock.expectNone("/server/autoqueue/remove/two"); tick(); expect(actualCount).toBe(1); httpMock.verify(); })); });
the_stack
import {default as codegen, FormattedCodeGen} from '@jsoverson/shift-codegen'; import DEBUG from 'debug'; import deepEqual from 'fast-deep-equal'; import {BindingIdentifier, Expression, IdentifierExpression, LiteralStringExpression, Node, Statement} from 'shift-ast'; import {parseScript} from 'shift-parser'; import {Declaration, Reference, Variable} from 'shift-scope'; import {GlobalState} from './global-state'; import {query} from './misc/query'; import { AsyncReplacer, RefactorError, Replacer, SelectorOrNode, SimpleIdentifier, SimpleIdentifierOwner, } from './misc/types'; import { copy, extractExpression, extractStatement, findNodes, isArray, isDeepSimilar, isFunction, isShiftNode, isStatement, isString, } from './misc/util'; import {waterfallMap} from './misc/waterfall'; const debug = DEBUG('shift-refactor'); /** * The Shift Refactor class that manages * * @deprecated * This was the original interface for shift-refactor pre-1.0. It remains similarly usable but is no longer intended to be instantiated directly. * Extend the chainable interface when necessary and use refactor() to instantiate. If a use case is not covered, submit an issue. * * @internal */ export class RefactorSession { nodes: Node[]; _root?: Node; globalSession: GlobalState; constructor(sourceOrNodes: Node | Node[] | string, globalSession?: GlobalState) { let nodes: Node[], tree: Node; if (!globalSession) { if (typeof sourceOrNodes === 'string' || !isArray(sourceOrNodes)) this.globalSession = new GlobalState(sourceOrNodes); else throw new Error('Only source or a single Script/Module node can be passed as input'); } else { this.globalSession = globalSession; } if (isArray(sourceOrNodes)) { nodes = (sourceOrNodes as any[]).filter((x: string | Node): x is Node => typeof x !== 'string'); } else { if (!isString(sourceOrNodes)) nodes = [sourceOrNodes]; else nodes = [this.globalSession.root]; } this.nodes = nodes; } get root(): Node { return this.globalSession.root; } get length(): number { return this.nodes.length; } $(querySessionOrNodes: SelectorOrNode | RefactorSession) { return this.subSession(querySessionOrNodes); } subSession(querySessionOrNodes: SelectorOrNode | RefactorSession) { const nodes = querySessionOrNodes instanceof RefactorSession ? querySessionOrNodes.nodes : findNodes(this.nodes, querySessionOrNodes); const subSession = new RefactorSession(nodes, this.globalSession); return subSession; } rename(selectorOrNode: SelectorOrNode, newName: string) { const lookupTable = this.globalSession.getLookupTable(); const nodes = findNodes(this.nodes, selectorOrNode); nodes.forEach((node: Node) => { if (node.type === 'VariableDeclarator') node = node.binding; const lookup = lookupTable.variableMap.get(node); if (!lookup) return; this.renameInPlace(lookup[0], newName); }); return this; } renameInPlace(lookup: Variable, newName: string) { if (!lookup || !newName) return; lookup.declarations.forEach(decl => ((decl.node as BindingIdentifier).name = newName)); lookup.references.forEach(ref => ((ref.node as IdentifierExpression).name = newName)); } delete(selectorOrNode: SelectorOrNode = this.nodes) { const nodes = findNodes(this.nodes, selectorOrNode); if (nodes.length > 0) { nodes.forEach((node: Node) => this.globalSession._queueDeletion(node)); } return this.globalSession.conditionalCleanup(); } replace(selectorOrNode: SelectorOrNode, replacer: Replacer | AsyncReplacer) { const nodes = findNodes(this.nodes, selectorOrNode); const replacementScript = typeof replacer === 'string' ? parseScript(replacer) : null; const replaced = nodes.map((node: Node) => { let replacement = null; if (isFunction(replacer)) { const rv = replacer(node); if (rv && rv instanceof Promise) { throw new RefactorError(`Promise returned from replacer function, use .replaceAsync() instead.`); } if (isShiftNode(rv)) { replacement = rv; } else if (isString(rv)) { const returnedTree = parseScript(rv); if (isStatement(node)) { replacement = extractStatement(returnedTree); } else { replacement = extractExpression(returnedTree); } } else { throw new RefactorError(`Invalid return type from replacement function: ${rv}`); } } else if (isShiftNode(replacer)) { replacement = copy(replacer); } else if (replacementScript) { if (isStatement(node)) { replacement = copy(replacementScript.statements[0]); } else { // if we have a directive, assume we parsed a single string and use it as a LiteralStringExpression if (replacementScript.directives.length > 0) { replacement = new LiteralStringExpression({value: replacementScript.directives[0].rawValue}); } else if (replacementScript.statements[0].type === 'ExpressionStatement') { replacement = copy(replacementScript.statements[0].expression); } } } if (node && replacement !== node) { this.globalSession._queueReplacement(node, replacement); return true; } else { return false; } }); this.globalSession.conditionalCleanup(); return replaced.filter((wasReplaced: any) => wasReplaced).length; } async replaceAsync(selectorOrNode: SelectorOrNode, replacer: AsyncReplacer): Promise<number> { const nodes = findNodes(this.nodes, selectorOrNode); if (!isFunction(replacer)) { throw new RefactorError(`Invalid replacer type for replaceAsync. Pass a function or use .replace() instead.`); } const promiseResults = await waterfallMap(nodes, async (node: Node, i: number) => { let replacement = null; const rv = await replacer(node); if (isShiftNode(rv)) { replacement = rv; } else if (isString(rv)) { const returnedTree = parseScript(rv); if (isStatement(node)) { replacement = extractStatement(returnedTree); } else { replacement = extractExpression(returnedTree); } } else { throw new RefactorError(`Invalid return type from replacement function: ${rv}`); } if (node && replacement !== node) { this.globalSession._queueReplacement(node, replacement); return true; } else { return false; } }); this.globalSession.conditionalCleanup(); return promiseResults.filter(result => result).length; } replaceRecursive(selectorOrNode: SelectorOrNode, replacer: Replacer) { const nodesReplaced = this.replace(selectorOrNode, replacer); this.globalSession.cleanup(); if (nodesReplaced > 0) this.replaceRecursive(selectorOrNode, replacer); return this; } first(): Node { return this.nodes[0]; } findParents(selectorOrNode: SelectorOrNode): Node[] { return this.globalSession.findParents(selectorOrNode); } prepend(selectorOrNode: SelectorOrNode, replacer: Replacer) { return this.globalSession.insert(selectorOrNode, replacer, false); } append(selectorOrNode: SelectorOrNode, replacer: Replacer) { return this.globalSession.insert(selectorOrNode, replacer, true); } query(selector: string | string[]) { return query(this.nodes, selector); } // alias for query because I refuse to name findOne()->queryOne() and I need the symmetry. find(selectorOrNode: string) { return this.query(selectorOrNode); } queryFrom(astNodes: Node | Node[], selectorOrNode: string) { return isArray(astNodes) ? astNodes.map(node => query(node, selectorOrNode)).flat() : query(astNodes, selectorOrNode); } findMatchingExpression(sampleSrc: string): Expression[] { const tree = parseScript(sampleSrc); if (tree.statements[0] && tree.statements[0].type === 'ExpressionStatement') { const sampleExpression = tree.statements[0].expression; const potentialMatches = this.query(sampleExpression.type); const matches = potentialMatches.filter((realNode: Node) => deepEqual(sampleExpression, realNode)); return matches as Expression[]; } return []; } findMatchingStatement(sampleSrc: string): Statement[] { const tree = parseScript(sampleSrc); if (tree.statements[0]) { const sampleStatement = tree.statements[0]; const potentialMatches = this.query(sampleStatement.type); const matches = potentialMatches.filter((realNode: Node) => isDeepSimilar(sampleStatement, realNode)); return matches as Statement[]; } return []; } findReferences(node: SimpleIdentifier | SimpleIdentifierOwner): Reference[] { const lookup = this.globalSession.lookupVariable(node); return lookup.references; } findDeclarations(node: SimpleIdentifier | SimpleIdentifierOwner): Declaration[] { const lookup = this.globalSession.lookupVariable(node); return lookup.declarations; } findOne(selectorOrNode: string) { const nodes = this.query(selectorOrNode); if (nodes.length !== 1) throw new Error(`findOne('${selectorOrNode}') found ${nodes.length} nodes. If this is intentional, use .find()`); return nodes[0]; } closest(originSelector: SelectorOrNode, closestSelector: string): Node[] { const nodes = findNodes(this.nodes, originSelector); const recurse = (node: Node, selector: string): Node[] => { const parent = this.findParents(node)[0]; if (!parent) return []; const matches = query(parent, selector); if (matches.length > 0) return matches; else return recurse(parent, selector); }; return nodes.flatMap((node: Node) => recurse(node, closestSelector)); } cleanup() { this.globalSession.cleanup(); return this; } print(ast?: Node) { const generator = new FormattedCodeGen(); return codegen(ast || this.first(), generator); } }
the_stack
import * as vscode from 'vscode'; import * as assert from 'assert'; import * as sinon from 'sinon'; import * as path from 'path'; import * as fs from 'fs'; import { afterEach, beforeEach } from 'mocha'; import { codeCovViewService } from '../../../src/services'; import { addErrorToDoc, removeErrorOnDoc, createForceJson, timeout, } from '../../testUtils/utils.test'; import { toArray } from '../../../src/util'; import { getSrcDir } from '../../../src/services/configuration'; suite('createClass.ts and compile.ts', () => { const sandbox = sinon.createSandbox(); beforeEach(() => { sandbox.stub(vscode.window, 'showWarningMessage').returns({ async then(callback: any) { return callback('Overwrite'); // LWC component }, }); }); afterEach(() => { sandbox.restore(); }); test('Creates new class', async () => { sandbox.stub(vscode.window, 'showQuickPick').callsFake(function (items: any, _options) { return { async then(callback: any) { return callback(toArray(items)[1]); // apex class }, }; }); sandbox.stub(vscode.window, 'showInputBox').callsFake(function (_options) { return { async then(callback: any) { return callback('testerson'); // name of class }, }; }); return await vscode.commands.executeCommand('ForceCode.createClass').then((_res) => { // verify the file was created let output = path.join(getSrcDir(), 'classes', 'testerson.cls'); return assert.strictEqual(fs.existsSync(output), true); }); }); test('Save class fail', async () => { await addErrorToDoc(); }); test('Save class pass', async () => { await removeErrorOnDoc(); }); test('Refresh class', async () => { let output = path.join(getSrcDir(), 'classes', 'testerson.cls'); // get the mTime for the file const mTime = fs.statSync(output).mtimeMs; return await vscode.workspace.openTextDocument(output).then((doc) => { return vscode.commands .executeCommand('ForceCode.refresh', undefined, [doc.uri]) .then((_res) => { // make sure the file actually refreshed return assert.notStrictEqual(mTime, fs.statSync(output).mtimeMs); }); }); }); test('Open file (class) in the org', async () => { let output = path.join(getSrcDir(), 'classes', 'testerson.cls'); return await vscode.workspace.openTextDocument(output).then((doc) => { return vscode.commands.executeCommand('ForceCode.openFileInOrg', doc.uri).then((_res) => { return assert.strictEqual(true, true); }); }); }); test('Saves class metadata fail', async () => { // open the testerson class metadata let output = path.join(getSrcDir(), 'classes', 'testerson.cls-meta.xml'); await vscode.workspace.openTextDocument(output).then((doc) => { return vscode.window.showTextDocument(doc).then(() => { // edit the doc to fail return addErrorToDoc(); }); }); }); test('Saves class metadata pass', async () => { // doc will already be active from the above test await removeErrorOnDoc(); }); test('Creates Visualforce Page', async () => { sandbox.stub(vscode.window, 'showQuickPick').callsFake(function (items: any, _options) { return { async then(callback: any) { return callback(toArray(items)[5]); // VF page }, }; }); sandbox.stub(vscode.window, 'showInputBox').callsFake(function (_options) { return { async then(callback: any) { return callback('testerson'); // name of VF page }, }; }); return await vscode.commands.executeCommand('ForceCode.createClass').then((_res) => { let output = path.join(getSrcDir(), 'pages', 'testerson.page'); return assert.strictEqual(fs.existsSync(output), true); }); }); test('Save VF page fail', async () => { await addErrorToDoc(); }); test('Save VF page pass', async () => { await removeErrorOnDoc(); }); test('Opens org via ForceCode menu', async () => { sandbox.stub(vscode.window, 'showQuickPick').callsFake(function (items: any, _options) { return { async then(callback: any) { return callback(toArray(items)[0]); // Open org option }, }; }); return await vscode.commands.executeCommand('ForceCode.showMenu').then((_res) => { return assert.strictEqual(true, true); }); }); test('Preview VF', async () => { let output = path.join(getSrcDir(), 'pages', 'testerson.page'); return await vscode.workspace.openTextDocument(output).then((doc) => { return vscode.commands.executeCommand('ForceCode.previewVF', doc.uri).then((_res) => { return assert.strictEqual(true, true); }); }); }); test('Creates Visualforce Component', async () => { sandbox.stub(vscode.window, 'showQuickPick').callsFake(function (items: any, _options) { return { async then(callback: any) { return callback(toArray(items)[6]); // VF component }, }; }); sandbox.stub(vscode.window, 'showInputBox').callsFake(function (_options) { return { async then(callback: any) { return callback('testerson'); // name of component }, }; }); return await vscode.commands.executeCommand('ForceCode.createClass').then((_res) => { let output = path.join(getSrcDir(), 'components', 'testerson.component'); return assert.strictEqual(fs.existsSync(output), true); }); }); test('Save VF component fail', async () => { await addErrorToDoc(); }); test('Save VF component pass', async () => { await removeErrorOnDoc(); }); test('Delete VF component', async () => { sandbox.restore(); sandbox .stub(vscode.window, 'showWarningMessage') .callsFake(function ( _message: string, _options: vscode.MessageOptions, ..._items: vscode.MessageItem[] ) { return { async then(callback: any) { return callback('Yes'); // Delete the file from the org }, }; }); sandbox .stub(vscode.window, 'showInformationMessage') .callsFake(function ( _message: string, _options: vscode.MessageOptions, ..._items: vscode.MessageItem[] ) { return { async then(callback: any) { return callback('Yes'); // Delete the file from the workspace }, }; }); // doc is already open from the save pass above return await vscode.commands.executeCommand('ForceCode.deleteFile').then((_res) => { let output = path.join(getSrcDir(), 'components', 'testerson.component'); return assert.strictEqual(fs.existsSync(output), false); }); }); test('Creates Aura App', async () => { sandbox.stub(vscode.window, 'showQuickPick').callsFake(function (items: any, _options) { return { async then(callback: any) { return callback(toArray(items)[0]); // Aura, app }, }; }); sandbox.stub(vscode.window, 'showInputBox').callsFake(function (_options) { return { async then(callback: any) { return callback('testersonAura'); // name of Aura app }, }; }); return await vscode.commands.executeCommand('ForceCode.createClass').then((_res) => { let output = path.join(getSrcDir(), 'aura', 'testersonAura'); return assert.strictEqual(fs.existsSync(output), true); }); }); test('Save Aura app fail', async () => { await addErrorToDoc(); }); test('Save Aura app pass', async () => { await removeErrorOnDoc(); }); test('Preview Aura app', async () => { let output = path.join(getSrcDir(), 'aura', 'testersonAura', 'testersonAura.app'); return await vscode.workspace.openTextDocument(output).then((doc) => { return vscode.commands.executeCommand('ForceCode.previewApp', doc.uri).then((_res) => { return assert.strictEqual(true, true); }); }); }); test('Delete Aura app DOCUMENTATION', async () => { sandbox.restore(); sandbox .stub(vscode.window, 'showWarningMessage') .callsFake(function ( _message: string, _options: vscode.MessageOptions, ..._items: vscode.MessageItem[] ) { return { async then(callback: any) { return callback('Yes'); // Delete the file from the org }, }; }); sandbox .stub(vscode.window, 'showInformationMessage') .callsFake(function ( _message: string, _options: vscode.MessageOptions, ..._items: vscode.MessageItem[] ) { return { async then(callback: any) { return callback('Yes'); // Delete the file from the workspace }, }; }); let output = path.join(getSrcDir(), 'aura', 'testersonAura', 'testersonAura.auradoc'); return await vscode.workspace.openTextDocument(output).then((doc) => { return vscode.commands.executeCommand('ForceCode.deleteFile', doc.uri).then((_res) => { return assert.strictEqual(fs.existsSync(output), false); }); }); }); test('Delete Aura app', async () => { sandbox.restore(); sandbox .stub(vscode.window, 'showWarningMessage') .callsFake(function ( _message: string, _options: vscode.MessageOptions, ..._items: vscode.MessageItem[] ) { return { async then(callback: any) { return callback('Yes'); // Delete the file from the org }, }; }); sandbox .stub(vscode.window, 'showInformationMessage') .callsFake(function ( _message: string, _options: vscode.MessageOptions, ..._items: vscode.MessageItem[] ) { return { async then(callback: any) { return callback('Yes'); // Delete the file from the workspace }, }; }); let output = path.join(getSrcDir(), 'aura', 'testersonAura', 'testersonAura.app'); return await vscode.workspace.openTextDocument(output).then((doc) => { return vscode.commands.executeCommand('ForceCode.deleteFile', doc.uri).then((_res) => { return assert.strictEqual(fs.existsSync(output), false); }); }); }); test('Creates Trigger on Account', async () => { sandbox.stub(vscode.window, 'showQuickPick').callsFake(function (items: any, _options) { return { async then(callback: any) { return callback(toArray(items)[4]); // Trigger }, }; }); let inputStub = sandbox .stub(vscode.window, 'showInputBox') .onFirstCall() .callsFake(function (_options) { return { async then(callback: any) { return callback('testerson'); // name of Trigger }, }; }); inputStub.onSecondCall().callsFake(function (_options) { return { async then(callback: any) { return callback('Account'); // Trigger is on Object Account }, }; }); return await vscode.commands.executeCommand('ForceCode.createClass').then((_res) => { let output = path.join(getSrcDir(), 'triggers', 'testerson.trigger'); return assert.strictEqual(fs.existsSync(output), true); }); }); test('Save Trigger fail', async () => { await addErrorToDoc(); }); test('Save Trigger pass', async () => { await removeErrorOnDoc(); }); test('Creates LWC Component', async () => { sandbox.stub(vscode.window, 'showQuickPick').callsFake(function (items: any, _options) { return { async then(callback: any) { return callback(toArray(items)[3]); // LWC component }, }; }); sandbox.stub(vscode.window, 'showInputBox').callsFake(function (_options) { return { async then(callback: any) { return callback('theLWCTest'); // name of component }, }; }); return await vscode.commands.executeCommand('ForceCode.createClass').then((_res) => { let output = path.join(getSrcDir(), 'lwc', 'theLWCTest'); return assert.strictEqual(fs.existsSync(output), true); }); }); test('Save LWC fail', async () => { await addErrorToDoc(); }); test('Creates LWC Component 2', async () => { sandbox.stub(vscode.window, 'showQuickPick').callsFake(function (items: any, _options) { return { async then(callback: any) { return callback(toArray(items)[3]); // LWC component }, }; }); sandbox.stub(vscode.window, 'showInputBox').callsFake(function (_options) { return { async then(callback: any) { return callback('theLWCTest2'); // name of component }, }; }); createForceJson(process.env.SF_USERNAME || '', true); // turn on autoCompile return await vscode.commands.executeCommand('ForceCode.createClass').then((_res) => { let output = path.join(getSrcDir(), 'lwc', 'theLWCTest2'); return assert.strictEqual(fs.existsSync(output), true); }); }); test('Save LWC pass', async () => { // indicate we shouldn't try and remove an error, and that autoCompile is on await removeErrorOnDoc(true, true); }); test('Creates Lightning Message Channel', async () => { sandbox.stub(vscode.window, 'showQuickPick').callsFake(function (items: any, _options) { return { async then(callback: any) { return callback(toArray(items)[2]); // Lightning Message Channel }, }; }); sandbox.stub(vscode.window, 'showInputBox').callsFake(function (_options) { return { async then(callback: any) { return callback('MyMessageChannel'); // name of component }, }; }); return await vscode.commands.executeCommand('ForceCode.createClass').then((_res) => { let output = path.join(getSrcDir(), 'messageChannels', 'MyMessageChannel.messageChannel'); return assert.strictEqual(fs.existsSync(output), true); }); }); test('Save Lightning Message Channel fail', async () => { await addErrorToDoc(); }); test('Creates Lightning Message Channel 2', async () => { sandbox.stub(vscode.window, 'showQuickPick').callsFake(function (items: any, _options) { return { async then(callback: any) { return callback(toArray(items)[2]); // Lightning Message Channel }, }; }); sandbox.stub(vscode.window, 'showInputBox').callsFake(function (_options) { return { async then(callback: any) { return callback('MyMessageChannel2'); // name of component }, }; }); createForceJson(process.env.SF_USERNAME || '', true); // turn on autoCompile return await vscode.commands.executeCommand('ForceCode.createClass').then((_res) => { let output = path.join(getSrcDir(), 'messageChannels', 'MyMessageChannel2.messageChannel'); return assert.strictEqual(fs.existsSync(output), true); }); }); test('Save Lightning Message Channel pass', async () => { // indicate we shouldn't try and remove an error, and that autoCompile is on await removeErrorOnDoc(true, true); }); test('Test multi-save', async () => { // indicate we shouldn't try and remove an error, and that autoCompile is on removeErrorOnDoc(true, true); await timeout(1000); await removeErrorOnDoc(true, true); }); test('Verify Code Coverage view now has contents', async () => { return assert.strictEqual(codeCovViewService.getChildren().length > 0, true); }); test('Check for file changes', async () => { return await vscode.commands.executeCommand('ForceCode.checkForFileChanges').then((_res) => { return assert.strictEqual(true, true); }); }); });
the_stack
import * as assert from 'assert'; import { commands, Uri, workspace } from 'vscode'; import { IDisposable } from '../../extension/types'; import * as tmp from 'tmp'; import * as fs from 'fs'; import { Compiler } from '../../extension/kernel/compiler'; import * as recast from 'recast'; import { parse } from 'acorn'; const { default: generate } = require('@babel/generator'); suite('Top level await compiler tests', () => { const testCases: [string, string][] = [ ['0', '(async () => { return 0;})();'], ['await 0', '(async () => {return (await 0);})()'], ['await 0;', '(async () => {return (await 0);})()'], ['(await 0)', '(async () => {return ((await 0));})()'], ['(await 0);', '(async () => {return ((await 0));})()'], [ 'async function foo() { await 0; }', 'var foo;(async () => {this.foo = foo;async function foo() { await 0; }})()' ], ['async () => await 0', '(async () => {return (async () => await 0);})()'], [ 'class A { async method() { await 0 } }', 'var A;(async () => {this.A = class A { async method() { await 0; }}})()' ], ['await 0; return 0;', '(async () => {await 0;return 0;})()'], ['var a = await 1', 'var a;(async () => { a = await 1;})()'], ['let a = await 1', 'var a;(async () => { a = await 1;})()'], ['const a = await 1', 'var a;(async () => { a = await 1;})()'], [ 'for (var i = 0; i < 1; ++i) { console.log(await Promise.resolve(1)); }', 'var i; (async () => { for (i = 0; i < 1; ++i) { console.log(await Promise.resolve(1)); } })()' ], ['for (let i = 0; i < 1; ++i) { await i }', '(async () => { for (let i = 0; i < 1; ++i) { await i } })()'], [ 'var {a} = {a:1}, [b] = [1], {c:{d}} = {c:{d: await 1}}', 'var a, b, d; (async () => { ({a} = {a:1}), ([b] = [1]), ' + '({c:{d}} = {c:{d: await 1}}) })()' ], ['let [a, b, c] = await ([1, 2, 3])', 'var a, b, c; (async () => { [a, b, c] = await ([1, 2, 3]) })()'], [ 'let {a,b,c} = await ({a: 1, b: 2, c: 3})', 'var a, b, c; (async () => { ({a,b,c} = ' + 'await ({a: 1, b: 2, c: 3})) })()' ], [ 'let {a: [b]} = {a: [await 1]}, [{d}] = [{d: 3}]', 'var b, d; (async () => { ( ({a: [b]} = {a: [await 1]}),' + ' ([{d}] = [{d: 3}])) })()' ], /* eslint-disable no-template-curly-in-string */ // acorn parser falls over if we don't put `(..)` around the `{a:1}` // Hence the original code was 'console.log(`${(await { a: 1 }).a}`)' ['console.log(`${(await ({ a: 1 })).a}`)', '(async () => { return (console.log(`${(await { a: 1 }).a}`)) })()'], /* eslint-enable no-template-curly-in-string */ ['await 0; function foo() {}', 'var foo; (async () => {await 0; this.foo = foo; function foo() {} })()'], ['await 0; class Foo {}', 'var Foo;(async () => {await 0; this.Foo = class Foo {} })()'], [ 'if (await true) { function foo() {} }', 'var foo;(async () => {if (await true) { this.foo = foo; function foo() {} } })()' ], ['if (await true) { class Foo{} }', '(async () => { if (await true) { class Foo{} } })()'], ['if (await true) { var a = 1; }', 'var a; (async () => { if (await true) { (a = 1); } })()'], ['if (await true) { let a = 1; }', '(async () => { if (await true) { let a = 1; } })()'], [ 'var a = await 1; let b = 2; const c = 3;', 'var a, b, c;(async () => { ( a = await 1); ( b = 2); ( c = 3);})()' ], ['let o = await 1, p', 'var o, p;(async () => { ( o = await 1, p=undefined);})()'], ['await 1234;', '(async () => { return await 1234;})()'], ['await Promise.resolve(1234);', '(async () => { return await Promise.resolve(1234);})()'], [ 'await (async () => Promise.resolve(1234))()', '(async () => { return await (async () => Promise.resolve(1234))();})();' ], [ 'await (async () => { let p = await 1; return p; })()', '(async () => { return await (async () => { let p = await 1; return p; })();})();' ], ['{ let p = await 1; }', '(async () => {{ let p = await 1;}})()'], ['var p = await 1', 'var p;(async () => { p = await 1;})();'], [ 'await (async () => { var p = await 1; return p; })()', '(async () => { return (await (async () => ' + '{ var p = await 1; return p; })()) })()' ], ['{ var p = await 1; }', 'var p;(async () => { { p = await 1; }})();'], [ 'for await (var i of asyncIterable) { console.log(i); }', 'var i;(async () => { for await ( i of asyncIterable) { console.log(i);}})()' ], [ 'for await (var [i] of asyncIterable) { i; }', 'var i;(async () => { for await ( [i] of asyncIterable) { i;}})()' ], [ 'for await (var {i} of asyncIterable) { i; }', 'var i;(async () => { for await ( { i } of asyncIterable) { i;}})()' ], [ 'for await (var [{i}, [j]] of asyncIterable) { i; }', 'var i,j;(async () => { for await ( [{ i }, [j]] of asyncIterable) { i;}})()' ], ['for await (let i of asyncIterable) { i; }', '(async () => { for await (let i of asyncIterable) { i;}})()'], [ 'for await (const i of asyncIterable) { i; }', '(async () => { for await (const i of asyncIterable) { i;}})()' ], ['for (var i of [1,2,3]) { await 1; }', 'var i; (async () => { for (i of [1,2,3]) { await 1; } })()'], ['for (var [i] of [[1], [2]]) { await 1; }', 'var i; (async () => { for ([i] of [[1], [2]]) { await 1; } })()'], [ 'for (var {i} of [{i: 1}, {i: 2}]) { await 1; }', 'var i; (async () => { for ({i} of [{i: 1}, {i: 2}]) { await 1; } })()' ], [ 'for (var [{i}, [j]] of [[{i: 1}, [2]]]) { await 1; }', 'var i, j; (async () => { for ([{i}, [j]] of [[{i: 1}, [2]]])' + ' { await 1; } })()' ], ['for (let i of [1,2,3]) { await 1; }', '(async () => { for (let i of [1,2,3]) { await 1; } })()'], ['for (const i of [1,2,3]) { await 1; }', '(async () => { for (const i of [1,2,3]) { await 1; } })()'], ['for (var i in {x:1}) { await 1 }', 'var i; (async () => { for (i in {x:1}) { await 1 } })()'], ['for (var [a,b] in {xy:1}) { await 1 }', 'var a, b; (async () => { for ([a,b] in {xy:1}) { await 1 } })()'], ['for (let i in {x:1}) { await 1 }', '(async () => { for (let i in {x:1}) { await 1 } })()'], ['for (const i in {x:1}) { await 1 }', '(async () => { for (const i in {x:1}) { await 1 } })()'], ['import * as fs from "fs"', 'var fs;void (fs = __importStar(require("fs")));'], [ 'import * as fs from "fs"; await fs.readFileSync("filename");', 'var fs;void (fs = __importStar(require("fs")));var fs;(async () => { fs = __importStar(require("fs")); return await fs.readFileSync("filename");})();' ], [ 'import {readFileSync, readFile} from "fs"; await readFileSync("filename");', 'var readFileSync;var readFile;void ({ readFileSync, readFile} = require("fs"));var fs_1;(async () => { fs_1 = require("fs"); return await fs_1.readFileSync("filename");})();' ], [ 'import {readFileSync:Read, readFile} from "fs"; await Read("filename");', 'var readFileSync;var Read;var readFile;void ({ readFileSync, Read, readFile} = require("fs"));var fs_1;(async () => { fs_1 = require("fs"); return await fs_1.Read("filename");})();' ] ]; const disposables: IDisposable[] = []; suiteTeardown(async () => { disposables.forEach((item) => { try { item.dispose(); } catch (ex) { // } }); await commands.executeCommand('workbench.action.closeAllEditors'); }); test('Sample test', () => { assert.equal(-1, [1, 2, 3].indexOf(5)); assert.equal(-1, [1, 2, 3].indexOf(0)); // const x = getCodeObject(undefined as any); }); [false, true].forEach((supportsExceptionBreakpoints) => { suite(`${supportsExceptionBreakpoints ? 'With' : 'Without'} exception breakpoints`, () => { testCases.forEach(([code, expected]) => { test(`test - ${code}`, async () => { const nb = await createNotebook(code); const codeObject = Compiler.getOrCreateCodeObject(nb.cellAt(0), code, supportsExceptionBreakpoints); // When supporting breakpoints in debugger, all we do is wrap the code in a try..catch.. if (supportsExceptionBreakpoints && expected.includes('})()')) { expected = expected.replace('(async () => {', '(async () => { try {'); expected = expected.substring(0, expected.lastIndexOf('})()')) + '} catch (__compilerEx){throw __compilerEx;}})()'; } let prettyExpectedCode = expected.trim(); let prettyGeneratedCode = codeObject.code.trim(); if (prettyExpectedCode !== prettyGeneratedCode) { try { prettyExpectedCode = getPrettyfiedCode(expected, 'recast'); prettyGeneratedCode = getPrettyfiedCode(codeObject.code, 'recast'); } catch (ex) { // recast parser fails when parsing async iterables, // Hence use babel in this case. // Could use babel always, but thats more work (plugins, etc). prettyExpectedCode = getPrettyfiedCode(expected, 'babel'); prettyGeneratedCode = getPrettyfiedCode(codeObject.code, 'babel'); } } assert.strictEqual(prettyExpectedCode, prettyGeneratedCode); }); }); }); }); function getPrettyfiedCode(source: string, formatter: 'recast' | 'babel') { if (formatter === 'recast') { const parsedCode = parse(source, { ecmaVersion: 'latest' } as any); return recast.prettyPrint(parsedCode).code.split(/\r?\n/).join('').trim(); } else { const parsedCode = parse(source, { ecmaVersion: 'latest' }); return generate(parsedCode, { compact: true }).code.split(/\r?\n/).join('').trim(); } } async function createNotebook(source: string) { const result = tmp.fileSync({ postfix: '.nnb' }); disposables.push({ dispose: () => result.removeCallback() }); fs.writeFileSync(result.name, JSON.stringify({ cells: [{ source, language: 'javascript' }] })); return workspace.openNotebookDocument(Uri.file(result.name)); } });
the_stack
import dynamicProto from "@microsoft/dynamicproto-js"; import { ISession, utlCanUseLocalStorage, utlGetLocalStorage, utlSetLocalStorage } from "@microsoft/applicationinsights-common"; import { IDiagnosticLogger, _InternalMessageId, LoggingSeverity, DiagnosticLogger, IAppInsightsCore, ICookieMgr, safeGetCookieMgr, isFunction, newId, dumpObj, getExceptionName, dateNow, safeGetLogger } from "@microsoft/applicationinsights-core-js"; const cookieNameConst = "ai_session"; export interface ISessionConfig { sessionRenewalMs?: () => number; sessionExpirationMs?: () => number; namePrefix?: () => string; sessionCookiePostfix?: () => string; idLength?: () => number; getNewId?: () => (idLength?: number) => string; /** * @deprecated Avoid using this value to override the cookie manager cookie domain. */ cookieDomain?: () => string; } export class Session implements ISession { /** * The session ID. */ public id?: string; /** * The date at which this guid was generated. * Per the spec the ID will be regenerated if more than acquisitionSpan milliseconds elapsed from this time. */ public acquisitionDate?: number; /** * The date at which this session ID was last reported. * This value should be updated whenever telemetry is sent using this ID. * Per the spec the ID will be regenerated if more than renewalSpan milliseconds elapse from this time with no activity. */ public renewalDate?: number; } export class _SessionManager { public static acquisitionSpan = 86400000; // 24 hours in ms public static renewalSpan = 1800000; // 30 minutes in ms public static cookieUpdateInterval = 60000 // 1 minute in ms public automaticSession: Session; public config: ISessionConfig; constructor(config: ISessionConfig, core?: IAppInsightsCore) { let self = this; let _storageNamePrefix: () => string; let _cookieUpdatedTimestamp: number; let _logger: IDiagnosticLogger = safeGetLogger(core); let _cookieManager: ICookieMgr = safeGetCookieMgr(core); dynamicProto(_SessionManager, self, (_self) => { if (!config) { config = ({} as any); } if (!isFunction(config.sessionExpirationMs)) { config.sessionExpirationMs = () => _SessionManager.acquisitionSpan; } if (!isFunction(config.sessionRenewalMs)) { config.sessionRenewalMs = () => _SessionManager.renewalSpan; } _self.config = config; // sessionCookiePostfix takes the preference if it is configured, otherwise takes namePrefix if configured. const sessionCookiePostfix = (_self.config.sessionCookiePostfix && _self.config.sessionCookiePostfix()) ? _self.config.sessionCookiePostfix() : ((_self.config.namePrefix && _self.config.namePrefix()) ? _self.config.namePrefix() : ""); _storageNamePrefix = () => cookieNameConst + sessionCookiePostfix; _self.automaticSession = new Session(); _self.update = () => { // Always using Date getTime() as there is a bug in older IE instances that causes the performance timings to have the hi-bit set eg 0x800000000 causing // the number to be incorrect. const nowMs = dateNow(); let isExpired = false; const session = _self.automaticSession; if (!session.id) { isExpired = !_initializeAutomaticSession(session, nowMs); } const sessionExpirationMs = _self.config.sessionExpirationMs(); if (!isExpired && sessionExpirationMs > 0) { const sessionRenewalMs = _self.config.sessionRenewalMs(); const timeSinceAcqMs = nowMs - session.acquisitionDate; const timeSinceRenewalMs = nowMs - session.renewalDate; isExpired = timeSinceAcqMs < 0 || timeSinceRenewalMs < 0; // expired if the acquisition or last renewal are in the future isExpired = isExpired || timeSinceAcqMs > sessionExpirationMs; // expired if the time since acquisition is more than session Expiration isExpired = isExpired || timeSinceRenewalMs > sessionRenewalMs; // expired if the time since last renewal is more than renewal period } // renew if acquisitionSpan or renewalSpan has elapsed if (isExpired) { // update automaticSession so session state has correct id _renew(nowMs); } else { // do not update the cookie more often than cookieUpdateInterval if (!_cookieUpdatedTimestamp || nowMs - _cookieUpdatedTimestamp > _SessionManager.cookieUpdateInterval) { _setCookie(session, nowMs); } } }; /** * Record the current state of the automatic session and store it in our cookie string format * into the browser's local storage. This is used to restore the session data when the cookie * expires. */ _self.backup = () => { const session = _self.automaticSession; _setStorage(session.id, session.acquisitionDate, session.renewalDate); }; /** * Use config.namePrefix + ai_session cookie data or local storage data (when the cookie is unavailable) to * initialize the automatic session. * @returns true if values set otherwise false */ function _initializeAutomaticSession(session: ISession, now: number): boolean { let isValid = false; const cookieValue = _cookieManager.get(_storageNamePrefix()); if (cookieValue && isFunction(cookieValue.split)) { isValid = _initializeAutomaticSessionWithData(session, cookieValue); } else { // There's no cookie, but we might have session data in local storage // This can happen if the session expired or the user actively deleted the cookie // We only want to recover data if the cookie is missing from expiry. We should respect the user's wishes if the cookie was deleted actively. // The User class handles this for us and deletes our local storage object if the persistent user cookie was removed. const storageValue = utlGetLocalStorage(_logger, _storageNamePrefix()); if (storageValue) { isValid = _initializeAutomaticSessionWithData(session, storageValue); } } return isValid || !!session.id; } /** * Extract id, acquisitionDate, and renewalDate from an ai_session payload string and * use this data to initialize automaticSession. * * @param {string} sessionData - The string stored in an ai_session cookie or local storage backup * @returns true if values set otherwise false */ function _initializeAutomaticSessionWithData(session: ISession, sessionData: string) { let isValid = false; const sessionReset = ", session will be reset"; const tokens = sessionData.split("|"); if (tokens.length >= 2) { try { const acqMs = +tokens[1] || 0; const renewalMs = +tokens[2] || 0; if (isNaN(acqMs) || acqMs <= 0) { _logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.SessionRenewalDateIsZero, "AI session acquisition date is 0" + sessionReset); } else if (isNaN(renewalMs) || renewalMs <= 0) { _logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.SessionRenewalDateIsZero, "AI session renewal date is 0" + sessionReset); } else if (tokens[0]) { // Everything looks valid so set the values session.id = tokens[0]; session.acquisitionDate = acqMs; session.renewalDate = renewalMs; isValid = true; } } catch (e) { _logger.throwInternal(LoggingSeverity.CRITICAL, _InternalMessageId.ErrorParsingAISessionCookie, "Error parsing ai_session value [" + (sessionData || "") + "]" + sessionReset + " - " + getExceptionName(e), { exception: dumpObj(e) }); } } return isValid; } function _renew(nowMs: number) { let theConfig = (_self.config ||{}); let getNewId = (theConfig.getNewId ? theConfig.getNewId() : null) || newId; _self.automaticSession.id = getNewId(theConfig.idLength ? theConfig.idLength() : 22); _self.automaticSession.acquisitionDate = nowMs; _setCookie(_self.automaticSession, nowMs); // If this browser does not support local storage, fire an internal log to keep track of it at this point if (!utlCanUseLocalStorage()) { _logger.throwInternal(LoggingSeverity.WARNING, _InternalMessageId.BrowserDoesNotSupportLocalStorage, "Browser does not support local storage. Session durations will be inaccurate."); } } function _setCookie(session: ISession, nowMs: number) { let acq = session.acquisitionDate; session.renewalDate = nowMs let config = _self.config; let renewalPeriodMs = config.sessionRenewalMs(); // Set cookie to expire after the session expiry time passes or the session renewal deadline, whichever is sooner // Expiring the cookie will cause the session to expire even if the user isn't on the page const acqTimeLeftMs = (acq + config.sessionExpirationMs()) - nowMs; const cookie = [session.id, acq, nowMs]; let maxAgeSec = 0; if (acqTimeLeftMs < renewalPeriodMs) { maxAgeSec = acqTimeLeftMs / 1000; } else { maxAgeSec = renewalPeriodMs / 1000; } const cookieDomain = config.cookieDomain ? config.cookieDomain() : null; // if sessionExpirationMs is set to 0, it means the expiry is set to 0 for this session cookie // A cookie with 0 expiry in the session cookie will never expire for that browser session. If the browser is closed the cookie expires. // Depending on the browser, another instance does not inherit this cookie, however, another tab will _cookieManager.set(_storageNamePrefix(), cookie.join("|"), config.sessionExpirationMs() > 0 ? maxAgeSec : null, cookieDomain); _cookieUpdatedTimestamp = nowMs; } function _setStorage(guid: string, acq: number, renewal: number) { // Keep data in local storage to retain the last session id, allowing us to cleanly end the session when it expires // Browsers that don't support local storage won't be able to end sessions cleanly from the client // The server will notice this and end the sessions itself, with loss of accurate session duration utlSetLocalStorage(_logger, _storageNamePrefix(), [guid, acq, renewal].join("|")); } }); } public update() { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } /** * Record the current state of the automatic session and store it in our cookie string format * into the browser's local storage. This is used to restore the session data when the cookie * expires. */ public backup() { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } }
the_stack
import { OutputTemplateConverter } from '@jovotech/output'; import { AlexaOutputTemplateConverterStrategy, CardType, OutputSpeechType } from '../src'; const converter = new OutputTemplateConverter( new AlexaOutputTemplateConverterStrategy({ validation: false, }), ); // Due to AlexaOutputTemplateConverterStrategy extending SingleResponseOutputTemplateConverterStrategy no tests are required for output arrays describe('toResponse', () => { describe('listen', () => { test('undefined passed', async () => { const response = await converter.toResponse({ message: 'Hello world', }); expect(response.response.shouldEndSession).toBe(false); }); describe('boolean passed', () => { test('true', async () => { const response = await converter.toResponse({ message: 'Hello world', listen: true, }); expect(response.response.shouldEndSession).toBe(false); }); test('false passed', async () => { const response = await converter.toResponse({ message: 'Hello world', listen: false, }); expect(response.response.shouldEndSession).toBe(true); }); }); test('dynamic entities passed', async () => { const response = await converter.toResponse({ message: 'Hello world', listen: { entities: { types: { ColorType: { values: [ { id: 'red', value: 'red', }, ], }, }, }, }, }); expect(response.response.directives?.[0]).toEqual({ type: 'Dialog.UpdateDynamicEntities', types: [ { name: 'ColorType', values: [ { id: 'red', name: { synonyms: undefined, value: 'red', }, }, ], }, ], updateBehavior: 'REPLACE', }); }); }); describe('message', () => { test('undefined passed', async () => { const response = await converter.toResponse({ message: undefined, }); expect(response.response.outputSpeech).toBe(undefined); }); test('string passed', async () => { const response = await converter.toResponse({ message: 'Hello world', }); expect(response.response.outputSpeech).toEqual({ type: OutputSpeechType.Ssml, ssml: `<speak>Hello world</speak>`, }); }); describe('object passed', () => { test('speech only', async () => { const response = await converter.toResponse({ message: { speech: 'Hello world' }, }); expect(response.response.outputSpeech).toEqual({ type: OutputSpeechType.Ssml, ssml: `<speak>Hello world</speak>`, }); }); test('text only', async () => { const response = await converter.toResponse({ message: { text: 'Hello world' }, }); expect(response.response.outputSpeech).toEqual({ type: OutputSpeechType.Plain, text: 'Hello world', }); }); test('speech and text', async () => { const response = await converter.toResponse({ message: { speech: 'Hello world', text: 'Hello world' }, }); expect(response.response.outputSpeech).toEqual({ type: OutputSpeechType.Ssml, ssml: `<speak>Hello world</speak>`, }); }); }); }); describe('reprompt', () => { test('undefined passed', async () => { const response = await converter.toResponse({ reprompt: undefined, }); expect(response.response.reprompt).toBe(undefined); }); test('string passed', async () => { const response = await converter.toResponse({ reprompt: 'Hello world', }); expect(response.response.reprompt?.outputSpeech).toEqual({ type: OutputSpeechType.Ssml, ssml: `<speak>Hello world</speak>`, }); }); describe('object passed', () => { test('speech only', async () => { const response = await converter.toResponse({ reprompt: { speech: 'Hello world' }, }); expect(response.response.reprompt?.outputSpeech).toEqual({ type: OutputSpeechType.Ssml, ssml: `<speak>Hello world</speak>`, }); }); test('text only', async () => { const response = await converter.toResponse({ reprompt: { text: 'Hello world' }, }); expect(response.response.reprompt?.outputSpeech).toEqual({ type: OutputSpeechType.Plain, text: 'Hello world', }); }); test('speech and text', async () => { const response = await converter.toResponse({ reprompt: { speech: 'Hello world', text: 'Hello world' }, }); expect(response.response.reprompt?.outputSpeech).toEqual({ type: OutputSpeechType.Ssml, ssml: `<speak>Hello world</speak>`, }); }); }); }); // Probably all APL tests can be improved. They are quite shallow and only test if a directive is set. // There are no tests yet to check if the content is correctly set due to the size of APL documents. describe('APL enabled', () => { beforeAll(() => { converter.strategy.config.genericOutputToApl = true; }); afterAll(() => { converter.strategy.config.genericOutputToApl = converter.strategy.getDefaultConfig().genericOutputToApl; }); describe('card', () => { test('undefined passed', async () => { const response = await converter.toResponse({ card: undefined, }); expect(response.response.directives?.length || 0).toBe(0); }); test('object passed', async () => { const response = await converter.toResponse({ card: { title: 'title', subtitle: 'subtitle', content: 'content', }, }); expect(response.response.directives?.[0]?.type).toBe( 'Alexa.Presentation.APL.RenderDocument', ); }); }); describe('carousel', () => { test('undefined passed', async () => { const response = await converter.toResponse({ card: undefined, }); expect(response.response.directives?.length || 0).toBe(0); }); test('object passed', async () => { const response = await converter.toResponse({ carousel: { title: 'title', items: [ { key: 'first', title: 'first', }, { key: 'second', title: 'second' }, ], }, }); expect(response.response.directives?.[0]?.type).toBe( 'Alexa.Presentation.APL.RenderDocument', ); }); }); describe('quickReplies', () => { // this is the current behavior but might change in the future test('no other APL document passed => ignored', async () => { const response = await converter.toResponse({ quickReplies: ['first', 'second'], }); expect(response.response.directives?.length || 0).toBe(0); }); test('undefined passed', async () => { const response = await converter.toResponse({ card: { title: 'title' }, quickReplies: undefined, }); // eslint-disable-next-line @typescript-eslint/no-explicit-any expect((response.response.directives?.[0] as any)?.datasources?.data?.quickReplies).toEqual( [], ); }); test('array passed', async () => { const response = await converter.toResponse({ card: { title: 'title' }, quickReplies: ['first', 'second'], }); // eslint-disable-next-line @typescript-eslint/no-explicit-any expect((response.response.directives?.[0] as any)?.datasources?.data?.quickReplies).toEqual( [ { intent: 'first', type: 'QuickReply' }, { intent: 'second', type: 'QuickReply' }, ], ); }); }); describe('list', () => { test('undefined passed', async () => { const response = await converter.toResponse({ list: undefined, }); expect(response.response.directives?.length || 0).toBe(0); }); test('object passed', async () => { const response = await converter.toResponse({ platforms: { alexa: { list: { title: 'title', items: [ { title: 'first', }, { title: 'second' }, ], }, }, }, }); expect(response.response.directives?.[0]?.type).toBe( 'Alexa.Presentation.APL.RenderDocument', ); }); }); }); describe('APL disabled', () => { beforeAll(() => { converter.strategy.config.genericOutputToApl = false; }); afterAll(() => { converter.strategy.config.genericOutputToApl = converter.strategy.getDefaultConfig().genericOutputToApl; }); describe('card', () => { test('undefined passed', async () => { const response = await converter.toResponse({ card: undefined, }); expect(response.response.card).toBe(undefined); }); test('object passed', async () => { const response = await converter.toResponse({ card: { title: 'title', subtitle: 'subtitle', content: 'content', }, }); expect(response.response.card).toEqual({ type: CardType.Standard, title: 'title', text: 'content', }); }); }); describe('carousel', () => { test('undefined passed', async () => { const response = await converter.toResponse({ card: undefined, }); expect(response.response.directives?.length || 0).toBe(0); }); test('object passed', async () => { const response = await converter.toResponse({ carousel: { title: 'title', items: [ { key: 'first', title: 'first', }, { key: 'second', title: 'second' }, ], }, }); expect(response.response.directives?.length || 0).toBe(0); }); }); describe('quickReplies', () => { test('undefined passed', async () => { const response = await converter.toResponse({ card: { title: 'title' }, quickReplies: undefined, }); expect(response.response.directives || []).toEqual([]); }); test('array passed', async () => { const response = await converter.toResponse({ card: { title: 'title' }, quickReplies: ['first', 'second'], }); expect(response.response.directives?.length || 0).toBe(0); }); }); describe('list', () => { test('undefined passed', async () => { const response = await converter.toResponse({ list: undefined, }); expect(response.response.directives?.length || 0).toBe(0); }); test('object passed', async () => { const response = await converter.toResponse({ platforms: { alexa: { list: { title: 'title', items: [ { title: 'first', }, { title: 'second' }, ], }, }, }, }); expect(response.response.directives?.length || 0).toBe(0); }); }); }); test('nativeResponse', async () => { const response = await converter.toResponse({ message: 'Hello world', platforms: { alexa: { nativeResponse: { sessionAttributes: { foo: 'bar', }, }, }, }, }); expect(response.sessionAttributes).toEqual({ foo: 'bar', }); }); }); describe('fromResponse', () => { describe('listen', () => { test('shouldEndSession undefined', async () => { const output = await converter.fromResponse({ version: '', response: { shouldEndSession: undefined, }, }); expect(output.listen).toBe(undefined); }); describe('boolean', () => { test('shouldEndSession true', async () => { const output = await converter.fromResponse({ version: '', response: { shouldEndSession: true, }, }); expect(output.listen).toBe(false); }); test('shouldEndSession false', async () => { const output = await converter.fromResponse({ version: '', response: { shouldEndSession: false, }, }); expect(output.listen).toBe(true); }); }); }); describe('message', () => { test('prompt undefined', async () => { const output = await converter.fromResponse({ version: '', response: { outputSpeech: undefined, }, }); expect(output.message).toBe(undefined); }); test('speech prompt', async () => { const output = await converter.fromResponse({ version: '', response: { outputSpeech: { type: OutputSpeechType.Ssml, ssml: `<speak>Hello world</speak>`, }, }, }); expect(output.message).toEqual({ speech: `<speak>Hello world</speak>` }); }); test('plain prompt', async () => { const output = await converter.fromResponse({ version: '', response: { outputSpeech: { type: OutputSpeechType.Plain, text: 'Hello world', }, }, }); expect(output.message).toEqual({ text: 'Hello world' }); }); }); describe('reprompt', () => { test('reprompt undefined', async () => { const output = await converter.fromResponse({ version: '', response: { reprompt: undefined, }, }); expect(output.reprompt).toBe(undefined); }); test('speech reprompt', async () => { const output = await converter.fromResponse({ version: '', response: { reprompt: { outputSpeech: { type: OutputSpeechType.Ssml, ssml: `<speak>Hello world</speak>`, }, }, }, }); expect(output.reprompt).toEqual({ speech: `<speak>Hello world</speak>` }); }); test('plain reprompt', async () => { const output = await converter.fromResponse({ version: '', response: { reprompt: { outputSpeech: { type: OutputSpeechType.Plain, text: 'Hello world', }, }, }, }); expect(output.reprompt).toEqual({ text: 'Hello world' }); }); }); describe('card', () => { test('card undefined', async () => { const output = await converter.fromResponse({ version: '', response: { card: undefined, }, }); expect(output.card).toBe(undefined); }); test('card is set', async () => { const output = await converter.fromResponse({ version: '', response: { card: { type: CardType.Standard, title: 'title', image: { smallImageUrl: 'foo', }, }, }, }); expect(output.card).toEqual({ title: 'title', imageUrl: 'foo' }); }); }); });
the_stack
import {Class, Equivalent, Initable} from "@swim/util"; import {Affinity, MemberFastenerClass, Animator} from "@swim/component"; import {AnyLength, Length, AnyAngle, Angle, AnyR2Point, R2Point, R2Box} from "@swim/math"; import {AnyFont, Font, AnyColor, Color} from "@swim/style"; import {Look, ThemeAnimator} from "@swim/theme"; import {ViewContextType, AnyView, View, ViewRef} from "@swim/view"; import { GraphicsViewInit, GraphicsView, PaintingContext, PaintingRenderer, CanvasContext, CanvasRenderer, FillView, Arc, TypesetView, TextRunView, } from "@swim/graphics"; import type {SliceViewObserver} from "./SliceViewObserver"; /** @public */ export type AnySliceView = SliceView | SliceViewInit; /** @public */ export interface SliceViewInit extends GraphicsViewInit { value?: number; total?: number; center?: AnyR2Point; innerRadius?: AnyLength; outerRadius?: AnyLength; phaseAngle?: AnyAngle; padAngle?: AnyAngle; padRadius?: AnyLength | null; cornerRadius?: AnyLength; labelRadius?: AnyLength; sliceColor?: AnyColor; tickAlign?: number; tickRadius?: AnyLength; tickLength?: AnyLength; tickWidth?: AnyLength; tickPadding?: AnyLength; tickColor?: AnyColor; font?: AnyFont; textColor?: AnyColor; label?: GraphicsView | string; legend?: GraphicsView | string; } /** @public */ export class SliceView extends GraphicsView { override readonly observerType?: Class<SliceViewObserver>; @Animator<SliceView, number>({ type: Number, value: 0, updateFlags: View.NeedsRender, willSetValue(newValue: number, oldValue: number): void { this.owner.callObservers("viewWillSetSliceValue", newValue, oldValue, this.owner); }, didSetValue(newValue: number, oldValue: number): void { this.owner.callObservers("viewDidSetSliceValue", newValue, oldValue, this.owner); }, }) readonly value!: Animator<this, number>; @Animator({type: Number, value: 1, updateFlags: View.NeedsRender}) readonly total!: Animator<this, number>; @Animator({type: R2Point, inherits: true, value: R2Point.origin(), updateFlags: View.NeedsRender}) readonly center!: Animator<this, R2Point, AnyR2Point>; @ThemeAnimator({type: Length, inherits: true, value: Length.pct(3), updateFlags: View.NeedsRender}) readonly innerRadius!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Length, inherits: true, value: Length.pct(25), updateFlags: View.NeedsRender}) readonly outerRadius!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Angle, value: Angle.zero(), updateFlags: View.NeedsRender}) readonly phaseAngle!: ThemeAnimator<this, Angle, AnyAngle>; @ThemeAnimator({type: Angle, inherits: true, value: Angle.deg(2), updateFlags: View.NeedsRender}) readonly padAngle!: ThemeAnimator<this, Angle, AnyAngle>; @ThemeAnimator({type: Length, inherits: true, value: null, updateFlags: View.NeedsRender}) readonly padRadius!: ThemeAnimator<this, Length | null, AnyLength | null>; @ThemeAnimator({type: Length, inherits: true, value: Length.zero(), updateFlags: View.NeedsRender}) readonly cornerRadius!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Length, inherits: true, value: Length.pct(50), updateFlags: View.NeedsRender}) readonly labelRadius!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Color, inherits: true, value: null, look: Look.accentColor, updateFlags: View.NeedsRender}) readonly sliceColor!: ThemeAnimator<this, Color | null, AnyColor | null>; @ThemeAnimator({type: Number, inherits: true, value: 0.5, updateFlags: View.NeedsRender}) readonly tickAlign!: ThemeAnimator<this, number>; @ThemeAnimator({type: Length, inherits: true, value: Length.pct(30), updateFlags: View.NeedsRender}) readonly tickRadius!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Length, inherits: true, value: Length.pct(50), updateFlags: View.NeedsRender}) readonly tickLength!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Length, inherits: true, value: Length.px(1), updateFlags: View.NeedsRender}) readonly tickWidth!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Length, inherits: true, value: Length.px(2), updateFlags: View.NeedsRender}) readonly tickPadding!: ThemeAnimator<this, Length, AnyLength>; @ThemeAnimator({type: Color, inherits: true, value: null, look: Look.neutralColor, updateFlags: View.NeedsRender}) readonly tickColor!: ThemeAnimator<this, Color | null, AnyColor | null>; @ThemeAnimator({type: Font, inherits: true, value: null, updateFlags: View.NeedsRender}) readonly font!: ThemeAnimator<this, Font | null, AnyFont | null>; @ThemeAnimator({type: Color, inherits: true, value: null, look: Look.mutedColor, updateFlags: View.NeedsRender}) readonly textColor!: ThemeAnimator<this, Color | null, AnyColor | null>; @ViewRef<SliceView, GraphicsView & Initable<GraphicsViewInit | string>>({ key: true, type: TextRunView, binds: true, willAttachView(labelView: GraphicsView): void { this.owner.callObservers("viewWillAttachSliceLabel", labelView, this.owner); }, didDetachView(labelView: GraphicsView): void { this.owner.callObservers("viewDidDetachSliceLabel", labelView, this.owner); }, fromAny(value: AnyView<GraphicsView> | string): GraphicsView { if (typeof value === "string") { if (this.view instanceof TextRunView) { this.view.text(value); return this.view; } else { return TextRunView.fromAny(value); } } else { return GraphicsView.fromAny(value); } }, }) readonly label!: ViewRef<this, GraphicsView & Initable<GraphicsViewInit | string>>; static readonly label: MemberFastenerClass<SliceView, "label">; @ViewRef<SliceView, GraphicsView & Initable<GraphicsViewInit | string>>({ key: true, type: TextRunView, binds: true, willAttachView(legendView: GraphicsView): void { this.owner.callObservers("viewWillAttachSliceLegend", legendView, this.owner); }, didDetachView(legendView: GraphicsView): void { this.owner.callObservers("viewDidDetachSliceLegend", legendView, this.owner); }, fromAny(value: AnyView<GraphicsView> | string): GraphicsView { if (typeof value === "string") { if (this.view instanceof TextRunView) { this.view.text(value); return this.view; } else { return TextRunView.fromAny(value); } } else { return GraphicsView.fromAny(value); } }, }) readonly legend!: ViewRef<this, GraphicsView & Initable<GraphicsViewInit | string>>; static readonly legend: MemberFastenerClass<SliceView, "legend">; protected override onLayout(viewContext: ViewContextType<this>): void { super.onLayout(viewContext); this.center.recohere(viewContext.updateTime); } protected override onRender(viewContext: ViewContextType<this>): void { super.onRender(viewContext); const renderer = viewContext.renderer; if (renderer instanceof PaintingRenderer && !this.hidden && !this.culled) { this.renderSlice(renderer.context, this.viewFrame); } } protected renderSlice(context: PaintingContext, frame: R2Box): void { const width = frame.width; const height = frame.height; const size = Math.min(width, height); const value = this.value.getValue(); const total = this.total.getValue(); const delta = total !== 0 ? value / total : 0; const center = this.center.getValue(); const innerRadius = this.innerRadius.getValue().px(size); const outerRadius = this.outerRadius.getValue().px(size); const deltaRadius = outerRadius.value - innerRadius.value; const startAngle = this.phaseAngle.getValue().rad(); const sweepAngle = Angle.rad(2 * Math.PI * delta); const padAngle = this.padAngle.getValue(); const padRadius = this.padRadius.getValueOr(null); const cornerRadius = this.cornerRadius.getValue().px(deltaRadius); const arc = new Arc(center, innerRadius, outerRadius, startAngle, sweepAngle, padAngle, padRadius, cornerRadius); const sliceColor = this.sliceColor.value; if (sliceColor !== null) { // save const contextFillStyle = context.fillStyle; context.beginPath(); context.fillStyle = sliceColor.toString(); arc.draw(context, frame); context.fill(); // restore context.fillStyle = contextFillStyle; } const labelView = this.label.view; if (labelView !== null && !labelView.hidden) { const labelRadius = this.labelRadius.getValue().pxValue(deltaRadius); const labelAngle = startAngle.value + sweepAngle.value / 2; const r = innerRadius.value + labelRadius; const rx = r * Math.cos(labelAngle); const ry = r * Math.sin(labelAngle); if (TypesetView.is(labelView)) { labelView.textAlign.setState("center", Affinity.Intrinsic); labelView.textBaseline.setState("middle", Affinity.Intrinsic); labelView.textOrigin.setState(new R2Point(center.x + rx, center.y + ry), Affinity.Intrinsic); } } const legendView = this.legend.view; if (legendView !== null && !legendView.hidden) { const tickAlign = this.tickAlign.getValue(); const tickAngle = startAngle.value + sweepAngle.value * tickAlign; const tickRadius = this.tickRadius.getValue().pxValue(size); const tickLength = this.tickLength.getValue().pxValue(width); const tickWidth = this.tickWidth.getValue().pxValue(size); const tickColor = this.tickColor.value; const cx = center.x; const cy = center.y; const r1x = outerRadius.value * Math.cos(tickAngle + Equivalent.Epsilon); const r1y = outerRadius.value * Math.sin(tickAngle + Equivalent.Epsilon); const r2x = tickRadius * Math.cos(tickAngle + Equivalent.Epsilon); const r2y = tickRadius * Math.sin(tickAngle + Equivalent.Epsilon); let dx = 0; if (tickColor !== null && tickWidth !== 0) { // save const contextLineWidth = context.lineWidth; const contextStrokeStyle = context.strokeStyle; context.beginPath(); context.lineWidth = tickWidth; context.strokeStyle = tickColor.toString(); context.moveTo(cx + r1x, cy + r1y); context.lineTo(cx + r2x, cy + r2y); if (tickLength !== 0) { if (r2x >= 0) { context.lineTo(cx + tickLength, cy + r2y); dx = tickLength - r2x; } else if (r2x < 0) { context.lineTo(cx - tickLength, cy + r2y); dx = tickLength + r2x; } } context.stroke(); // restore context.lineWidth = contextLineWidth; context.strokeStyle = contextStrokeStyle; } let textAlign: CanvasTextAlign; if (r2x >= 0) { if (r2y >= 0) { // top-right textAlign = "end"; } else { // bottom-right textAlign = "end"; } } else { dx = -dx; if (r2y < 0) { // bottom-left textAlign = "start"; } else { // top-left textAlign = "start"; } } if (TypesetView.is(legendView)) { const tickPadding = this.tickPadding.getValue().pxValue(size); if (FillView.is(legendView)) { legendView.fill.setState(tickColor, Affinity.Intrinsic); } legendView.textAlign.setState(textAlign, Affinity.Intrinsic); legendView.textBaseline.setState("alphabetic", Affinity.Intrinsic); legendView.textOrigin.setState(new R2Point(cx + r2x + dx, cy + r2y - tickPadding), Affinity.Intrinsic); } } } protected override hitTest(x: number, y: number, viewContext: ViewContextType<this>): GraphicsView | null { const renderer = viewContext.renderer; if (renderer instanceof CanvasRenderer) { const p = renderer.transform.transform(x, y); return this.hitTestSlice(p.x, p.y, renderer.context, this.viewFrame); } return null; } protected hitTestSlice(x: number, y: number, context: CanvasContext, frame: R2Box): GraphicsView | null { const size = Math.min(frame.width, frame.height); const value = this.value.getValue(); const total = this.total.getValue(); const delta = total !== 0 ? value / total : 0; const center = this.center.getValue(); const innerRadius = this.innerRadius.getValue().px(size); const outerRadius = this.outerRadius.getValue().px(size); const deltaRadius = outerRadius.value - innerRadius.value; const startAngle = this.phaseAngle.getValue().rad(); const sweepAngle = Angle.rad(2 * Math.PI * delta); const padAngle = this.padAngle.getValue(); const padRadius = this.padRadius.getValueOr(null); const cornerRadius = this.cornerRadius.getValue().px(deltaRadius); const arc = new Arc(center, innerRadius, outerRadius, startAngle, sweepAngle, padAngle, padRadius, cornerRadius); context.beginPath(); arc.draw(context, frame); if (context.isPointInPath(x, y)) { return this; } return null; } override init(init: SliceViewInit): void { super.init(init); if (init.value !== void 0) { this.value(init.value); } if (init.total !== void 0) { this.total(init.total); } if (init.center !== void 0) { this.center(init.center); } if (init.innerRadius !== void 0) { this.innerRadius(init.innerRadius); } if (init.outerRadius !== void 0) { this.outerRadius(init.outerRadius); } if (init.phaseAngle !== void 0) { this.phaseAngle(init.phaseAngle); } if (init.padAngle !== void 0) { this.padAngle(init.padAngle); } if (init.padRadius !== void 0) { this.padRadius(init.padRadius); } if (init.cornerRadius !== void 0) { this.cornerRadius(init.cornerRadius); } if (init.labelRadius !== void 0) { this.labelRadius(init.labelRadius); } if (init.sliceColor !== void 0) { this.sliceColor(init.sliceColor); } if (init.tickAlign !== void 0) { this.tickAlign(init.tickAlign); } if (init.tickRadius !== void 0) { this.tickRadius(init.tickRadius); } if (init.tickLength !== void 0) { this.tickLength(init.tickLength); } if (init.tickWidth !== void 0) { this.tickWidth(init.tickWidth); } if (init.tickPadding !== void 0) { this.tickPadding(init.tickPadding); } if (init.tickColor !== void 0) { this.tickColor(init.tickColor); } if (init.font !== void 0) { this.font(init.font); } if (init.textColor !== void 0) { this.textColor(init.textColor); } if (init.label !== void 0) { this.label(init.label); } if (init.legend !== void 0) { this.legend(init.legend); } } }
the_stack
import * as fs from "fs"; import * as path from "path"; import { schema } from "yaml-cfn"; import yaml from "js-yaml"; interface AwsSamProjectMap { [pname: string]: string; } interface AwsSamPluginOptions { projects: AwsSamProjectMap; outFile: string; vscodeDebug: boolean; } interface IEntryPointMap { [pname: string]: string; } interface SamConfig { buildRoot: string; entryPointName: string; outFile: string; projectKey: string; samConfig: any; templateName: string; } interface IEntryForResult { entryPoints: IEntryPointMap; launchConfigs: any[]; samConfigs: SamConfig[]; } class AwsSamPlugin { private static defaultTemplates = ["template.yaml", "template.yml"]; private launchConfig: any; private options: AwsSamPluginOptions; private samConfigs: SamConfig[]; constructor(options?: Partial<AwsSamPluginOptions>) { this.options = { projects: { default: "." }, outFile: "app", vscodeDebug: true, ...options, }; this.samConfigs = []; } // Returns the name of the SAM template file or null if it's not found private findTemplateName(prefix: string) { for (const f of AwsSamPlugin.defaultTemplates) { const template = `${prefix}/${f}`; if (fs.existsSync(template)) { return template; } } return null; } // Returns a webpack entry object based on the SAM template public entryFor( projectKey: string, projectPath: string, projectTemplateName: string, projectTemplate: string, outFile: string ): IEntryForResult { const entryPoints: IEntryPointMap = {}; const launchConfigs: any[] = []; const samConfigs: SamConfig[] = []; const samConfig = yaml.load(projectTemplate, { filename: projectTemplateName, schema }) as any; const defaultRuntime = samConfig.Globals?.Function?.Runtime ?? null; const defaultHandler = samConfig.Globals?.Function?.Handler ?? null; const defaultCodeUri = samConfig.Globals?.Function?.CodeUri ?? null; // Loop through all of the resources for (const resourceKey in samConfig.Resources) { const resource = samConfig.Resources[resourceKey]; const buildRoot = projectPath === "" ? `.aws-sam/build` : `${projectPath}/.aws-sam/build`; // Correct paths for files that can be uploaded using "aws couldformation package" if (resource.Type === "AWS::ApiGateway::RestApi" && typeof resource.Properties.BodyS3Location === "string") { samConfig.Resources[resourceKey].Properties.BodyS3Location = path.relative( buildRoot, resource.Properties.BodyS3Location ); } if (resource.Type === "AWS::Lambda::Function" && typeof resource.Properties.Code === "string") { samConfig.Resources[resourceKey].Properties.Code = path.relative(buildRoot, resource.Properties.Code); } if ( resource.Type === "AWS::AppSync::GraphQLSchema" && typeof resource.Properties.DefinitionS3Location === "string" && resource.Properties.DefinitionS3Location.startsWith("s3://") === false ) { samConfig.Resources[resourceKey].Properties.DefinitionS3Location = path.relative( buildRoot, resource.Properties.DefinitionS3Location ); } if ( resource.Type === "AWS::AppSync::Resolver" && typeof resource.Properties.RequestMappingTemplateS3Location === "string" && resource.Properties.RequestMappingTemplateS3Location.startsWith("s3://") === false ) { samConfig.Resources[resourceKey].Properties.RequestMappingTemplateS3Location = path.relative( buildRoot, resource.Properties.RequestMappingTemplateS3Location ); } if ( resource.Type === "AWS::AppSync::Resolver" && typeof resource.Properties.ResponseMappingTemplateS3Location === "string" && resource.Properties.ResponseMappingTemplateS3Location.startsWith("s3://") === false ) { samConfig.Resources[resourceKey].Properties.ResponseMappingTemplateS3Location = path.relative( buildRoot, resource.Properties.ResponseMappingTemplateS3Location ); } if ( resource.Type === "AWS::Serverless::Api" && typeof resource.Properties.DefinitionUri === "string" && resource.Properties.DefinitionUri.startsWith("s3://") === false ) { samConfig.Resources[resourceKey].Properties.DefinitionUri = path.relative( buildRoot, resource.Properties.DefinitionUri ); } if ( resource.Type === "AWS::Include" && typeof resource.Properties.Location === "string" && resource.Properties.Location.startsWith("s3://") === false ) { samConfig.Resources[resourceKey].Properties.Location = path.relative(buildRoot, resource.Properties.Location); } if ( resource.Type === "AWS::ElasticBeanstalk::ApplicationVersion" && typeof resource.Properties.SourceBundle === "string" && resource.Properties.SourceBundle.startsWith("s3://") === false ) { samConfig.Resources[resourceKey].Properties.SourceBundle = path.relative( buildRoot, resource.Properties.SourceBundle ); } if ( resource.Type === "AWS::CloudFormation::Stack" && typeof resource.Properties.TemplateURL === "string" && resource.Properties.TemplateURL.startsWith("s3://") === false ) { samConfig.Resources[resourceKey].Properties.TemplateURL = path.relative( buildRoot, resource.Properties.TemplateURL ); } if ( resource.Type === "AWS::Glue::Job" && resource.Properties.Command && typeof resource.Properties.Command.ScriptLocation === "string" && resource.Properties.Command.ScriptLocation.startsWith("s3://") === false ) { samConfig.Resources[resourceKey].Properties.Command.ScriptLocation = path.relative( buildRoot, resource.Properties.Command.ScriptLocation ); } if ( resource.Type === "AWS::StepFunctions::StateMachine" && typeof resource.Properties.DefinitionS3Location === "string" && resource.Properties.DefinitionS3Location.startsWith("s3://") === false ) { samConfig.Resources[resourceKey].Properties.DefinitionS3Location = path.relative( buildRoot, resource.Properties.DefinitionS3Location ); } // Find all of the functions if (resource.Type === "AWS::Serverless::Function") { const properties = resource.Properties; if (!properties) { throw new Error(`${resourceKey} is missing Properties`); } // Check the runtime is supported if (!["nodejs10.x", "nodejs12.x", "nodejs14.x"].includes(properties.Runtime ?? defaultRuntime)) { throw new Error(`${resourceKey} has an unsupport Runtime. Must be nodejs10.x, nodejs12.x or nodejs14.x`); } // Continue with a warning if they're using inline code if (properties.InlineCode) { console.log( `WARNING: This plugin does not compile inline code. The InlineCode for '${resourceKey}' will be copied 'as is'.` ); continue; } // Check we have a valid handler const handler = properties.Handler ?? defaultHandler; if (!handler) { throw new Error(`${resourceKey} is missing a Handler`); } const handlerComponents = handler.split("."); if (handlerComponents.length !== 2) { throw new Error(`${resourceKey} Handler must contain exactly one "."`); } // Check we have a CodeUri const codeUri = properties.CodeUri ?? defaultCodeUri; if (!codeUri) { throw new Error(`${resourceKey} is missing a CodeUri`); } const basePathPrefix = projectPath === "" ? "." : `./${projectPath}`; const basePath = `${basePathPrefix}/${codeUri}`; const fileBase = `${basePath}/${handlerComponents[0]}`; // Generate the launch config for the VS Code debugger launchConfigs.push({ name: projectKey === "default" ? resourceKey : `${projectKey}:${resourceKey}`, type: "node", request: "attach", address: "localhost", port: 5858, localRoot: `\${workspaceFolder}/${buildRoot}/${resourceKey}`, remoteRoot: "/var/task", protocol: "inspector", stopOnEntry: false, outFiles: [`\${workspaceFolder}/${buildRoot}/${resourceKey}/**/*.js`], sourceMaps: true, skipFiles: ["/var/runtime/**/*.js", "<node_internals>/**/*.js"], }); // Add the entry point for webpack const entryPointName = projectKey === "default" ? resourceKey : `${projectKey}#${resourceKey}`; entryPoints[entryPointName] = fileBase; samConfig.Resources[resourceKey].Properties.CodeUri = resourceKey; samConfig.Resources[resourceKey].Properties.Handler = `${outFile}.${handlerComponents[1]}`; samConfigs.push({ buildRoot, entryPointName, outFile: `./${buildRoot}/${resourceKey}/${outFile}.js`, projectKey, samConfig, templateName: projectTemplateName, }); } } return { entryPoints, launchConfigs, samConfigs }; } public entry() { // Reset the entry points and launch config let allEntryPoints: IEntryPointMap = {}; this.launchConfig = { version: "0.2.0", configurations: [], }; this.samConfigs = []; // The name of the out file const outFile = this.options.outFile; // Loop through each of the "projects" from the options for (const projectKey in this.options.projects) { // The value will be the name of a folder or a template file const projectFolderOrTemplateName = this.options.projects[projectKey]; // If the projectFolderOrTemplateName isn't a file then we should look for common template file names const projectTemplateName = fs.statSync(projectFolderOrTemplateName).isFile() ? projectFolderOrTemplateName : this.findTemplateName(projectFolderOrTemplateName); // If we still cannot find a project template name then throw an error because something is wrong if (projectTemplateName === null) { throw new Error( `Could not find ${AwsSamPlugin.defaultTemplates.join(" or ")} in ${projectFolderOrTemplateName}` ); } // Retrieve the entry points, VS Code debugger launch configs and SAM config for this entry const { entryPoints, launchConfigs, samConfigs } = this.entryFor( projectKey, path.relative(".", path.dirname(projectTemplateName)), path.basename(projectTemplateName), fs.readFileSync(projectTemplateName).toString(), outFile ); // Addd them to the entry pointsm launch configs and SAM confis we've already discovered. allEntryPoints = { ...allEntryPoints, ...entryPoints, }; this.launchConfig.configurations = [...this.launchConfig.configurations, ...launchConfigs]; this.samConfigs = [...this.samConfigs, ...samConfigs]; } // Once we're done return the entry points return allEntryPoints; } public filename(chunkData: any) { const samConfig = this.samConfigs.find((c) => c.entryPointName === chunkData.chunk.name); if (!samConfig) { throw new Error(`Unable to find filename for ${chunkData.chunk.name}`); } return samConfig.outFile; } public apply(compiler: any) { compiler.hooks.afterEmit.tap("SamPlugin", (_compilation: any) => { if (!(this.samConfigs && this.launchConfig)) { throw new Error("It looks like AwsSamPlugin.entry() was not called"); } const yamlUnique = this.samConfigs.reduce((a, e) => { const { buildRoot, samConfig } = e; a[buildRoot] = samConfig; return a; }, {} as Record<string, any>); for (const buildRoot in yamlUnique) { const samConfig = yamlUnique[buildRoot]; fs.writeFileSync(`${buildRoot}/template.yaml`, yaml.dump(samConfig, { indent: 2, quotingType: '"', schema })); } if (this.options.vscodeDebug !== false) { if (!fs.existsSync(".vscode")) { fs.mkdirSync(".vscode"); } fs.writeFileSync(".vscode/launch.json", JSON.stringify(this.launchConfig, null, 2)); } }); } } export = AwsSamPlugin;
the_stack
import { Button, Col, Row, Space, Tooltip } from 'antd' import { ThemeContext } from 'contexts/themeContext' import { Split } from 'models/v2/splits' import { PropsWithChildren, useContext, useState } from 'react' import { parseWad } from 'utils/formatNumber' import FormattedAddress from 'components/shared/FormattedAddress' import { BigNumber } from '@ethersproject/bignumber' import { formatDate } from 'utils/formatDate' import { CrownFilled, LockOutlined, DeleteOutlined } from '@ant-design/icons' import { V2ProjectContext } from 'contexts/v2/projectContext' import { formatSplitPercent, MAX_DISTRIBUTION_LIMIT, preciseFormatSplitPercent, SPLITS_TOTAL_PERCENT, } from 'utils/v2/math' import CurrencySymbol from 'components/shared/CurrencySymbol' import { adjustedSplitPercents, amountFromPercent, getNewDistributionLimit, } from 'utils/v2/distributions' import { t, Trans } from '@lingui/macro' import TooltipIcon from 'components/shared/TooltipIcon' import DistributionSplitModal from './DistributionSplitModal' import { CurrencyName } from 'constants/currency' const Parens = ({ withParens = false, children, }: PropsWithChildren<{ withParens: boolean }>) => { if (withParens) return <>({children})</> return <>{children}</> } export default function DistributionSplitCard({ split, editableSplitIndex, splits, editableSplits, onSplitsChanged, distributionLimit, setDistributionLimit, currencyName, onCurrencyChange, isLocked, isProjectOwner, }: { split: Split splits: Split[] editableSplits: Split[] editableSplitIndex: number onSplitsChanged: (splits: Split[]) => void distributionLimit: string | undefined setDistributionLimit: (distributionLimit: string) => void currencyName: CurrencyName onCurrencyChange?: (currencyName: CurrencyName) => void isLocked?: boolean isProjectOwner?: boolean }) { const { theme: { colors, radii }, } = useContext(ThemeContext) const { projectOwnerAddress } = useContext(V2ProjectContext) const [editSplitModalOpen, setEditSplitModalOpen] = useState<boolean>(false) const gutter = 10 const labelColSpan = 9 const dataColSpan = 15 const isProject = parseInt(split.projectId ?? '0') > 0 // !isProject added here because we don't want to show the crown next to // a project recipient whose token benefiary is the owner of this project const isOwner = (projectOwnerAddress === split.beneficiary && !isProject) || isProjectOwner const distributionLimitIsInfinite = !distributionLimit || parseWad(distributionLimit).eq(MAX_DISTRIBUTION_LIMIT) // If percentage has greater than 2 dp it will be rounded in the UI const percentIsRounded = split.percent !== SPLITS_TOTAL_PERCENT && (split.percent / SPLITS_TOTAL_PERCENT).toString().split('.')[1]?.length > 4 const cursor = isLocked ? 'default' : 'pointer' return ( <div style={{ display: 'flex', padding: 10, border: '1px solid ' + (isLocked ? colors.stroke.disabled : colors.stroke.tertiary), borderRadius: radii.md, }} key={split.beneficiary ?? '' + editableSplitIndex} > <Space direction="vertical" style={{ width: '100%', color: colors.text.primary, cursor, }} onClick={!isLocked ? () => setEditSplitModalOpen(true) : undefined} > {split.projectId && parseInt(split.projectId) > 0 ? ( <Row gutter={gutter} style={{ width: '100%' }} align="middle"> <Col span={labelColSpan}> <label style={{ cursor }}> <Trans>Project ID:</Trans> </label>{' '} </Col> <Col span={dataColSpan}> <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', }} > <span style={{ cursor }}>{split.projectId}</span> </div> </Col> </Row> ) : ( <Row gutter={gutter} style={{ width: '100%' }} align="middle"> <Col span={labelColSpan}> <label style={{ cursor }}> <Trans>Address:</Trans> </label>{' '} </Col> <Col span={dataColSpan}> <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', }} > {isOwner && !split.beneficiary ? ( <span style={{ cursor }}> <Trans>Project owner (you)</Trans> </span> ) : ( <span style={{ cursor: 'pointer' }}> <FormattedAddress address={split.beneficiary} /> </span> )} {isOwner && ( <Tooltip title={t`Project owner`}> <CrownFilled /> </Tooltip> )} </div> </Col> </Row> )} {parseInt(split.projectId ?? '0') > 0 ? ( <Row> <Col span={labelColSpan}> <label style={{ cursor }}> <Trans>Token beneficiary:</Trans> </label> </Col> <Col span={dataColSpan}> <span style={{ cursor: 'pointer' }}> <FormattedAddress address={split.beneficiary} /> </span> </Col> </Row> ) : null} <Row gutter={gutter} style={{ width: '100%' }} align="middle"> <Col span={labelColSpan}> <label style={{ cursor }}> {distributionLimitIsInfinite ? ( <Trans>Percentage:</Trans> ) : ( <Trans>Amount:</Trans> )} </label> </Col> <Col span={dataColSpan}> <div style={{ display: 'flex', width: '100%', justifyContent: 'space-between', alignItems: 'center', }} > <span style={{ marginRight: 10, width: 100, maxWidth: 100, }} > <Space size="small" direction="horizontal"> {!distributionLimitIsInfinite && ( <span> <CurrencySymbol currency={currencyName} /> {parseFloat( amountFromPercent({ percent: preciseFormatSplitPercent(split.percent), amount: distributionLimit, }).toFixed(4), )} </span> )} <span> <Parens withParens={!distributionLimitIsInfinite}> {percentIsRounded ? '~' : null} {formatSplitPercent(BigNumber.from(split.percent))}% </Parens> </span> </Space> </span> </div> </Col> </Row> {split.lockedUntil ? ( <Row gutter={gutter} style={{ width: '100%' }} align="middle"> <Col span={labelColSpan}> <label style={{ cursor }}> <Trans>Locked:</Trans> </label> </Col> <Col span={dataColSpan}> until {formatDate((split.lockedUntil ?? 0) * 1000, 'yyyy-MM-DD')} </Col> </Row> ) : null} </Space> {isLocked ? ( <> {!isOwner ? ( <Tooltip title={<Trans>Payout is locked</Trans>}> <LockOutlined style={{ color: colors.icon.disabled, paddingTop: '4px' }} /> </Tooltip> ) : ( <TooltipIcon iconStyle={{ paddingTop: '4px' }} tip={ <Trans> You have configured for all funds to be distributed from the treasury. Your current payouts do not sum to 100%, so the remainder will go to the project owner. </Trans> } /> )} </> ) : ( <Tooltip title={<Trans>Delete payout</Trans>}> <Button type="text" onClick={e => { let adjustedSplits = splits // Adjust all split percents if // - distributionLimit is not infinite // - not deleting the last split if (!distributionLimitIsInfinite && splits.length !== 1) { const newDistributionLimit = getNewDistributionLimit({ currentDistributionLimit: distributionLimit, newSplitAmount: 0, editingSplitPercent: splits[editableSplitIndex].percent, }).toString() adjustedSplits = adjustedSplitPercents({ splits: editableSplits, oldDistributionLimit: distributionLimit, newDistributionLimit, }) setDistributionLimit(newDistributionLimit) } if (splits.length === 1) setDistributionLimit('0') onSplitsChanged([ ...adjustedSplits.slice(0, editableSplitIndex), ...adjustedSplits.slice(editableSplitIndex + 1), ]) e.stopPropagation() }} icon={<DeleteOutlined />} style={{ height: 16 }} /> </Tooltip> )} {!isLocked ? ( <DistributionSplitModal visible={editSplitModalOpen} onSplitsChanged={onSplitsChanged} editableSplits={editableSplits} mode={'Edit'} splits={splits} distributionLimit={distributionLimit} setDistributionLimit={setDistributionLimit} onClose={() => setEditSplitModalOpen(false)} currencyName={currencyName} onCurrencyChange={onCurrencyChange} editableSplitIndex={editableSplitIndex} /> ) : null} </div> ) }
the_stack
import { Component, DoCheck, EventEmitter, Input, IterableDiffers, OnChanges, Output, SimpleChange } from '@angular/core'; import { BasicList } from './basic-list'; export type compareFunction = (a: any, b: any) => number; var nextId = 0; @Component({ selector: 'dual-list', templateUrl: './dual-list.component.html', styleUrls: [ './dual-list.component.css' ] }) export class DualListComponent implements DoCheck, OnChanges { static AVAILABLE_LIST_NAME = 'available'; static CONFIRMED_LIST_NAME = 'confirmed'; static LTR = 'left-to-right'; static RTL = 'right-to-left'; static DEFAULT_FORMAT = { add: 'Add', remove: 'Remove', all: 'All', none: 'None', direction: DualListComponent.LTR, draggable: true, locale: undefined }; @Input() id = `dual-list-${nextId++}`; @Input() key = '_id'; @Input() display: any = '_name'; @Input() height = '100px'; @Input() filter = false; @Input() format = DualListComponent.DEFAULT_FORMAT; @Input() sort = false; @Input() compare: compareFunction; @Input() disabled = false; @Input() source: Array<any>; @Input() destination: Array<any>; @Output() destinationChange = new EventEmitter(); available: BasicList; confirmed: BasicList; sourceDiffer: any; destinationDiffer: any; private sorter = (a: any, b: any) => { return (a._name < b._name) ? -1 : ((a._name > b._name) ? 1 : 0); }; constructor(private differs: IterableDiffers) { this.available = new BasicList(DualListComponent.AVAILABLE_LIST_NAME); this.confirmed = new BasicList(DualListComponent.CONFIRMED_LIST_NAME); } ngOnChanges(changeRecord: {[key: string]: SimpleChange}) { if (changeRecord['filter']) { if (changeRecord['filter'].currentValue === false) { this.clearFilter(this.available); this.clearFilter(this.confirmed); } } if (changeRecord['sort']) { if (changeRecord['sort'].currentValue === true && this.compare === undefined) { this.compare = this.sorter; } else if (changeRecord['sort'].currentValue === false) { this.compare = undefined; } } if (changeRecord['format']) { this.format = changeRecord['format'].currentValue; if (typeof(this.format.direction) === 'undefined') { this.format.direction = DualListComponent.LTR; } if (typeof(this.format.add) === 'undefined') { this.format.add = DualListComponent.DEFAULT_FORMAT.add; } if (typeof(this.format.remove) === 'undefined') { this.format.remove = DualListComponent.DEFAULT_FORMAT.remove; } if (typeof(this.format.all) === 'undefined') { this.format.all = DualListComponent.DEFAULT_FORMAT.all; } if (typeof(this.format.none) === 'undefined') { this.format.none = DualListComponent.DEFAULT_FORMAT.none; } if (typeof(this.format.draggable) === 'undefined') { this.format.draggable = DualListComponent.DEFAULT_FORMAT.draggable; } } if (changeRecord['source']) { this.available = new BasicList(DualListComponent.AVAILABLE_LIST_NAME); this.updatedSource(); this.updatedDestination(); } if (changeRecord['destination']) { this.confirmed = new BasicList(DualListComponent.CONFIRMED_LIST_NAME); this.updatedDestination(); this.updatedSource(); } } ngDoCheck() { if (this.source && this.buildAvailable(this.source)) { this.onFilter(this.available); } if (this.destination && this.buildConfirmed(this.destination)) { this.onFilter(this.confirmed); } } buildAvailable(source: Array<any>): boolean { const sourceChanges = this.sourceDiffer.diff(source); if (sourceChanges) { sourceChanges.forEachRemovedItem((r: any) => { const idx = this.findItemIndex(this.available.list, r.item, this.key); if (idx !== -1) { this.available.list.splice(idx, 1); } }); sourceChanges.forEachAddedItem((r: any) => { // Do not add duplicates even if source has duplicates. if (this.findItemIndex(this.available.list, r.item, this.key) === -1) { this.available.list.push( { _id: this.makeId(r.item), _name: this.makeName(r.item) }); } }); if (this.compare !== undefined) { this.available.list.sort(this.compare); } this.available.sift = this.available.list; return true; } return false; } buildConfirmed(destination: Array<any>): boolean { let moved = false; const destChanges = this.destinationDiffer.diff(destination); if (destChanges) { destChanges.forEachRemovedItem((r: any) => { const idx = this.findItemIndex(this.confirmed.list, r.item, this.key); if (idx !== -1) { if (!this.isItemSelected(this.confirmed.pick, this.confirmed.list[idx])) { this.selectItem(this.confirmed.pick, this.confirmed.list[idx]); } this.moveItem(this.confirmed, this.available, this.confirmed.list[idx], false); moved = true; } }); destChanges.forEachAddedItem((r: any) => { const idx = this.findItemIndex(this.available.list, r.item, this.key); if (idx !== -1) { if (!this.isItemSelected(this.available.pick, this.available.list[idx])) { this.selectItem(this.available.pick, this.available.list[idx]); } this.moveItem(this.available, this.confirmed, this.available.list[idx], false); moved = true; } }); if (this.compare !== undefined) { this.confirmed.list.sort(this.compare); } this.confirmed.sift = this.confirmed.list; if (moved) { this.trueUp(); } return true; } return false; } updatedSource() { this.available.list.length = 0; this.available.pick.length = 0; if (this.source !== undefined) { this.sourceDiffer = this.differs.find(this.source).create(null); } } updatedDestination() { if (this.destination !== undefined) { this.destinationDiffer = this.differs.find(this.destination).create(null); } } direction() { return this.format.direction === DualListComponent.LTR; } dragEnd(list: BasicList = null): boolean { if (list) { list.dragStart = false; } else { this.available.dragStart = false; this.confirmed.dragStart = false; } return false; } drag(event: DragEvent, item: any, list: BasicList) { if (!this.isItemSelected(list.pick, item)) { this.selectItem(list.pick, item); } list.dragStart = true; // Set a custom type to be this dual-list's id. event.dataTransfer.setData(this.id, item['_id']); } allowDrop(event: DragEvent, list: BasicList): boolean { if (event.dataTransfer.types.length && (event.dataTransfer.types[0] === this.id)) { event.preventDefault(); if (!list.dragStart) { list.dragOver = true; } } return false; } dragLeave() { this.available.dragOver = false; this.confirmed.dragOver = false; } drop(event: DragEvent, list: BasicList) { if (event.dataTransfer.types.length && (event.dataTransfer.types[0] === this.id)) { event.preventDefault(); this.dragLeave(); this.dragEnd(); if (list === this.available) { this.moveItem(this.available, this.confirmed); } else { this.moveItem(this.confirmed, this.available); } } } private trueUp() { let changed = false; // Clear removed items. let pos = this.destination.length; while ((pos -= 1) >= 0) { const mv = this.confirmed.list.filter( conf => { if (typeof this.destination[pos] === 'object') { return conf._id === this.destination[pos][this.key]; } else { return conf._id === this.destination[pos]; } }); if (mv.length === 0) { // Not found so remove. this.destination.splice(pos, 1); changed = true; } } // Push added items. for (let i = 0, len = this.confirmed.list.length; i < len; i += 1) { let mv = this.destination.filter( (d: any) => { if (typeof d === 'object') { return (d[this.key] === this.confirmed.list[i]._id); } else { return (d === this.confirmed.list[i]._id); } }); if (mv.length === 0) { // Not found so add. mv = this.source.filter( (o: any) => { if (typeof o === 'object') { return (o[this.key] === this.confirmed.list[i]._id); } else { return (o === this.confirmed.list[i]._id); } }); if (mv.length > 0) { this.destination.push(mv[0]); changed = true; } } } if (changed) { this.destinationChange.emit(this.destination); } } findItemIndex(list: Array<any>, item: any, key: any = '_id') { let idx = -1; function matchObject(e: any) { if (e._id === item[key]) { idx = list.indexOf(e); return true; } return false; } function match(e: any) { if (e._id === item) { idx = list.indexOf(e); return true; } return false; } // Assumption is that the arrays do not have duplicates. if (typeof item === 'object') { list.filter(matchObject); } else { list.filter(match); } return idx; } private makeUnavailable(source: BasicList, item: any) { const idx = source.list.indexOf(item); if (idx !== -1) { source.list.splice(idx, 1); } } moveItem(source: BasicList, target: BasicList, item: any = null, trueup = true) { let i = 0; let len = source.pick.length; if (item) { i = source.list.indexOf(item); len = i + 1; } for (; i < len; i += 1) { // Is the pick still in list? let mv: Array<any> = []; if (item) { const idx = this.findItemIndex(source.pick, item); if (idx !== -1) { mv[0] = source.pick[idx]; } } else { mv = source.list.filter( src => { return (src._id === source.pick[i]._id); }); } // Should only ever be 1 if (mv.length === 1) { // Add if not already in target. if (target.list.filter(trg => trg._id === mv[0]._id).length === 0) { target.list.push( mv[0] ); } this.makeUnavailable(source, mv[0]); } } if (this.compare !== undefined) { target.list.sort(this.compare); } source.pick.length = 0; // Update destination if (trueup) { this.trueUp(); } // Delay ever-so-slightly to prevent race condition. setTimeout( () => { this.onFilter(source); this.onFilter(target); }, 10); } isItemSelected(list: Array<any>, item: any): boolean { if (list.filter(e => Object.is(e, item)).length > 0) { return true; } return false; } shiftClick(event: MouseEvent, index: number, source: BasicList, item: any) { if (event.shiftKey && source.last && !Object.is(item, source.last)) { const idx = source.sift.indexOf(source.last); if (index > idx) { for (let i = (idx + 1); i < index; i += 1) { this.selectItem(source.pick, source.sift[i]); } } else if (idx !== -1) { for (let i = (index + 1); i < idx; i += 1) { this.selectItem(source.pick, source.sift[i]); } } } source.last = item; } selectItem(list: Array<any>, item: any) { const pk = list.filter( (e: any) => { return Object.is(e, item); }); if (pk.length > 0) { // Already in list, so deselect. for (let i = 0, len = pk.length; i < len; i += 1) { const idx = list.indexOf(pk[i]); if (idx !== -1) { list.splice(idx, 1); } } } else { list.push(item); } } selectAll(source: BasicList) { source.pick.length = 0; source.pick = source.sift.slice(0); } selectNone(source: BasicList) { source.pick.length = 0; } isAllSelected(source: BasicList): boolean { if (source.list.length === 0 || source.list.length === source.pick.length) { return true; } return false; } isAnySelected(source: BasicList): boolean { if (source.pick.length > 0) { return true; } return false; } private unpick(source: BasicList) { for (let i = source.pick.length - 1; i >= 0; i -= 1) { if (source.sift.indexOf(source.pick[i]) === -1) { source.pick.splice(i, 1); } } } clearFilter(source: BasicList) { if (source) { source.picker = ''; this.onFilter(source); } } onFilter(source: BasicList) { if (source.picker.length > 0) { try { const filtered = source.list.filter( (item: any) => { if (Object.prototype.toString.call(item) === '[object Object]') { if (item._name !== undefined) { // @ts-ignore: remove when d.ts has locale as an argument. return item._name.toLocaleLowerCase(this.format.locale).indexOf(source.picker.toLocaleLowerCase(this.format.locale)) !== -1; } else { // @ts-ignore: remove when d.ts has locale as an argument. return JSON.stringify(item).toLocaleLowerCase(this.format.locale).indexOf(source.picker.toLocaleLowerCase(this.format.locale)) !== -1; } } else { // @ts-ignore: remove when d.ts has locale as an argument. return item.toLocaleLowerCase(this.format.locale).indexOf(source.picker.toLocaleLowerCase(this.format.locale)) !== -1; } }); source.sift = filtered; this.unpick(source); } catch (e) { if (e instanceof RangeError) { this.format.locale = undefined; } source.sift = source.list; } } else { source.sift = source.list; } } private makeId(item: any): string | number { if (typeof item === 'object') { return item[this.key]; } else { return item; } } // Allow for complex names by passing an array of strings. // Example: [display]="[ '_type.substring(0,1)', '_name' ]" protected makeName(item: any, separator = '_'): string { const display = this.display; function fallback(itm: any) { switch (Object.prototype.toString.call(itm)) { case '[object Number]': return itm; case '[object String]': return itm; default: if (itm !== undefined) { return itm[display]; } else { return 'undefined'; } } } let str = ''; if (this.display !== undefined) { switch (Object.prototype.toString.call(this.display)) { case '[object Function]': str = this.display(item); break; case '[object Array]': for (let i = 0, len = this.display.length; i < len; i += 1) { if (str.length > 0) { str = str + separator; } if (this.display[i].indexOf('.') === -1) { // Simple, just add to string. str = str + item[this.display[i]]; } else { // Complex, some action needs to be performed const parts = this.display[i].split('.'); const s = item[parts[0]]; if (s) { // Use brute force if (parts[1].indexOf('substring') !== -1) { const nums = (parts[1].substring(parts[1].indexOf('(') + 1, parts[1].indexOf(')'))).split(','); switch (nums.length) { case 1: str = str + s.substring(parseInt(nums[0], 10)); break; case 2: str = str + s.substring(parseInt(nums[0], 10), parseInt(nums[1], 10)); break; default: str = str + s; break; } } else { // method not approved, so just add s. str = str + s; } } } } break; default: str = fallback(item); break; } } else { str = fallback(item); } return str; } }
the_stack
import { fancy } from 'fancy-test' import chai, { expect } from 'chai' import sinonChai from 'sinon-chai' import { useFakeTimers } from 'sinon' import { createQuote, createLightOrder } from '@airswap/utils' import { ADDRESS_ZERO, REQUEST_TIMEOUT } from '@airswap/constants' import { Server } from '..' import { addJSONRPCAssertions, createRequest, createResponse, MockSocketServer, nextEvent, } from './test-utils' import { LightOrder } from '@airswap/types' import { JsonRpcErrorCodes } from '@airswap/jsonrpc-client-websocket' addJSONRPCAssertions() declare global { // External library defines a namespace so ignore this rule. // eslint-disable-next-line @typescript-eslint/no-namespace export namespace Chai { interface Assertion { JSONRpcRequest(method: string, params?: any): void JSONRpcResponse(id: string, result: any): void JSONRpcError(id: string, error: any): void } } } const badQuote = { bad: 'quote' } const emptyQuote = createQuote({}) const URL = 'maker.example.com' chai.use(sinonChai) function mockHttpServer(api) { api.post('/').reply(200, async (uri, body) => { const params = body['params'] let res switch (body['method']) { case 'getMaxQuote': res = emptyQuote break case 'getSignerSideQuote': res = badQuote break case 'getSenderSideQuote': res = createQuote({ signer: { token: params.signerToken, amount: params.signerAmount, }, sender: { token: params.senderToken, }, }) break case 'getSignerSideOrder': res = createLightOrder({ signerToken: params.signerToken, senderToken: params.senderToken, senderAmount: params.senderAmount, senderWallet: params.senderWallet, }) break case 'consider': res = true break } return { jsonrpc: '2.0', id: body['id'], result: res, } }) } describe('HTTPServer', () => { fancy .nock('https://' + URL, mockHttpServer) .do(async () => { const server = await Server.at(URL) await server.getSignerSideQuote('', '', '') }) .catch(/Server response is not a valid quote: {"bad":"quote"}/) .it('Server getSignerSideQuote() throws') fancy .nock('https://' + URL, mockHttpServer) .do(async () => { const server = await Server.at(URL) await server.getMaxQuote('', '') }) .catch( /Server response differs from request params: signerToken,senderToken/ ) .it('Server getMaxQuote() throws') fancy .nock('https://' + URL, mockHttpServer) .it('Server getSenderSideQuote()', async () => { const server = await Server.at(URL) const quote = await server.getSenderSideQuote('1', 'SIGNERTOKEN', '') expect(quote.signer.token).to.equal('SIGNERTOKEN') }) fancy .nock('https://' + URL, mockHttpServer) .it('Server getSignerSideOrder()', async () => { const server = await Server.at(URL) const order = await server.getSignerSideOrder( '0', ADDRESS_ZERO, ADDRESS_ZERO, ADDRESS_ZERO ) expect(order.signerToken).to.equal(ADDRESS_ZERO) }) }) const samplePairs = [ { baseToken: '0xbase1', quoteToken: '0xquote1', }, { baseToken: '0xbase2', quoteToken: '0xquote2', }, ] const samplePricing = [ { baseToken: '0xbase1', quoteToken: '0xquote1', bid: [ ['100', '0.00053'], ['1000', '0.00061'], ['10000', '0.0007'], ], ask: [ ['100', '0.00055'], ['1000', '0.00067'], ['10000', '0.0008'], ], }, { baseToken: '0xbase2', quoteToken: '0xquote2', bid: [ ['100', '0.00053'], ['1000', '0.00061'], ['10000', '0.0007'], ], ask: [ ['100', '0.00055'], ['1000', '0.00067'], ['10000', '0.0008'], ], }, ] const fakeOrder: LightOrder = { nonce: '1', expiry: '1234', signerWallet: '0xsigner', signerToken: '0xtokena', signerAmount: '100', senderToken: '0xtokenb', senderAmount: '200', v: 'v', r: 'r', s: 's', } describe('WebSocketServer', () => { const url = `ws://maker.com:1234/` let mockServer: MockSocketServer before(() => { MockSocketServer.startMockingWebSocket() }) beforeEach(async () => { mockServer = new MockSocketServer(url) mockServer.resetInitOptions() }) it('should be initialized after Server.at has resolved', async () => { const server = await Server.at(url) const correctInitializeResponse = new Promise<void>((resolve) => { const onResponse = (socket, data) => { // Note mock server implementation uses id '123' for initialize. expect(data).to.be.a.JSONRpcResponse('123', true) resolve() } mockServer.setNextMessageCallback(onResponse) }) expect(server.supportsProtocol('last-look')).to.equal(true) expect(server.supportsProtocol('request-for-quote')).to.equal(false) await correctInitializeResponse }) it('should call subscribe with the correct params and emit pricing', async () => { const server = await Server.at(url) // Ensure subscribe method is correct format. const onSubscribe = (socket, data) => { expect(data).to.be.a.JSONRpcRequest('subscribe', [samplePairs]) socket.send(JSON.stringify(createResponse(data.id, samplePricing))) } mockServer.setNextMessageCallback(onSubscribe, true) const pricing = nextEvent(server, 'pricing') server.subscribe(samplePairs) // Ensure pricing is emitted and has the correct values. expect(await pricing).to.eql(samplePricing) const updatedPricing = nextEvent(server, 'pricing') const latestPricing = [ [ { baseToken: '0xbase1', quoteToken: '0xquote1', bid: [ ['100', '0.00055'], ['1000', '0.00064'], ['10000', '0.0008'], ], ask: [ ['100', '0.00056'], ['1000', '0.00068'], ['10000', '0.0009'], ], }, ], ] const updatePricingRequestId = '456' // Ensure client responds to server correctly when pricing is updated const correctUpdatePricingResponse = new Promise<void>((resolve) => { const onResponse = (socket, data) => { expect(data).to.be.a.JSONRpcResponse(updatePricingRequestId, true) resolve() } mockServer.setNextMessageCallback(onResponse) }) // Ensure updatePricing is correctly called and causes pricing to be emitted mockServer.emit( 'message', JSON.stringify( createRequest('updatePricing', latestPricing, updatePricingRequestId) ) ) expect(await updatedPricing).to.eql(latestPricing[0]) await correctUpdatePricingResponse }) it('should call consider with the correct parameters', async () => { const server = await Server.at(url) const onConsider = (socket, data) => { expect(data).to.be.a.JSONRpcRequest('consider', fakeOrder) socket.send(JSON.stringify(createResponse(data.id, true))) } mockServer.setNextMessageCallback(onConsider, true) const result = await server.consider(fakeOrder) expect(result).to.equal(true) }) fancy .nock('https://' + URL, mockHttpServer) .it( 'should use HTTP for consider when senderServer is provided', async () => { mockServer.initOptions = { lastLook: '1.0.0', params: { swapContract: '0x1234', senderWallet: '0x2345', senderServer: URL, }, } const server = await Server.at(url) const result = await server.consider(fakeOrder) expect(result).to.equal(true) } ) it('should call unsubscribe with the correct parameters', async () => { const server = await Server.at(url) const onUnsubscribe = (socket, data) => { expect(data).to.be.a.JSONRpcRequest('unsubscribe', [samplePairs]) socket.send(JSON.stringify(createResponse(data.id, true))) } mockServer.setNextMessageCallback(onUnsubscribe, true) const result = await server.unsubscribe(samplePairs) expect(result).to.equal(true) }) it('should call subscribeAll and unsubscribeAll correctly', async () => { const server = await Server.at(url) const onSubscribeAll = (socket, data) => { expect(data).to.be.a.JSONRpcRequest('subscribeAll') socket.send(JSON.stringify(createResponse(data.id, true))) } const onUnsubscribeAll = (socket, data) => { expect(data).to.be.a.JSONRpcRequest('unsubscribeAll') socket.send(JSON.stringify(createResponse(data.id, true))) } mockServer.setNextMessageCallback(onSubscribeAll, true) const subscribeResult = await server.subscribeAll() expect(subscribeResult).to.equal(true) mockServer.setNextMessageCallback(onUnsubscribeAll, true) const unsubscribeResult = await server.unsubscribeAll() expect(unsubscribeResult).to.equal(true) }) it("should throw if the server doesn't initialize within timeout", async () => { const fakeTimers = useFakeTimers() // prevent server from initializing mockServer.initOptions = null const initializePromise = Server.at(url) // This is the default timeout. fakeTimers.tick(REQUEST_TIMEOUT) try { await initializePromise throw new Error('Server.at should not resolve before initialize') } catch (e) { expect(e).to.equal('Server did not call initialize in time') } fakeTimers.restore() }) it('should correctly indicate support for protocol versions', async () => { // Protocol is supported if the major version is the same, // and minor and patch versions are the same or greater than requried mockServer.initOptions = { lastLook: '1.2.3' } const server = await Server.at(url) expect(server.supportsProtocol('last-look')).to.be.true expect(server.supportsProtocol('request-for-quote')).to.be.false expect(server.supportsProtocol('last-look', '0.9.1')).to.be.false expect(server.supportsProtocol('last-look', '1.0.0')).to.be.true expect(server.supportsProtocol('last-look', '1.1.1')).to.be.true expect(server.supportsProtocol('last-look', '1.2.3')).to.be.true expect(server.supportsProtocol('last-look', '1.2.4')).to.be.false expect(server.supportsProtocol('last-look', '1.3.0')).to.be.false expect(server.supportsProtocol('last-look', '2.2.3')).to.be.false }) it('should reject when calling a method from an unsupported protocol', async () => { const server = await Server.at(url) try { await server.getMaxQuote('', '') throw new Error('expected getMaxQuote method to reject') } catch (e) { expect(e.message).to.match(/support/) } }) it('should respond with an error if initialize is called with bad params', async () => { mockServer.initOptions = null const responseReceived = new Promise<void>((resolve) => { const onInitializeResponse = (socket, data) => { expect(data).to.be.a.JSONRpcError('abc', { code: JsonRpcErrorCodes.INVALID_PARAMS, message: 'Invalid params', }) resolve() } mockServer.setNextMessageCallback(onInitializeResponse) }) mockServer.on('connection', (socket) => { socket.send( JSON.stringify(createRequest('initialize', [{ bad: 'params' }], 'abc')) ) }) Server.at(url).catch(() => { /* this is expected, server won't init */ }) await responseReceived }) it('should respond with an error if pricing is called with bad params', async () => { await Server.at(url) const initResponseReceived = new Promise<void>((resolve) => { mockServer.setNextMessageCallback(() => resolve()) }) await initResponseReceived const responseReceived = new Promise<void>((resolve) => { const onPricingReponse = (socket, data) => { expect(data).to.be.a.JSONRpcError('abc', { code: JsonRpcErrorCodes.INVALID_PARAMS, message: 'Invalid params', }) resolve() } mockServer.setNextMessageCallback(onPricingReponse) }) mockServer.emit( 'message', JSON.stringify( createRequest('updatePricing', [{ bad: 'pricing' }], 'abc') ) ) await responseReceived }) it('should return the correct sender wallet', async () => { mockServer.initOptions = { lastLook: '1.2.3', params: { senderWallet: '0xmySender', }, } const server = await Server.at(url) expect(server.getSenderWallet()).to.equal('0xmySender') }) afterEach(() => { mockServer.close() }) after(() => { MockSocketServer.stopMockingWebSocket() }) })
the_stack
import * as fs from "fs"; import * as querystring from 'querystring' import * as terminalImage from 'terminal-image' import { Logger } from "log4js"; import { $axios } from "../http"; import { log4js } from "../log"; import * as crypt from '@/util/crypt' const md5 = require('md5-node') export class User { private readonly APPKEY: string private readonly APPSECRET: string private _access_token: string; private _mid: number; private _password: string; private _username: string; private logger: Logger; private sessionID: string | undefined; private JSESSIONID: string | undefined; private _refresh_token: string | undefined; private _expires_in: number | undefined; private _nickname: string | ''; private _tokenSignDate: Date | string; constructor(username: string, password: string, access_token: string = '', refresh_token: string = '', expires_in: number = 0, nickname: string = '', tokenSignDate: string, mid: number) { this.APPKEY = "aae92bc66f3edfab"; this.APPSECRET = "af125a0d5279fd576c1b4418a3e8276d" this._username = username; this._password = password; this._access_token = access_token || ''; this._refresh_token = refresh_token || ''; this._expires_in = expires_in || undefined; this._nickname = nickname || ''; this._tokenSignDate = tokenSignDate || ''; this.logger = log4js.getLogger('User') this._mid = mid || 0; } get access_token(): string { return this._access_token; } set access_token(value: string) { this._access_token = value; } get password(): string { return this._password; } set password(value: string) { this._password = value; } get username(): string { return this._username; } set username(value: string) { this._username = value; } /** * 同步个人数据到配置文件 */ sync = async () => { this.logger.info(`Sync User info ...`) try { const text = fs.readFileSync('./templates/info.json') const obj = JSON.parse(text.toString()) obj.personInfo = { nickname: this._nickname, username: this._username, password: this._password, access_token: this._access_token, refresh_token: this._refresh_token, expires_in: this._expires_in, tokenSignDate: this._tokenSignDate, mid: this._mid } const stringifies = JSON.stringify(obj, null, ' ') fs.writeFileSync('./templates/info.json', stringifies) this.logger.info(`Sync User info ... DONE`) } catch (e) { this.logger.error(e) } } // /** * 登陆 Check username && password => checkToken => getKey => auth(Username) => auth(captcha) */ login = async () => { if (!this._username) return this.logger.error(`Check your username !!`) if (!this._password) return this.logger.error(`Check your password !!`) try { await this.checkToken() // Judge Refresh Token const time = Math.floor((new Date().valueOf() - new Date(this._tokenSignDate).valueOf()) / 1000) if (this._tokenSignDate && this._expires_in && time >= this._expires_in / 2) await this.refreshToken() } catch (e) { await this.loginAccount() this.logger.error(e) } } loginAccount = async () => { return new Promise<void>(async (resolve, reject) => { const { hash, key }: any = await this.getKey() const encoded_password = crypt.make_rsa(`${hash}${this._password}`, key) const url = "https://passport.bilibili.com/api/oauth2/login" const headers: any = { 'Connection': 'keep-alive', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'User-Agent': '', 'Accept-Encoding': 'gzip,deflate', 'cookie': '' } if (this.sessionID) { headers.cookie += `sid:${this.sessionID}; ` } if (this.JSESSIONID) { headers.cookie += `JSESSIONID:${this.JSESSIONID}; ` } let data: { appkey: string | undefined; password: string; platform: string; ts: number; username: string; sign?: string | undefined } = { 'appkey': this.APPKEY, 'password': encoded_password, 'platform': "pc", 'ts': parseInt(String(new Date().valueOf() / 1000)), 'username': this._username } data.sign = md5(crypt.make_sign(data, this.APPSECRET)) try { this.logger.debug(`Login Post Data: ${JSON.stringify(data, null, 2)}`) const { code, message, data: { access_token, mid, refresh_token, expires_in } = { access_token: '', mid: 0, refresh_token: '', expires_in: undefined } }: { code: number, message: string, data: { access_token: string; mid: number; refresh_token: string; expires_in: number | undefined } } = await $axios.$request({ method: "POST", url, data: querystring.stringify(data), headers }) this.logger.debug(`code ${code} message ${message} access-token ${access_token} mid ${mid} refresh_token ${refresh_token} expires_in ${expires_in}`) // captcha error if (code === -105) { await this.getCapcha() } if (code !== 0) { this.logger.error(`An error occurred when login: ${message}`) return } this._access_token = access_token this._mid = mid this._refresh_token = refresh_token this._expires_in = expires_in this._tokenSignDate = new Date() this.logger.info(`mid ${mid}`) this.logger.info(`access-token ${access_token}`) this.logger.info(`token expires_in ${expires_in}s`) this.logger.info(`refresh_token ${refresh_token}`) this.logger.info(`Login succeed !!`) await this.sync() resolve() } catch (err) { this.logger.error(err) reject(err) } }) } getKey = async () => { return new Promise(async (resolve, reject) => { this.logger.debug(`start getKey`) let url = "https://passport.bilibili.com/api/oauth2/getKey" let data: { appkey: string | undefined; platform: string; ts: string; sign?: string } = { 'appkey': this.APPKEY, 'platform': "pc", 'ts': (+new Date()).toString().substr(0, 10) }; data.sign = md5(crypt.make_sign(data, this.APPSECRET)) this.logger.debug(`getKey data ${JSON.stringify(data)} APPSECRET ${this.APPSECRET}`) const headers: any = { 'Content-Type': 'application/x-www-form-urlencoded', 'Accept': "application/json, text/javascript, */*; q=0.01", 'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36" } try { if (this.sessionID) { headers.cookie += `sid:${this.sessionID}; ` } if (this.JSESSIONID) { headers.cookie += `JSESSIONID:${this.JSESSIONID}; ` } const { resHeaders, code, data: { hash, key } }: { resHeaders: { "set-cookie": string }; code: number; data: { hash: string; key: string; } } = await $axios.$request({ method: "post", url, data: querystring.stringify(data), headers }) this.logger.debug(`Get key \n ${key} hash ${hash} code ${code} \n resHeaders ${JSON.stringify(resHeaders, null, 2)} ${this.sessionID}`) this.logger.debug(`${resHeaders["set-cookie"]}`) const regex = /^sid=([\w]*)/g; for (const resHeader of resHeaders["set-cookie"]) { let tmp = resHeader.match(regex) if (tmp) { this.sessionID = tmp[0].split("=")[1] this.logger.info(`sessionID ${this.sessionID}`) } } if (code !== 0) { this.logger.error(`Get key error , code ${code}`) reject() } resolve({ hash, key }) } catch (e) { this.logger.error(`An error occurred when getKey: ${e}`) reject(`An error occurred when getKey: ${e}`) } }) } checkToken = async () => { return new Promise(async (resolve, reject) => { this.logger.info(`Check token ${this._access_token}`) if (this._access_token === "") { this.logger.error(`Access Token not define`) return reject() } let url = `https://api.snm0516.aisee.tv/x/tv/account/myinfo?access_key=${this._access_token}` try { const { code, message, data: { mid, name } } = await $axios.$get(url) if (code !== 0) { this.logger.error(`An error occurred when try to auth by access_token: ${message}`) reject() } this.logger.info(`Token is valid. ${mid} ${name}`) this._mid = mid this._nickname = name await this.sync() resolve(true) } catch (err) { this.logger.error(`An error occurred when try to check token: ${err}`) reject(err) } }) } refreshToken = async () => { return new Promise<void>(async (resolve, reject) => { let url: string = 'https://passport.bilibili.com/api/v2/oauth2/refresh_token' let data: any = { access_token: this._access_token, refresh_token: this._refresh_token, access_key: this._access_token, actionKey: 'appkey', platform: 'android', appkey: this.APPKEY, build: 5511400, devices: 'android', mobi_app: 'android', ts: parseInt(String(new Date().valueOf() / 1000)) } data.sign = md5(crypt.make_sign(data, this.APPSECRET)) const headers: any = {} if (this.sessionID) { headers.cookie += `sid:${this.sessionID}; ` } if (this.JSESSIONID) { headers.cookie += `JSESSIONID:${this.JSESSIONID}; ` } try { const { code, data: { "token_info": { mid, access_token, refresh_token, expires_in } } = { token_info: { mid: 0, access_token: '', refresh_token: '', expires_in: 0 } } } = await $axios.$request({ url, data: querystring.stringify(data), headers, method: "post" }) // auth fail { message: 'user not login', ts: 1612252355, code: -101 } if (code === 0) { this._mid = mid this._access_token = access_token this._refresh_token = refresh_token this._expires_in = expires_in this._tokenSignDate = new Date() this.logger.info(`Token refresh succeed !!`) this.logger.info(`access_token ${access_token}`) this.logger.info(`refresh_token ${refresh_token}`) this.logger.info(`expires_in ${expires_in}`) await this.sync() resolve() } else if (code === -101) { this.logger.error(`Access Token expire ...`) reject() } } catch (e) { this.logger.error(e) reject() } }) } // loginCaptcha = async () => {} // DEV getCapcha = async () => { return new Promise(async () => { const headers: any = { 'User-Agent': '', 'Accept-Encoding': 'gzip,deflate', cookie: '' } if (this.sessionID) { headers.cookie = headers.cookie + `sid:${this.sessionID}; ` } if (this.JSESSIONID) { headers.cookie = headers.cookie + `JSESSIONID:${this.JSESSIONID}; ` } const data: any = { 'appkey': this.APPKEY, 'platform': 'pc', 'ts': parseInt(String(new Date().valueOf() / 1000)), } data['sign'] = md5(crypt.make_sign(data, this.APPSECRET)) let url = 'https://passport.bilibili.com/captcha' console.log(JSON.stringify(headers, null, 2)); const dataImg = await $axios.request({ url, method: "get", headers, responseType: "arraybuffer", params: querystring.stringify(data) }) console.log(dataImg); console.log(await terminalImage.buffer(dataImg.data)); const regex = /^JSESSIONID=([\w]*)/g; for (const headerElement of dataImg.headers["set-cookie"]) { let tmp = headerElement.match(regex) if (tmp) { this.JSESSIONID = tmp[0].split("=")[1] this.logger.info(`JSESSIONID ${this.JSESSIONID}`) } } }) } } // const { // username, // password, // access_token, // refresh_token, // expires_in, // tokenSignDate, // nickname // } = require('../../templates/info.json').personInfo // const user = new User(username, password, access_token, refresh_token, expires_in, nickname, tokenSignDate) // // // user.getKey().then(r => console.log(r)) // // user.login().then(r => console.log(r)) // // // user.refreshToken().then(r => console.log(r)) // // // user.getCapcha().then(r => console.log(r))
the_stack
import urlJoin from 'url-join'; import mapValues from 'lodash/mapValues'; import { assert } from 'common/utils'; import statesByFipsJson from 'common/data/states_by_fips.json'; export type FipsCode = string; export type ZipCode = string; export enum RegionType { NATION = 'nation', COUNTY = 'county', STATE = 'state', MSA = 'MSA', } /* Used to rename some metro principal cities for clarity: */ const DC_METRO_FIPS = '47900'; const NY_METRO_FIPS = '35620'; interface FipsToPrincipalCityName { [key: string]: string; } const fipsToPrincipalCityRenames: FipsToPrincipalCityName = { [DC_METRO_FIPS]: 'Washington DC', [NY_METRO_FIPS]: 'New York City', }; /** * Common name-to-url-segment manipulation. * Some have custom things to do though, which are handled below. */ const mungeName = (s: string) => { let t = s; // make lowercase (order of this matters for above) t = t.toLowerCase(); // replace slashes with dashes t = t.replace(/\//g, '-'); // replace double-dashes with dashes t = t.replace(/--/g, '-'); // remove accents from characters t = t.normalize('NFD').replace(/[\u0300-\u036f]/g, ''); // replace O' with O_ (e.g., O'Brien) t = t.replace(/^o'/, 'o_'); // remove periods t = t.replace(/[.]/g, ''); // remove apostrophes t = t.replace(/[']/g, ''); return t; }; /** * Compute the urlSegment for a state based on the name and stateCode. * Must match the one that would have been provided by input data, * the validator in the generator script will check that. */ export const generateStateUrlSegment = (name: string, stateCode: string) => { let s = mungeName(name); // for states, replace spaces with underscores s = s.replace(/ /g, '_'); return `${s}-${stateCode.toLowerCase()}`; }; /** * Compute the urlSegment for a county based on the name. * Must match the one that would have been provided by input data, * the validator in the generator script will check that. */ export const generateCountyUrlSegment = (name: string) => { // this one is misspelled, so special case it if (name === 'Tinian Municipality') { return 'tianian_municipality'; } let s = name; // for counties, split e.g. DeKalb into De_Kalb s = s.replace(/([a-z])([A-Z])/g, '$1_$2'); // for counties, replace spaces with underscores s = s.replace(/ /g, '_'); // for Counties, replace dashes with underscores s = s.replace(/[-]/g, '_'); s = mungeName(s); return s; }; /** * Compute the urlSegment for a metroArea based on the name and states. * Must match the one that would have been provided by input data, * the validator in the generator script will check that. */ export const generateMetroAreaUrlSegment = ( name: string, statesFips: FipsCode[], ) => { // this one is missing 'city' so special case it: if (name === 'New York-Newark-Jersey City') { return 'new-york-city-newark-jersey-city_ny-nj-pa'; } const states = statesFips .map(fips => statesByFips[fips].stateCode.toLowerCase()) .join('-'); let s = name; // for metroareas, replace apostrophes with dashes s = s.replace(/[']/g, '-'); s = mungeName(s); // for MetroAreas, replace spaces with dashes s = s.replace(/ /g, '-'); return `${s}_${states}`; }; // JSON-serializable representation of a Region object export interface RegionObject { n: string; // name f: FipsCode; // fips code p: number; // population } export abstract class Region { constructor( public readonly name: string, public readonly fipsCode: FipsCode, public readonly population: number, public readonly regionType: RegionType, ) {} abstract get fullName(): string; abstract get shortName(): string; abstract get abbreviation(): string; abstract get relativeUrl(): string; /** * Returns true if this region (at least partially) contains the specified subregion. * * Notes: * - If a metro is partially contained within a state, state.contains(metro) returns true * - Regions do not contain themselves, i.e. region.contains(region) returns false */ abstract contains(subregion: Region): boolean; get canonicalUrl() { return urlJoin('https://covidactnow.org', this.relativeUrl); } toString() { return `${this.name} (fips=${this.fipsCode})`; } abstract toJSON(): RegionObject; } export interface StateObject extends RegionObject { s: string; } export class USA extends Region { private constructor() { super('USA', '0', 331486822, RegionType.NATION); } static instance = new USA(); fullName = 'United States of America'; shortName = 'USA'; abbreviation = 'USA'; get relativeUrl(): string { throw new Error('Method not implemented.'); } contains(subregion: Region): boolean { throw new Error('Method not implemented.'); } toJSON(): RegionObject { throw new Error('Method not implemented.'); } } export class State extends Region { constructor( name: string, fipsCode: FipsCode, population: number, public readonly stateCode: string, ) { super(name, fipsCode, population, RegionType.STATE); } get fullName() { return this.name; } get shortName() { return this.name; } get abbreviation() { return this.stateCode; } get urlSegment() { return generateStateUrlSegment(this.name, this.stateCode); } get relativeUrl() { return `/us/${this.urlSegment}/`; } contains(subregion: Region): boolean { return ( (subregion instanceof MetroArea && subregion.states.includes(this)) || (subregion instanceof County && subregion.state === this) ); } public toJSON(): StateObject { return { n: this.name, f: this.fipsCode, p: this.population, s: this.stateCode, }; } public static fromJSON(obj: StateObject): State { return new State(obj.n, obj.f, obj.p, obj.s); } } /** * Construct this mapping here, so we can reference it to simplify reconstitution * of County and MetroArea objects. The overall size for ~50 states is quite small, * so it's not worth trying to pull out of the main bundle, and having the lookup * available is quite handy. */ export const statesByFips = mapValues( statesByFipsJson as { [fips: string]: StateObject }, v => State.fromJSON(v), ); export const findStateByFipsCode = (fips: FipsCode): State | null => { return statesByFips[fips] ?? null; }; export const findStateByFipsCodeStrict = (fips: FipsCode): State => { const state = findStateByFipsCode(fips); assert(state, `State unexpectedly not found for ${fips}`); return state; }; /** * Shortens the county name by using the abbreviated version of 'county' * or the equivalent administrative division. */ export function getAbbreviatedCounty(fullCountyName: string) { if (fullCountyName.includes('Parish')) return fullCountyName.replace('Parish', 'Par.'); if (fullCountyName.includes('Borough')) return fullCountyName.replace('Borough', 'Bor.'); if (fullCountyName.includes('Census Area')) return fullCountyName.replace('Census Area', 'C.A.'); if (fullCountyName.includes('Municipality')) return fullCountyName.replace('Municipality', 'Mun.'); if (fullCountyName.includes('Municipio')) return fullCountyName.replace('Municipio', 'Mun.'); else return fullCountyName.replace('County', 'Co.'); } export interface CountyObject extends RegionObject { s: FipsCode; } export class County extends Region { public readonly state: State; constructor( name: string, fipsCode: FipsCode, population: number, stateFips: FipsCode, ) { super(name, fipsCode, population, RegionType.COUNTY); this.state = statesByFips[stateFips]; } get fullName() { return `${this.name}, ${this.state.name}`; } get shortName() { return `${this.name}, ${this.stateCode}`; } get abbreviation() { return getAbbreviatedCounty(this.name); } get urlSegment() { return generateCountyUrlSegment(this.name); } get relativeUrl() { return urlJoin(this.state.relativeUrl, `county/${this.urlSegment}/`); } get stateCode() { return this.state.stateCode; } contains(subregion: Region): boolean { return false; } public toJSON(): CountyObject { return { n: this.name, f: this.fipsCode, p: this.population, s: this.state.fipsCode, }; } public static fromJSON(obj: CountyObject): County { return new County(obj.n, obj.f, obj.p, obj.s); } } export interface MetroAreaObject extends RegionObject { c: FipsCode[]; s: FipsCode[]; } /** * Metropolitan Statistical Areas */ export class MetroArea extends Region { public readonly states: State[]; constructor( name: string, fipsCode: FipsCode, population: number, // MetroAreas are constructed by FIPS for states, but the states are retrieved // and stored as objects statesFips: FipsCode[], // We intentionally only store counties by FIPS code instead of rich objects // so we can construct MetroArea objects without loading the entire counties DB. // This will be very useful for rendering things above the fold on location pages // and deferred loading the big data for charts down below. // If you need the county object, you can look it up by FIPS from the regions_db. public readonly countiesFips: FipsCode[], ) { super(name, fipsCode, population, RegionType.MSA); this.states = statesFips.map(fips => statesByFips[fips]); } private get principalCityName() { if (this.fipsCode in fipsToPrincipalCityRenames) { return fipsToPrincipalCityRenames[this.fipsCode]; } return this.name.split('-')[0]; } get isSingleStateMetro() { return this.states.length === 1; } get fullName() { return `${this.principalCityName} metro area`; } get shortName() { return `${this.principalCityName} metro`; } get abbreviation() { return this.shortName; } get urlSegment() { return generateMetroAreaUrlSegment( this.name, this.states.map(state => state.fipsCode), ); } get relativeUrl() { return `/us/metro/${this.urlSegment}/`; } get stateCodes() { return this.states.map(state => state.stateCode).join('-'); } contains(subregion: Region): boolean { return ( subregion instanceof County && this.countiesFips.includes(subregion.fipsCode) ); } public toJSON(): MetroAreaObject { return { n: this.name, f: this.fipsCode, p: this.population, s: this.states.map(state => state.fipsCode), c: this.countiesFips, }; } public static fromJSON(obj: MetroAreaObject): MetroArea { return new MetroArea(obj.n, obj.f, obj.p, obj.s, obj.c); } }
the_stack
import type * as babel from '@babel/core'; import * as parser from '@babel/parser'; import traverse from '@babel/traverse'; import { RemoteConsole } from 'vscode-languageserver/node'; import * as util from 'util'; const PLACEHOLDER = 'TRIGGER_CHARACTER'; export interface VisitorSelection { start: { line: number, character: number }; end: { line: number, character: number }; } export interface VisitorTextAndSelection { textFromEditor: string; selection: VisitorSelection; } export interface CompletionState { databaseName: string | null; collectionName: string | null; isObject: boolean; isArray: boolean; isObjectKey: boolean; isShellMethod: boolean; isUseCallExpression: boolean; isDbCallExpression: boolean; isCollectionName: boolean; isAggregationCursor: boolean; isFindCursor: boolean; } export class Visitor { _state: CompletionState; _selection: VisitorSelection; _console: RemoteConsole; constructor(console: RemoteConsole) { this._state = this._getDefaultNodesValues(); this._selection = { start: { line: 0, character: 0 }, end: { line: 0, character: 0 } }; this._console = console; } _visitCallExpression(node: babel.types.Node): void { if (node.type !== 'CallExpression') { return; } this._checkIsBSONSelection(node); this._checkIsUseCall(node); this._checkIsCollectionName(node); this._checkHasDatabaseName(node); } _visitMemberExpression(node: babel.types.Node): void { if (node.type !== 'MemberExpression') { return; } this._checkHasAggregationCall(node); this._checkHasFindCall(node); this._checkIsShellMethod(node); this._checkIsCollectionName(node); this._checkHasCollectionName(node); } _visitExpressionStatement(node: babel.types.Node): void { if (node.type === 'ExpressionStatement') { this._checkIsDbCall(node); } } _visitObjectExpression(node: babel.types.Node): void { if (node.type === 'ObjectExpression') { this._checkIsObjectKey(node); } } _visitArrayExpression(node: babel.types.Node): void { if (node.type === 'ArrayExpression') { this._checkIsBSONSelection(node); } } _visitVariableDeclarator(node: babel.types.Node): void { if (node.type === 'VariableDeclarator') { this._checkIsBSONSelection(node); } } _visitObjectProperty(node: babel.types.Node): void { if (node.type === 'ObjectProperty') { this._checkIsBSONSelection(node); } } _handleTriggerCharacter( textFromEditor: string, position: { line: number; character: number } ): string { const textLines = textFromEditor.split('\n'); // Text before the current character const prefix = position.character === 0 ? '' : textLines[position.line].slice(0, position.character); // Text after the current character const postfix = position.character === 0 ? textLines[position.line] : textLines[position.line].slice(position.character); // Use a placeholder to handle a trigger dot // and track of the current character position // TODO: check the absolute character position textLines[position.line] = `${prefix}${PLACEHOLDER}${postfix}`; return textLines.join('\n'); } parseASTWithPlaceholder( textFromEditor: string, position: { line: number; character: number } ): CompletionState { const selection: VisitorSelection = { start: position, end: { line: 0, character: 0 } }; textFromEditor = this._handleTriggerCharacter( textFromEditor, position ); return this.parseAST({ textFromEditor, selection }); } parseAST({ textFromEditor, selection }: VisitorTextAndSelection): CompletionState { let ast: any; this._state = this._getDefaultNodesValues(); this._selection = selection; try { ast = parser.parse(textFromEditor, { // Parse in strict mode and allow module declarations sourceType: 'module' }); } catch (error) { this._console.error(`parseAST error: ${util.inspect(error)}`); return this._state; } traverse(ast, { enter: (path: babel.NodePath) => { this._visitCallExpression(path.node); this._visitMemberExpression(path.node); this._visitExpressionStatement(path.node); this._visitObjectExpression(path.node); this._visitArrayExpression(path.node); this._visitVariableDeclarator(path.node); this._visitObjectProperty(path.node); } }); return this._state; } _getDefaultNodesValues() { return { databaseName: null, collectionName: null, isObject: false, isArray: false, isObjectKey: false, isShellMethod: false, isUseCallExpression: false, isDbCallExpression: false, isCollectionName: false, isAggregationCursor: false, isFindCursor: false }; } _checkIsUseCallAsSimpleString(node: babel.types.CallExpression): void { if ( node.callee.type === 'Identifier' && node.callee.name === 'use' && node.arguments && node.arguments.length === 1 && node.arguments[0].type === 'StringLiteral' && node.arguments[0].value.includes(PLACEHOLDER) ) { this._state.isUseCallExpression = true; } } _checkIsUseCallAsTemplate(node: babel.types.CallExpression): void { if ( node.arguments && node.arguments.length === 1 && node.arguments[0].type === 'TemplateLiteral' && node.arguments[0].quasis && node.arguments[0].quasis.length === 1 && node.arguments[0].quasis[0].value?.raw && node.arguments[0].quasis[0].value?.raw.includes(PLACEHOLDER) ) { this._state.isUseCallExpression = true; } } _checkIsUseCall(node: babel.types.CallExpression): void { this._checkIsUseCallAsSimpleString(node); this._checkIsUseCallAsTemplate(node); } _checkIsDbCall(node: babel.types.ExpressionStatement): void { if ( node.expression.type === 'MemberExpression' && node.expression.object.type === 'Identifier' && node.expression.object.name === 'db' ) { this._state.isDbCallExpression = true; } } _checkIsObjectKey(node: babel.types.ObjectExpression): void { this._state.isObjectKey = !!node.properties.find( (item: any) => !!(item.key.name && item.key.name.includes(PLACEHOLDER)) ); } _isParentAroundSelection(node: babel.types.Node): boolean { if ( node.loc?.start?.line && ( node.loc.start.line - 1 < this._selection.start?.line || node.loc.start.line - 1 === this._selection.start?.line && node.loc.start.column < this._selection.start?.character ) && node.loc?.end?.line && ( node.loc.end.line - 1 > this._selection.end?.line || node.loc.end.line - 1 === this._selection.end?.line && node.loc.end.column > this._selection.end?.character ) ) { return true; } return false; } _isObjectPropBeforeSelection(node: babel.types.ObjectProperty): boolean { if ( node.key.loc?.end && ( node.key.loc?.end.line - 1 < this._selection.start?.line || ( node.key.loc?.end.line - 1 === this._selection.start?.line && node.key.loc?.end.column < this._selection.start?.character ) ) ) { return true; } return false; } _isVariableIdentifierBeforeSelection(node: babel.types.VariableDeclarator): boolean { if ( node.id.loc?.end && ( node.id.loc?.end.line - 1 < this._selection.start?.line || ( node.id.loc?.end.line - 1 === this._selection.start?.line && node.id.loc?.end.column < this._selection.start?.character ) ) ) { return true; } return false; } _isWithinSelection(node: babel.types.Node): boolean { if ( node.loc?.start?.line && node.loc.start.line - 1 === this._selection.start?.line && node.loc?.start?.column && node.loc.start.column >= this._selection.start?.character && node.loc?.end?.line && node.loc.end.line - 1 === this._selection.end?.line && node.loc?.end?.column && node.loc.end.column <= this._selection.end?.character ) { return true; } return false; } _checkIsArrayWithinSelection(node: babel.types.Node): void { if (node.type === 'ArrayExpression' && this._isWithinSelection(node)) { this._state.isArray = true; } } _checkIsObjectWithinSelection(node: babel.types.Node): void { if (node.type === 'ObjectExpression' && this._isWithinSelection(node)) { this._state.isObject = true; } } _checkIsBSONSelectionInArray(node: babel.types.Node): void { if (node.type === 'ArrayExpression' && node.elements && this._isParentAroundSelection(node)) { node.elements.forEach((item) => { if (item) { this._checkIsObjectWithinSelection(item); this._checkIsArrayWithinSelection(item); } }); } } _checkIsBSONSelectionInFunction(node: babel.types.Node): void { if (node.type === 'CallExpression' && node.arguments && this._isParentAroundSelection(node)) { node.arguments.forEach((item) => { if (item) { this._checkIsObjectWithinSelection(item); this._checkIsArrayWithinSelection(item); } }); } } _checkIsBSONSelectionInVariable(node: babel.types.Node) { if ( node.type === 'VariableDeclarator' && node.init && this._isVariableIdentifierBeforeSelection(node) ) { this._checkIsObjectWithinSelection(node.init); this._checkIsArrayWithinSelection(node.init); } } _checkIsBSONSelectionInObject(node: babel.types.Node) { if ( node.type === 'ObjectProperty' && node.value && this._isObjectPropBeforeSelection(node) ) { this._checkIsObjectWithinSelection(node.value); this._checkIsArrayWithinSelection(node.value); } } _checkIsBSONSelection(node: babel.types.Node): void { this._checkIsBSONSelectionInFunction(node); this._checkIsBSONSelectionInArray(node); this._checkIsBSONSelectionInVariable(node); this._checkIsBSONSelectionInObject(node); } _checkIsCollectionNameAsMemberExpression(node: babel.types.Node): void { if ( node.type === 'MemberExpression' && node.object.type === 'Identifier' && node.object.name === 'db' && node.property.type === 'Identifier' && node.property.name.includes(PLACEHOLDER) ) { this._state.isCollectionName = true; } } _checkIsCollectionNameAsCallExpression(node: babel.types.Node): void { if (node.type === 'CallExpression' && node.callee.type === 'MemberExpression') { this._checkIsCollectionName(node.callee); } } _checkIsCollectionName(node: babel.types.CallExpression | babel.types.MemberExpression): void { this._checkIsCollectionNameAsMemberExpression(node); this._checkIsCollectionNameAsCallExpression(node); } _checkHasAggregationCall(node: babel.types.MemberExpression): void { if ( node.object.type === 'CallExpression' && node.property.type === 'Identifier' && node.property.name.includes(PLACEHOLDER) && node.object.callee.type === 'MemberExpression' && !node.object.callee.computed && node.object.callee.property.type === 'Identifier' && node.object.callee.property.name === 'aggregate' ) { this._state.isAggregationCursor = true; } } _checkHasFindCall(node: babel.types.MemberExpression): void { if ( node.object.type === 'CallExpression' && node.property.type === 'Identifier' && node.property.name.includes(PLACEHOLDER) && node.object.callee.type === 'MemberExpression' && !node.object.callee.computed && node.object.callee.property.type === 'Identifier' && node.object.callee.property.name === 'find' ) { this._state.isFindCursor = true; } } _checkHasDatabaseName(node: babel.types.CallExpression): void { if ( node.callee.type === 'Identifier' && node.callee.name === 'use' && node.arguments && node.arguments.length === 1 && node.arguments[0].type === 'StringLiteral' && node.loc && (this._selection.start.line > node.loc.end.line - 1 || (this._selection.start.line === node.loc.end.line - 1 && this._selection.start.character >= node.loc.end.column)) ) { this._state.databaseName = node.arguments[0].value; } } _checkHasCollectionName(node: babel.types.MemberExpression): void { if ( node.object.type === 'MemberExpression' && node.object.object.type === 'Identifier' && node.object.object.name === 'db' ) { this._state.collectionName = (node.object.property as babel.types.Identifier).name; } } _checkIsShellMethod(node: babel.types.MemberExpression): void { if ( node.object.type === 'MemberExpression' && node.object.object.type === 'Identifier' && node.object.object.name === 'db' && node.property.type === 'Identifier' && node.property.name.includes(PLACEHOLDER) ) { this._state.isShellMethod = true; } } }
the_stack
* #%L * %% * Copyright (C) 2019 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /*eslint no-use-before-define: "off"*/ import util from "util"; import * as MessageSerializer from "../MessageSerializer"; import * as WebSocketAddress from "../../../generated/joynr/system/RoutingTypes/WebSocketAddress"; import * as WebSocketClientAddress from "../../../generated/joynr/system/RoutingTypes/WebSocketClientAddress"; import WebSocketNode = require("../../../global/WebSocketNode"); import LongTimer from "../../util/LongTimer"; import LoggingManager from "../../system/LoggingManager"; import JoynrMessage = require("../JoynrMessage"); const log = LoggingManager.getLogger("joynr.messaging.websocket.SharedWebSocket"); /** * @param address * @param address to which messages are sent on the clustercontroller. * @returns a url */ function webSocketAddressToUrl(address: WebSocketAddress): string { let url = `${address.protocol.name.toLowerCase()}://${address.host}:${address.port}`; if (address.path) { url += address.path; } return url; } interface SharedWebSocketSettings { localAddress: WebSocketClientAddress; remoteAddress: WebSocketAddress; provisioning: { reconnectSleepTimeMs?: number; useUnencryptedTls?: boolean }; keychain: any; } class SharedWebSocket { public static EVENT_CODE_SHUTDOWN = 4000; /** util.promisify creates the callback which will be called by ws once the message was sent. When the callback is called with an error it will reject the promise, otherwise resolve it. The arrow function is there to assure that websocket.send is called with websocket as its this context. */ private webSocketSendAsync: (marshalledMessage: Buffer) => Promise<void>; private sendConfig = { binary: true }; private reconnectTimer: any; private closed: boolean = false; private queuedMessages: any = []; private onmessageCallback: any = null; private remoteUrl: any; private localAddress: WebSocketClientAddress; private useUnencryptedTls: boolean; // default to unencrypted Tls communication private reconnectSleepTimeMs: number; // default value = 1000ms private websocket: WebSocketNode | null = null; private keychain: any; /** * @constructor * @param settings * @param settings.localAddress address used by the websocket server to contact this * client. This address is used in in the init phase on the websocket, and * then registered with the message router on the remote side * @param settings.remoteAddress to which messages are sent on the websocket server. * @param settings.provisioning * @param settings.provisioning.reconnectSleepTimeMs * @param settings.keychain */ public constructor(settings: SharedWebSocketSettings) { settings.provisioning = settings.provisioning || {}; this.reconnectSleepTimeMs = settings.provisioning.reconnectSleepTimeMs || 1000; this.useUnencryptedTls = settings.provisioning.useUnencryptedTls !== false; this.localAddress = settings.localAddress; this.remoteUrl = webSocketAddressToUrl(settings.remoteAddress); this.webSocketSendAsync = util.promisify((marshaledMessage: Buffer, cb: any) => this.websocket!.send(marshaledMessage, this.sendConfig, cb) ); this.keychain = settings.keychain; this.onOpen = this.onOpen.bind(this); this.onClose = this.onClose.bind(this); this.onError = this.onError.bind(this); this.resetConnection = this.resetConnection.bind(this); this.resetConnection(); } public get onmessage(): Function { return this.onmessageCallback; } public set onmessage(newCallback: Function) { this.onmessageCallback = (data: any) => { try { const joynrMessage = MessageSerializer.parse(data.data as Buffer); if (joynrMessage) { newCallback(joynrMessage); } } catch (e) { log.error(`could not unmarshal joynrMessage: ${e}`); } }; this.websocket!.onmessage = this.onmessageCallback; } public get numberOfQueuedMessages(): number { return this.queuedMessages.length; } private sendQueuedMessages(): void { while (this.queuedMessages.length) { const queued = this.queuedMessages.shift(); try { this.websocket!.send(queued, { binary: true }); // Error is thrown if the socket is no longer open } catch (e) { // so add the message back to the front of the queue this.queuedMessages.unshift(queued); throw e; } } } private resetConnection(): void { this.reconnectTimer = undefined; if (this.closed) { return; } this.websocket = new WebSocketNode(this.remoteUrl, this.keychain, this.useUnencryptedTls); this.websocket.onopen = this.onOpen; this.websocket.onclose = this.onClose; this.websocket.onerror = this.onError; if (this.onmessageCallback !== null) { this.websocket.onmessage = this.onmessageCallback; } } private onError(event: any): void { if (this.closed) { return; } log.error(`error in websocket: ${util.inspect(event)}. Resetting connection`); if (this.reconnectTimer !== undefined) { LongTimer.clearTimeout(this.reconnectTimer); } if (this.websocket) { this.websocket.close(SharedWebSocket.EVENT_CODE_SHUTDOWN, "shutdown"); this.websocket = null; } this.reconnectTimer = LongTimer.setTimeout(this.resetConnection, this.reconnectSleepTimeMs); } private onClose(event: { wasClean: boolean; code: number; reason: string; target: any }): void { if (this.closed) { return; } if (event.code !== SharedWebSocket.EVENT_CODE_SHUTDOWN) { log.info( `connection closed unexpectedly. code: ${event.code} reason: ${event.reason}. Trying to reconnect...` ); if (this.reconnectTimer !== undefined) { LongTimer.clearTimeout(this.reconnectTimer); } if (this.websocket) { this.websocket.close(SharedWebSocket.EVENT_CODE_SHUTDOWN, "shutdown"); this.websocket = null; } this.reconnectTimer = LongTimer.setTimeout(this.resetConnection, this.reconnectSleepTimeMs); } else { log.info(`connection closed. reason: ${event.reason}`); if (this.websocket) { this.websocket.close(SharedWebSocket.EVENT_CODE_SHUTDOWN, "shutdown"); this.websocket = null; } } } /* send all queued messages, requeuing to the front in case of a problem*/ private onOpen(): void { try { log.debug("connection opened."); this.websocket!.send(Buffer.from(JSON.stringify(this.localAddress)), this.sendConfig); this.sendQueuedMessages(); } catch (e) { this.resetConnection(); } } public async sendInternal(marshaledMessage: Buffer): Promise<void> { this.websocket!.send(marshaledMessage, this.sendConfig); } public async sendMessage(joynrMessage: JoynrMessage): Promise<void> { let marshaledMessage; try { marshaledMessage = MessageSerializer.stringify(joynrMessage); } catch (e) { log.error(`could not marshal joynrMessage: ${joynrMessage.msgId} ${e}`); return Promise.resolve(); } if (this.websocket !== null && this.websocket!.readyState === WebSocketNode.WSN_OPEN) { try { await this.sendInternal(marshaledMessage); // Error is thrown if the socket is no longer open, so requeue to the front } catch (e) { // add the message back to the front of the queue this.queuedMessages.unshift(marshaledMessage); log.error(`could not send joynrMessage: ${joynrMessage.msgId} requeuing message. Error: ${e}`); } } else { // push new messages onto the back of the queue this.queuedMessages.push(marshaledMessage); } } /** * @param joynrMessage the joynr message to transmit */ public send(joynrMessage: JoynrMessage): Promise<void> { log.debug(`>>> OUTGOING >>> message with ID ${joynrMessage.msgId}`); return this.sendMessage(joynrMessage); } /** * Normally the SharedWebsocket.send api automatically resolves the Promise * when it's called. But this doesn't mean that the data was actually * written out. This method is a helper for a graceful shutdown which delays * the resolving of the SharedWebSocket.send Promise till the data is * written out, to make sure that unsubscribe messages are successfully sent. */ public enableShutdownMode(): void { this.sendInternal = this.webSocketSendAsync; } public close(): void { this.closed = true; if (this.reconnectTimer !== undefined) { LongTimer.clearTimeout(this.reconnectTimer); this.reconnectTimer = undefined; } if (this.websocket !== null) { this.websocket.close(SharedWebSocket.EVENT_CODE_SHUTDOWN, "shutdown"); this.websocket = null; } } } export = SharedWebSocket;
the_stack
import * as assert from 'assert' import * as O from 'fp-ts/Option' import * as RA from 'fp-ts/ReadonlyArray' import * as _ from '../src/Markdown' import { Class, Constant, Documentable, Export, Function, Interface, Method, Module, Property, TypeAlias } from '../src/Module' const content = _.PlainText('a') const testCases = { class: Class( Documentable('A', O.some('a class'), O.some('1.0.0'), false, ['example 1'], O.some('category')), 'declare class A { constructor() }', [ Method(Documentable('hasOwnProperty', O.none, O.some('1.0.0'), false, RA.empty, O.none), [ 'hasOwnProperty(): boolean' ]) ], [ Method(Documentable('staticTest', O.none, O.some('1.0.0'), false, RA.empty, O.none), [ 'static testStatic(): string;' ]) ], [Property(Documentable('foo', O.none, O.some('1.0.0'), false, RA.empty, O.none), 'foo: string')] ), constant: Constant( Documentable('test', O.some('the test'), O.some('1.0.0'), false, RA.empty, O.some('constants')), 'declare const test: string' ), export: Export( Documentable('test', O.none, O.some('1.0.0'), false, RA.empty, O.none), 'export declare const test: typeof test' ), function: Function(Documentable('func', O.some('a function'), O.some('1.0.0'), true, ['example 1'], O.none), [ 'declare const func: (test: string) => string' ]), interface: Interface( Documentable('A', O.none, O.some('1.0.0'), false, RA.empty, O.none), 'export interface A extends Record<string, unknown> {}' ), typeAlias: TypeAlias(Documentable('A', O.none, O.some('1.0.0'), false, RA.empty, O.none), 'export type A = number') } describe('Markdown', () => { describe('constructors', () => { it('Bold', () => { assert.deepStrictEqual(_.Bold(content), { _tag: 'Bold', content }) }) it('Fence', () => { assert.deepStrictEqual(_.Fence('ts', content), { _tag: 'Fence', language: 'ts', content }) }) it('Header', () => { assert.deepStrictEqual(_.Header(1, content), { _tag: 'Header', level: 1, content }) }) it('Newline', () => { assert.deepStrictEqual(_.Newline, { _tag: 'Newline' }) }) it('Paragraph', () => { assert.deepStrictEqual(_.Paragraph(content), { _tag: 'Paragraph', content }) }) it('PlainText', () => { assert.deepStrictEqual(_.PlainText('a'), { _tag: 'PlainText', content: 'a' }) }) it('PlainTexts', () => { assert.deepStrictEqual(_.PlainTexts([content]), { _tag: 'PlainTexts', content: [content] }) }) it('Strikethrough', () => { assert.deepStrictEqual(_.Strikethrough(content), { _tag: 'Strikethrough', content }) }) }) describe('destructors', () => { it('fold', () => { const fold: (markdown: _.Markdown) => string = _.fold({ Bold: (c) => `Bold(${fold(c)})`, Fence: (l, c) => `Fence(${l}, ${fold(c)})`, Header: (l, c) => `Header(${l}, ${fold(c)})`, Newline: () => `Newline`, Paragraph: (c) => `Paragraph(${fold(c)})`, PlainText: (s) => s, PlainTexts: (cs) => `PlainTexts(${RA.getShow({ show: fold }).show(cs)})`, Strikethrough: (c) => `Strikethrough(${fold(c)})` }) assert.strictEqual(fold(_.Bold(content)), 'Bold(a)') assert.strictEqual(fold(_.Fence('ts', content)), 'Fence(ts, a)') assert.strictEqual(fold(_.Header(1, content)), 'Header(1, a)') assert.strictEqual(fold(_.Newline), 'Newline') assert.strictEqual(fold(_.Paragraph(content)), 'Paragraph(a)') assert.strictEqual(fold(_.PlainText('a')), 'a') assert.strictEqual(fold(_.PlainTexts([content])), 'PlainTexts([a])') assert.strictEqual(fold(_.Strikethrough(content)), 'Strikethrough(a)') assert.throws(() => { // @ts-expect-error - valid Markdown instance required fold({}) }) }) }) describe('instances', () => { it('semigroupMarkdown', () => { assert.deepStrictEqual(_.semigroupMarkdown.concat(_.Bold(content), _.Strikethrough(content)), { _tag: 'PlainTexts', content: [ { _tag: 'Bold', content: { _tag: 'PlainText', content: 'a' } }, { _tag: 'Strikethrough', content: { _tag: 'PlainText', content: 'a' } } ] }) }) it('monoidMarkdown', () => { assert.deepStrictEqual(_.monoidMarkdown.empty, { _tag: 'PlainText', content: '' }) assert.deepStrictEqual(_.monoidMarkdown.concat(_.Bold(content), _.Strikethrough(content)), { _tag: 'PlainTexts', content: [ { _tag: 'Bold', content: { _tag: 'PlainText', content: 'a' } }, { _tag: 'Strikethrough', content: { _tag: 'PlainText', content: 'a' } } ] }) }) it('showMarkdown', () => { // Prettier will add a trailing newline to the document so `a` becomes `\n` // and strips extra trailing newlines so `\n\n` becomes `\n` assert.strictEqual(_.showMarkdown.show(_.Bold(content)), '**a**\n') assert.strictEqual(_.showMarkdown.show(_.Header(1, content)), '# a\n') assert.strictEqual(_.showMarkdown.show(_.Header(2, content)), '## a\n') assert.strictEqual(_.showMarkdown.show(_.Header(3, content)), '### a\n') assert.strictEqual(_.showMarkdown.show(_.Fence('ts', content)), '```ts\na\n```\n') assert.strictEqual(_.showMarkdown.show(_.monoidMarkdown.concat(content, _.Newline)), 'a\n') assert.strictEqual(_.showMarkdown.show(_.Paragraph(content)), 'a\n') assert.strictEqual(_.showMarkdown.show(_.PlainText('a')), 'a\n') assert.strictEqual(_.showMarkdown.show(_.PlainTexts([content, _.Newline, content])), 'a\na\n') assert.strictEqual(_.showMarkdown.show(_.Strikethrough(content)), '~~a~~\n') assert.strictEqual( _.showMarkdown.show( _.PlainTexts([ _.PlainText(''), _.Bold(content), _.Header(1, content), _.Fence('ts', content), _.Newline, _.Paragraph(content), _.PlainText('a'), _.PlainTexts([content]), _.Strikethrough(content) ]) ), `**a** # a \`\`\`ts a \`\`\` a aa~~a~~ ` ) }) }) describe('printers', () => { it('printClass', () => { assert.strictEqual( _.printClass(testCases.class), `## A (class) a class **Signature** \`\`\`ts declare class A { constructor() } \`\`\` **Example** \`\`\`ts example 1 \`\`\` Added in v1.0.0 ### staticTest (static method) **Signature** \`\`\`ts static testStatic(): string; \`\`\` Added in v1.0.0 ### hasOwnProperty (function) (method) **Signature** \`\`\`ts hasOwnProperty(): boolean \`\`\` Added in v1.0.0 ### foo (property) **Signature** \`\`\`ts foo: string \`\`\` Added in v1.0.0 ` ) }) it('printConstant', () => { assert.strictEqual( _.printConstant(testCases.constant), `## test the test **Signature** \`\`\`ts declare const test: string \`\`\` Added in v1.0.0 ` ) }) it('printExport', () => { assert.strictEqual( _.printExport(testCases.export), `## test **Signature** \`\`\`ts export declare const test: typeof test \`\`\` Added in v1.0.0 ` ) }) it('printFunction', () => { assert.strictEqual( _.printFunction(testCases.function), `## ~~func~~ a function **Signature** \`\`\`ts declare const func: (test: string) => string \`\`\` **Example** \`\`\`ts example 1 \`\`\` Added in v1.0.0 ` ) }) it('printInterface', () => { assert.strictEqual( _.printInterface(testCases.interface), `## A (interface) **Signature** \`\`\`ts export interface A extends Record<string, unknown> {} \`\`\` Added in v1.0.0 ` ) }) it('printTypeAlias', () => { assert.strictEqual( _.printTypeAlias(testCases.typeAlias), `## A (type alias) **Signature** \`\`\`ts export type A = number \`\`\` Added in v1.0.0 ` ) assert.strictEqual( _.printTypeAlias({ ...testCases.typeAlias, since: O.none }), `## A (type alias) **Signature** \`\`\`ts export type A = number \`\`\` ` ) }) it('printModule', () => { const documentation = Documentable('tests', O.none, O.some('1.0.0'), false, RA.empty, O.none) const m = Module( documentation, ['src', 'tests.ts'], [testCases.class], [testCases.interface], [testCases.function], [testCases.typeAlias], [testCases.constant], [testCases.export] ) assert.strictEqual( _.printModule(m, 1), `--- title: tests.ts nav_order: 1 parent: Modules --- ## tests overview Added in v1.0.0 --- <h2 class="text-delta">Table of contents</h2> - [category](#category) - [A (class)](#a-class) - [staticTest (static method)](#statictest-static-method) - [hasOwnProperty (function) (method)](#hasownproperty-function-method) - [foo (property)](#foo-property) - [constants](#constants) - [test](#test) - [utils](#utils) - [A (interface)](#a-interface) - [A (type alias)](#a-type-alias) - [test](#test-1) - [~~func~~](#func) --- # category ## A (class) a class **Signature** \`\`\`ts declare class A { constructor() } \`\`\` **Example** \`\`\`ts example 1 \`\`\` Added in v1.0.0 ### staticTest (static method) **Signature** \`\`\`ts static testStatic(): string; \`\`\` Added in v1.0.0 ### hasOwnProperty (function) (method) **Signature** \`\`\`ts hasOwnProperty(): boolean \`\`\` Added in v1.0.0 ### foo (property) **Signature** \`\`\`ts foo: string \`\`\` Added in v1.0.0 # constants ## test the test **Signature** \`\`\`ts declare const test: string \`\`\` Added in v1.0.0 # utils ## A (interface) **Signature** \`\`\`ts export interface A extends Record<string, unknown> {} \`\`\` Added in v1.0.0 ## A (type alias) **Signature** \`\`\`ts export type A = number \`\`\` Added in v1.0.0 ## test **Signature** \`\`\`ts export declare const test: typeof test \`\`\` Added in v1.0.0 ## ~~func~~ a function **Signature** \`\`\`ts declare const func: (test: string) => string \`\`\` **Example** \`\`\`ts example 1 \`\`\` Added in v1.0.0 ` ) const empty = Module( documentation, ['src', 'tests.ts'], RA.empty, RA.empty, RA.empty, RA.empty, RA.empty, RA.empty ) assert.strictEqual( _.printModule(empty, 1), `--- title: tests.ts nav_order: 1 parent: Modules --- ## tests overview Added in v1.0.0 --- <h2 class="text-delta">Table of contents</h2> --- ` ) const throws = Module( documentation, ['src', 'tests.ts'], // @ts-expect-error - valid Markdown instance required [{ category: 'invalid markdown' }], RA.empty, RA.empty, RA.empty, RA.empty, RA.empty ) assert.throws(() => { _.printModule(throws, 1) }) }) }) })
the_stack
import { TypedEmitter } from 'tiny-typed-emitter' import { IpcServerOptions } from '@src/sharding/interfaces/ipc/IpcServerOptions' import { IPC as RawIpc, server as RawIpcServer } from 'node-ipc' import { Collection } from '@discordoo/collection' import { IpcCacheOpCodes, IpcEvents, IpcOpCodes, RAW_IPC_EVENT } from '@src/constants' import { IpcPacket } from '@src/sharding' import { DiscordooError, DiscordooSnowflake } from '@src/utils' import { IpcServerSendOptions } from '@src/sharding/interfaces/ipc/IpcServerSendOptions' import { IpcCacheRequestPacket, IpcCacheResponsePacket, IpcDispatchPacket, IpcEmergencyPackets, IpcGuildMembersRequestPacket, IpcGuildMembersResponsePacket, IpcHelloPacket, IpcIdentifyPacket } from '@src/sharding/interfaces/ipc/IpcPackets' import { IpcServerEvents } from '@src/sharding/interfaces/ipc/IpcServerEvents' import { Client } from '@src/core' import { GuildMemberData } from '@src/api' import { RawGuildMembersFetchOptions } from '@src/api/managers/members/RawGuildMembersFetchOptions' import { fromJson, toJson } from '@src/utils/toJson' import { evalWithoutScopeChain } from '@src/utils/evalWithoutScopeChain' import { serializeError } from 'serialize-error' import { IpcEmergencyOpCodes } from '@src/constants/sharding/IpcEmergencyOpCodes' export class LocalIpcServer extends TypedEmitter<IpcServerEvents> { private readonly bucket: Collection = new Collection() private managerSocket: any private readonly MANAGER_IPC: string private readonly eventsHandler: any public ipc: InstanceType<typeof RawIpc> public server?: typeof RawIpcServer public readonly INSTANCE_IPC: string public readonly instance: number public readonly client: Client constructor(client: Client, options: IpcServerOptions) { super() this.client = client this.ipc = new RawIpc() this.INSTANCE_IPC = this.ipc.config.id = options.INSTANCE_IPC this.MANAGER_IPC = options.MANAGER_IPC this.instance = options.instance this.ipc.config = Object.assign(this.ipc.config, options.config ?? {}) this.eventsHandler = (data: IpcPacket, socket: any) => { if (this.listeners('RAW').length) this.emit('RAW', data) return this.onPacket(data, socket) } } async serve(): Promise<IpcHelloPacket> { this.ipc.serve(() => { this.server!.on(RAW_IPC_EVENT, this.eventsHandler) }) this.server = this.ipc.server this.server.start() let promise return new Promise((resolve, reject) => { promise = { res: resolve, rej: reject } promise.timeout = setTimeout(() => { this.bucket.delete('__CONNECTION_PROMISE__') reject(new DiscordooError('LocalIpcServer#serve', 'connection to sharding manager timed out.')) }, 30000) this.bucket.set('__CONNECTION_PROMISE__', promise) }) } destroy() { if (!this.server) return this.server.off(RAW_IPC_EVENT, this.eventsHandler) this.server.stop() } private async onPacket(packet: IpcPacket, socket: any) { // console.log('IPC SERVER', this.instance, 'ON PACKET', process.hrtime.bigint()) if (packet.d?.event_id) { const promise = this.bucket.get(packet.d.event_id) if (promise) { clearTimeout(promise.timeout) this.bucket.delete(packet.d.event_id) packet.op === IpcOpCodes.ERROR ? promise.rej(packet) : promise.res(packet) if (packet.op !== IpcOpCodes.HELLO) return } } switch (packet.op) { case IpcOpCodes.HELLO: return this.hello(packet as IpcHelloPacket, socket) case IpcOpCodes.DISPATCH: return this.dispatch(packet as IpcDispatchPacket) case IpcOpCodes.CACHE_OPERATE: { // console.log('IPC SERVER', this.instance, 'ON CACHE OPERATE', process.hrtime.bigint()) let success = true // console.log('IPC SERVER', this.instance, 'ON RESULT', packet) const result = await this.cacheOperate(packet as IpcCacheRequestPacket) .catch(e => { success = false return e }) // console.log('IPC SERVER', this.instance, 'ON RESPONSE', result) const response: IpcCacheResponsePacket = { op: IpcOpCodes.CACHE_OPERATE, d: { event_id: packet.d.event_id, success, result: toJson(result) } } // console.log('IPC SERVER', this.instance, 'ON CACHE OPERATE REPLY', process.hrtime.bigint()) return this.send(response) } } } private emergency(packet: IpcEmergencyPackets) { switch (packet.d.op) { case IpcEmergencyOpCodes.GLOBAL_RATE_LIMIT_ALMOST_REACHED: case IpcEmergencyOpCodes.GLOBAL_RATE_LIMIT_HIT: case IpcEmergencyOpCodes.INVALID_REQUEST_LIMIT_ALMOST_REACHED: case IpcEmergencyOpCodes.INVALID_REQUEST_LIMIT_HIT: { const now = Date.now() if (now < packet.d.block_until) { console.error( `[DISCORDOO]: SHARDING INSTANCE NUMBER ${this.instance} RECEIVED EMERGENCY COMMAND.`, 'IF YOU SEE THIS MESSAGE,', 'IT MEANS THAT YOUR CLIENT VIOLATES OR ALMOST VIOLATES DISCORD\'S GLOBAL RATE LIMIT OR CLOUDFLARE\'S INVALID REQUEST LIMIT.', `WE STOP ANY API REQUESTS FOR ${packet.d.block_until - now} MILLISECONDS.`, ) } } break } } private async dispatch(packet: IpcDispatchPacket) { // TODO: IpcDispatchPackets switch (packet.t) { case IpcEvents.DESTROYING: this.destroy() process.exit(0) break case IpcEvents.GUILD_MEMBERS_REQUEST: { const members = await this.guildMembersRequest(packet as IpcGuildMembersRequestPacket) const response: IpcGuildMembersResponsePacket = { op: IpcOpCodes.DISPATCH, t: IpcEvents.GUILD_MEMBERS_REQUEST, d: { shard_id: packet.d.shard_id, members, event_id: packet.d.event_id } } await this.send(response) } break case IpcEvents.BROADCAST_EVAL: { const context = packet.d.context ?? {}, script = packet.d.script let isError = false // console.log('context', context) const result = await evalWithoutScopeChain({ ...fromJson(context), client: this.client }, script) .catch(e => { isError = true; return e }) let response try { response = { op: isError ? IpcOpCodes.ERROR : IpcOpCodes.DISPATCH, t: IpcEvents.BROADCAST_EVAL, d: { event_id: packet.d.event_id, result: isError ? serializeError(result) : toJson(result) } } } catch (e) { response = { op: IpcOpCodes.ERROR, t: IpcEvents.BROADCAST_EVAL, d: { event_id: packet.d.event_id, result: serializeError(result) } } } // console.log(response) await this.send(response) } break case IpcEvents.MESSAGE: { this.client.emit('ipcMessage', { message: packet.d.message, from: packet.d.from, }) } break } } private async guildMembersRequest(packet: IpcGuildMembersRequestPacket): Promise<GuildMemberData[]> { const data = packet.d const options: RawGuildMembersFetchOptions = { nonce: data.nonce, limit: data.limit, guild_id: data.guild_id, presences: data.presences, query: data.query, } if (data.user_ids) { options.user_ids = data.user_ids } const members = await this.client.internals.actions.fetchWsGuildMembers(data.shard_id, options) return members.map(m => m.toJson()) as any } private cacheOperate(request: IpcCacheRequestPacket): any { const keyspace = request.d.keyspace, storage = request.d.storage switch (request.d.op) { case IpcCacheOpCodes.GET: return this.client.internals.cache.get(keyspace, storage, request.d.entity_key, request.d.key) case IpcCacheOpCodes.SET: return this.client.internals.cache.set(keyspace, storage, request.d.entity_key, request.d.policy, request.d.key, request.d.value) case IpcCacheOpCodes.DELETE: return this.client.internals.cache.delete(keyspace, storage, request.d.key) case IpcCacheOpCodes.SIZE: return this.client.internals.cache.size(keyspace, storage) case IpcCacheOpCodes.HAS: return this.client.internals.cache.has(keyspace, storage, request.d.key) case IpcCacheOpCodes.CLEAR: return this.client.internals.cache.clear(keyspace, storage) case IpcCacheOpCodes.COUNTS: { const scripts = request.d.scripts const predicates = scripts.map(script => { // eslint-disable-next-line @typescript-eslint/no-unused-vars return (value, key, provider) => { return eval(script + '.bind(provider)(value, key, provider)') } }) return this.client.internals.cache.counts(keyspace, storage, request.d.entity_key, predicates) } case IpcCacheOpCodes.COUNT: case IpcCacheOpCodes.FILTER: case IpcCacheOpCodes.SWEEP: case IpcCacheOpCodes.MAP: case IpcCacheOpCodes.FIND: case IpcCacheOpCodes.FOREACH: { const script = request.d.script let method = 'forEach' switch (request.d.op) { case IpcCacheOpCodes.SWEEP: method = 'sweep' break case IpcCacheOpCodes.MAP: method = 'map' break case IpcCacheOpCodes.FIND: method = 'find' break case IpcCacheOpCodes.FILTER: method = 'filter' break } // eslint-disable-next-line @typescript-eslint/no-unused-vars const predicate = (value, key, provider) => { return eval(script + '.bind(provider)(value, key, provider)') } return this.client.internals.cache[method](keyspace, storage, request.d.entity_key, predicate) } } } private hello(packet: IpcHelloPacket, socket: any) { if (!packet.d || (packet.d && packet.d.id !== this.MANAGER_IPC)) { return this.send({ op: IpcOpCodes.INVALID_SESSION, d: { id: this.INSTANCE_IPC } }, { socket: socket }) } const promise = this.bucket.get('__CONNECTION_PROMISE__') if (promise) { this.bucket.delete('__CONNECTION_PROMISE__') promise.res(packet) clearTimeout(promise.timeout) } this.managerSocket = socket return this.identify(packet) } private identify(packet: IpcHelloPacket) { const data: IpcIdentifyPacket = { op: IpcOpCodes.IDENTIFY, d: { id: this.INSTANCE_IPC, event_id: packet.d.event_id } } return this.send(data) } send(data: IpcPacket, options?: IpcServerSendOptions): Promise<void> send<P extends IpcPacket>(data: IpcPacket, options?: IpcServerSendOptions): Promise<P> send<P extends IpcPacket = IpcPacket>(data: IpcPacket, options: IpcServerSendOptions = {}): Promise<P | void> { if (typeof options !== 'object') throw new DiscordooError('LocalIpcServer#send', 'options must be object type only') if (!options.socket) options.socket = this.managerSocket if (!options.socket) throw new DiscordooError('LocalIpcServer#send', 'cannot find socket to send packet:', data) if (!this.server) throw new DiscordooError('LocalIpcServer#send', 'ipc server not started') // console.log('IPC SERVER', this.instance, 'ON SEND BEFORE PROMISE', data) let promise: any return new Promise((resolve, reject) => { promise = { res: resolve, rej: reject } if (options.waitResponse && data.d?.event_id) { promise.timeout = setTimeout(() => { this.bucket.delete(data.d.event_id) reject(new DiscordooError('LocalIpcServer#send', 'response time is up')) }, options.responseTimeout ?? 60_000) this.bucket.set(data.d.event_id, promise) } // console.log('IPC SERVER', this.instance, 'ON SEND AFTER PROMISE', process.hrtime.bigint()) this.server!.emit(options.socket, RAW_IPC_EVENT, data) if (!options.waitResponse) resolve(void 0) }) } generate() { // console.log('SERVER', this.instance) return DiscordooSnowflake.generate(this.instance, process.pid) } }
the_stack
import * as React from "react"; import { PureComponent, ReactNode, RefObject, CSSProperties } from "react"; import { isMobileDevice, supportPassive } from "./eventHelpers"; import { Placement, TouchPosition } from "./Airr"; import { getProperContent, isTopOrLeftPlacement, isBottomOrRightPlacement, isLeftOrRightPlacement } from "./Utils"; import { makeNewValStickyToLimits, getProgressValueForTLSide, getProgressValueForBRSide, updateDOMItemsStyles, bubbleChildTillParent, getPosition, getLastPosition, getEventPos, updateShownVal, updateCurrentVal, updateLastVals, getClassName, getDOMNodesStyles } from "./SidepanelHelpers"; export interface SidepanelProps { /** * Side to which sidepanel will be attached */ side?: Placement; /** * Bool determining if sidepanel is shown or not. Readonly. Set by inner callback. Do not overwrite. */ isShown?: boolean; /** * Bool determining if sidepanel is enabled. */ enabled?: boolean; /** * Number between 0 and 1 determining how much size of whole screen sidepanel will take */ sizeFactor?: number; /** * Parent scene width dimension. Set by parent scene. Do not overwrite!. */ sceneWidth?: number; /** * Parent scene height dimension. Set by parent scene. Do not overwrite!. */ sceneHeight?: number; /** * Callback invoked when sidepanel changes its visibility during touch events. Set by parent scene. Do not overwrite!. */ visibilityCallback?: (isShown: boolean) => void; /** * Animation time in miliseconds */ animationTime?: number; /** * Boolean saying if parent scene has any open mayer. Set by parent scene. Do not overwrite!. */ sceneHasMayers?: boolean; /** * Opacity between 0 and 1 */ bgLayerOpacity?: number; children?: ReactNode; ref?: RefObject<Sidepanel>; } export type Axis = "X" | "Y"; export interface DOMNodesStyles { dragCtnStyle: CSSProperties; sidepanelStyle: CSSProperties; bgLayerStyle: CSSProperties; } export default class Sidepanel< P extends SidepanelProps = SidepanelProps, S = {} > extends PureComponent<P, S> { static defaultProps: SidepanelProps = { side: "left", isShown: false, enabled: false, sizeFactor: 2 / 3, sceneWidth: null, sceneHeight: null, visibilityCallback: (isShown: boolean): void => {}, animationTime: 200, bgLayerOpacity: 0.7, sceneHasMayers: false }; currentVal: number; transformScheme: string; size: number; sceneSize: number; hiddenVal: number; shownVal: number; axis: Axis; lastSide: Placement; lastSizeFactor: number; refDOMDragCtn = React.createRef<HTMLDivElement>(); refDOMBgLayer = React.createRef<HTMLDivElement>(); refDOM = React.createRef<HTMLDivElement>(); sceneDOM: Node; lastTouch: TouchPosition; startEvent = isMobileDevice ? "touchstart" : "mousedown"; moveEvent = isMobileDevice ? "touchmove" : "mousemove"; endEvent = isMobileDevice ? "touchend" : "mouseup"; animating = false; lastSceneWidth: number; lastSceneHeight: number; enable(): void { this.sceneDOM.removeEventListener(this.startEvent, this.handleTouchStart); this.sceneDOM.addEventListener(this.startEvent, this.handleTouchStart, supportPassive); } disable(): void { this.sceneDOM.removeEventListener(this.startEvent, this.handleTouchStart); } componentDidMount(): void { const refSceneDOM = this.refDOM.current && this.refDOM.current.parentNode; if (refSceneDOM) { this.sceneDOM = refSceneDOM; } if (this.props.enabled) { this.enable(); } } componentWillUnmount(): void { this.disable(); } private handleTouchStart = (e: TouchEvent | MouseEvent): void => { if (this.props.sceneHasMayers) { return; } const pos = getPosition(e, this.axis); let dragCtnOnTouchPath = false; // @ts-ignore const path = e.path || (e.composedPath && e.composedPath()); if (path) { dragCtnOnTouchPath = path.reduce((dragCtnOnTouchPath: boolean, item: HTMLElement) => { if (item === this.refDOMDragCtn.current) { dragCtnOnTouchPath = true; } return dragCtnOnTouchPath; }, false); } else { if ( e.target instanceof Element && (e.target === this.refDOMDragCtn.current || bubbleChildTillParent(e.target, this.refDOMDragCtn.current, [ this.refDOMDragCtn.current.parentElement, document.body ])) ) { dragCtnOnTouchPath = true; } } if ( !dragCtnOnTouchPath && ((isTopOrLeftPlacement(this.props.side) && pos < 20) || (isBottomOrRightPlacement(this.props.side) && pos > this.hiddenVal - 20)) ) { //corner touch, show moves this.refDOM.current.style.display = "block"; this.sceneDOM.addEventListener( this.moveEvent, this.handleShowTouchMove, supportPassive ); this.sceneDOM.addEventListener(this.endEvent, this.handleTouchEnd, false); // this.triggerCustom("showTouchStart"); const showmoveend = (): void => { this.sceneDOM.removeEventListener(this.endEvent, showmoveend); //remove self to act like once listener this.sceneDOM.removeEventListener(this.moveEvent, this.handleShowTouchMove); // this.triggerCustom("showTouchEnd"); }; this.sceneDOM.addEventListener(this.endEvent, showmoveend, false); } else if (this.currentVal === this.shownVal) { //fully visible, hide moves this.sceneDOM.addEventListener( this.moveEvent, this.handleHideTouchMove, supportPassive ); this.sceneDOM.addEventListener(this.endEvent, this.handleTouchEnd, false); // this.triggerCustom("hideTouchStart"); const hidemoveend = (): void => { this.sceneDOM.removeEventListener(this.endEvent, hidemoveend); this.sceneDOM.removeEventListener(this.moveEvent, this.handleHideTouchMove); // this.triggerCustom("hideTouchEnd"); }; this.sceneDOM.addEventListener(this.endEvent, hidemoveend, false); } if (e.target === this.refDOMBgLayer.current) { //tap to hide if ( (isTopOrLeftPlacement(this.props.side) && this.currentVal === 0) || (isBottomOrRightPlacement(this.props.side) && this.currentVal) ) { const hidedragctn = (e: TouchEvent | MouseEvent): void => { this.sceneDOM.removeEventListener(this.endEvent, hidedragctn); if (Math.abs(pos - getPosition(e, this.axis)) <= 2.5) { this.hide(); } }; this.sceneDOM.addEventListener(this.endEvent, hidedragctn, false); } } this.lastTouch = getLastPosition(e); }; private handleShowTouchMove = (e: TouchEvent | MouseEvent): void => { const pos = getPosition(e, this.axis); let newVal: number, progress = 0; if (isTopOrLeftPlacement(this.props.side)) { if (pos <= -1 * this.hiddenVal) { newVal = this.hiddenVal + pos; } else { newVal = this.shownVal; } progress = pos / this.size; } else { if (this.hiddenVal - pos <= this.size) { newVal = pos; } else { newVal = this.shownVal; } progress = (this.sceneSize - pos) / this.size; } updateDOMItemsStyles(newVal, progress, this); this.lastTouch = getLastPosition(e); if (!supportPassive) { e.preventDefault(); } }; private handleHideTouchMove = (e: TouchEvent | MouseEvent): void => { let progress = 0, newVal: number, change: number, moveAxis: string; if (this.lastTouch) { if ( Math.abs(this.lastTouch.clientX - getEventPos(e, "X")) >= Math.abs(this.lastTouch.clientY - getEventPos(e, "Y")) ) { moveAxis = "X"; } else { moveAxis = "Y"; } } if ( moveAxis === this.axis && ((isTopOrLeftPlacement(this.props.side) && getPosition(e, moveAxis) < this.size) || (isBottomOrRightPlacement(this.props.side) && getPosition(e, moveAxis) > this.hiddenVal - this.size)) ) { change = getPosition(e, this.axis) - this.lastTouch["client" + this.axis]; newVal = this.currentVal + change; if (isTopOrLeftPlacement(this.props.side)) { newVal = makeNewValStickyToLimits(newVal, this.hiddenVal, this.shownVal); progress = getProgressValueForTLSide(newVal, this.size); } else { newVal = makeNewValStickyToLimits(newVal, this.shownVal, this.hiddenVal); progress = getProgressValueForBRSide(newVal, this.size, this.sceneSize); } updateDOMItemsStyles(newVal, progress, this); } this.lastTouch = getLastPosition(e); if (!supportPassive) { e.preventDefault(); } }; private handleTouchEnd = (e: TouchEvent | MouseEvent): void => { let val = null; if (!this.animating) { if (this.currentVal !== this.shownVal && this.currentVal !== this.hiddenVal) { if (isTopOrLeftPlacement(this.props.side)) { if (this.currentVal >= this.hiddenVal / 2) { val = this.shownVal; } else { val = this.hiddenVal; } } else { if (this.currentVal < this.hiddenVal - this.size / 2) { val = this.shownVal; } else { val = this.hiddenVal; } } } else if (this.currentVal === this.hiddenVal) { this.refDOM.current.style.display = "none"; } if (val !== null) { this.translateTo(val); } else { this.checkAndRevokeVisibilityCallback(); } } this.sceneDOM.removeEventListener(this.endEvent, this.handleTouchEnd); }; private checkAndRevokeVisibilityCallback(): void { if (this.props.isShown !== this.isShown()) { this.props.visibilityCallback(this.isShown()); } } hide = (): Promise<boolean> => { return this.translateTo(this.hiddenVal); }; show = (): Promise<boolean> => { this.enable(); return this.translateTo(this.shownVal); }; isShown = (): boolean => { return this.refDOM.current.offsetParent !== null; }; private translateTo = (finishVal: number): Promise<boolean> => { return new Promise( (resolve): void => { this.animating = true; this.refDOMBgLayer.current.style.webkitTransition = `opacity ${ this.props.animationTime }ms ease-in`; this.refDOMBgLayer.current.style.transition = `opacity ${ this.props.animationTime }ms ease-in`; this.refDOMBgLayer.current.offsetHeight; if (finishVal === this.shownVal) { if (!this.isShown()) { this.refDOM.current.style.display = "block"; } this.refDOMBgLayer.current.style.opacity = String(this.props.bgLayerOpacity); } else if (finishVal === this.hiddenVal) { this.refDOMBgLayer.current.style.opacity = "0"; } this.refDOM.current.offsetHeight; this.refDOM.current.style.webkitTransition = "initial"; this.refDOM.current.style.transition = "initial"; this.refDOMDragCtn.current.style.webkitTransition = `-webkit-transform ${ this.props.animationTime }ms ease-out`; this.refDOMDragCtn.current.style.webkitTransition = `transform ${ this.props.animationTime }ms ease-out`; this.refDOMDragCtn.current.style.transition = `transform ${ this.props.animationTime }ms ease-out`; this.refDOMDragCtn.current.offsetHeight; this.refDOMDragCtn.current.style.webkitTransform = this.transformScheme.replace( "%v", String(finishVal) ); this.refDOMDragCtn.current.style.transform = this.transformScheme.replace( "%v", String(finishVal) ); this.refDOMDragCtn.current.offsetHeight; this.refDOMDragCtn.current.style.webkitTransition = "initial"; this.refDOMDragCtn.current.style.transition = "initial"; setTimeout((): void => { this.refDOMBgLayer.current.style.webkitTransition = "initial"; this.refDOMBgLayer.current.style.transition = "initial"; this.currentVal = finishVal; if (finishVal === this.hiddenVal) { this.refDOM.current.style.display = "none"; } this.animating = false; this.checkAndRevokeVisibilityCallback(); resolve(this.isShown()); }, this.props.animationTime + 5); } ); }; private updateSideProps = (): void => { if (isLeftOrRightPlacement(this.props.side)) { this.size = this.props.sceneWidth * this.props.sizeFactor; this.sceneSize = this.props.sceneWidth; this.hiddenVal = this.props.side === "left" ? -1 * this.size : this.props.sceneWidth; this.transformScheme = "translate3d(%vpx,0,0)"; this.axis = "X"; } else { //top,bottom this.size = this.props.sceneHeight * this.props.sizeFactor; this.sceneSize = this.props.sceneHeight; this.hiddenVal = this.props.side === "top" ? -1 * this.size : this.props.sceneHeight; this.transformScheme = "translate3d(0,%vpx,0)"; this.axis = "Y"; } updateShownVal(this); updateCurrentVal(this); updateLastVals(this); }; componentDidUpdate(prevProps: SidepanelProps): void { if (prevProps.enabled !== this.props.enabled) { this[this.props.enabled ? "enable" : "disable"](); } } /** * Primary render method. * Should be overwritten in descendant class. * @returns {ReactNode} */ content(): ReactNode { return undefined; } private conditionalyUpdateSideProps(): void { if ( this.props.side !== this.lastSide || this.props.sizeFactor !== this.lastSizeFactor || this.props.sceneWidth !== this.lastSceneWidth || this.props.sceneHeight !== this.lastSceneHeight ) { this.updateSideProps(); } } render(): ReactNode { const className = getClassName(this.props.side, this.props.enabled); this.conditionalyUpdateSideProps(); const { dragCtnStyle, sidepanelStyle, bgLayerStyle } = getDOMNodesStyles(this); const content: ReactNode = getProperContent(this.content(), this.props.children); return ( <div className={className} ref={this.refDOM} style={sidepanelStyle}> <div ref={this.refDOMBgLayer} style={bgLayerStyle} /> <div ref={this.refDOMDragCtn} style={dragCtnStyle}> {content} </div> </div> ); } }
the_stack
import * as ts from 'typescript'; import { resolveCachedResult, hasSupportedExtension, mapDefined } from './utils'; import * as path from 'path'; import { ProcessorLoader } from './services/processor-loader'; import { FileKind, CachedFileSystem } from './services/cached-file-system'; import { Configuration, AbstractProcessor } from '@fimbul/ymir'; import { bind } from 'bind-decorator'; import { ConfigurationManager } from './services/configuration-manager'; import debug = require('debug'); const log = debug('wotan:projectHost'); const additionalExtensions = ['.json']; // @internal export interface ProcessedFileInfo { originalName: string; originalContent: string; // TODO this should move into processor because this property is never updated, but the processor is processor: AbstractProcessor; } // @internal export class ProjectHost implements ts.CompilerHost { private reverseMap = new Map<string, string>(); private files: string[] = []; private directoryEntries = new Map<string, ts.FileSystemEntries>(); private processedFiles = new Map<string, ProcessedFileInfo>(); private sourceFileCache = new Map<string, ts.SourceFile | undefined>(); private fileContent = new Map<string, string>(); private tsconfigCache = new Map<string, ts.ExtendedConfigCacheEntry>(); private commandLineCache = new Map<string, ts.ParsedCommandLine>(); private parseConfigHost: ts.ParseConfigHost = { useCaseSensitiveFileNames: this.useCaseSensitiveFileNames(), readDirectory: (rootDir, extensions, excludes, includes, depth) => this.readDirectory(rootDir, extensions, excludes, includes, depth), fileExists: (f) => this.fileExists(f), readFile: (f) => this.readFile(f), }; public getCanonicalFileName = ts.sys.useCaseSensitiveFileNames ? (f: string) => f : (f: string) => f.toLowerCase(); private moduleResolutionCache = ts.createModuleResolutionCache(this.cwd, this.getCanonicalFileName); private compilerOptions: ts.CompilerOptions = {}; constructor( public cwd: string, public config: Configuration | undefined, private fs: CachedFileSystem, private configManager: ConfigurationManager, private processorLoader: ProcessorLoader, ) {} public getProcessedFileInfo(fileName: string) { return this.processedFiles.get(fileName); } public readDirectory( rootDir: string, extensions: ReadonlyArray<string>, excludes: ReadonlyArray<string> | undefined, includes: ReadonlyArray<string>, depth?: number, ) { return ts.matchFiles( rootDir, extensions, excludes, includes, this.useCaseSensitiveFileNames(), this.cwd, depth, (dir) => resolveCachedResult(this.directoryEntries, dir, this.processDirectory), (f) => this.safeRealpath(f), ); } /** * Try to find and load the configuration for a file. * If it fails, just continue as if there was no config. * This may happen during project setup if there is an invalid config file anywhere in a scanned folder. */ private tryFindConfig(file: string) { try { return this.configManager.find(file); } catch (e) { log("Error while loading configuration for '%s': %s", file, e.message); return; } } @bind private processDirectory(dir: string): ts.FileSystemEntries { const files: string[] = []; const directories: string[] = []; const result: ts.FileSystemEntries = {files, directories}; let entries; try { entries = this.fs.readDirectory(dir); } catch { return result; } for (const entry of entries) { switch (entry.kind) { case FileKind.File: { const fileName = `${dir}/${entry.name}`; if (!hasSupportedExtension(fileName, additionalExtensions)) { const c = this.config || this.tryFindConfig(fileName); const processor = c && this.configManager.getProcessor(c, fileName); if (processor) { const ctor = this.processorLoader.loadProcessor(processor); const suffix = ctor.getSuffixForFile({ fileName, getSettings: () => this.configManager.getSettings(c!, fileName), readFile: () => this.fs.readFile(fileName), }); const newName = fileName + suffix; if (hasSupportedExtension(newName, additionalExtensions)) { files.push(entry.name + suffix); this.reverseMap.set(newName, fileName); break; } } } files.push(entry.name); this.files.push(fileName); break; } case FileKind.Directory: directories.push(entry.name); } } return result; } public fileExists(file: string): boolean { switch (this.fs.getKind(file)) { case FileKind.Directory: case FileKind.Other: return false; case FileKind.File: return true; default: return hasSupportedExtension(file, additionalExtensions) && this.getFileSystemFile(file) !== undefined; } } public directoryExists(dir: string) { return this.fs.isDirectory(dir); } public getFileSystemFile(file: string): string | undefined { if (this.files.includes(file)) return file; const reverse = this.reverseMap.get(file); if (reverse !== undefined) return reverse; const dirname = path.posix.dirname(file); if (this.directoryEntries.has(dirname)) return; if (this.fs.isFile(file)) return file; this.directoryEntries.set(dirname, this.processDirectory(dirname)); return this.getFileSystemFile(file); } public readFile(file: string) { return resolveCachedResult(this.fileContent, file, (f) => this.fs.readFile(f)); } private readProcessedFile(file: string): string | undefined { const realFile = this.getFileSystemFile(file); if (realFile === undefined) return; let content = this.fs.readFile(realFile); const config = this.config || this.tryFindConfig(realFile); if (config === undefined) return content; const processorPath = this.configManager.getProcessor(config, realFile); if (processorPath === undefined) return content; const ctor = this.processorLoader.loadProcessor(processorPath); const processor = new ctor({ source: content, sourceFileName: realFile, targetFileName: file, settings: this.configManager.getSettings(config, realFile), }); this.processedFiles.set(file, { processor, originalContent: content, originalName: realFile, }); content = processor.preprocess(); return content; } public writeFile() {} public useCaseSensitiveFileNames() { return ts.sys.useCaseSensitiveFileNames; } public getDefaultLibFileName = ts.getDefaultLibFilePath; public getNewLine() { return this.compilerOptions.newLine === ts.NewLineKind.CarriageReturnLineFeed ? '\r\n' : '\n'; } public realpath = this.fs.realpath === undefined ? undefined : (fileName: string) => this.fs.realpath!(fileName); private safeRealpath(f: string) { if (this.realpath !== undefined) { try { return this.realpath(f); } catch {} } return f; } public getCurrentDirectory() { return this.cwd; } public getDirectories(dir: string) { const cached = this.directoryEntries.get(dir); if (cached !== undefined) return cached.directories.slice(); return mapDefined( this.fs.readDirectory(dir), (entry) => entry.kind === FileKind.Directory ? entry.name : undefined, ); } public getSourceFile(fileName: string, languageVersion: ts.ScriptTarget.JSON): ts.JsonSourceFile | undefined; public getSourceFile(fileName: string, languageVersion: ts.ScriptTarget): ts.SourceFile | undefined; public getSourceFile(fileName: string, languageVersion: ts.ScriptTarget) { return resolveCachedResult( this.sourceFileCache, fileName, () => { const content = this.readProcessedFile(fileName); return content !== undefined ? ts.createSourceFile(fileName, content, languageVersion, true) : undefined; }, ); } public createProgram( rootNames: ReadonlyArray<string>, options: ts.CompilerOptions, oldProgram: ts.Program | undefined, projectReferences: ReadonlyArray<ts.ProjectReference> | undefined, ) { options = {...options, suppressOutputPathCheck: true}; this.compilerOptions = options; this.moduleResolutionCache = ts.createModuleResolutionCache(this.cwd, this.getCanonicalFileName, options); return ts.createProgram({rootNames, options, oldProgram, projectReferences, host: this}); } public updateSourceFile(sourceFile: ts.SourceFile) { this.sourceFileCache.set(sourceFile.fileName, sourceFile); } public updateProgram(program: ts.Program) { return ts.createProgram({ rootNames: program.getRootFileNames(), options: program.getCompilerOptions(), oldProgram: program, projectReferences: program.getProjectReferences(), host: this, }); } public onReleaseOldSourceFile(sourceFile: ts.SourceFile) { // this is only called for paths that are no longer referenced // it's safe to remove the cache entry completely because it won't be called with updated SourceFiles this.uncacheFile(sourceFile.fileName); } public uncacheFile(fileName: string) { this.sourceFileCache.delete(fileName); this.processedFiles.delete(fileName); } public getParsedCommandLine(fileName: string) { return resolveCachedResult(this.commandLineCache, fileName, this.parseConfigFile); } @bind private parseConfigFile(fileName: string) { // Note to future self: it's highly unlikely that a tsconfig of a project reference is used as base config for another tsconfig. // Therefore it doesn't make such sense to read or write the tsconfigCache here. const sourceFile = this.getSourceFile(fileName, ts.ScriptTarget.JSON); if (sourceFile === undefined) return; return ts.parseJsonSourceFileConfigFileContent( sourceFile, this.parseConfigHost, path.dirname(fileName), undefined, fileName, undefined, undefined, this.tsconfigCache, ); } public resolveModuleNames( names: string[], file: string, _: unknown | undefined, reference: ts.ResolvedProjectReference | undefined, options: ts.CompilerOptions, ) { const seen = new Map<string, ts.ResolvedModuleFull | undefined>(); const resolve = (name: string) => ts.resolveModuleName(name, file, options, this, this.moduleResolutionCache, reference).resolvedModule; return names.map((name) => resolveCachedResult(seen, name, resolve)); } } // @internal declare module 'typescript' { function matchFiles( path: string, extensions: ReadonlyArray<string>, excludes: ReadonlyArray<string> | undefined, includes: ReadonlyArray<string>, useCaseSensitiveFileNames: boolean, currentDirectory: string, depth: number | undefined, getFileSystemEntries: (path: string) => ts.FileSystemEntries, realpath: (path: string) => string, ): string[]; interface FileSystemEntries { readonly files: ReadonlyArray<string>; readonly directories: ReadonlyArray<string>; } }
the_stack
import * as fs from "fs"; import * as path from "path"; import { Dictionary, DictionaryNoCase, find, SAXStackParser, scopedLogger, XMLNode } from "@hpcc-js/util"; import { ClientTools, locateClientTools } from "./eclcc"; const logger = scopedLogger("clienttools/eclmeta"); export interface IFilePath { scope: ECLScope; } const _inspect = false; function inspect(obj: any, _id: string, known: any) { if (_inspect) { for (const key in obj) { const id = `${_id}.${key}`; if (key !== "$" && known[key] === undefined && known[key.toLowerCase() + "s"] === undefined) { logger.debug(id); } } if (obj.$) { inspect(obj.$, _id + ".$", known); } } } export class Attr { __attrs: { [id: string]: string }; name: string; constructor(xmlAttr: XMLNode) { this.__attrs = xmlAttr.$; this.name = xmlAttr.$.name; } } export class Field { __attrs: { [id: string]: string }; definition: Definition; get scope(): ECLScope { return this.definition; } name: string; type: string; constructor(definition: Definition, xmlField: XMLNode) { this.__attrs = xmlField.$; this.definition = definition; this.name = xmlField.$.name; this.type = xmlField.$.type; } } export interface ECLDefinitionLocation { filePath: string; line: number; charPos: number; definition?: Definition; source?: Source; } export interface ISuggestion { name: string; type: string; } export class ECLScope implements IFilePath { get scope(): ECLScope { return this; } name: string; type: string; sourcePath: string; line: number; start: number; body: number; end: number; definitions: Definition[]; constructor(name: string, type: string, sourcePath: string, xmlDefinitions: XMLNode[], line: number = 1, start: number = 0, body: number = 0, end: number = Number.MAX_VALUE) { this.name = name; this.type = type; this.sourcePath = path.normalize(sourcePath); this.line = +line - 1; this.start = +start; this.body = +body; this.end = +end; this.definitions = this.parseDefinitions(xmlDefinitions); } private parseDefinitions(definitions: XMLNode[] = []): Definition[] { return definitions.map(definition => { const retVal = new Definition(this.sourcePath, definition); inspect(definition, "definition", retVal); return retVal; }); } contains(charOffset: number) { return charOffset >= this.start && charOffset <= this.end; } scopeStackAt(charOffset: number): ECLScope[] { let retVal: ECLScope[] = []; if (this.contains(charOffset)) { retVal.push(this); this.definitions.forEach(def => { retVal = def.scopeStackAt(charOffset).concat(retVal); }); } return retVal; } private _resolve(defs: Definition[] = [], qualifiedID: string): Definition | undefined { const qualifiedIDParts = qualifiedID.split("."); const base = qualifiedIDParts.shift(); const retVal = find(defs, def => { if (typeof def.name === "string" && typeof base === "string" && def.name.toLowerCase() === base.toLowerCase()) { return true; } return false; }); if (retVal && retVal.definitions.length && qualifiedIDParts.length) { return this._resolve(retVal.definitions, qualifiedIDParts.join(".")); } return retVal; } resolve(qualifiedID: string): Definition | undefined { return this._resolve(this.definitions, qualifiedID); } suggestions(): ISuggestion[] { return this.definitions.map(def => { return { name: def.name, type: this.type }; }); } } export class Definition extends ECLScope { __attrs: { [id: string]: string }; exported: boolean; shared: boolean; fullname: string; inherittype: string; attrs: Attr[]; fields: Field[]; constructor(sourcePath: string, xmlDefinition: XMLNode) { super(xmlDefinition.$.name, xmlDefinition.$.type, sourcePath, xmlDefinition.children("Definition"), xmlDefinition.$.line, xmlDefinition.$.start, xmlDefinition.$.body, xmlDefinition.$.end); this.__attrs = xmlDefinition.$; this.exported = !!xmlDefinition.$.exported; this.shared = !!xmlDefinition.$.shared; this.fullname = xmlDefinition.$.fullname; this.inherittype = xmlDefinition.$.inherittype; this.attrs = this.parseAttrs(xmlDefinition.children("Attr")); this.fields = this.parseFields(xmlDefinition.children("Field")); } private parseAttrs(attrs: XMLNode[] = []): Attr[] { return attrs.map(attr => { const retVal = new Attr(attr); inspect(attr, "attr", retVal); return retVal; }); } private parseFields(fields: XMLNode[] = []): Field[] { return fields.map(field => { const retVal = new Field(this, field); inspect(field, "field", retVal); return retVal; }); } suggestions() { return super.suggestions().concat(this.fields.map(field => { return { name: field.name, type: field.type }; })); } } export class Import { __attrs: { [id: string]: string }; name: string; ref: string; start: number; end: number; line: number; constructor(xmlImport: XMLNode) { this.__attrs = xmlImport.$; this.name = xmlImport.$.name; this.ref = xmlImport.$.ref; this.start = xmlImport.$.start; this.end = xmlImport.$.end; this.line = xmlImport.$.line; } } export class Source extends ECLScope { imports: Import[]; __attrs: { [id: string]: string }; constructor(xmlSource: XMLNode) { super(xmlSource.$.name, "source", xmlSource.$.sourcePath, xmlSource.children("Definition")); this.__attrs = xmlSource.$; const nameParts = xmlSource.$.name.split("."); nameParts.pop(); const fakeNode = new XMLNode(""); fakeNode.appendAttribute("name", "$"); fakeNode.appendAttribute("ref", nameParts.join(".")); this.imports = [ new Import(fakeNode), ...this.parseImports(xmlSource.children("Import")) ]; } private parseImports(imports: XMLNode[] = []): Import[] { return imports.map(imp => { const retVal = new Import(imp); inspect(imp, "import", retVal); return retVal; }); } resolve(qualifiedID: string, charOffset?: number): Definition | undefined { let retVal; // Check Inner Scopes --- if (!retVal && charOffset !== undefined) { const scopes = this.scopeStackAt(charOffset); scopes.some(scope => { retVal = scope.resolve(qualifiedID); return !!retVal; }); } // Check Definitions --- if (!retVal) { retVal = super.resolve(qualifiedID); } return retVal; } } const isHiddenDirectory = source => path.basename(source).indexOf(".") === 0; const isDirectory = source => fs.lstatSync(source).isDirectory() && !isHiddenDirectory(source); const isEcl = source => [".ecl", ".ecllib"].indexOf(path.extname(source).toLowerCase()) >= 0; const modAttrs = source => fs.readdirSync(source).map(name => path.join(source, name)).filter(path => isDirectory(path) || isEcl(path)); export class File extends ECLScope { constructor(name: string, sourcePath: string) { super(name, "file", sourcePath, []); } suggestions(): ISuggestion[] { return []; } } export class Folder extends ECLScope { constructor(name: string, sourcePath: string) { super(name, "folder", sourcePath, []); } suggestions(): ISuggestion[] { return modAttrs(this.sourcePath).map(folder => { return { name: path.basename(folder, ".ecl"), type: "folder" }; }); } } export class Workspace { _workspacePath: string; _eclccPath?: string; _clientTools: ClientTools; _sourceByID: DictionaryNoCase<Source> = new DictionaryNoCase<Source>(); _sourceByPath: Dictionary<Source> = new Dictionary<Source>(); private _test: DictionaryNoCase<IFilePath> = new DictionaryNoCase<IFilePath>(); constructor(workspacePath: string, eclccPath?: string) { this._workspacePath = workspacePath; this._eclccPath = eclccPath; } refresh() { this.primeWorkspace(); this.primeClientTools(); } primeClientTools(): Promise<this> { return locateClientTools(this._eclccPath, "", this._workspacePath).then(clientTools => { this._clientTools = clientTools; return clientTools.paths(); }).then(paths => { for (const knownFolder of ["ECLCC_ECLLIBRARY_PATH", "ECLCC_PLUGIN_PATH"]) { if (paths[knownFolder] && fs.existsSync(paths[knownFolder])) { this.walkChildFolders(paths[knownFolder], paths[knownFolder]); } } return this; }); } primeWorkspace() { if (fs.existsSync(this._workspacePath)) { this.visitFolder(this._workspacePath, this._workspacePath); } } walkChildFolders(folderPath: string, refPath: string, force: boolean = false) { for (const child of modAttrs(folderPath)) { if (!isDirectory(child)) { this.visitFile(child, refPath, force); } else { this.visitFolder(child, refPath, force); } } } visitFile(filePath: string, refPath: string, force: boolean = false) { const filePathInfo = path.parse(filePath); const pathNoExt = path.join(filePathInfo.dir, filePathInfo.name); const name = path.relative(refPath, pathNoExt).split(path.sep).join("."); if (force || !this._test.has(name)) { this._test.set(name, new File("", filePath)); } } visitFolder(folderPath: string, refPath: string, force: boolean = false) { const name = path.relative(refPath, folderPath).split(path.sep).join("."); if (force || !this._test.has(name)) { this._test.set(name, new Folder(name, folderPath)); this.walkChildFolders(folderPath, refPath, force); } } buildStack(parentStack: string[], name: string, removeDupID: boolean): { stack: string[], qid: string } { const nameStack = name.split("."); if (removeDupID && parentStack[parentStack.length - 1] === nameStack[0]) { nameStack.shift(); } const stack = [...parentStack, ...nameStack]; const qid: string = stack.join("."); return { stack, qid }; } walkECLScope(parentStack: string[], scope: ECLScope) { const info = this.buildStack(parentStack, scope.name, true); this._test.set(info.qid, scope); for (const def of scope.definitions) { this.walkDefinition(info.stack, def); } } walkField(parentStack: string[], field: Field) { const info = this.buildStack(parentStack, field.name, false); this._test.set(info.qid, field); } walkDefinition(parentStack: string[], definition: Definition) { const info = this.buildStack(parentStack, definition.name, true); this.walkECLScope(parentStack, definition); for (const field of definition.fields) { this.walkField(info.stack, field); } } walkSource(source: Source) { // const dirName = path.dirname(source.sourcePath); // const relName = path.relative(this._workspacePath, dirName).split(path.sep).join("."); // const folder = new Folder(relName, dirName); // this._test.set(folder.name, folder); this.walkECLScope([], source); } parseSources(sources: XMLNode[] = []): void { for (const _source of sources) { if (_source.$.name) { // Plugins have no name... const source = new Source(_source); inspect(_source, "source", source); this._sourceByID.set(source.name, source); this._sourceByPath.set(source.sourcePath, source); // If external source like "std.system.ThorLib" then need to backup to "std" and add its folder if (source.name) { const sourceNameParts = source.name.split("."); let depth = sourceNameParts.length; if (depth > 1) { let sourcePath = source.sourcePath; while (depth > 1) { sourcePath = path.dirname(sourcePath); --depth; } this.visitFolder(sourcePath, path.dirname(sourcePath)); } } this.walkSource(source); } } } parseMetaXML(metaXML: string): string[] { const metaParser = new MetaParser(); metaParser.parse(metaXML); this.parseSources(metaParser.sources); return metaParser.sources.map(source => path.normalize(source.$.sourcePath)); } resolveQualifiedID(filePath: string, qualifiedID: string, charOffset?: number): ECLScope | undefined { let retVal: ECLScope | undefined; if (!retVal && this._test.has(qualifiedID)) { retVal = this._test.get(qualifiedID).scope; } if (!retVal && this._sourceByPath.has(filePath)) { const eclSource = this._sourceByPath.get(filePath); // Resolve Imports --- const qualifiedIDParts = qualifiedID.split("."); for (const imp of eclSource.imports) { if (imp.name.toLowerCase() === qualifiedIDParts[0].toLowerCase()) { if (imp.ref) { qualifiedIDParts[0] = imp.ref; } else { qualifiedIDParts.shift(); } break; } } let realQID = qualifiedIDParts.join("."); if (!retVal && this._test.has(realQID)) { retVal = this._test.get(realQID).scope; } if (!retVal) { realQID = [...eclSource.name.split("."), ...qualifiedIDParts].join("."); if (this._test.has(realQID)) { retVal = this._test.get(realQID).scope; } } } return retVal; } resolvePartialID(filePath: string, partialID: string, charOffset: number): ECLScope | undefined { partialID = partialID.toLowerCase(); const partialIDParts = partialID.split("."); partialIDParts.pop(); const partialIDQualifier = partialIDParts.length === 1 ? partialIDParts[0] : partialIDParts.join("."); return this.resolveQualifiedID(filePath, partialIDQualifier, charOffset); } } const workspaceCache = new Dictionary<Workspace>(); export function attachWorkspace(_workspacePath: string, eclccPath?: string): Workspace { const workspacePath = path.normalize(_workspacePath); if (!workspaceCache.has(workspacePath)) { const workspace = new Workspace(workspacePath, eclccPath); workspaceCache.set(workspacePath, workspace); workspace.refresh(); } return workspaceCache.get(workspacePath); } function isQualifiedIDChar(lineText: string, charPos: number, reverse: boolean) { if (charPos < 0) return false; const testChar = lineText.charAt(charPos); return (reverse ? /[a-zA-Z\d_\.$]/ : /[a-zA-Z\d_]/).test(testChar); } export function qualifiedIDBoundary(lineText: string, charPos: number, reverse: boolean) { while (isQualifiedIDChar(lineText, charPos, reverse)) { charPos += reverse ? -1 : 1; } return charPos + (reverse ? 1 : -1); } class MetaParser extends SAXStackParser { sources: XMLNode[] = []; endXMLNode(e: XMLNode) { switch (e.name) { case "Source": this.sources.push(e); break; default: break; } super.endXMLNode(e); } }
the_stack
import { expect } from 'chai'; import { merge as _merge } from 'lodash'; import * as listValidation from '../../../../../src/lib/device/validation/list'; describe('./lib/device/validation/list.ts', () => { it('should validate thumbnail - positive', () => { // GIVEN const input = 'http://someimage.com/foo.jpg'; // WHEN expect(() => { listValidation.validateThumbnail(input); }).to.not.throw; }); it('should validate thumbnail - empty', () => { // WHEN expect(() => { // @ts-ignore listValidation.validateThumbnail(); }).to.throw(/ERROR_LIST_THUMBNAIL_EMPTY/); }); it('should validate thumbnail - not URL', () => { // GIVEN const input = 'somethingThatIsNotAURL'; // WHEN expect(() => { listValidation.validateThumbnail(input); }).to.throw(/ERROR_LIST_THUMBNAIL_NO_URL/); }); it('should validate item params - positive', () => { // GIVEN const input = { someparam: 'foo', }; // WHEN const validatedParams = listValidation.validateItemParams(input); // THEN expect(validatedParams).to.deep.equal(input); }); it('should validate item params - negative', () => { // WHEN expect(() => { // @ts-ignore listValidation.validateItemParams(); }).to.throw(/ERROR_LIST_ITEM_PARAMS_EMPTY/); }); it('should validate button params - positive', () => { // WHEN expect(() => { listValidation.validateButton({ title: 'foo', }); }).to.not.throw(/ERROR_LIST_BUTTON_TITLE_EMPTY/); }); it('should validate button params - negative', () => { // WHEN expect(() => { // @ts-ignore listValidation.validateButton(); }).to.throw(/ERROR_LIST_BUTTON_TITLE_OR_ICON_EMPTY/); }); it('should validate button row params - no object', () => { // WHEN expect(() => { // @ts-ignore listValidation.validateRow(true, 'buttons'); }).to.throw(/ERROR_LIST_BUTTONS_NO_ARRAY/); }); it('should validate button row params - too many buttons', () => { // WHEN expect(() => { listValidation.validateRow( [{ title: '1' }, { title: '2' }, { title: '3' }, { title: '4' }], 'buttons' ); }).to.throw(/ERROR_LIST_BUTTONS_TOO_MANY_BUTTONS/); }); it('should validate button row params - object', () => { // WHEN expect(() => { // @ts-ignore listValidation.validateRow({}, 'buttons'); }).to.not.throw; }); it('should validate button row params - array', () => { // WHEN expect(() => { listValidation.validateRow([], 'buttons'); }).to.not.throw; }); it('should validate inexistent limit param', () => { // WHEN expect(() => { listValidation.validateLimit(); }).to.not.throw(/ERROR_LIST_LIMIT_MAXIMUM_EXCEEDED/); }); it('should return max limit if inexistent param', () => { // GIVEN const expectedLimit = 64; // WHEN const result = listValidation.validateLimit(); expect(result).to.equal(expectedLimit); }); it('should validate with small limit param', () => { // GIVEN const limit = 5; // WHEN expect(() => { listValidation.validateLimit(limit); }).to.not.throw(/ERROR_LIST_LIMIT_MAXIMUM_EXCEEDED/); }); it('should return custom limit if validation is ok', () => { // GIVEN const limit = 5; // WHEN const result = listValidation.validateLimit(limit); expect(result).to.equal(limit); }); it('should fail validation with too big limit param', () => { // GIVEN const tooLargeLimit = 500000; // WHEN expect(() => { listValidation.validateLimit(tooLargeLimit); }).to.throw(/ERROR_LIST_LIMIT_MAXIMUM_EXCEEDED/); }); it('should fail button icon validation with not allowed icon', () => { // GIVEN const iconName = 'foo'; // WHEN expect(() => { // @ts-ignore listValidation.validateButtonIcon(iconName); }).to.throw(/INVALID_ICON_NAME: foo/); }); it('should not fail button icon validation without icon name', () => { // WHEN expect(() => { // @ts-ignore listValidation.validateButtonIcon(); }).to.not.throw; }); it('should return allowed icon after validation', () => { // GIVEN const iconName = 'repeat'; // WHEN const icon = listValidation.validateButtonIcon(iconName); // THEN expect(icon).to.equal('repeat'); }); it('should ignore invalid icon name', () => { const iconName = 5; // @ts-ignore const icon = listValidation.validateButtonIcon(iconName); expect(icon).to.equal(undefined); }); it('should return action after action validation', () => { // GIVEN const actionName = 'close'; // WHEN const action = listValidation.validateUIAction(actionName); expect(action).to.equal(actionName); }); it('should return action after action validation - UPPERCASE', () => { // GIVEN const actionName = 'close'; // WHEN const action = listValidation.validateUIAction(actionName); expect(action).to.equal(actionName); }); it('should return undefined action after action validation - undefined', () => { // GIVEN const actionName = undefined; // WHEN const action = listValidation.validateUIAction(actionName); expect(action).to.equal(undefined); }); describe('validate full list:', () => { let validList; beforeEach(() => { validList = { browseIdentifier: 'root', _meta: { previous: { browseIdentifier: 'previous-uri', offset: 0, limit: 32 }, current: { browseIdentifier: 'current-uri', offset: 32, limit: 32 }, next: { browseIdentifier: 'next-uri', offset: 64, limit: 32 }, }, items: [ { title: 'item-title', label: 'item-label', thumbnailUri: 'http://example.com/item-image-uri.png', browseIdentifier: 'current-uri', actionIdentifier: 'current-action-uri', uiAction: 'close', metaData: 'current-meta-data', }, ], }; }); const tests = [ { name: 'valid browse result' }, { name: 'missing "_meta" property', shouldFail: true, data: { _meta: null }, error: /property "_meta" not present/, }, { name: 'missing "_meta.current" property', shouldFail: true, data: { _meta: { current: null } }, error: /property "current" not present/, }, { name: '"_meta.current.browseIdentifier" must be string', shouldFail: true, data: { _meta: { current: { browseIdentifier: 3 } } }, error: /no string/, }, { name: '"_meta.current.browseIdentifier" can be empty', shouldFail: false, data: { _meta: { current: { browseIdentifier: null } } }, }, { name: '"_meta.current.offset" must be integer', shouldFail: true, data: { _meta: { current: { offset: null } } }, error: /no integer/, }, { name: '"_meta.current.limit" must be integer', shouldFail: true, data: { _meta: { current: { limit: null } } }, error: /no integer/, }, { name: '"_meta.previous.browseIdentifier" must be string', shouldFail: true, data: { _meta: { previous: { browseIdentifier: 3 } } }, error: /no string/, }, { name: '"_meta.previous.browseIdentifier" can be empty', shouldFail: false, data: { _meta: { current: { browseIdentifier: undefined } } }, }, { name: '"_meta.previous.offset" must be integer', shouldFail: true, data: { _meta: { previous: { offset: null } } }, error: /no integer/, }, { name: '"_meta.previous.limit" must be integer', shouldFail: true, data: { _meta: { previous: { limit: null } } }, error: /no integer/, }, { name: '"_meta.next.browseIdentifier" must be string', shouldFail: true, data: { _meta: { next: { browseIdentifier: 3 } } }, error: /no string/, }, { name: '"_meta.next.browseIdentifier" can be empty', shouldFail: false, data: { _meta: { current: { browseIdentifier: undefined } } }, }, { name: '"_meta.next.offset" must be integer', shouldFail: true, data: { _meta: { next: { offset: null } } }, error: /no integer/, }, { name: '"_meta.next.limit" must be integer', shouldFail: true, data: { _meta: { next: { limit: null } } }, error: /no integer/, }, { name: '"items" must be array', shouldFail: true, data: { items: null }, error: /no array/, }, { name: '"items[x].title" must be string', shouldFail: true, data: { items: [{ title: Math.PI }], error: /no string/ }, }, { name: '"items[x].thumbnailUri" must be string', shouldFail: true, data: { items: [{ thumbnailUri: Math.PI }], error: /no string/ }, }, { name: '"items[x].browseIdentifier" must be string', shouldFail: true, data: { items: [{ browseIdentifier: Math.PI }], error: /no string/ }, }, { name: '"items[x].actionIdentifier" must be string', shouldFail: true, data: { items: [{ actionIdentifier: Math.PI }], error: /no string/ }, }, { name: '"items[x].uiAction" must be string', shouldFail: true, data: { items: [{ uiAction: 2 }], error: /no string/ }, }, ]; tests.forEach((test) => { it(test.name, () => { // GIVEN const testData = _merge(validList, test.data); // WHEN const fn = () => listValidation.validateList(testData); // THEN if (!test.shouldFail) { expect(fn).to.not.throw(); } else { expect(fn).to.throw(test.error); } }); }); }); });
the_stack
import BN from 'bn.js'; import Web3 from 'web3'; import { TransactionReceipt, TransactionConfig } from 'web3-core'; import { ContractOptions } from 'web3-eth-contract'; import { AbiItem } from 'web3-utils'; import ERC20ABI from '../contracts/abi/erc-20'; import ForeignAMBABI from '../contracts/abi/foreign-amb'; import ForeignBridgeABI from '../contracts/abi/foreign-bridge-mediator'; import { getAddress } from '../contracts/addresses'; import { TransactionOptions, waitUntilTransactionMined, isTransactionHash, waitUntilBlock, } from './utils/general-utils'; // The TokenBridge is created between 2 networks, referred to as a Native (or Home) Network and a Foreign network. // The Native or Home network has fast and inexpensive operations. All bridge operations to collect validator confirmations are performed on this side of the bridge. // The Foreign network can be any chain, but generally refers to the Ethereum mainnet. export interface ITokenBridgeForeignSide { unlockTokens(txnHash: string): Promise<TransactionReceipt>; unlockTokens( tokenAddress: string, amount: string, txnOptions?: TransactionOptions, contractOptions?: ContractOptions ): Promise<TransactionReceipt>; relayTokens(txnHash: string): Promise<TransactionReceipt>; relayTokens( tokenAddress: string, recipientAddress: string, amount: string, txnOptions?: TransactionOptions, contractOptions?: ContractOptions ): Promise<TransactionReceipt>; claimBridgedTokens(txnHash: string): Promise<TransactionReceipt>; claimBridgedTokens( messageId: string, encodedData: string, signatures: string[], txnOptions?: TransactionOptions, contractOptions?: ContractOptions ): Promise<TransactionReceipt>; } // Note that as we support new CPXD tokens, we'll need to measure the gas limit // the new tokens require for transfer which will effect this value. Ultimately // this value reflects the gas limit that the token bridge is configured with // for performing withdrawals. const CLAIM_BRIDGED_TOKENS_GAS_LIMIT = 350000; // Note: To accommodate the fix for infura block mismatch errors (made in // CS-2391), we are waiting one extra block for all layer 1 transactions. export default class TokenBridgeForeignSide implements ITokenBridgeForeignSide { constructor(private layer1Web3: Web3) {} async unlockTokens(txnHash: string): Promise<TransactionReceipt>; async unlockTokens( tokenAddress: string, amount: string, txnOptions?: TransactionOptions, contractOptions?: ContractOptions ): Promise<TransactionReceipt>; async unlockTokens( tokenAddressOrTxnHash: string, amount?: string, txnOptions?: TransactionOptions, contractOptions?: ContractOptions ): Promise<TransactionReceipt> { if (isTransactionHash(tokenAddressOrTxnHash)) { let txnHash = tokenAddressOrTxnHash; return await waitUntilOneBlockAfterTxnMined(this.layer1Web3, txnHash); } let tokenAddress = tokenAddressOrTxnHash; if (!amount) { throw new Error('amount is required'); } let from = contractOptions?.from ?? (await this.layer1Web3.eth.getAccounts())[0]; let token = new this.layer1Web3.eth.Contract(ERC20ABI as AbiItem[], tokenAddress); let foreignBridge = await getAddress('foreignBridge', this.layer1Web3); let nextNonce = await this.getNextNonce(from); return await new Promise((resolve, reject) => { let { nonce, onNonce, onTxnHash } = txnOptions ?? {}; let data = token.methods.approve(foreignBridge, amount).encodeABI(); let tx: TransactionConfig = { ...contractOptions, from, to: tokenAddress, data, }; if (nonce != null) { tx.nonce = parseInt(nonce.toString()); // the web3 API requires this be a number, it should be ok to downcast this } else if (typeof onNonce === 'function') { onNonce(nextNonce); } this.layer1Web3.eth .sendTransaction(tx) .on('transactionHash', async (txnHash: string) => { if (typeof onTxnHash === 'function') { onTxnHash(txnHash); } try { resolve(await waitUntilOneBlockAfterTxnMined(this.layer1Web3, txnHash)); } catch (e) { reject(e); } }) .on('error', (error: Error) => { reject(error); }); }); } async relayTokens(txnHash: string): Promise<TransactionReceipt>; async relayTokens( tokenAddress: string, recipientAddress: string, amount: string, txnOptions?: TransactionOptions, contractOptions?: ContractOptions ): Promise<TransactionReceipt>; async relayTokens( tokenAddressOrTxnHash: string, recipientAddress?: string, amount?: string, txnOptions?: TransactionOptions, contractOptions?: ContractOptions ): Promise<TransactionReceipt> { if (isTransactionHash(tokenAddressOrTxnHash)) { let txnHash = tokenAddressOrTxnHash; return await waitUntilOneBlockAfterTxnMined(this.layer1Web3, txnHash); } let tokenAddress = tokenAddressOrTxnHash; if (!recipientAddress) { throw new Error('recipientAddress is required'); } if (!amount) { throw new Error('amount is required'); } let from = contractOptions?.from ?? (await this.layer1Web3.eth.getAccounts())[0]; let foreignBridgeAddress = await getAddress('foreignBridge', this.layer1Web3); let foreignBridge = new this.layer1Web3.eth.Contract(ForeignBridgeABI as any, foreignBridgeAddress); let nextNonce = await this.getNextNonce(from); return await new Promise((resolve, reject) => { let { nonce, onNonce, onTxnHash } = txnOptions ?? {}; let data = foreignBridge.methods.relayTokens(tokenAddress, recipientAddress, amount).encodeABI(); let tx: TransactionConfig = { ...contractOptions, from, to: foreignBridgeAddress, data, }; if (nonce != null) { tx.nonce = parseInt(nonce.toString()); // the web3 API requires this be a number, it should be ok to downcast this } else if (typeof onNonce === 'function') { onNonce(nextNonce); } this.layer1Web3.eth .sendTransaction(tx) .on('transactionHash', async (txnHash: string) => { if (typeof onTxnHash === 'function') { onTxnHash(txnHash); } try { resolve(await waitUntilOneBlockAfterTxnMined(this.layer1Web3, txnHash)); } catch (e) { reject(e); } }) .on('error', (error: Error) => { reject(error); }); }); } async getEstimatedGasForWithdrawalClaim(_tokenAddress: string): Promise<BN> { // per Hassan, eventually this will be a token address specific amount, hence the for-now unused arg let withdrawalGasLimit = new BN(CLAIM_BRIDGED_TOKENS_GAS_LIMIT); let gasPrice = await this.layer1Web3.eth.getGasPrice(); let estimatedGasInWei = withdrawalGasLimit.mul(new BN(gasPrice)); let rounder = new BN(1e12); return estimatedGasInWei.divRound(rounder).mul(rounder); } async claimBridgedTokens(txnHash: string): Promise<TransactionReceipt>; async claimBridgedTokens( messageId: string, encodedData: string, signatures: string[], txnOptions?: TransactionOptions, contractOptions?: ContractOptions ): Promise<TransactionReceipt>; async claimBridgedTokens( messageIdOrTxnHash: string, encodedData?: string, signatures?: string[], txnOptions?: TransactionOptions, contractOptions?: ContractOptions ): Promise<TransactionReceipt> { if (!encodedData) { let txnHash = messageIdOrTxnHash; return await waitUntilOneBlockAfterTxnMined(this.layer1Web3, txnHash); } let messageId = messageIdOrTxnHash; if (!signatures) { throw new Error('signatures is required'); } let from = contractOptions?.from ?? (await this.layer1Web3.eth.getAccounts())[0]; let foreignAmbAddress = await getAddress('foreignAMB', this.layer1Web3); let foreignAmb = new this.layer1Web3.eth.Contract(ForeignAMBABI as AbiItem[], foreignAmbAddress); let events = await foreignAmb.getPastEvents('RelayedMessage', { fromBlock: 0, toBlock: 'latest', filter: { messageId }, }); if (events.length === 1) { let txnHash = events[0].transactionHash; return await waitUntilOneBlockAfterTxnMined(this.layer1Web3, txnHash); } const packedSignatures = prepSignaturesForExecution(signatures); let nextNonce = await this.getNextNonce(from); let { nonce, onNonce, onTxnHash } = txnOptions ?? {}; return await new Promise((resolve, reject) => { let data = foreignAmb.methods.executeSignatures(encodedData, packedSignatures).encodeABI(); let tx: TransactionConfig = { ...contractOptions, from, to: foreignAmbAddress, data, gas: CLAIM_BRIDGED_TOKENS_GAS_LIMIT, }; if (nonce != null) { tx.nonce = parseInt(nonce.toString()); // the web3 API requires this be a number, it should be ok to downcast this } else if (typeof onNonce === 'function') { onNonce(nextNonce); } this.layer1Web3.eth .sendTransaction(tx) .on('transactionHash', async (txnHash: string) => { if (typeof onTxnHash === 'function') { onTxnHash(txnHash); } try { resolve(await waitUntilOneBlockAfterTxnMined(this.layer1Web3, txnHash)); } catch (e) { reject(e); } }) .on('error', (error: Error) => { reject(error); }); }); } private async getNextNonce(from?: string): Promise<BN> { from = from ?? (await this.layer1Web3.eth.getAccounts())[0]; // To accommodate the fix for infura block mismatch errors (made in CS-2391), we // are waiting one extra block for all layer 1 transactions. let previousBlockNumber = (await this.layer1Web3.eth.getBlockNumber()) - 1; let nonce = await this.layer1Web3.eth.getTransactionCount(from, previousBlockNumber); return new BN(String(nonce)); // EOA nonces are zero based } } function prepSignaturesForExecution(signatures: string[]) { return packSignatures(signatures.map(signatureToVRS)); } function signatureToVRS(rawSignature: string) { const signature = strip0x(rawSignature); const v = signature.substr(64 * 2); const r = signature.substr(0, 32 * 2); const s = signature.substr(32 * 2, 32 * 2); return { v, r, s }; } function packSignatures(array: { v: string; r: string; s: string }[]) { const length = strip0x(Web3.utils.toHex(array.length)); const msgLength = length.length === 1 ? `0${length}` : length; const [v, r, s] = array.reduce(([vs, rs, ss], { v, r, s }) => [vs + v, rs + r, ss + s], ['', '', '']); return `0x${msgLength}${v}${r}${s}`; } function strip0x(s: string) { return Web3.utils.isHexStrict(s) ? s.substr(2) : s; } async function waitUntilOneBlockAfterTxnMined(web3: Web3, txnHash: string) { let receipt = await waitUntilTransactionMined(web3, txnHash); await waitUntilBlock(web3, receipt.blockNumber + 1); return receipt; }
the_stack
import App from "../app"; import {gql, withFilter} from "apollo-server-express"; import {pubsub} from "../helpers/subscriptionManager"; import GraphQLClient from "../helpers/graphqlClient"; import request from "request"; import fetch from "node-fetch"; import uuid from "uuid"; import {capitalCase} from "change-case"; import heap from "../helpers/heap"; import tokenGenerator from "../helpers/tokenGenerator"; const issuesUrl = "https://12usj3vwf1.execute-api.us-east-1.amazonaws.com/prod/issueTracker"; let spaceEdventuresData = null; let spaceEdventuresTimeout = 0; const version = require("../../package.json").version; // We define a schema that encompasses all of the types // necessary for the functionality in this file. const schema = gql` type Thorium { thoriumId: String doTrack: Boolean askedToTrack: Boolean addedTaskTemplates: Boolean spaceEdventuresToken: String spaceEdventuresCenter: SpaceEdventuresCenter port: Int httpOnly: Boolean } type SpaceEdventuresCenter { id: ID name: String token: String simulators: [NamedObject] missions: [NamedObject] badges: [NamedObject] flightTypes: [FlightType] } type NamedObject { id: ID name: String description: String } type FlightType { id: ID name: String flightHours: Float classHours: Float } extend type Query { thorium: Thorium } extend type Mutation { setTrackingPreference(pref: Boolean!): String importTaskTemplates: String setSpaceEdventuresToken(token: String!): SpaceEdventuresCenter """ Macro: Space EdVentures: Assign Space EdVentures Badge Requires: - Space EdVentures """ assignSpaceEdventuresBadge( """ Dynamic: Station """ station: String badgeId: ID! ): String """ Macro: Space EdVentures: Assign Space EdVentures Mission Requires: - Space EdVentures """ assignSpaceEdventuresMission(station: String, badgeId: ID!): String """ Macro: Space EdVentures: Change Flight Type Requires: - Space EdVentures """ assignSpaceEdventuresFlightType(flightId: ID!, flightType: ID!): String """ Macro: Space EdVentures: Transmit to Space EdVentures Requires: - Space EdVentures """ assignSpaceEdventuresFlightRecord(flightId: ID!): String getSpaceEdventuresLogin(token: String!): String removeSpaceEdventuresClient(flightId: ID!, clientId: ID!): String """ Macro: Generic: Do a generic thing. Use for triggers. """ generic(simulatorId: ID!, key: String!): String clockSync(clientId: ID!): String addIssue( title: String! body: String! person: String! priority: String! type: String! ): String addIssueUpload(data: String!, filename: String!, ext: String!): String } extend type Subscription { thoriumUpdate: Thorium clockSync(clientId: ID!): String } `; const badgeAssign = ( rootValue, {badgeId, station}, {simulator, clientId, flight}, ) => { const clients = App.clients.filter(c => { if (clientId) return c.id === clientId; if (station) return ( c.simulatorId === simulator.id && (c.station === station || c.id === station) ); return c.flightId === flight.id; }); const badges = clients.map(c => ({clientId: c.id, badgeId})); flight.addBadges(badges); }; const resolver = { Thorium: { spaceEdventuresCenter: () => { // Simple timeout based caching if ( !spaceEdventuresData || spaceEdventuresTimeout + 1000 * 60 * 5 < Number(new Date()) ) { spaceEdventuresTimeout = Date.now(); return GraphQLClient.query({ query: `query { center { id name simulators { id name } badges(type:badge) { id name description } missions: badges(type:mission) { id name description } flightTypes { id name flightHours classHours } } }`, }).then(({data: {center}}) => { if (!center) return spaceEdventuresData; spaceEdventuresData = {...center, token: App.spaceEdventuresToken}; return spaceEdventuresData; }); } if (spaceEdventuresData) { return spaceEdventuresData; } }, }, Query: { thorium(root) { return App; }, }, Mutation: { setTrackingPreference: (rootValue, {pref}) => { App.doTrack = pref; App.askedToTrack = true; heap.stubbed = !pref; }, importTaskTemplates: () => { if (App.addedTaskTemplates) return; App.addedTaskTemplates = true; const templates = require("../helpers/baseTaskTemplates.js")(); App.taskTemplates = App.taskTemplates.concat(templates); pubsub.publish("taskTemplatesUpdate", App.taskTemplates); }, setSpaceEdventuresToken: async (rootValue, {token}) => { // Check the token first const { data: {center}, } = await GraphQLClient.query({ query: `query { center { id name } }`, headers: { authorization: `Bearer ${token}`, }, }); if (center) { App.spaceEdventuresToken = token; return center; } }, assignSpaceEdventuresFlightRecord: (rootValue, {simulatorId, flightId}) => { const flight = App.flights.find( f => f.id === flightId || f.simulators.includes(simulatorId), ); flight.submitSpaceEdventure(); }, assignSpaceEdventuresFlightType: ( rootValue, {flightId, simulatorId, flightType}, ) => { const flight = App.flights.find( f => f.id === flightId || f.simulators.includes(simulatorId), ); if (!flight) return; flight.setFlightType(flightType); pubsub.publish("flightsUpdate", App.flights); }, removeSpaceEdventuresClient: (rootValue, {flightId, clientId}) => { const flight = App.flights.find(f => f.id === flightId); if (!flight) return; flight.removeClient(clientId); pubsub.publish("flightsUpdate", App.flights); }, assignSpaceEdventuresBadge: badgeAssign, assignSpaceEdventuresMission: badgeAssign, getSpaceEdventuresLogin: async (rootValue, {token}, context) => { async function doLogin() { let res: any = {}; try { res = await GraphQLClient.query({ query: `query GetUser($token:String!) { user:userByToken(token:$token) { id profile { name displayName rank { name } } } } `, variables: {token}, }); } catch (err) { return err.message.replace("GraphQL error:", "Error:"); } const { data: {user}, } = res; const clientId = context.clientId; if (user) { const client = App.clients.find(c => c.id === clientId); client.login( user.profile.displayName || user.profile.name || user.profile.rank.name, true, ); const flight = App.flights.find(f => f.id === client.flightId); if (flight) { flight.addSpaceEdventuresUser(client.id, user.id); flight.loginClient({ id: client.id, token: tokenGenerator(), simulatorId: client.simulatorId, name: client.station, }); } } pubsub.publish("clientChanged", App.clients); } return doLogin(); }, addIssue(rootValue, {title, body, person, priority, type}) { // Create our body var postBody = ` ### Requested By: ${person} ### Priority: ${capitalCase(priority)} ### Version: ${version} ` .replace(/^\s+/gm, "") .replace(/\s+$/m, "\n\n") + body; var postOptions = { title, body: postBody, labels: [ version.includes("beta") && "beta", `priority/${priority}`, type, ].filter(Boolean), }; request.post( {url: issuesUrl, body: postOptions, json: true}, function () {}, ); }, async addIssueUpload(rootValue, {data, filename, ext}) { const uploadPath = `uploads/${filename}-${uuid.v4()}.${ext}`; const url = "https://api.github.com/repos/thorium-sim/issue-uploads/contents/" + uploadPath; const payload = { message: "issue tracker snapshot", branch: "master", content: data, }; return fetch(url, { method: "PUT", headers: { "Content-Type": "application/json", Authorization: "token " + process.env.GH_ISSUE_TOKEN, }, body: JSON.stringify(payload), }) .then(res => res.json()) .then(res => { if (!res.content || !res.content.html_url) return null; return res.content.html_url + "?raw=true"; }) .catch(err => console.error(err)); }, clockSync(rootValue, {clientId}) { pubsub.publish("clockSync", {clientId}); }, }, Subscription: { thoriumUpdate: { resolve(rootValue) { return rootValue; }, subscribe: () => pubsub.asyncIterator("thoriumUpdate"), }, clockSync: { resolve() { return new Date(); }, subscribe: withFilter( () => pubsub.asyncIterator("clockSync"), (rootValue, {clientId}) => rootValue.clientId === clientId, ), }, }, }; export default {schema, resolver};
the_stack
import anyTest, { afterEach as anyAfterEach, beforeEach as anyBeforeEach, } from 'ava'; import type { AfterInterface, BeforeInterface, TestInterface, } from 'ava'; import delay from 'delay'; import { BackendTerminatedError, createPool, InvalidInputError, sql, StatementCancelledError, StatementTimeoutError, TupleMovedToAnotherPartitionError, UnexpectedStateError, } from '../../src'; import type { PgClientType, } from '../../src'; type TestContextType = { dsn: string, testDatabaseName: string, }; export const createTestRunner = (pgClient: PgClientType, name: string) => { let testId = 0; const test = anyTest as TestInterface<TestContextType>; const beforeEach = anyBeforeEach as BeforeInterface<TestContextType>; const afterEach = anyAfterEach as AfterInterface<TestContextType>; beforeEach(async (t) => { ++testId; const TEST_DATABASE_NAME = [ 'slonik_test', name, String(testId), ].join('_'); t.context = { dsn: 'postgresql://postgres@localhost/' + TEST_DATABASE_NAME, testDatabaseName: TEST_DATABASE_NAME, }; const pool0 = createPool('postgresql://postgres@localhost', { maximumPoolSize: 1, pgClient, }); await pool0.connect(async (connection) => { await connection.query(sql` SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid != pg_backend_pid() AND datname = 'slonik_test' `); await connection.query(sql`DROP DATABASE IF EXISTS ${sql.identifier([TEST_DATABASE_NAME])}`); await connection.query(sql`CREATE DATABASE ${sql.identifier([TEST_DATABASE_NAME])}`); }); await pool0.end(); const pool1 = createPool(t.context.dsn, { maximumPoolSize: 1, pgClient, }); await pool1.connect(async (connection) => { await connection.query(sql` CREATE TABLE person ( id SERIAL PRIMARY KEY, name text, birth_date date, payload bytea ) `); }); await pool1.end(); }); afterEach(async (t) => { const pool = createPool('postgresql://postgres@localhost', { maximumPoolSize: 1, pgClient, }); await pool.connect(async (connection) => { await connection.query(sql` SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid != pg_backend_pid() AND datname = 'slonik_test' `); await connection.query(sql`DROP DATABASE IF EXISTS ${sql.identifier([t.context.testDatabaseName])}`); }); await pool.end(); }); return { test, }; }; export const createIntegrationTests = ( test: TestInterface<TestContextType>, pgClient: PgClientType, ) => { test('returns expected query result object (array bytea)', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); const result = await pool.query(sql` SELECT ${sql.array([Buffer.from('foo')], 'bytea')} "names" `); t.deepEqual(result, { command: 'SELECT', fields: [ { dataTypeId: 1001, name: 'names', }, ], notices: [], rowCount: 1, rows: [ { names: [ Buffer.from('foo'), ], }, ], }); await pool.end(); }); test('returns expected query result object (INSERT)', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); const result = await pool.query(sql` INSERT INTO person ( name ) VALUES ( 'foo' ) RETURNING name `); t.deepEqual(result, { command: 'INSERT', fields: [ { dataTypeId: 25, name: 'name', }, ], notices: [], rowCount: 1, rows: [ { name: 'foo', }, ], }); await pool.end(); }); test('returns expected query result object (UPDATE)', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); await pool.query(sql` INSERT INTO person ( name ) VALUES ( 'foo' ) RETURNING name `); const result = await pool.query(sql` UPDATE person SET name = 'bar' WHERE name = 'foo' RETURNING name `); t.deepEqual(result, { command: 'UPDATE', fields: [ { dataTypeId: 25, name: 'name', }, ], notices: [], rowCount: 1, rows: [ { name: 'bar', }, ], }); await pool.end(); }); test('returns expected query result object (DELETE)', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); await pool.query(sql` INSERT INTO person ( name ) VALUES ( 'foo' ) RETURNING name `); const result = await pool.query(sql` DELETE FROM person WHERE name = 'foo' RETURNING name `); t.deepEqual(result, { command: 'DELETE', fields: [ { dataTypeId: 25, name: 'name', }, ], notices: [], rowCount: 1, rows: [ { name: 'foo', }, ], }); await pool.end(); }); test('terminated backend produces BackendTerminatedError error', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); const error = await t.throwsAsync(pool.connect(async (connection) => { const connectionPid = await connection.oneFirst(sql` SELECT pg_backend_pid() `); setTimeout(() => { void pool.query(sql`SELECT pg_terminate_backend(${connectionPid})`); }, 100); await connection.query(sql`SELECT pg_sleep(2)`); })); t.true(error instanceof BackendTerminatedError); await pool.end(); }); test('cancelled statement produces StatementCancelledError error', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); const error = await t.throwsAsync(pool.connect(async (connection) => { const connectionPid = await connection.oneFirst(sql` SELECT pg_backend_pid() `); setTimeout(() => { void pool.query(sql`SELECT pg_cancel_backend(${connectionPid})`); }, 100); await connection.query(sql`SELECT pg_sleep(2)`); })); t.true(error instanceof StatementCancelledError); await pool.end(); }); test('statement cancelled because of statement_timeout produces StatementTimeoutError error', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); const error = await t.throwsAsync(pool.connect(async (connection) => { await connection.query(sql` SET statement_timeout=100 `); await connection.query(sql`SELECT pg_sleep(1)`); })); t.true(error instanceof StatementTimeoutError); await pool.end(); }); test.skip('transaction terminated while in an idle state is rejected (at the next transaction query)', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); await pool.connect(async (connection) => { await connection.query(sql`SET idle_in_transaction_session_timeout=500`); const error = await t.throwsAsync(connection.transaction(async (transaction) => { await delay(1000); await transaction.query(sql`SELECT 1`); })); t.true(error instanceof BackendTerminatedError); }); await pool.end(); }); test.skip('connection of transaction terminated while in an idle state is rejected (at the end of the transaction)', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); await pool.connect(async (connection) => { await connection.query(sql`SET idle_in_transaction_session_timeout=500`); const error = await t.throwsAsync(connection.transaction(async () => { await delay(1000); })); t.true(error instanceof BackendTerminatedError); }); await pool.end(); }); test('throws an error if an attempt is made to make multiple transactions at once using the same connection', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); const error = await t.throwsAsync(pool.connect(async (connection) => { await Promise.all([ connection.transaction(async () => { await delay(1000); }), connection.transaction(async () => { await delay(1000); }), connection.transaction(async () => { await delay(1000); }), ]); })); t.true(error instanceof UnexpectedStateError); t.is(error.message, 'Cannot use the same connection to start a new transaction before completing the last transaction.'); await pool.end(); }); test('writes and reads buffers', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); const payload = 'foobarbazqux'; await pool.query(sql` INSERT INTO person ( payload ) VALUES ( ${sql.binary(Buffer.from(payload))} ) `); const result = await pool.oneFirst<Buffer>(sql` SELECT payload FROM person `); t.is(result.toString(), payload); await pool.end(); }); // REMOVED test('explicit connection configuration is persisted', async (t) => { const pool = createPool(t.context.dsn, { maximumPoolSize: 1, pgClient, }); await pool.connect(async (connection) => { const originalStatementTimeout = await connection.oneFirst(sql`SHOW statement_timeout`); t.not(originalStatementTimeout, '50ms'); await connection.query(sql`SET statement_timeout=50`); const statementTimeout = await connection.oneFirst(sql`SHOW statement_timeout`); t.is(statementTimeout, '50ms'); }); await pool.end(); }); test('serves waiting requests', async (t) => { t.timeout(10000); const pool = createPool(t.context.dsn, { maximumPoolSize: 1, pgClient, }); let index = 100; const queue = []; while (index--) { queue.push(pool.query(sql`SELECT 1`)); } await Promise.all(queue); await pool.end(); // We are simply testing to ensure that requests in a queue // are assigned a connection after a preceding request is complete. t.true(true); }); test('pool.end() resolves when there are no more connections (no connections at start)', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); t.deepEqual(pool.getPoolState(), { activeConnectionCount: 0, ended: false, idleConnectionCount: 0, waitingClientCount: 0, }); await pool.end(); t.deepEqual(pool.getPoolState(), { activeConnectionCount: 0, ended: true, idleConnectionCount: 0, waitingClientCount: 0, }); }); test('pool.end() resolves when there are no more connections (implicit connection)', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); t.deepEqual(pool.getPoolState(), { activeConnectionCount: 0, ended: false, idleConnectionCount: 0, waitingClientCount: 0, }); await pool.query(sql` SELECT 1 `); t.deepEqual(pool.getPoolState(), { activeConnectionCount: 0, ended: false, idleConnectionCount: 1, waitingClientCount: 0, }); await pool.end(); t.deepEqual(pool.getPoolState(), { activeConnectionCount: 0, ended: true, idleConnectionCount: 0, waitingClientCount: 0, }); }); test('pool.end() resolves when there are no more connections (explicit connection holding pool alive)', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); t.deepEqual(pool.getPoolState(), { activeConnectionCount: 0, ended: false, idleConnectionCount: 0, waitingClientCount: 0, }); void pool.connect(async () => { await delay(500); }); await delay(100); t.deepEqual(pool.getPoolState(), { activeConnectionCount: 1, ended: false, idleConnectionCount: 0, waitingClientCount: 0, }); await pool.end(); t.deepEqual(pool.getPoolState(), { activeConnectionCount: 0, ended: true, idleConnectionCount: 0, waitingClientCount: 0, }); }); test('pool.end() resolves when there are no more connections (terminates idle connections)', async (t) => { t.timeout(1000); const pool = createPool(t.context.dsn, { idleTimeout: 5000, maximumPoolSize: 5, pgClient, }); t.deepEqual(pool.getPoolState(), { activeConnectionCount: 0, ended: false, idleConnectionCount: 0, waitingClientCount: 0, }); await Promise.all([ pool.query(sql` SELECT 1 `), pool.query(sql` SELECT 1 `), pool.query(sql` SELECT 1 `), pool.query(sql` SELECT 1 `), pool.query(sql` SELECT 1 `), ]); t.deepEqual(pool.getPoolState(), { activeConnectionCount: 0, ended: false, idleConnectionCount: 5, waitingClientCount: 0, }); await pool.end(); t.deepEqual(pool.getPoolState(), { activeConnectionCount: 0, ended: true, idleConnectionCount: 0, waitingClientCount: 0, }); }); test.skip('idle transactions are terminated after `idleInTransactionSessionTimeout`', async (t) => { t.timeout(10000); const pool = createPool(t.context.dsn, { idleInTransactionSessionTimeout: 1000, maximumPoolSize: 5, pgClient, }); t.deepEqual(pool.getPoolState(), { activeConnectionCount: 0, ended: false, idleConnectionCount: 0, waitingClientCount: 0, }); const error = await t.throwsAsync(pool.transaction(async () => { await delay(2000); })); t.true(error instanceof BackendTerminatedError); await pool.end(); }); // Skipping test because of a bug in node-postgres. // @see https://github.com/brianc/node-postgres/issues/2103 test.skip('statements are cancelled after `statementTimeout`', async (t) => { t.timeout(5000); const pool = createPool(t.context.dsn, { maximumPoolSize: 5, pgClient, statementTimeout: 1000, }); t.deepEqual(pool.getPoolState(), { activeConnectionCount: 0, ended: false, idleConnectionCount: 0, waitingClientCount: 0, }); const error = await t.throwsAsync(pool.query(sql`SELECT pg_sleep(2000)`)); t.true(error instanceof StatementTimeoutError); await pool.end(); }); test.serial.skip('retries failing transactions (deadlock)', async (t) => { t.timeout(2000); const pool = createPool(t.context.dsn, { pgClient, }); const firstPersonId = await pool.oneFirst(sql` INSERT INTO person (name) VALUES ('foo') RETURNING id `); const secondPersonId = await pool.oneFirst(sql` INSERT INTO person (name) VALUES ('bar') RETURNING id `); let transactionCount = 0; let resolveDeadlock: any; const deadlock = new Promise((resolve) => { resolveDeadlock = resolve; }); const updatePerson: (...args: any) => any = async (firstUpdateId, firstUpdateName, secondUpdateId, secondUpdateName, delayDeadlock) => { await pool.transaction(async (transaction) => { await transaction.query(sql` SET deadlock_timeout='1s' `); await transaction.query(sql` UPDATE person SET name = ${firstUpdateName} WHERE id = ${firstUpdateId} `); ++transactionCount; if (transactionCount === 2) { resolveDeadlock(); } await delay(delayDeadlock); await deadlock; await transaction.query(sql` UPDATE person SET name = ${secondUpdateName} WHERE id = ${secondUpdateId} `); }); }; await t.notThrowsAsync(Promise.all([ updatePerson(firstPersonId, 'foo 0', secondPersonId, 'foo 1', 50), updatePerson(secondPersonId, 'bar 0', firstPersonId, 'bar 1', 0), ])); t.is( await pool.oneFirst(sql` SELECT name FROM person WHERE id = ${firstPersonId} `), 'bar 1', ); t.is( await pool.oneFirst(sql` SELECT name FROM person WHERE id = ${secondPersonId} `), 'bar 0', ); await pool.end(); }); test('does not throw an error if running a query with array_agg on dates', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); await pool.query(sql` INSERT INTO person ( name, birth_date ) VALUES ('foo', '2020-01-01'), ('foo', '2020-01-02'), ('bar', '2020-01-03') `); const result = await pool.query(sql` SELECT p1.name, array_agg(p1.birth_date) birth_dates FROM person p1 GROUP BY p1.name `); t.deepEqual(result, { command: 'SELECT', fields: [ { dataTypeId: 25, name: 'name', }, { dataTypeId: 1182, name: 'birth_dates', }, ], notices: [], rowCount: 2, rows: [ { birth_dates: ['2020-01-03'], name: 'bar', }, { birth_dates: ['2020-01-01', '2020-01-02'], name: 'foo', }, ], }); await pool.end(); }); test('returns true if returns rows', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); t.true( await pool.exists(sql` SELECT LIMIT 1 `), ); await pool.end(); }); test('returns false if returns rows', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); t.false( await pool.exists(sql` SELECT LIMIT 0 `), ); await pool.end(); }); test('returns expected query result object (SELECT)', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); const result = await pool.query(sql` SELECT 1 "name" `); t.deepEqual(result, { command: 'SELECT', fields: [ { dataTypeId: 23, name: 'name', }, ], notices: [], rowCount: 1, rows: [ { name: 1, }, ], }); await pool.end(); }); test('throw error with notices', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); await pool.query(sql` CREATE OR REPLACE FUNCTION error_notice ( v_test INTEGER ) RETURNS BOOLEAN LANGUAGE plpgsql AS $$ BEGIN RAISE NOTICE '1. TEST NOTICE [%]',v_test; RAISE NOTICE '2. TEST NOTICE [%]',v_test; RAISE NOTICE '3. TEST NOTICE [%]',v_test; RAISE WARNING '4. TEST LOG [%]',v_test; RAISE NOTICE '5. TEST NOTICE [%]',v_test; RAISE EXCEPTION 'THIS IS AN ERROR'; END; $$; `); try { await pool.query(sql`SELECT * FROM error_notice(${10});`); } catch (error) { if (error?.notices) { t.assert(error.notices.length = 5); } } await pool.end(); }); test('error messages include original pg error', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); await pool.query(sql` INSERT INTO person (id) VALUES (1) `); const error = await t.throwsAsync(async () => { return pool.query(sql` INSERT INTO person (id) VALUES (1) `); }); t.is( error.message, // @ts-expect-error 'Query violates a unique integrity constraint. ' + String(error?.originalError?.message), ); await pool.end(); }); test('Tuple moved to another partition due to concurrent update error handled', async (t) => { const pool = createPool(t.context.dsn, { pgClient, transactionRetryLimit: 0, }); await pool.connect(async (connection) => { await connection.query(sql`CREATE TABLE foo (a int, b text) PARTITION BY LIST(a)`); await connection.query(sql`CREATE TABLE foo1 PARTITION OF foo FOR VALUES IN (1)`); await connection.query(sql`CREATE TABLE foo2 PARTITION OF foo FOR VALUES IN (2)`); await connection.query(sql`INSERT INTO foo VALUES (1, 'ABC')`); }); await pool.connect(async (connection1) => { await pool.connect(async (connection2) => { await connection1.query(sql`BEGIN`); await connection2.query(sql`BEGIN`); await connection1.query(sql`UPDATE foo SET a = 2 WHERE a = 1`); connection2.query(sql`UPDATE foo SET b = 'XYZ'`).catch((error) => { t.is( error.message, 'Tuple moved to another partition due to concurrent update. ' + String(error?.originalError?.message), ); t.true(error instanceof TupleMovedToAnotherPartitionError); }); // Ensures that query is processed before concurrent commit is called. await delay(1000); await connection1.query(sql`COMMIT`); await connection2.query(sql`COMMIT`); }); }); await pool.end(); }); test('throws InvalidInputError in case of invalid bound value', async (t) => { const pool = createPool(t.context.dsn, { pgClient, }); await pool.query(sql` CREATE TABLE invalid_input_error_test ( id uuid NOT NULL PRIMARY KEY DEFAULT '00000000-0000-0000-0000-000000000000' ); `); const error = await t.throwsAsync(pool.query(sql`SELECT * FROM invalid_input_error_test where id = '1';`)); t.true(error instanceof InvalidInputError); }); };
the_stack
import { Component, OnInit, OnDestroy, EventEmitter, ViewChild } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { MatOptionSelectionChange } from '@angular/material/core/option'; import { Store, select } from '@ngrx/store'; import { Observable, combineLatest, Subject } from 'rxjs'; import { filter, takeUntil, map } from 'rxjs/operators'; import { isNil } from 'lodash/fp'; import { NgrxStateAtom } from 'app/ngrx.reducers'; import { Regex } from 'app/helpers/auth/regex'; import { HttpStatus, SortDirection } from 'app/types/types'; import { loading, EntityStatus, pending } from 'app/entities/entities'; import { LayoutFacadeService, Sidebar } from 'app/entities/layout/layout.facade'; import { Destination } from 'app/entities/destinations/destination.model'; import { allDestinations, getStatus, saveStatus, saveError } from 'app/entities/destinations/destination.selectors'; import { CreateDestination, GetDestinations, DeleteDestination, TestDestination, CreateDestinationPayload } from 'app/entities/destinations/destination.actions'; import { DestinationRequests } from 'app/entities/destinations/destination.requests'; import { AuthTypes, DataFeedCreateComponent, IntegrationTypes, StorageIntegrationTypes, WebhookIntegrationTypes } from '../data-feed-create/data-feed-create.component'; export enum UrlTestState { Inactive, Loading, Success, Failure } @Component({ selector: 'app-data-feed', templateUrl: './data-feed.component.html', styleUrls: ['./data-feed.component.scss'] }) export class DataFeedComponent implements OnInit, OnDestroy { public loading$: Observable<boolean>; public sortedDestinations$: Observable<Destination[]>; public createModalVisible = false; public createDataFeedForm: FormGroup; public creatingDataFeed = false; public conflictErrorEvent = new EventEmitter<boolean>(); public dataFeedToDelete: Destination; public deleteModalVisible = false; public sendingDataFeed = false; private isDestroyed = new Subject<boolean>(); public checkedHeaders = false; @ViewChild(DataFeedCreateComponent) createChild: DataFeedCreateComponent; // The field or column used to sort nodes sortField$: Observable<string>; // The direction nodes are sorted fieldDirection$: Observable<SortDirection>; constructor( private store: Store<NgrxStateAtom>, private fb: FormBuilder, private layoutFacade: LayoutFacadeService, private datafeedRequests: DestinationRequests ) { this.loading$ = store.pipe(select(getStatus), map(loading)); this.sortedDestinations$ = store.pipe( select(allDestinations)); this.createDataFeedForm = this.fb.group({ // Must stay in sync with error checks in create-data-feed-modal.component.html name: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]], endpoint: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]], // Note that URL here may be FQDN -or- IP! url: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]], tokenType: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]], token: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]], username: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]], password: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]], headers: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]], bucketName: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]], accessKey: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]], secretKey: ['', [Validators.required, Validators.pattern(Regex.patterns.NON_BLANK)]] }); } ngOnInit() { this.layoutFacade.showSidebar(Sidebar.Settings); this.store.dispatch(new GetDestinations()); this.store.pipe( select(saveStatus), takeUntil(this.isDestroyed), filter(state => this.createModalVisible && !pending(state))) .subscribe(state => { this.creatingDataFeed = false; if (state === EntityStatus.loadingSuccess) { this.closeSlider(); } }); combineLatest([ this.store.select(saveStatus), this.store.select(saveError) ]).pipe( takeUntil(this.isDestroyed), filter(() => this.createModalVisible), filter(([state, error]) => state === EntityStatus.loadingFailure && !isNil(error))) .subscribe(([_, error]) => { if (error.status === HttpStatus.CONFLICT) { this.conflictErrorEvent.emit(true); } else { this.createChild.conflictErrorSetter = `Could not create data feed: ${error?.error?.error || error}.`; this.conflictErrorEvent.emit(false); } }); } ngOnDestroy(): void { this.isDestroyed.next(true); this.isDestroyed.complete(); } public closeSlider() { this.createChild.closeCreateSlider(); this.createChild.saveDone = false; this.createModalVisible = false; this.conflictErrorEvent.emit(false); } public startDataFeedDelete($event: MatOptionSelectionChange, destination: Destination): void { if ($event.isUserInput) { this.dataFeedToDelete = destination; this.deleteModalVisible = true; } } public startDataFeedSendTest($event: MatOptionSelectionChange, destination: Destination) { if ($event.isUserInput) { this.store.dispatch(new TestDestination({destination})); } } public deleteDataFeed(): void { this.closeDeleteModal(); this.store.dispatch(new DeleteDestination(this.dataFeedToDelete)); } public closeDeleteModal(): void { this.deleteModalVisible = false; } public setCheck(event) { this.checkedHeaders = event; } public addHeadersforCustomDataFeed(customHeaders: string): {} { const headersJson = {}; const headersVal = customHeaders.split('\n'); for (const values in headersVal) { if (headersVal[values]) { const word = headersVal[values].split(':'); headersJson[word[0]] = word[1]; } } return headersJson; } public sendTestForDataFeed(event: {name: string, auth: string, region: string}): void { let testConnectionObservable: Observable<Object> = null; switch (event.name) { case WebhookIntegrationTypes.SERVICENOW: case WebhookIntegrationTypes.SPLUNK: case WebhookIntegrationTypes.ELK_KIBANA: case WebhookIntegrationTypes.CUSTOM: { switch (event.auth) { case AuthTypes.ACCESSTOKEN: { const targetUrl: string = this.createDataFeedForm.controls['url'].value; const tokenType: string = this.createDataFeedForm.controls['tokenType'].value; const token: string = this.createDataFeedForm.controls['token'].value; const headerVal: string = this.createDataFeedForm.controls['headers'].value; const userToken = JSON.stringify({ Authorization: tokenType + ' ' + token }); let value; if (headerVal && this.checkedHeaders) { const headersJson = this.addHeadersforCustomDataFeed(headerVal); const headers = {...headersJson, ...JSON.parse(userToken)}; value = JSON.stringify(headers); } else { value = userToken; } testConnectionObservable = this.datafeedRequests. testDestinationWithHeaders(targetUrl, value); break; } case AuthTypes.USERNAMEANDPASSWORD: { const targetUrl: string = this.createDataFeedForm.controls['url'].value; const targetUsername: string = this.createDataFeedForm.controls['username'].value; const targetPassword: string = this.createDataFeedForm.controls['password'].value; const headerVal: string = this.createDataFeedForm.controls['headers'].value; const userToken = JSON.stringify({ Authorization: 'Basic ' + btoa(targetUsername + ':' + targetPassword) }); let value; if (headerVal && this.checkedHeaders) { const headersJson = this.addHeadersforCustomDataFeed(headerVal); const headers = {...headersJson, ...JSON.parse(userToken)}; value = JSON.stringify(headers); } else { value = userToken; } testConnectionObservable = this.datafeedRequests. testDestinationWithHeaders(targetUrl, value); break; } } break; } case StorageIntegrationTypes.MINIO: { // handling minio const targetUrl: string = this.createDataFeedForm.controls['endpoint'].value; const data = { url: targetUrl, aws: { access_key: this.createDataFeedForm.controls['accessKey'].value.trim(), secret_access_key: this.createDataFeedForm.controls['secretKey'].value.trim(), bucket: this.createDataFeedForm.controls['bucketName'].value.trim() } }; testConnectionObservable = this.datafeedRequests.testDestinationForStorage(data); break; } case StorageIntegrationTypes.AMAZON_S3: { const data = { url: 'null', aws: { access_key: this.createDataFeedForm.controls['accessKey'].value.trim(), secret_access_key: this.createDataFeedForm.controls['secretKey'].value.trim(), bucket: this.createDataFeedForm.controls['bucketName'].value.trim(), region: event.region } }; testConnectionObservable = this.datafeedRequests.testDestinationForStorage(data); } } if (testConnectionObservable != null) { testConnectionObservable.subscribe( () => this.revealUrlStatus(UrlTestState.Success), () => this.revealUrlStatus(UrlTestState.Failure) ); } } revealUrlStatus(status: UrlTestState) { this.createChild.testDoneSetter = false; if (status === UrlTestState.Success) { this.createChild.testSuccessSetter = true; } else { this.createChild.testErrorSetter = true; } } public slidePanel(): void { this.createModalVisible = true; this.createChild.slidePanel(); } public saveDestination(event: {name: string, auth: string, region: string}) { let destinationObj: CreateDestinationPayload, headers: string, storage: any; this.creatingDataFeed = true; switch (event.name) { case WebhookIntegrationTypes.SERVICENOW: case WebhookIntegrationTypes.SPLUNK: case WebhookIntegrationTypes.ELK_KIBANA: case WebhookIntegrationTypes.CUSTOM: { destinationObj = { name: this.createDataFeedForm.controls['name'].value.trim(), url: this.createDataFeedForm.controls['url'].value.trim(), integration_types: IntegrationTypes.WEBHOOK, services: event.name }; switch (event.auth) { case AuthTypes.ACCESSTOKEN: { const tokenType: string = this.createDataFeedForm.controls['tokenType'].value.trim(); const token: string = this.createDataFeedForm.controls['token'].value.trim(); const headerVal: string = this.createDataFeedForm.controls['headers'].value; const userToken = JSON.stringify({ Authorization: tokenType + ' ' + token }); if (headerVal && this.checkedHeaders) { const headersJson = this.addHeadersforCustomDataFeed(headerVal); const value = {...headersJson, ...JSON.parse(userToken)}; headers = JSON.stringify(value); } else { headers = userToken; } storage = null; break; } case AuthTypes.USERNAMEANDPASSWORD: { const username: string = this.createDataFeedForm.controls['username'].value.trim(); const password: string = this.createDataFeedForm.controls['password'].value.trim(); const headerVal: string = this.createDataFeedForm.controls['headers'].value; const userToken = JSON.stringify({ Authorization: 'Basic ' + btoa(username + ':' + password) }); if (headerVal && this.checkedHeaders) { const headersJson = this.addHeadersforCustomDataFeed(headerVal); const value = {...headersJson, ...JSON.parse(userToken)}; headers = JSON.stringify(value); } else { headers = userToken; } storage = null; break; } } break; } case StorageIntegrationTypes.MINIO: { // handling minio destinationObj = { name: this.createDataFeedForm.controls['name'].value.trim(), url: this.createDataFeedForm.controls['endpoint'].value.trim(), integration_types: IntegrationTypes.STORAGE, services: event.name, meta_data: [ { key: 'bucket', value: this.createDataFeedForm.controls['bucketName'].value.trim() } ] }; const accessKey: string = this.createDataFeedForm.controls['accessKey'].value.trim(); const secretKey: string = this.createDataFeedForm.controls['secretKey'].value.trim(); storage = { accessKey, secretKey }; headers = null; break; } case StorageIntegrationTypes.AMAZON_S3: { destinationObj = { name: this.createDataFeedForm.controls['name'].value.trim(), url: 'null', integration_types: IntegrationTypes.STORAGE, services: event.name, meta_data: [ { key: 'bucket', value: this.createDataFeedForm.controls['bucketName'].value.trim() }, { key: 'region', value: event.region } ] }; const accessKey: string = this.createDataFeedForm.controls['accessKey'].value.trim(); const secretKey: string = this.createDataFeedForm.controls['secretKey'].value.trim(); storage = { accessKey, secretKey }; headers = null; break; } } if (destinationObj && (headers || storage)) { this.store.dispatch(new CreateDestination(destinationObj, headers, storage)); } } }
the_stack
import { Inject, Injectable, Optional } from '@angular/core'; import { Http, Headers, URLSearchParams } from '@angular/http'; import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http'; import { Response, ResponseContentType } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import '../rxjs-operators'; import { InlineResponse200 } from '../model/inlineResponse200'; import { InlineResponse2001 } from '../model/inlineResponse2001'; import { InlineResponse2002 } from '../model/inlineResponse2002'; import { InlineResponse2003 } from '../model/inlineResponse2003'; import { InlineResponse2005 } from '../model/inlineResponse2005'; import { Room } from '../model/room'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ @Injectable() export class RoomService { protected basePath = 'http://localhost:3000/api'; public defaultHeaders: Headers = new Headers(); public configuration: Configuration = new Configuration(); constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { if (basePath) { this.basePath = basePath; } if (configuration) { this.configuration = configuration; this.basePath = basePath || configuration.basePath || this.basePath; } } /** * * Extends object by coping non-existing properties. * @param objA object to be extended * @param objB source object */ private extendObj<T1,T2>(objA: T1, objB: T2) { for(let key in objB){ if(objB.hasOwnProperty(key)){ (objA as any)[key] = (objB as any)[key]; } } return <T1&T2>objA; } /** * @param consumes string[] mime-types * @return true: consumes contains 'multipart/form-data', false: otherwise */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; for (let consume of consumes) { if (form === consume) { return true; } } return false; } /** * Count instances of the model matched by where from the data source. * * @param where Criteria to match model instances */ public roomCount(where?: string, extraHttpRequestParams?: any): Observable<InlineResponse200> { return this.roomCountWithHttpInfo(where, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Create a new instance of the model and persist it into the data source. * * @param data Model instance data */ public roomCreate(data?: Room, extraHttpRequestParams?: any): Observable<Room> { return this.roomCreateWithHttpInfo(data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Create a change stream. * * @param options */ public roomCreateChangeStreamGetRoomsChangeStream(options?: string, extraHttpRequestParams?: any): Observable<Blob> { return this.roomCreateChangeStreamGetRoomsChangeStreamWithHttpInfo(options, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.blob(); } }); } /** * Create a change stream. * * @param options */ public roomCreateChangeStreamPostRoomsChangeStream(options?: string, extraHttpRequestParams?: any): Observable<Blob> { return this.roomCreateChangeStreamPostRoomsChangeStreamWithHttpInfo(options, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.blob(); } }); } /** * Deletes all data. * */ public roomDeleteAllRooms(extraHttpRequestParams?: any): Observable<InlineResponse2003> { return this.roomDeleteAllRoomsWithHttpInfo(extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Delete a model instance by {{id}} from the data source. * * @param id Model id */ public roomDeleteById(id: string, extraHttpRequestParams?: any): Observable<any> { return this.roomDeleteByIdWithHttpInfo(id, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Check whether a model instance exists in the data source. * * @param id Model id */ public roomExistsGetRoomsidExists(id: string, extraHttpRequestParams?: any): Observable<InlineResponse2001> { return this.roomExistsGetRoomsidExistsWithHttpInfo(id, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Check whether a model instance exists in the data source. * * @param id Model id */ public roomExistsHeadRoomsid(id: string, extraHttpRequestParams?: any): Observable<InlineResponse2001> { return this.roomExistsHeadRoomsidWithHttpInfo(id, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Find all instances of the model matched by filter from the data source. * * @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public roomFind(filter?: string, extraHttpRequestParams?: any): Observable<Array<Room>> { return this.roomFindWithHttpInfo(filter, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Find a model instance by {{id}} from the data source. * * @param id Model id * @param filter Filter defining fields and include - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public roomFindById(id: string, filter?: string, extraHttpRequestParams?: any): Observable<Room> { return this.roomFindByIdWithHttpInfo(id, filter, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Find first instance of the model matched by filter from the data source. * * @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public roomFindOne(filter?: string, extraHttpRequestParams?: any): Observable<Room> { return this.roomFindOneWithHttpInfo(filter, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Insert sample data set of test rooms. * * @param locale */ public roomInsertTestData(locale?: string, extraHttpRequestParams?: any): Observable<InlineResponse2005> { return this.roomInsertTestDataWithHttpInfo(locale, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Patch an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public roomPatchOrCreate(data?: Room, extraHttpRequestParams?: any): Observable<Room> { return this.roomPatchOrCreateWithHttpInfo(data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Patch attributes for a model instance and persist it into the data source. * * @param id Room id * @param data An object of model property name/value pairs */ public roomPrototypePatchAttributes(id: string, data?: Room, extraHttpRequestParams?: any): Observable<Room> { return this.roomPrototypePatchAttributesWithHttpInfo(id, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Replace attributes for a model instance and persist it into the data source. * * @param id Model id * @param data Model instance data */ public roomReplaceByIdPostRoomsidReplace(id: string, data?: Room, extraHttpRequestParams?: any): Observable<Room> { return this.roomReplaceByIdPostRoomsidReplaceWithHttpInfo(id, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Replace attributes for a model instance and persist it into the data source. * * @param id Model id * @param data Model instance data */ public roomReplaceByIdPutRoomsid(id: string, data?: Room, extraHttpRequestParams?: any): Observable<Room> { return this.roomReplaceByIdPutRoomsidWithHttpInfo(id, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Replace an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public roomReplaceOrCreatePostRoomsReplaceOrCreate(data?: Room, extraHttpRequestParams?: any): Observable<Room> { return this.roomReplaceOrCreatePostRoomsReplaceOrCreateWithHttpInfo(data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Replace an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public roomReplaceOrCreatePutRooms(data?: Room, extraHttpRequestParams?: any): Observable<Room> { return this.roomReplaceOrCreatePutRoomsWithHttpInfo(data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Update instances of the model matched by {{where}} from the data source. * * @param where Criteria to match model instances * @param data An object of model property name/value pairs */ public roomUpdateAll(where?: string, data?: Room, extraHttpRequestParams?: any): Observable<InlineResponse2002> { return this.roomUpdateAllWithHttpInfo(where, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Update an existing model instance or insert a new one into the data source based on the where criteria. * * @param where Criteria to match model instances * @param data An object of model property name/value pairs */ public roomUpsertWithWhere(where?: string, data?: Room, extraHttpRequestParams?: any): Observable<Room> { return this.roomUpsertWithWhereWithHttpInfo(where, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Count instances of the model matched by where from the data source. * * @param where Criteria to match model instances */ public roomCountWithHttpInfo(where?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms/count'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (where !== undefined) { queryParameters.set('where', <any>where); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Create a new instance of the model and persist it into the data source. * * @param data Model instance data */ public roomCreateWithHttpInfo(data?: Room, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Create a change stream. * * @param options */ public roomCreateChangeStreamGetRoomsChangeStreamWithHttpInfo(options?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms/change-stream'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (options !== undefined) { queryParameters.set('options', <any>options); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, responseType: ResponseContentType.Blob, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Create a change stream. * * @param options */ public roomCreateChangeStreamPostRoomsChangeStreamWithHttpInfo(options?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms/change-stream'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header let consumes: string[] = [ 'application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml' ]; let canConsumeForm = this.canConsumeForm(consumes); let useForm = false; let formParams = new (useForm ? FormData : URLSearchParams as any)() as { set(param: string, value: any): void; }; // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; if (options !== undefined) { formParams.set('options', <any>options); } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: formParams, responseType: ResponseContentType.Blob, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Deletes all data. * */ public roomDeleteAllRoomsWithHttpInfo(extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms/deleteAll'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Delete a model instance by {{id}} from the data source. * * @param id Model id */ public roomDeleteByIdWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling roomDeleteById.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Check whether a model instance exists in the data source. * * @param id Model id */ public roomExistsGetRoomsidExistsWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms/${id}/exists' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling roomExistsGetRoomsidExists.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Check whether a model instance exists in the data source. * * @param id Model id */ public roomExistsHeadRoomsidWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling roomExistsHeadRoomsid.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Head, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Find all instances of the model matched by filter from the data source. * * @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public roomFindWithHttpInfo(filter?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (filter !== undefined) { queryParameters.set('filter', <any>filter); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Find a model instance by {{id}} from the data source. * * @param id Model id * @param filter Filter defining fields and include - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public roomFindByIdWithHttpInfo(id: string, filter?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling roomFindById.'); } if (filter !== undefined) { queryParameters.set('filter', <any>filter); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Find first instance of the model matched by filter from the data source. * * @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public roomFindOneWithHttpInfo(filter?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms/findOne'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (filter !== undefined) { queryParameters.set('filter', <any>filter); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Insert sample data set of test rooms. * * @param locale */ public roomInsertTestDataWithHttpInfo(locale?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms/insertTestData'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (locale !== undefined) { queryParameters.set('locale', <any>locale); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Patch an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public roomPatchOrCreateWithHttpInfo(data?: Room, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Patch, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Patch attributes for a model instance and persist it into the data source. * * @param id Room id * @param data An object of model property name/value pairs */ public roomPrototypePatchAttributesWithHttpInfo(id: string, data?: Room, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling roomPrototypePatchAttributes.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Patch, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Replace attributes for a model instance and persist it into the data source. * * @param id Model id * @param data Model instance data */ public roomReplaceByIdPostRoomsidReplaceWithHttpInfo(id: string, data?: Room, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms/${id}/replace' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling roomReplaceByIdPostRoomsidReplace.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Replace attributes for a model instance and persist it into the data source. * * @param id Model id * @param data Model instance data */ public roomReplaceByIdPutRoomsidWithHttpInfo(id: string, data?: Room, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling roomReplaceByIdPutRoomsid.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Replace an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public roomReplaceOrCreatePostRoomsReplaceOrCreateWithHttpInfo(data?: Room, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms/replaceOrCreate'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Replace an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public roomReplaceOrCreatePutRoomsWithHttpInfo(data?: Room, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Update instances of the model matched by {{where}} from the data source. * * @param where Criteria to match model instances * @param data An object of model property name/value pairs */ public roomUpdateAllWithHttpInfo(where?: string, data?: Room, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms/update'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (where !== undefined) { queryParameters.set('where', <any>where); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Update an existing model instance or insert a new one into the data source based on the where criteria. * * @param where Criteria to match model instances * @param data An object of model property name/value pairs */ public roomUpsertWithWhereWithHttpInfo(where?: string, data?: Room, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Rooms/upsertWithWhere'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (where !== undefined) { queryParameters.set('where', <any>where); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } }
the_stack
export async function listDurableObjectsNamespaces(accountId: string, apiToken: string): Promise<readonly DurableObjectsNamespace[]> { const url = `${computeAccountBaseUrl(accountId)}/workers/durable_objects/namespaces`; return (await execute('listDurableObjectsNamespaces', 'GET', url, apiToken) as ListDurableObjectsNamespacesResponse).result; } export async function createDurableObjectsNamespace(accountId: string, apiToken: string, payload: { name: string, script?: string, class?: string}): Promise<DurableObjectsNamespace> { const url = `${computeAccountBaseUrl(accountId)}/workers/durable_objects/namespaces`; return (await execute('createDurableObjectsNamespace', 'POST', url, apiToken, JSON.stringify(payload)) as CreateDurableObjectsNamespaceResponse).result; } export async function updateDurableObjectsNamespace(accountId: string, apiToken: string, payload: { id: string, name?: string, script?: string, class?: string }): Promise<DurableObjectsNamespace> { const url = `${computeAccountBaseUrl(accountId)}/workers/durable_objects/namespaces/${payload.id}`; return (await execute('updateDurableObjectsNamespace', 'PUT', url, apiToken, JSON.stringify(payload)) as UpdateDurableObjectsNamespaceResponse).result; } export async function deleteDurableObjectsNamespace(accountId: string, apiToken: string, namespaceId: string): Promise<void> { const url = `${computeAccountBaseUrl(accountId)}/workers/durable_objects/namespaces/${namespaceId}`; await execute('deleteDurableObjectsNamespace', 'DELETE', url, apiToken) as CloudflareApiResponse; } //#endregion //#region Worker scripts export async function listScripts(accountId: string, apiToken: string): Promise<readonly Script[]> { const url = `${computeAccountBaseUrl(accountId)}/workers/scripts`; return (await execute('listScripts', 'GET', url, apiToken) as ListScriptsResponse).result; } export async function putScript(accountId: string, scriptName: string, apiToken: string, opts: { scriptContents: Uint8Array, bindings?: Binding[], migrations?: Migrations, parts?: Part[], isModule: boolean, usageModel?: 'bundled' | 'unbound' }): Promise<Script> { const { scriptContents, bindings, migrations, parts, isModule, usageModel } = opts; const url = `${computeAccountBaseUrl(accountId)}/workers/scripts/${scriptName}`; const formData = new FormData(); const metadata: Record<string, unknown> = { bindings, usage_model: usageModel, migrations }; if (isModule) { metadata['main_module'] = 'main'; } else { metadata['body_part'] = 'script'; } const metadataBlob = new Blob([ JSON.stringify(metadata) ], { type: APPLICATION_JSON }); formData.set('metadata', metadataBlob); if (isModule) { const scriptBlob = new Blob([ scriptContents.buffer ], { type: 'application/javascript+module' }); formData.set('script', scriptBlob, 'main'); } else { const scriptBlob = new Blob([ scriptContents.buffer ], { type: 'application/javascript' }); formData.set('script', scriptBlob); } for (const { name, value, fileName } of (parts || [])) { formData.set(name, value, fileName); } return (await execute('putScript', 'PUT', url, apiToken, formData) as PutScriptResponse).result; } export async function deleteScript(accountId: string, scriptName: string, apiToken: string): Promise<DeleteScriptResult> { const url = `${computeAccountBaseUrl(accountId)}/workers/scripts/${scriptName}`; return (await execute('deleteScript', 'DELETE', url, apiToken) as DeleteScriptResponse).result; } //#endregion //#region Worker Account Settings export async function getWorkerAccountSettings(accountId: string, apiToken: string): Promise<WorkerAccountSettings> { const url = `${computeAccountBaseUrl(accountId)}/workers/account-settings`; return (await execute('getWorkerAccountSettings', 'GET', url, apiToken) as WorkerAccountSettingsResponse).result; } export async function putWorkerAccountSettings(accountId: string, apiToken: string, opts: { defaultUsageModel: 'bundled' | 'unbound' }): Promise<WorkerAccountSettings> { const { defaultUsageModel: default_usage_model } = opts; const url = `${computeAccountBaseUrl(accountId)}/workers/account-settings`; return (await execute('putWorkerAccountSettings', 'PUT', url, apiToken, JSON.stringify({ default_usage_model })) as WorkerAccountSettingsResponse).result; } //#endregion //#region Workers KV export async function getKeyValue(accountId: string, namespaceId: string, key: string, apiToken: string): Promise<Uint8Array | undefined> { const url = `${computeAccountBaseUrl(accountId)}/storage/kv/namespaces/${namespaceId}/values/${key}`; return await execute('getKeyValue', 'GET', url, apiToken, undefined, 'bytes?'); } export async function getKeyMetadata(accountId: string, namespaceId: string, key: string, apiToken: string): Promise<Record<string, string>> { const url = `${computeAccountBaseUrl(accountId)}/storage/kv/namespaces/${namespaceId}/metadata/${key}`; return (await execute('getKeyMetadata', 'GET', url, apiToken, undefined) as GetKeyMetadataResponse).result; } //#endregion //#region Workers Tails /** * List Tails * Lists all active Tail sessions for a given Worker * https://api.cloudflare.com/#worker-tails-list-tails */ export async function listTails(accountId: string, scriptName: string, apiToken: string): Promise<readonly Tail[]> { const url = `${computeAccountBaseUrl(accountId)}/workers/scripts/${scriptName}/tails`; return (await execute('listTails', 'GET', url, apiToken) as ListTailsResponse).result; } /** * Create Tail * https://api.cloudflare.com/#worker-create-tail * * Constrained to at most one tail per script */ export async function createTail(accountId: string, scriptName: string, apiToken: string): Promise<Tail> { const url = `${computeAccountBaseUrl(accountId)}/workers/scripts/${scriptName}/tails`; return (await execute('createTail', 'POST', url, apiToken) as CreateTailResponse).result; } /** * Send Tail Heartbeat * https://api.cloudflare.com/#worker-tail-heartbeat */ export async function sendTailHeartbeat(accountId: string, scriptName: string, tailId: string, apiToken: string): Promise<Tail> { const url = `${computeAccountBaseUrl(accountId)}/workers/scripts/${scriptName}/tails/${tailId}/heartbeat`; return (await execute('sendTailHeartbeat', 'POST', url, apiToken) as SendTailHeartbeatResponse).result; } /** * Delete Tail * https://api.cloudflare.com/#worker-delete-tail */ export async function deleteTail(accountId: string, scriptName: string, tailId: string, apiToken: string): Promise<void> { const url = `${computeAccountBaseUrl(accountId)}/workers/scripts/${scriptName}/tails/${tailId}`; await execute('deleteTail', 'DELETE', url, apiToken); // result = null } export interface CreateTailResponse extends CloudflareApiResponse { readonly result: Tail; } export interface Tail { readonly id: string; // cf id readonly url: string // e.g. wss://tail.developers.workers.dev/<tail-id> readonly 'expires_at': string; // e.g. 2021-08-20T23:45:17Z (4-6 hrs from creation) } export interface ListTailsResponse extends CloudflareApiResponse { readonly result: readonly Tail[]; } export interface SendTailHeartbeatResponse extends CloudflareApiResponse { readonly result: Tail; } //#endregion export class CloudflareApi { static DEBUG = false; static URL_TRANSFORMER: (url: string) => string = v => v; } // const APPLICATION_JSON = 'application/json'; const APPLICATION_JSON_UTF8 = 'application/json; charset=UTF-8'; const APPLICATION_OCTET_STREAM = 'application/octet-stream'; function computeAccountBaseUrl(accountId: string): string { return CloudflareApi.URL_TRANSFORMER(`https://api.cloudflare.com/client/v4/accounts/${accountId}`); } async function execute(op: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE', url: string, apiToken: string, body?: string /*json*/ | FormData, responseType?: 'json'): Promise<CloudflareApiResponse>; async function execute(op: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE', url: string, apiToken: string, body?: string /*json*/ | FormData, responseType?: 'bytes'): Promise<Uint8Array>; async function execute(op: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE', url: string, apiToken: string, body?: string /*json*/ | FormData, responseType?: 'bytes?'): Promise<Uint8Array | undefined>; async function execute(op: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE', url: string, apiToken: string, body?: string /*json*/ | FormData, responseType: 'json' | 'bytes' | 'bytes?' = 'json'): Promise<CloudflareApiResponse | Uint8Array | undefined> { if (CloudflareApi.DEBUG) console.log(`${op}: ${method} ${url}`); const headers = new Headers({ 'Authorization': `Bearer ${apiToken}`}); if (typeof body === 'string') { headers.set('Content-Type', APPLICATION_JSON_UTF8); if (CloudflareApi.DEBUG) console.log(body); } const fetchResponse = await fetch(url, { method, headers, body }); const contentType = fetchResponse.headers.get('Content-Type') || ''; if ((responseType === 'bytes' || responseType === 'bytes?') && contentType === APPLICATION_OCTET_STREAM) { const buffer = await fetchResponse.arrayBuffer(); return new Uint8Array(buffer); } if (![APPLICATION_JSON_UTF8, APPLICATION_JSON].includes(contentType)) { throw new Error(`Unexpected content-type: ${contentType}, fetchResponse=${fetchResponse}, body=${await fetchResponse.text()}`); } const apiResponse = await fetchResponse.json() as CloudflareApiResponse; if (CloudflareApi.DEBUG) console.log(apiResponse); if (!apiResponse.success) { if (fetchResponse.status === 404 && responseType === 'bytes?') return undefined; throw new CloudflareApiError(`${op} failed: status=${fetchResponse.status}, errors=${apiResponse.errors.map(v => `${v.code} ${v.message}`).join(', ')}`, fetchResponse.status, apiResponse.errors); } return apiResponse; } // export class CloudflareApiError extends Error { readonly status: number; readonly errors: readonly Message[]; constructor(message: string, status: number, errors: readonly Message[]) { super(message); this.status = status; this.errors = errors; } } export type Binding = PlainTextBinding | SecretTextBinding | KvNamespaceBinding | DurableObjectNamespaceBinding | WasmModuleBinding | ServiceBinding; export interface PlainTextBinding { readonly type: 'plain_text'; readonly name: string; readonly text: string; } export interface SecretTextBinding { readonly type: 'secret_text'; readonly name: string; readonly text: string; } export interface KvNamespaceBinding { readonly type: 'kv_namespace'; readonly name: string; readonly 'namespace_id': string; } export interface DurableObjectNamespaceBinding { readonly type: 'durable_object_namespace'; readonly name: string; readonly 'namespace_id': string; } export interface WasmModuleBinding { readonly type: 'wasm_module'; readonly name: string; readonly part: string; } export interface ServiceBinding { readonly type: 'service'; readonly name: string; readonly service: string; readonly environment: string; } // this is likely not correct, but it works to delete obsolete DO classes at least export interface Migrations { readonly tag: string; readonly deleted_classes: string[]; } export interface Part { readonly name: string; readonly value: string | Blob; readonly fileName?: string; readonly valueBytes?: Uint8Array; } export interface Message { readonly code: number; readonly message: string; } export interface CloudflareApiResponse { readonly success: boolean; readonly errors: readonly Message[]; readonly messages?: readonly Message[]; } export interface ListDurableObjectsNamespacesResponse extends CloudflareApiResponse { readonly result: readonly DurableObjectsNamespace[]; } export interface CreateDurableObjectsNamespaceResponse extends CloudflareApiResponse { readonly result: DurableObjectsNamespace; } export interface UpdateDurableObjectsNamespaceResponse extends CloudflareApiResponse { readonly result: DurableObjectsNamespace; } export interface DurableObjectsNamespace { readonly id: string; readonly name: string; readonly script: string | null; readonly class: string | undefined; } export interface PutScriptResponse extends CloudflareApiResponse { readonly result: Script; } export interface Script { readonly id: string; readonly etag: string; readonly handlers: readonly string[]; readonly 'named_handlers'?: readonly NamedHandler[]; readonly 'modified_on': string; readonly 'created_on': string; readonly 'usage_model': string; } export interface NamedHandler { readonly name: string; readonly handlers: readonly string[]; } export interface DeleteScriptResponse extends CloudflareApiResponse { readonly result: DeleteScriptResult; } export interface DeleteScriptResult { readonly id: string; } export interface ListScriptsResponse extends CloudflareApiResponse { readonly result: readonly Script[]; } export interface GetKeyMetadataResponse extends CloudflareApiResponse { readonly result: Record<string, string>; } export interface WorkerAccountSettings { readonly 'default_usage_model': string, readonly 'green_compute': boolean, } export interface WorkerAccountSettingsResponse extends CloudflareApiResponse { readonly result: WorkerAccountSettings; }
the_stack
import set from 'lodash/set'; import cloneDeep from 'lodash/cloneDeep'; import '../../fixtures/window'; import { Project } from '../../../src/project/project'; import { Node } from '../../../src/document/node/node'; import { Designer } from '../../../src/designer/designer'; import formSchema from '../../fixtures/schema/form'; import { getIdsFromSchema, getNodeFromSchemaById } from '../../utils'; import { EBADF } from 'constants'; const mockCreateSettingEntry = jest.fn(); jest.mock('../../../src/designer/designer', () => { return { Designer: jest.fn().mockImplementation(() => { return { getComponentMeta() { return { getMetadata() { return { configure: { advanced: null } }; }, }; }, transformProps(props) { return props; }, createSettingEntry: mockCreateSettingEntry, postEvent() {}, }; }), }; }); let designer = null; beforeAll(() => { designer = new Designer({}); }); describe('schema 生成节点模型测试', () => { describe('block ❌ | component ❌ | slot ❌', () => { let project: Project; beforeEach(() => { project = new Project(designer, { componentsTree: [ formSchema, ], }); project.open(); }); afterEach(() => { project.unload(); }); it('基本的节点模型初始化,模型导出', () => { expect(project).toBeTruthy(); const { currentDocument } = project; const { nodesMap } = currentDocument; const ids = getIdsFromSchema(formSchema); const expectedNodeCnt = ids.length; expect(nodesMap.size).toBe(expectedNodeCnt); ids.forEach(id => { expect(nodesMap.get(id).componentName).toBe(getNodeFromSchemaById(formSchema, id).componentName); }); const pageNode = currentDocument?.getNode('page'); expect(pageNode?.getComponentName()).toBe('Page'); expect(pageNode?.getIcon()).toBeUndefined(); const exportSchema = currentDocument?.export(1); expect(getIdsFromSchema(exportSchema).length).toBe(expectedNodeCnt); nodesMap.forEach(node => { // 触发 getter node.settingEntry; }); expect(mockCreateSettingEntry).toBeCalledTimes(expectedNodeCnt); }); it('基本的节点模型初始化,节点深度', () => { expect(project).toBeTruthy(); const { currentDocument } = project; const getNode = currentDocument.getNode.bind(currentDocument); const pageNode = getNode('page'); const rootHeaderNode = getNode('node_k1ow3cba'); const rootContentNode = getNode('node_k1ow3cbb'); const rootFooterNode = getNode('node_k1ow3cbc'); const formNode = getNode('form'); const cardNode = getNode('node_k1ow3cbj'); const cardContentNode = getNode('node_k1ow3cbk'); const columnsLayoutNode = getNode('node_k1ow3cbw'); const columnNode = getNode('node_k1ow3cbx'); const textFieldNode = getNode('node_k1ow3cbz'); expect(pageNode?.zLevel).toBe(0); expect(rootHeaderNode?.zLevel).toBe(1); expect(rootContentNode?.zLevel).toBe(1); expect(rootFooterNode?.zLevel).toBe(1); expect(formNode?.zLevel).toBe(2); expect(cardNode?.zLevel).toBe(3); expect(cardContentNode?.zLevel).toBe(4); expect(columnsLayoutNode?.zLevel).toBe(5); expect(columnNode?.zLevel).toBe(6); expect(textFieldNode?.zLevel).toBe(7); expect(textFieldNode?.getZLevelTop(7)).toEqual(textFieldNode); expect(textFieldNode?.getZLevelTop(6)).toEqual(columnNode); expect(textFieldNode?.getZLevelTop(5)).toEqual(columnsLayoutNode); expect(textFieldNode?.getZLevelTop(4)).toEqual(cardContentNode); expect(textFieldNode?.getZLevelTop(3)).toEqual(cardNode); expect(textFieldNode?.getZLevelTop(2)).toEqual(formNode); expect(textFieldNode?.getZLevelTop(1)).toEqual(rootContentNode); expect(textFieldNode?.getZLevelTop(0)).toEqual(pageNode); // 异常情况 expect(textFieldNode?.getZLevelTop(8)).toBeNull(); expect(textFieldNode?.getZLevelTop(-1)).toBeNull(); }); it('基本的节点模型初始化,节点父子、兄弟相关方法', () => { expect(project).toBeTruthy(); const { currentDocument } = project; const getNode = currentDocument.getNode.bind(currentDocument); const pageNode = getNode('page'); const rootHeaderNode = getNode('node_k1ow3cba'); const rootContentNode = getNode('node_k1ow3cbb'); const rootFooterNode = getNode('node_k1ow3cbc'); const formNode = getNode('form'); const cardNode = getNode('node_k1ow3cbj'); const cardContentNode = getNode('node_k1ow3cbk'); const columnsLayoutNode = getNode('node_k1ow3cbw'); const columnNode = getNode('node_k1ow3cbx'); const textFieldNode = getNode('node_k1ow3cbz'); expect(pageNode?.index).toBe(-1); expect(pageNode?.children.toString()).toBe('[object Array]'); expect(pageNode?.children?.get(1)).toBe(rootContentNode); expect(pageNode?.getChildren()?.get(1)).toBe(rootContentNode); expect(pageNode?.getNode()).toBe(pageNode); expect(rootFooterNode?.index).toBe(2); expect(textFieldNode?.getParent()).toBe(columnNode); expect(columnNode?.getParent()).toBe(columnsLayoutNode); expect(columnsLayoutNode?.getParent()).toBe(cardContentNode); expect(cardContentNode?.getParent()).toBe(cardNode); expect(cardNode?.getParent()).toBe(formNode); expect(formNode?.getParent()).toBe(rootContentNode); expect(rootContentNode?.getParent()).toBe(pageNode); expect(rootContentNode?.prevSibling).toBe(rootHeaderNode); expect(rootContentNode?.nextSibling).toBe(rootFooterNode); expect(pageNode?.isRoot()).toBe(true); expect(pageNode?.contains(textFieldNode)).toBe(true); expect(textFieldNode?.getRoot()).toBe(pageNode); expect(columnNode?.getRoot()).toBe(pageNode); expect(columnsLayoutNode?.getRoot()).toBe(pageNode); expect(cardContentNode?.getRoot()).toBe(pageNode); expect(cardNode?.getRoot()).toBe(pageNode); expect(formNode?.getRoot()).toBe(pageNode); expect(rootContentNode?.getRoot()).toBe(pageNode); }); it('基本的节点模型初始化,节点新建、删除等事件', () => { expect(project).toBeTruthy(); const { currentDocument } = project; const getNode = currentDocument.getNode.bind(currentDocument); const createNode = currentDocument.createNode.bind(currentDocument); const pageNode = getNode('page'); const nodeCreateHandler = jest.fn(); const offCreate = currentDocument?.onNodeCreate(nodeCreateHandler); const node = createNode({ componentName: 'TextInput', props: { propA: 'haha', }, }); currentDocument?.insertNode(pageNode, node); expect(nodeCreateHandler).toHaveBeenCalledTimes(1); expect(nodeCreateHandler.mock.calls[0][0]).toBe(node); expect(nodeCreateHandler.mock.calls[0][0].componentName).toBe('TextInput'); expect(nodeCreateHandler.mock.calls[0][0].getPropValue('propA')).toBe('haha'); const nodeDestroyHandler = jest.fn(); const offDestroy = currentDocument?.onNodeDestroy(nodeDestroyHandler); node.remove(); expect(nodeDestroyHandler).toHaveBeenCalledTimes(1); expect(nodeDestroyHandler.mock.calls[0][0]).toBe(node); expect(nodeDestroyHandler.mock.calls[0][0].componentName).toBe('TextInput'); expect(nodeDestroyHandler.mock.calls[0][0].getPropValue('propA')).toBe('haha'); offCreate(); offDestroy(); }); it.skip('基本的节点模型初始化,节点插入等方法', () => { expect(project).toBeTruthy(); const { currentDocument } = project; const getNode = currentDocument.getNode.bind(currentDocument); const formNode = getNode('form'); const node1 = currentDocument.createNode({ componentName: 'TextInput', props: { propA: 'haha', }, }); const node2 = currentDocument.createNode({ componentName: 'TextInput', props: { propA: 'heihei', }, }); const node3 = currentDocument.createNode({ componentName: 'TextInput', props: { propA: 'heihei2', }, }); const node4 = currentDocument.createNode({ componentName: 'TextInput', props: { propA: 'heihei3', }, }); formNode?.insertBefore(node2); // formNode?.insertBefore(node1, node2); // formNode?.insertAfter(node3); // formNode?.insertAfter(node4, node3); expect(formNode?.children?.get(0)).toBe(node1); expect(formNode?.children?.get(1)).toBe(node2); // expect(formNode?.children?.get(5)).toBe(node3); // expect(formNode?.children?.get(6)).toBe(node4); }); it('基本的节点模型初始化,节点其他方法', () => { expect(project).toBeTruthy(); const { currentDocument } = project; const getNode = currentDocument.getNode.bind(currentDocument); const pageNode = getNode('page'); expect(pageNode?.isPage()).toBe(true); expect(pageNode?.isComponent()).toBe(false); expect(pageNode?.isSlot()).toBe(false); expect(pageNode?.title).toBe('hey, i\' a page!'); }); describe('节点新增(insertNode)', () => { let project: Project; beforeEach(() => { project = new Project(designer, { componentsTree: [ formSchema, ], }); project.open(); }); it('场景一:插入 NodeSchema,不指定 index', () => { expect(project).toBeTruthy(); const ids = getIdsFromSchema(formSchema); const { currentDocument } = project; const { nodesMap } = currentDocument; const formNode = nodesMap.get('form') as Node; const formNode2 = currentDocument?.getNode('form'); expect(formNode).toEqual(formNode2); currentDocument?.insertNode(formNode, { componentName: 'TextInput', id: 'nodeschema-id1', props: { propA: 'haha', propB: 3, }, }); expect(nodesMap.size).toBe(ids.length + 1); expect(formNode.children?.length).toBe(4); const insertedNode = formNode.children.get(formNode.children.length - 1); expect(insertedNode.componentName).toBe('TextInput'); expect(insertedNode.propsData).toEqual({ propA: 'haha', propB: 3, }); // TODO: 把 checkId 的 commit pick 过来 // expect(nodesMap.get('nodeschema-id1').componentName).toBe('TextInput'); }); it('场景一:插入 NodeSchema,指定 index: 0', () => { expect(project).toBeTruthy(); const ids = getIdsFromSchema(formSchema); const { currentDocument } = project; const { nodesMap } = currentDocument; const formNode = nodesMap.get('form'); currentDocument?.insertNode(formNode, { componentName: 'TextInput', id: 'nodeschema-id1', props: { propA: 'haha', propB: 3, }, }, 0); expect(nodesMap.size).toBe(ids.length + 1); expect(formNode.children.length).toBe(4); const insertedNode = formNode.children.get(0); expect(insertedNode.componentName).toBe('TextInput'); expect(insertedNode.propsData).toEqual({ propA: 'haha', propB: 3, }); // TODO: 把 checkId 的 commit pick 过来 // expect(nodesMap.get('nodeschema-id1').componentName).toBe('TextInput'); }); it('场景一:插入 NodeSchema,指定 index: 1', () => { expect(project).toBeTruthy(); const ids = getIdsFromSchema(formSchema); const { currentDocument } = project; const { nodesMap } = currentDocument; const formNode = nodesMap.get('form'); currentDocument?.insertNode(formNode, { componentName: 'TextInput', id: 'nodeschema-id1', props: { propA: 'haha', propB: 3, }, }, 1); expect(nodesMap.size).toBe(ids.length + 1); expect(formNode.children.length).toBe(4); const insertedNode = formNode.children.get(1); expect(insertedNode.componentName).toBe('TextInput'); expect(insertedNode.propsData).toEqual({ propA: 'haha', propB: 3, }); // TODO: 把 checkId 的 commit pick 过来 // expect(nodesMap.get('nodeschema-id1').componentName).toBe('TextInput'); }); it('场景一:插入 NodeSchema,有 children', () => { expect(project).toBeTruthy(); const ids = getIdsFromSchema(formSchema); const { currentDocument } = project; const { nodesMap } = currentDocument; const formNode = nodesMap.get('form') as Node; currentDocument?.insertNode(formNode, { componentName: 'ParentNode', props: { propA: 'haha', propB: 3, }, children: [ { componentName: 'SubNode', props: { propA: 'haha', propB: 3, }, }, { componentName: 'SubNode2', props: { propA: 'haha', propB: 3, }, }, ], }); expect(nodesMap.size).toBe(ids.length + 3); expect(formNode.children.length).toBe(4); expect(formNode.children?.get(3)?.componentName).toBe('ParentNode'); expect(formNode.children?.get(3)?.children?.get(0)?.componentName).toBe('SubNode'); expect(formNode.children?.get(3)?.children?.get(1)?.componentName).toBe('SubNode2'); }); it.skip('场景一:插入 NodeSchema,id 与现有 schema 里的 id 重复', () => { expect(project).toBeTruthy(); const ids = getIdsFromSchema(formSchema); const { currentDocument } = project; const { nodesMap } = currentDocument; const formNode = nodesMap.get('form'); currentDocument?.insertNode(formNode, { componentName: 'TextInput', id: 'nodeschema-id1', props: { propA: 'haha', propB: 3, }, }); expect(nodesMap.get('nodeschema-id1').componentName).toBe('TextInput'); expect(nodesMap.size).toBe(ids.length + 1); }); it.skip('场景一:插入 NodeSchema,id 与现有 schema 里的 id 重复,但关闭了 id 检测器', () => { expect(project).toBeTruthy(); const ids = getIdsFromSchema(formSchema); const { currentDocument } = project; const { nodesMap } = currentDocument; const formNode = nodesMap.get('form'); currentDocument?.insertNode(formNode, { componentName: 'TextInput', id: 'nodeschema-id1', props: { propA: 'haha', propB: 3, }, }); expect(nodesMap.get('nodeschema-id1').componentName).toBe('TextInput'); expect(nodesMap.size).toBe(ids.length + 1); }); it('场景二:插入 Node 实例', () => { expect(project).toBeTruthy(); const ids = getIdsFromSchema(formSchema); const { currentDocument } = project; const { nodesMap } = currentDocument; const formNode = nodesMap.get('form'); const inputNode = currentDocument?.createNode({ componentName: 'TextInput', id: 'nodeschema-id2', props: { propA: 'haha', propB: 3, }, }); currentDocument?.insertNode(formNode, inputNode); expect(formNode.children?.get(3)?.componentName).toBe('TextInput'); expect(nodesMap.size).toBe(ids.length + 1); }); it('场景三:插入 JSExpression', () => { expect(project).toBeTruthy(); const ids = getIdsFromSchema(formSchema); const { currentDocument } = project; const { nodesMap } = currentDocument; const formNode = nodesMap.get('form') as Node; currentDocument?.insertNode(formNode, { type: 'JSExpression', value: 'just a expression', }); expect(nodesMap.size).toBe(ids.length + 1); expect(formNode.children?.get(3)?.componentName).toBe('Leaf'); // expect(formNode.children?.get(3)?.children).toEqual({ // type: 'JSExpression', // value: 'just a expression' // }); }); it('场景四:插入 string', () => { expect(project).toBeTruthy(); const ids = getIdsFromSchema(formSchema); const { currentDocument } = project; const { nodesMap } = currentDocument; const formNode = nodesMap.get('form') as Node; currentDocument?.insertNode(formNode, 'just a string'); expect(nodesMap.size).toBe(ids.length + 1); expect(formNode.children?.get(3)?.componentName).toBe('Leaf'); // expect(formNode.children?.get(3)?.children).toBe('just a string'); }); }); describe('节点新增(insertNodes)', () => { let project: Project; beforeEach(() => { project = new Project(designer, { componentsTree: [ formSchema, ], }); project.open(); }); it('场景一:插入 NodeSchema,指定 index', () => { expect(project).toBeTruthy(); const ids = getIdsFromSchema(formSchema); const { currentDocument } = project; const { nodesMap } = currentDocument; const formNode = nodesMap.get('form') as Node; const formNode2 = currentDocument?.getNode('form'); expect(formNode).toEqual(formNode2); currentDocument?.insertNodes(formNode, [ { componentName: 'TextInput', props: { propA: 'haha2', propB: 3, }, }, { componentName: 'TextInput2', props: { propA: 'haha', propB: 3, }, }, ], 1); expect(nodesMap.size).toBe(ids.length + 2); expect(formNode.children?.length).toBe(5); const insertedNode1 = formNode.children.get(1); const insertedNode2 = formNode.children.get(2); expect(insertedNode1.componentName).toBe('TextInput'); expect(insertedNode1.propsData).toEqual({ propA: 'haha2', propB: 3, }); expect(insertedNode2.componentName).toBe('TextInput2'); expect(insertedNode2.propsData).toEqual({ propA: 'haha', propB: 3, }); }); it('场景二:插入 Node 实例,指定 index', () => { expect(project).toBeTruthy(); const ids = getIdsFromSchema(formSchema); const { currentDocument } = project; const { nodesMap } = currentDocument; const formNode = nodesMap.get('form') as Node; const formNode2 = currentDocument?.getNode('form'); expect(formNode).toEqual(formNode2); const createdNode1 = currentDocument?.createNode({ componentName: 'TextInput', props: { propA: 'haha2', propB: 3, }, }); const createdNode2 = currentDocument?.createNode({ componentName: 'TextInput2', props: { propA: 'haha', propB: 3, }, }); currentDocument?.insertNodes(formNode, [createdNode1, createdNode2], 1); expect(nodesMap.size).toBe(ids.length + 2); expect(formNode.children?.length).toBe(5); const insertedNode1 = formNode.children.get(1); const insertedNode2 = formNode.children.get(2); expect(insertedNode1.componentName).toBe('TextInput'); expect(insertedNode1.propsData).toEqual({ propA: 'haha2', propB: 3, }); expect(insertedNode2.componentName).toBe('TextInput2'); expect(insertedNode2.propsData).toEqual({ propA: 'haha', propB: 3, }); }); }); }); describe('block ❌ | component ❌ | slot ✅', () => { it('基本的 slot 创建', () => { const formSchemaWithSlot = set(cloneDeep(formSchema), 'children[0].children[0].props.title.type', 'JSSlot'); const project = new Project(designer, { componentsTree: [ formSchemaWithSlot, ], }); project.open(); expect(project).toBeTruthy(); const { currentDocument } = project; const { nodesMap } = currentDocument; const ids = getIdsFromSchema(formSchema); // 目前每个 slot 会新增(1 + children.length)个节点 const expectedNodeCnt = ids.length + 2; expect(nodesMap.size).toBe(expectedNodeCnt); // PageHeader expect(nodesMap.get('node_k1ow3cbd').slots).toHaveLength(1); }); }); });
the_stack
import { version as v } from "../package.json"; const version: string = v; import languageJson from "./tag_language.json"; import extlangJson from "./tag_extlang.json"; import grandfatheredJson from "./tag_grandfathered.json"; // import redundant from "./tag_redundant.json"; import regionJson from "./tag_region.json"; import scriptJson from "./tag_script.json"; import variantJson from "./tag_variant.json"; // import ranged from "./tag_ranged.json"; const language: (string | RegExp)[] = languageJson; const extlang: string[] = extlangJson; const grandfathered: string[] = grandfatheredJson; const region: (string | RegExp)[] = regionJson; const script: (string | RegExp)[] = scriptJson; const variant: string[] = variantJson; function isRegExp(something: any): boolean { return something instanceof RegExp; } // Array.prototype.includes() beefed up to support regexp too function includes(arr: string[] | any, whatToMatch: string | RegExp) { if (!Array.isArray(arr) || !arr.length) { return false; } return arr.some( (val) => (isRegExp(val) && (whatToMatch as string).match(val)) || (typeof val === "string" && whatToMatch === val) ); } interface Res { res: boolean; message: string | null; } function isLangCode(str: string): Res { if (typeof str !== "string") { return { res: false, message: `Not a string given.`, }; } if (!str.trim()) { return { res: false, message: `Empty language tag string given.`, }; } // https://www.ietf.org/rfc/rfc1766.txt // https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry // --------------------------------------------------------------------------- // r1. very rough regex to ensure letters are separated with dashes, in chunks // of up to eight characters const r1 = /^[a-z0-9]{1,8}(-[a-z0-9]{1,8})*$/gi; // r2. subtags qaa..qtz - "language" subtag const r2 = /^q[a-t][a-z]$/gi; language.push(r2); // r3. subtags Qaaa..Qabx - "script" subtag const r3 = /^qa[a-b][a-x]$/gi; script.push(r3); // r4. subtags qm..qz - "region" subtag const r4 = /^q[m-z]$/gi; region.push(r4); // r5. subtags xa..xz - "region" subtag const r5 = /^x[a-z]$/gi; region.push(r5); // 6. singleton const singletonRegex = /^[0-9a-wy-z]$/gi; // the "x" is reserved for private use, that is, singletons can't be "...-x-..." // AA and ZZ // --------------------------------------------------------------------------- // preliminary validation using R1 - if chunks are not letters/numbers, // separated with dashes, its' an instant "false" if (!str.match(r1)) { console.log( `091 isLangCode(): ${`\u001b[${31}m${`R1`}\u001b[${39}m`} failed` ); return { res: false, message: `Does not resemble a language tag.` }; } // grandfathered tags are evaluated as whole if (includes(grandfathered, str)) { console.log( `099 ${`\u001b[${32}m${`MATCHED`}\u001b[${39}m`} grandfathered tag` ); return { res: true, message: null }; } // if by now program is still going, value is process-able: // language tags are case-insensitive, "there exist // conventions for the capitalization of some of the subtags, but these // MUST NOT be taken to carry meaning" (https://tools.ietf.org/html/rfc5646) const split = str.toLowerCase().split("-"); console.log( `110 isLangCode(): ${`\u001b[${32}m${`THE SPLIT`}\u001b[${39}m`} ${`\u001b[${33}m${`split`}\u001b[${39}m`} = ${JSON.stringify( split, null, 4 )}` ); let type; // private|normal - used as a "global" marker among rules, when iterating // will help to enforce the sequence: let languageMatched: string | undefined; let scriptMatched: string | undefined; let regionMatched: string | undefined; let variantMatched: string | undefined; let extlangMatched: string | undefined; // the plan: we split by dash ("-") and get array. We iterate it and each // time variable "ok" is set to "true" by some logic rules OR if end of // an item is reached, function returns failure result. let allOK; // track repeated variant subtags const variantGathered: string[] = []; const singletonGathered: string[] = []; // iterate through every chunk: console.log("isLangCode() loop"); for (let i = 0, len = split.length; i < len; i++) { // // // // // // // // // // // TOP CLAUSES // // // // // // // // // // // frontal logging console.log( `${`\u001b[${36}m${`------------------------------------`}\u001b[${39}m`} split[${`\u001b[${35}m${i}\u001b[${39}m`}] = ${`\u001b[${35}m${ split[i] }\u001b[${39}m`} ${`\u001b[${36}m${`------------------------------------`}\u001b[${39}m`}` ); // on each iteration, reset allOK allOK = false; // if it stays false to the end of all the processing of this // iteration, it means this chunk was not validated and whole // result will be "false" // set type if (i === 0) { type = split[0] === "x" ? "private" : "normal"; } if (split[i] === "x") { if (!split[i + 1]) { console.log(`180 ${`\u001b[${31}m${`RETURN`}\u001b[${39}m`} false`); return { res: false, message: `Ends with private use subtag, "x".`, }; } console.log( `188 PRIVATE SUBTAG DETECTED, skipping checks for subsequent subtags` ); console.log(`190 ${`\u001b[${32}m${`RETURN`}\u001b[${39}m`} true`); // TODO - add more logic return { res: true, message: null }; } // catch multiple recognised region tags if (regionMatched && region.includes(split[i])) { console.log(`197 multiple recognised region subtags`); console.log(`198 ${`\u001b[${31}m${`RETURN`}\u001b[${39}m`} false`); return { res: false, message: `Two region subtags, "${regionMatched}" and "${split[i]}".`, }; } // // // // // // // // // // // MIDDLE CLAUSES // // // // // // // // // // // validate the first element if (i === 0) { console.log(`229 isLangCode(): first element, LANGUAGE, clauses`); console.log( `232 isLangCode(): ${`\u001b[${33}m${`split[0]`}\u001b[${39}m`} = ${JSON.stringify( split[0], null, 4 )}` ); if (type === "normal") { // validate if (includes(language, split[i])) { console.log( `243 ${`\u001b[${32}m${`MATCHED`}\u001b[${39}m`} ${`\u001b[${36}m${`language`}\u001b[${39}m`} subtag` ); languageMatched = split[i]; console.log( `248 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`languageMatched`}\u001b[${39}m`} = ${languageMatched}` ); allOK = true; console.log( `253 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`allOK`}\u001b[${39}m`} = ${allOK}` ); } else { console.log( `257 ${`\u001b[${31}m${`language subtag not recognised`}\u001b[${39}m`} - ${`\u001b[${31}m${`allOK not set`}\u001b[${39}m`}` ); } } } else if (i === 1) { console.log( `263 isLangCode(): second element, either EXTENSION or SCRIPT, clauses` ); // validate if (type === "normal") { if (includes(script, split[i])) { console.log( `269 ${`\u001b[${32}m${`MATCHED`}\u001b[${39}m`} ${`\u001b[${36}m${`script`}\u001b[${39}m`} subtag` ); scriptMatched = split[i]; console.log( `274 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`scriptMatched`}\u001b[${39}m`} = ${scriptMatched}` ); allOK = true; console.log( `279 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`allOK`}\u001b[${39}m`} = ${allOK}` ); } else if (includes(extlang, split[i])) { console.log( `283 ${`\u001b[${32}m${`MATCHED`}\u001b[${39}m`} ${`\u001b[${36}m${`extlang`}\u001b[${39}m`} subtag` ); extlangMatched = split[i]; console.log( `288 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`extlangMatched`}\u001b[${39}m`} = ${extlangMatched}` ); allOK = true; console.log( `293 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`allOK`}\u001b[${39}m`} = ${allOK}` ); } else if (includes(region, split[i])) { console.log( `297 ${`\u001b[${32}m${`MATCHED`}\u001b[${39}m`} ${`\u001b[${36}m${`region`}\u001b[${39}m`} subtag` ); regionMatched = split[i]; console.log( `302 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`regionMatched`}\u001b[${39}m`} = ${regionMatched}` ); allOK = true; console.log( `307 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`allOK`}\u001b[${39}m`} = ${allOK}` ); } else if (includes(variant, split[i])) { console.log( `311 ${`\u001b[${32}m${`MATCHED`}\u001b[${39}m`} ${`\u001b[${36}m${`variant`}\u001b[${39}m`} subtag` ); variantMatched = split[i]; console.log( `316 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`variantMatched`}\u001b[${39}m`} = ${variantMatched}` ); allOK = true; console.log( `321 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`allOK`}\u001b[${39}m`} = ${allOK}` ); if (!variantGathered.includes(split[i])) { variantGathered.push(split[i]); } else { console.log(`327 ERROR! Repeated variant!`); console.log(`328 ${`\u001b[${31}m${`RETURN`}\u001b[${39}m`} false`); return { res: false, message: `Repeated variant subtag, "${split[i]}".`, }; } } else { // neither extlang nor script console.log( `337 ${`\u001b[${31}m${`script subtag not recognised`}\u001b[${39}m`}` ); } } // } else if (i === 2) { if (type === "normal") { // at position 3, it's either: // * script (language-extlang-script-region) // * region (language-script-region) // * variant (language-region-variant) // * region (language-extlang-region) if (languageMatched && extlangMatched) { // similar to language-extlang-script-region console.log(`351 inside language + extlang matched`); // match script if (includes(script, split[i])) { console.log( `356 ${`\u001b[${32}m${`MATCHED`}\u001b[${39}m`} ${`\u001b[${36}m${`script`}\u001b[${39}m`} subtag` ); scriptMatched = split[i]; console.log( `361 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`scriptMatched`}\u001b[${39}m`} = ${scriptMatched}` ); allOK = true; console.log( `366 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`allOK`}\u001b[${39}m`} = ${allOK}` ); } else if (includes(region, split[i])) { // language-extlang-region // match region console.log( `372 ${`\u001b[${32}m${`MATCHED`}\u001b[${39}m`} ${`\u001b[${36}m${`region`}\u001b[${39}m`} subtag` ); regionMatched = split[i]; console.log( `377 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`regionMatched`}\u001b[${39}m`} = ${regionMatched}` ); allOK = true; console.log( `382 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`allOK`}\u001b[${39}m`} = ${allOK}` ); } } else if (languageMatched && scriptMatched) { // similar to language-script-region console.log(`387 inside language + script matched`); // match region if (includes(region, split[i])) { console.log( `392 ${`\u001b[${32}m${`MATCHED`}\u001b[${39}m`} ${`\u001b[${36}m${`region`}\u001b[${39}m`} subtag` ); regionMatched = split[i]; console.log( `397 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`regionMatched`}\u001b[${39}m`} = ${regionMatched}` ); allOK = true; console.log( `402 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`allOK`}\u001b[${39}m`} = ${allOK}` ); } } else if (languageMatched && regionMatched) { // language-region-variant console.log(`407 inside language + region matched`); // similar to de-CH-1901 or ca-ES-VALENCIA // match variant if (includes(variant, split[i])) { console.log( `414 ${`\u001b[${32}m${`MATCHED`}\u001b[${39}m`} ${`\u001b[${36}m${`variant`}\u001b[${39}m`} subtag` ); variantMatched = split[i]; console.log( `419 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`variantMatched`}\u001b[${39}m`} = ${variantMatched}` ); allOK = true; console.log( `424 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`allOK`}\u001b[${39}m`} = ${allOK}` ); if (!variantGathered.includes(split[i])) { variantGathered.push(split[i]); } else { console.log(`430 ERROR! Repeated variant!`); console.log( `432 ${`\u001b[${31}m${`RETURN`}\u001b[${39}m`} false` ); return { res: false, message: `Repeated variant subtag, "${split[i]}".`, }; } } } } } else if (i === 3) { if (type === "normal") { // at position 4, it's either: // * region (language-extlang-script-region) // * variant (language-script-region-variant) if (languageMatched && extlangMatched && scriptMatched) { // match region if (includes(region, split[i])) { console.log( `451 ${`\u001b[${32}m${`MATCHED`}\u001b[${39}m`} ${`\u001b[${36}m${`region`}\u001b[${39}m`} subtag` ); regionMatched = split[i]; console.log( `456 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`regionMatched`}\u001b[${39}m`} = ${regionMatched}` ); allOK = true; console.log( `461 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`allOK`}\u001b[${39}m`} = ${allOK}` ); } } else if (languageMatched && scriptMatched && regionMatched) { // match variant if (includes(variant, split[i])) { console.log( `468 ${`\u001b[${32}m${`MATCHED`}\u001b[${39}m`} ${`\u001b[${36}m${`variant`}\u001b[${39}m`} subtag` ); variantMatched = split[i]; console.log( `473 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`variantMatched`}\u001b[${39}m`} = ${variantMatched}` ); allOK = true; console.log( `478 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`allOK`}\u001b[${39}m`} = ${allOK}` ); } } } } console.log(`485 non-positional clauses`); // // // // // NON-POSITIONAL CLAUSES // // // // // catch the singleton-extension if (split[i].match(singletonRegex)) { if (i === 0) { console.log(`500 starts with singleton!`); return { res: false, message: `Starts with singleton, "${split[i]}".`, }; } // ELSE - continue the checks console.log(`507 continue checks`); if (!languageMatched) { console.log(`509 ${`\u001b[${31}m${`RETURN`}\u001b[${39}m`} false`); return { res: false, message: `Extension must follow at least a primary language subtag.`, }; } if (!singletonGathered.includes(split[i])) { console.log(`516 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`} ${split[i]}`); singletonGathered.push(split[i]); console.log( `519 ${`\u001b[${32}m${`NOW`}\u001b[${39}m`} ${`\u001b[${33}m${`singletonGathered`}\u001b[${39}m`} = ${JSON.stringify( singletonGathered, null, 4 )}` ); } else { console.log(`526 ${`\u001b[${31}m${`RETURN`}\u001b[${39}m`} false`); return { res: false, message: `Two extensions with same single-letter prefix "${split[i]}".`, }; } if (split[i + 1]) { console.log(`534`); console.log( `536 split[i + 1].match(singletonRegex) = ${split[i + 1].match( singletonRegex )}` ); if (!split[i + 1].match(singletonRegex)) { allOK = true; extlangMatched = split[i]; console.log( `544 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`allOK`}\u001b[${39}m`} = ${allOK}; ${`\u001b[${33}m${`extlangMatched`}\u001b[${39}m`} = ${extlangMatched}` ); i += 1; console.log(`547 SET i++, now i = ${i}; then CONTINUE`); continue; } else { console.log(`550 singleton sequence caught`); console.log(`551 ${`\u001b[${31}m${`RETURN`}\u001b[${39}m`} false`); return { res: false, message: `Multiple singleton sequence "${split[i]}", "${ split[i + 1] }".`, }; } } else { console.log(`560 ${`\u001b[${31}m${`RETURN`}\u001b[${39}m`} false`); return { res: false, message: `Ends with singleton, "${split[i]}".`, }; } } // catch the sequence of variant chunks if (!allOK && variantMatched && includes(variant, split[i])) { console.log( `571 ${`\u001b[${32}m${`MATCHED`}\u001b[${39}m`} ${`\u001b[${36}m${`variant`}\u001b[${39}m`} subtag` ); if (i && includes(variant, split[i - 1])) { console.log(`575 variant subtag in front of this confirmed`); if (!variantGathered.includes(split[i])) { variantGathered.push(split[i]); } else { console.log(`580 ERROR! Repeated variant!`); console.log(`581 ${`\u001b[${31}m${`RETURN`}\u001b[${39}m`} false`); return { res: false, message: `Repeated variant subtag, "${split[i]}".`, }; } allOK = true; console.log( `590 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`allOK`}\u001b[${39}m`} = ${allOK}` ); } else { console.log( `594 ${`\u001b[${31}m${`multiple variant subtags must be consecutive!`}\u001b[${39}m`}` ); variantGathered.push(split[i]); console.log(`597 ${`\u001b[${31}m${`RETURN`}\u001b[${39}m`} false`); return { res: false, message: `Variant subtags ${variantGathered .map((val) => `"${val}"`) .join(", ")} not in a sequence.`, }; } } // catch repeated subtags if (!allOK && languageMatched && extlangMatched) { if (split[i].length > 1) { console.log( `611 ${`\u001b[${32}m${`SET`}\u001b[${39}m`} ${`\u001b[${33}m${`allOK`}\u001b[${39}m`} = ${allOK}` ); allOK = true; } } console.log(`617`); // // // // // // // // // // // BOTTOM CLAUSES // // // // // // // // // // if (!allOK) { console.log(`642 bottom reached, ${split[i]} was not matched!`); console.log(`643 ${`\u001b[${31}m${`RETURN`}\u001b[${39}m`} false`); return { res: false, message: `Unrecognised language subtag, "${split[i]}".`, }; } // logging console.log(`${`\u001b[${90}m${`██`}\u001b[${39}m`}`); console.log( `${`\u001b[${90}m${`languageMatched =`}\u001b[${39}m`} ${`\u001b[${ languageMatched ? 32 : 31 }m${languageMatched}\u001b[${39}m`}` ); console.log( `${`\u001b[${90}m${`scriptMatched =`}\u001b[${39}m`} ${`\u001b[${ scriptMatched ? 32 : 31 }m${scriptMatched}\u001b[${39}m`}` ); console.log( `${`\u001b[${90}m${`regionMatched =`}\u001b[${39}m`} ${`\u001b[${ regionMatched ? 32 : 31 }m${regionMatched}\u001b[${39}m`}` ); console.log( `${`\u001b[${90}m${`variantMatched =`}\u001b[${39}m`} ${`\u001b[${ variantMatched ? 32 : 31 }m${variantMatched}\u001b[${39}m`}` ); console.log( `${`\u001b[${90}m${`extlangMatched =`}\u001b[${39}m`} ${`\u001b[${ extlangMatched ? 32 : 31 }m${extlangMatched}\u001b[${39}m`}` ); console.log(`${`\u001b[${90}m${`-`}\u001b[${39}m`}`); console.log( `${`\u001b[${90}m${`variantGathered = ${JSON.stringify( variantGathered, null, 4 )}`}\u001b[${39}m`} ` ); } console.log(`687 end reached`); // --------------------------------------------------------------------------- // default answer is true, but we'll make // hell of a check obstacles to reach this point console.log(`694 ${`\u001b[${32}m${`RETURN`}\u001b[${39}m`} true`); return { res: true, message: null }; } export { isLangCode, version };
the_stack
import { signer, } from './signer'; import { readArrayPrefix, readIntoArray, teeResponse, } from './streams'; import { arrayBufferToBase64, } from './utils'; import { WasmResponse, workerPromise, WasmRequest, } from './wasmFunctions'; addEventListener('fetch', (event) => { event.respondWith(handleRequest(event.request)) }) function responseFromWasm(data: WasmResponse): Response { return new Response( new Uint8Array(data.body), { status: data.status, headers: data.headers, }, ); } async function wasmFromResponse(response: Response): Promise<WasmResponse> { return { body: Array.from(new Uint8Array(await response.arrayBuffer())), headers: Array.from(response.headers), status: response.status, }; } // Fetches latest OCSP from the CA, and writes it into key-value store. // The outgoing traffic to the CA is throttled; when this function is called // concurrently, the first fetched OCSP will be reused to be returned to all // callers. const fetchOcspFromCa = (() => { // The un-throttled implementation to fetch OCSP async function fetchOcspFromCaImpl() { let worker = await workerPromise; const ocspDer = await worker.fetchOcspFromCa(fetcher); const ocspBase64 = arrayBufferToBase64(ocspDer); const now = Date.now() / 1000; OCSP.put( /*key=*/'ocsp', /*value=*/JSON.stringify({ expirationTime: now + 3600 * 24 * 6, nextFetchTime: now + 3600 * 24, ocspBase64, }), { expirationTtl: 3600 * 24 * 6, // in seconds }, ); return ocspBase64; } let singletonTask: Promise<string> | null = null; return async function() { if (singletonTask !== null) { return await singletonTask; } else { singletonTask = fetchOcspFromCaImpl(); const result = await singletonTask; singletonTask = null; return result; } }; })(); async function getOcsp() { const ocspInCache = await OCSP.get('ocsp'); if (ocspInCache) { const { expirationTime, nextFetchTime, ocspBase64, } = JSON.parse(ocspInCache); const now = Date.now() / 1000; if (now >= expirationTime) { return await fetchOcspFromCa(); } if (now >= nextFetchTime) { // Spawns a non-blocking task to update latest OCSP in store fetchOcspFromCa(); } return ocspBase64; } else { return await fetchOcspFromCa(); } } // Returns the proper fallbackUrl and certOrigin. fallbackUrl should be // https://my_domain.com in all environments, and certOrigin should be the // origin of the worker (localhost, foo.bar.workers.dev, or my_domain.com). // // The request.url for each environment is as follows: // wrangler dev: https://my_domain.com/ // wrangler publish + workers_dev = true: https://sxg.user.workers.dev/ // wrangler publish + workers_dev = false: https://my_domain.com/ // // So gen-config tool sets HTML_HOST = my_domain.com when workers_dev is true. // // For wrangler dev, add CERT_ORIGIN = 'http://localhost:8787' to [vars] in // wrangler.toml. Afterwards, set it to '' for production. // // For preset content, replaceHost is false because the fallback is on the // worker origin, not the HTML_HOST. function fallbackUrlAndCertOrigin(url: string, replaceHost: boolean): [string, string] { let fallbackUrl = new URL(url); let certOrigin = typeof CERT_ORIGIN !== 'undefined' && CERT_ORIGIN ? CERT_ORIGIN : fallbackUrl.origin; if (replaceHost && typeof HTML_HOST !== 'undefined' && HTML_HOST) { fallbackUrl.host = HTML_HOST; } return [fallbackUrl.toString(), certOrigin]; } async function handleRequest(request: Request) { let worker = await workerPromise; let sxgPayload: Response | undefined; let fallback: Response | undefined; let response: Response | undefined; try { const ocsp = await getOcsp(); const presetContent = worker.servePresetContent(request.url, ocsp); let fallbackUrl: string; let certOrigin: string; if (presetContent) { if (presetContent.kind === 'direct') { return responseFromWasm(presetContent); } else { [fallbackUrl, certOrigin] = fallbackUrlAndCertOrigin(presetContent.url, false); fallback = responseFromWasm(presetContent.fallback); sxgPayload = responseFromWasm(presetContent.payload); // Although we are not sending any request to the backend, // we still need to check the validity of the request header. // For example, if the header does not contain // `Accept: signed-exchange;v=b3`, we will throw an error. worker.createRequestHeaders('AcceptsSxg', Array.from(request.headers)); } } else { [fallbackUrl, certOrigin] = fallbackUrlAndCertOrigin(request.url, true); const requestHeaders = worker.createRequestHeaders('PrefersSxg', Array.from(request.headers)); [sxgPayload, fallback] = teeResponse(await fetch( fallbackUrl, { headers: requestHeaders, } )); } sxgPayload = await processHTML(sxgPayload, [ new PromoteLinkTagsToHeaders, new SXGOnly(true), ]); response = await generateSxgResponse(fallbackUrl, certOrigin, sxgPayload); } catch (e: any) { sxgPayload?.body?.cancel(); if (!fallback) { // The error occurs before fetching from origin server, hence we need to // fetch now. Since we are not generating SXG anyway in this case, we // simply use all http headers from the user. fallback = await fetch(request); } let fallwayback; [fallback, fallwayback] = teeResponse(fallback); try { // If the body is HTML >8MB, processHTML will fail. fallback = await processHTML(fallback, [ new SXGOnly(false), ]); fallwayback.body?.cancel(); } catch { fallback.body?.cancel(); fallback = fallwayback; } if (worker.shouldRespondDebugInfo() && e.toString) { let message = e.toString(); return new Response( fallback.body, { status: fallback.status, headers: [ ...Array.from(fallback.headers || []), ['sxg-edge-worker-debug-info', message], ], }, ); } else { return fallback; } } fallback.body?.cancel(); return response; } // SXGs larger than 8MB are not accepted by // https://github.com/google/webpackager/blob/main/docs/cache_requirements.md. const PAYLOAD_SIZE_LIMIT = 8000000; // https://datatracker.ietf.org/doc/html/rfc7230#section-3.2.6 const TOKEN = /^[!#$%&'*+.^_`|~0-9a-zA-Z-]+$/; // Matcher for HTML with either UTF-8 or unspecified character encoding. // Capture group 1 indicates that charset=utf-8 was explicitly stated. // // https://datatracker.ietf.org/doc/html/rfc7231#section-3.1.1.5 // // The list of aliases for UTF-8 is codified in // https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/wtf/text/text_codec_utf8.cc;l=52-68;drc=984c3018ecb2ff818e900fdb7c743fc00caf7efe // and https://encoding.spec.whatwg.org/#concept-encoding-get. // These are not currently supported, but could be if desired. const HTML = /^text\/html([ \t]*;[ \t]*charset=(utf-8|"utf-8"))?$/i; interface HTMLProcessor { register(rewriter: HTMLRewriter): void; // Returns true iff the processor modified the HTML body. processHTML uses // the rewritten HTML body iff one of the processors returns true. modified: boolean; onEnd(payload: Response): void; } // If any <link rel=preload>s are found, they are promoted to Link headers. // Later, generateSxgResponse will further modify the link header to support // SXG preloading of eligible subresources. class PromoteLinkTagsToHeaders implements HTMLProcessor { modified: boolean = false; link_tags: {href: string, as: string}[] = []; register(rewriter: HTMLRewriter): void { rewriter.on('link[rel~="preload" i][href][as]', { element: (link: Element) => { const href = link.getAttribute('href'); const as = link.getAttribute('as'); // Ensure the values can be placed inside a Link header without // escaping or quoting. if (href && !href.includes('>') && as?.match(TOKEN)) { this.link_tags.push({href, as}); } }, }); } onEnd(payload: Response): void { if (this.link_tags.length) { const link = this.link_tags.map(({href, as}) => `<${href}>;rel=preload;as=${as}`).join(','); payload.headers.append('Link', link); } } } // Provides two syntaxes for SXG-only behavior: // // For `<template data-sxg-only>` elements: // - If SXG, they are "unwrapped" (i.e. their children promoted out of the <teplate>). // - Else, they are deleted. // // For `<meta name=declare-issxg-var>` elements, they are replaced with // `<script>window.isSXG=...</script>`, where `...` is true or false. class SXGOnly { isSXG: boolean; modified: boolean = false; constructor(isSXG: boolean) { this.isSXG = isSXG; } register(rewriter: HTMLRewriter): void { rewriter.on('script[data-issxg-var]', { element: (script: Element) => { script.setInnerContent(`window.isSXG=${this.isSXG}`); this.modified = true; }, }).on('template[data-sxg-only]', { element: (template: Element) => { if (this.isSXG) { template.removeAndKeepContent(); } else { template.remove(); } this.modified = true; }, }); } onEnd(_payload: Response): void { } } // Processes HTML using the given processors. // // Out of an abundance of caution, this is limited to documents that are // explicitly labeled as UTF-8 via Content-Type or <meta>. This could be // expanded in the future, as the risk of misinterpreting type or encoding is // rare and low-impact: producing `Link: rel=preload` headers for incorrect // refs, which would waste bytes. async function processHTML(payload: Response, processors: HTMLProcessor[]): Promise<Response> { if (!payload.body) { return payload; } let known_utf8 = false; // Only run HTMLRewriter if the content is HTML. const content_type_match = payload.headers.get('content-type')?.match(HTML); if (!content_type_match) { return payload; } if (content_type_match[1]) { known_utf8 = true; } // A temporary response. let toConsume; // Check for UTF-16 BOM, which overrides the <meta> tag, per the implementation at // https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/html/parser/text_resource_decoder.cc;l=394;drc=7a0b88f6d5c015fd3c280b58c7a99d8e1dca28ac // and the spec at // https://html.spec.whatwg.org/multipage/parsing.html#encoding-sniffing-algorithm. [payload, toConsume] = teeResponse(payload); const bom = await readArrayPrefix(toConsume.body, 2); if (bom && (bom[0] == 0xFE && bom[1] == 0xFF || bom[0] == 0xFF && bom[1] == 0xFE)) { // Somebody set up us the BOM. return payload; } // Tee the original payload to be sure that HTMLRewriter doesn't make any // breaking modifications to the HTML. This is especially likely if the // document is in a non-ASCII-compatible encoding like UTF-16. [payload, toConsume] = teeResponse(payload); let rewriter = new HTMLRewriter() // Parse the meta tag, per the implementation in HTMLMetaCharsetParser::CheckForMetaCharset: // https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/html/parser/html_meta_charset_parser.cc;l=62-125;drc=7a0b88f6d5c015fd3c280b58c7a99d8e1dca28ac. // This differs slightly from what's described at https://github.com/whatwg/html/issues/6962, and // differs drastically from what's specified in // https://html.spec.whatwg.org/multipage/parsing.html#prescan-a-byte-stream-to-determine-its-encoding. .on('meta', { element: (meta: Element) => { // EncodingFromMetaAttributes: // https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/html/parser/html_parser_idioms.cc;l=362-393;drc=7a0b88f6d5c015fd3c280b58c7a99d8e1dca28ac let value = meta.getAttribute('charset'); if (value) { if (value.toLowerCase() === 'utf-8') { known_utf8 = true; } } else if (meta.getAttribute('http-equiv')?.toLowerCase() === 'content-type' && meta.getAttribute('content')?.match(HTML)?.[1]) { // https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/html/parser/html_parser_idioms.cc;l=308-354;drc=984c3018ecb2ff818e900fdb7c743fc00caf7efe // https://html.spec.whatwg.org/multipage/urls-and-fetching.html#extracting-character-encodings-from-meta-elements // HTMLRewriter doesn't appear to decode HTML entities inside // attribute values, so a tag like // <meta http-equiv=content-type content="text/html;charset=&quot;utf-8&quot;"> // won't work. This could be supported in the future. known_utf8 = true; } }, }); processors.forEach((p) => p.register(rewriter)); toConsume = rewriter.transform(toConsume); const modifiedBody = await readIntoArray(toConsume.body, PAYLOAD_SIZE_LIMIT); if (!modifiedBody) { throw `The size of payload exceeds the limit ${PAYLOAD_SIZE_LIMIT}`; } // NOTE: It's also possible for a <?xml encoding="utf-16"?> directive to // override <meta>, per // https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/core/html/parser/text_resource_decoder.cc;l=427-441;drc=7a0b88f6d5c015fd3c280b58c7a99d8e1dca28ac. // (This differs from the specification, which prioritizes <meta> over // <?xml?>.) However, the case is very rare, and HTMLRewriter doesn't have a // handler for XML declarations, so we skip the check. if (known_utf8) { if (processors.some((p) => p.modified)) { payload = new Response(modifiedBody, { status: payload.status, statusText: payload.statusText, headers: payload.headers, }); // TODO: This modifiedBody is later extracted again via the readIntoArray // call in generateSxgResponse. Is this a significant performance hit? If // so, return the array from this function. } processors.forEach((p) => p.onEnd(payload)); } return payload; } async function generateSxgResponse(fallbackUrl: string, certOrigin: string, payload: Response) { let worker = await workerPromise; const payloadHeaders = Array.from(payload.headers); worker.validatePayloadHeaders(payloadHeaders); const payloadBody = await readIntoArray(payload.body, PAYLOAD_SIZE_LIMIT); if (!payloadBody) { throw `The size of payload exceeds the limit ${PAYLOAD_SIZE_LIMIT}`; } let {get: headerIntegrityGet, put: headerIntegrityPut} = await headerIntegrityCache(); const now_in_seconds = Math.floor(Date.now() / 1000); const sxg = await worker.createSignedExchange( fallbackUrl, certOrigin, payload.status, payloadHeaders, payloadBody, now_in_seconds, signer, fetcher, headerIntegrityGet, headerIntegrityPut, ); return responseFromWasm(sxg); } async function fetcher(request: WasmRequest): Promise<WasmResponse> { let requestInit: RequestInit = { headers: request.headers, method: request.method, }; if (request.body.length > 0) { requestInit.body = new Uint8Array(request.body); } const response = await fetch(request.url, requestInit); let body; if (response.body) { body = await readIntoArray(response.body, PAYLOAD_SIZE_LIMIT); if (!body) { throw `The size of payload exceeds the limit ${PAYLOAD_SIZE_LIMIT}`; } } else { body = new Uint8Array(0); } return await wasmFromResponse(new Response(body, { headers: response.headers, status: response.status, })); } type HttpCache = { get: (url: string) => Promise<WasmResponse>, put: (url: string, response: WasmResponse) => Promise<void>, }; const NOT_FOUND_RESPONSE: WasmResponse = { body: [], headers: [], status: 404, }; async function headerIntegrityCache(): Promise<HttpCache> { let cache = await caches.open('header-integrity'); return { get: async (url: string) => { const response = await cache.match(url); return response ? await wasmFromResponse(response) : NOT_FOUND_RESPONSE; }, put: async (url: string, response: WasmResponse) => { return cache.put(url, responseFromWasm(response)); } } }
the_stack
import { Field, Label } from "@components/field"; import { act, waitFor } from "@testing-library/react"; import { DateInput } from "@components/date-input"; import { createRef } from "react"; import { renderWithTheme } from "@jest-utils"; import userEvent from "@testing-library/user-event"; // Using userEvent.type with a string having multiple characters doesn't work because of the mask. Only the last character ends up being typed. // Providing an option.delay fix the problem but we get the following warning: "You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one." function type(element: Element, text: string) { [...text].forEach(x => { act(() => { userEvent.type(element, x); }); }); } function backspace(element: Element, times = 1) { for (let x = 0; x < times; x += 1) { act(() => { userEvent.type(element, "{backspace}"); }); } } // ***** Behaviors ***** test("only accept number characters", async () => { const { getByTestId } = renderWithTheme( <DateInput data-testid="date" /> ); act(() => { getByTestId("date").focus(); }); type(getByTestId("date"), "aA"); await waitFor(() => expect(getByTestId("date")).toHaveValue("")); type(getByTestId("date"), "(@$"); await waitFor(() => expect(getByTestId("date")).toHaveValue("")); type(getByTestId("date"), "010"); await waitFor(() => expect(getByTestId("date")).toHaveValue("01/0")); }); test("when the input has no value and a partial date has been entered, reset to an empty value on blur", async () => { const { getByTestId } = renderWithTheme( <DateInput data-testid="date" /> ); act(() => { getByTestId("date").focus(); }); type(getByTestId("date"), "010"); await waitFor(() => expect(getByTestId("date")).toHaveValue("01/0")); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getByTestId("date")).toHaveValue("")); act(() => { getByTestId("date").focus(); }); await waitFor(() => expect(getByTestId("date")).toHaveValue("")); }); test("when the input has no value and an invalid date has been entered, clear the input value on blur", async () => { const { getByTestId } = renderWithTheme( <DateInput data-testid="date" /> ); act(() => { getByTestId("date").focus(); }); type(getByTestId("date"), "99999999"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getByTestId("date")).toHaveValue("")); act(() => { getByTestId("date").focus(); }); await waitFor(() => expect(getByTestId("date")).toHaveValue("")); }); test("when the entered date is lower than the min date, reset value to min date", async () => { const { getByTestId } = renderWithTheme( <DateInput min={new Date(2021, 0, 1)} data-testid="date" /> ); act(() => { getByTestId("date").focus(); }); type(getByTestId("date"), "01012020"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getByTestId("date")).toHaveValue("Fri, Jan 1, 2021")); act(() => { getByTestId("date").focus(); }); await waitFor(() => expect(getByTestId("date")).toHaveValue("01/01/2021")); }); test("when the entered date is greater than the max date, reset the date to the max date value", async () => { const { getByTestId } = renderWithTheme( <DateInput max={new Date(2021, 0, 1)} data-testid="date" /> ); act(() => { getByTestId("date").focus(); }); type(getByTestId("date"), "01012022"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getByTestId("date")).toHaveValue("Fri, Jan 1, 2021")); act(() => { getByTestId("date").focus(); }); await waitFor(() => expect(getByTestId("date")).toHaveValue("01/01/2021")); }); test("when a valid date is entered, convert the date format to a read format on blur", async () => { const { getByTestId } = renderWithTheme( <DateInput data-testid="date" /> ); act(() => { getByTestId("date").focus(); }); type(getByTestId("date"), "01012021"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getByTestId("date")).toHaveValue("Fri, Jan 1, 2021")); }); test("when the input value has a valid date and receive focus, convert the date format to an editable format", async () => { const { getByTestId } = renderWithTheme( <DateInput defaultValue={new Date(2021, 0, 1)} data-testid="date" /> ); act(() => { getByTestId("date").focus(); }); await waitFor(() => expect(getByTestId("date")).toHaveValue("01/01/2021")); }); test("when the input value has a valid date and a partial date has been entered entered, reset to the last valid date on blur", async () => { const { getByTestId } = renderWithTheme( <DateInput defaultValue={new Date(2021, 0, 1)} data-testid="date" /> ); act(() => { getByTestId("date").focus(); }); type(getByTestId("date"), "010"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getByTestId("date")).toHaveValue("Fri, Jan 1, 2021")); act(() => { getByTestId("date").focus(); }); await waitFor(() => expect(getByTestId("date")).toHaveValue("01/01/2021")); }); test("when the input value has a valid date and a malformed date has been entered, reset to the last valid date", async () => { const { getByTestId } = renderWithTheme( <DateInput defaultValue={new Date(2021, 0, 1)} data-testid="date" /> ); act(() => { getByTestId("date").focus(); }); backspace(getByTestId("date"), 6); type(getByTestId("date"), "999999"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getByTestId("date")).toHaveValue("Fri, Jan 1, 2021")); act(() => { getByTestId("date").focus(); }); await waitFor(() => expect(getByTestId("date")).toHaveValue("01/01/2021")); }); test("when in a field, clicking on the field label focus the date input", async () => { const { getByTestId } = renderWithTheme( <Field> <Label data-testid="label">Date</Label> <DateInput data-testid="date" /> </Field> ); act(() => { userEvent.click(getByTestId("label")); }); await waitFor(() => expect(getByTestId("date")).toHaveFocus()); }); test("when autofocus is true, the date input is focused on render", async () => { const { getByTestId } = renderWithTheme( <DateInput autoFocus data-testid="date" /> ); await waitFor(() => expect(getByTestId("date")).toHaveFocus()); }); test("when autofocus is true and the date input is disabled, the date input is not focused on render", async () => { const { getByTestId } = renderWithTheme( <DateInput disabled autoFocus data-testid="date" /> ); await waitFor(() => expect(getByTestId("date")).not.toHaveFocus()); }); test("when autofocus is true and the date input is readonly, the date input is not focused on render", async () => { const { getByTestId } = renderWithTheme( <DateInput readOnly autoFocus data-testid="date" /> ); await waitFor(() => expect(getByTestId("date")).not.toHaveFocus()); }); test("when autofocus is specified with a de lay, the date input is focused after the delay", async () => { const { getByTestId } = renderWithTheme( <DateInput autoFocus={10} data-testid="date" /> ); expect(getByTestId("date")).not.toHaveFocus(); await waitFor(() => expect(getByTestId("date")).toHaveFocus()); }); describe("compact presets", () => { test("when a preset is selected, both inputs are filled with the preset dates", async () => { const { container, getByRole, getByPlaceholderText } = renderWithTheme( <DateInput presets={[{ text: "Preset 1", date: new Date(2020, 0, 1) }]} presetsVariant="compact" placeholder="date-input" /> ); act(() => { userEvent.click(container.querySelector(":scope [aria-label=\"Date presets\"]")); }); await waitFor(() => expect(getByRole("menu")).toBeInTheDocument()); act(() => { userEvent.click(getByRole("menuitemradio")); }); await waitFor(() => expect(getByPlaceholderText("date-input")).toHaveValue("Wed, Jan 1, 2020")); act(() => { getByPlaceholderText("date-input").focus(); }); await waitFor(() => expect(getByPlaceholderText("date-input")).toHaveValue("01/01/2020")); }); test("when a preset is selected, the preset menu trigger is focused", async () => { const { container, getByRole } = renderWithTheme( <DateInput presets={[{ text: "Preset 1", date: new Date(2020, 0, 1) }]} presetsVariant="compact" placeholder="date-range" /> ); act(() => { userEvent.click(container.querySelector(":scope [aria-label=\"Date presets\"]")); }); await waitFor(() => expect(getByRole("menu")).toBeInTheDocument()); act(() => { userEvent.click(getByRole("menuitemradio")); }); await waitFor(() => expect(container.querySelector(":scope [aria-label=\"Date presets\"]")).toHaveFocus()); }); test("when a preset is selected from the menu, the selected item of the menu match the selected preset", async () => { const { container, getByRole } = renderWithTheme( <DateInput presets={[{ text: "Preset 1", date: new Date(2020, 0, 1) }]} presetsVariant="compact" placeholder="date-range" /> ); act(() => { userEvent.click(container.querySelector(":scope [aria-label=\"Date presets\"]")); }); await waitFor(() => expect(getByRole("menu")).toBeInTheDocument()); act(() => { userEvent.click(getByRole("menuitemradio")); }); await waitFor(() => expect(getByRole("menuitemradio")).toHaveAttribute("aria-checked", "true")); }); test("when the date value match a preset, the selected item of the menu match the preset", async () => { const { container, getByRole } = renderWithTheme( <DateInput value={new Date(2020, 0, 1)} presets={[{ text: "Preset 1", date: new Date(2020, 0, 1) }]} presetsVariant="compact" placeholder="date-range" /> ); act(() => { userEvent.click(container.querySelector(":scope [aria-label=\"Date presets\"]")); }); await waitFor(() => expect(getByRole("menu")).toBeInTheDocument()); await waitFor(() => expect(getByRole("menuitemradio")).toHaveAttribute("aria-checked", "true")); }); }); describe("expanded presets", () => { test("when a preset is selected, the input is filled with the preset date", async () => { const { getByRole, getByPlaceholderText } = renderWithTheme( <DateInput presets={[{ text: "Preset 1", date: new Date(2020, 0, 1) }]} presetsVariant="expanded" placeholder="date-input" /> ); act(() => { userEvent.click(getByRole("radio")); }); await waitFor(() => expect(getByPlaceholderText("date-input")).toHaveValue("Wed, Jan 1, 2020")); act(() => { getByPlaceholderText("date-input").focus(); }); await waitFor(() => expect(getByPlaceholderText("date-input")).toHaveValue("01/01/2020")); }); test("when a preset is selected, the toggled button match the selected preset", async () => { const { getByRole } = renderWithTheme( <DateInput presets={[{ text: "Preset 1", date: new Date(2020, 0, 1) }]} presetsVariant="expanded" placeholder="date-input" /> ); act(() => { userEvent.click(getByRole("radio")); }); await waitFor(() => expect(getByRole("radio")).toHaveAttribute("aria-checked", "true")); }); test("when the date match a preset, the toggled button match the preset", async () => { const { getByRole } = renderWithTheme( <DateInput value={new Date(2020, 0, 1)} presets={[{ text: "Preset 1", date: new Date(2020, 0, 1) }]} presetsVariant="expanded" placeholder="date-input" /> ); await waitFor(() => expect(getByRole("radio")).toHaveAttribute("aria-checked", "true")); }); }); // ***** Api ***** test("when the input has no value and a valid date has been entered, call onDateChange with the new date on blur", async () => { const handler = jest.fn(); const { getByTestId } = renderWithTheme( <DateInput onDateChange={handler} data-testid="date" /> ); act(() => { getByTestId("date").focus(); }); type(getByTestId("date"), "01012021"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); await waitFor(() => expect(handler).toHaveBeenCalledWith(expect.anything(), new Date(2021, 0, 1))); }); test("when the input has no value and a partial date has been cleared, do not call onDateChange", async () => { const handler = jest.fn(); const { getByTestId } = renderWithTheme( <DateInput onDateChange={handler} data-testid="date" /> ); act(() => { getByTestId("date").focus(); }); type(getByTestId("date"), "010"); await waitFor(() => expect(getByTestId("date")).toHaveValue("01/0")); act(() => { userEvent.clear(getByTestId("date")); }); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getByTestId("date")).toHaveValue("")); await waitFor(() => expect(handler).not.toHaveBeenCalled()); }); test("when the input has no value and a malformed date has been entered, do not call onDateChange", async () => { const handler = jest.fn(); const { getByTestId } = renderWithTheme( <DateInput onDateChange={handler} data-testid="date" /> ); act(() => { getByTestId("date").focus(); }); type(getByTestId("date"), "99999999"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getByTestId("date")).toHaveValue("")); await waitFor(() => expect(handler).not.toHaveBeenCalled()); }); test("when the input value has a valid date and a new valid date has been entered, call onDateChange with the new date", async () => { const handler = jest.fn(); const { getByTestId } = renderWithTheme( <DateInput defaultValue={new Date(2021, 0, 1)} onDateChange={handler} data-testid="date" /> ); act(() => { getByTestId("date").focus(); }); backspace(getByTestId("date")); act(() => { userEvent.type(getByTestId("date"), "0"); }); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); await waitFor(() => expect(handler).toHaveBeenCalledWith(expect.anything(), new Date(2020, 0, 1))); }); test("when the input value has a valid date and the date has been cleared, call onDateChange with null", async () => { const handler = jest.fn(); const { getByTestId } = renderWithTheme( <DateInput defaultValue={new Date(2021, 0, 1)} onDateChange={handler} data-testid="date" /> ); act(() => { getByTestId("date").focus(); }); act(() => { userEvent.clear(getByTestId("date")); }); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(handler).toHaveBeenCalledWith(expect.anything(), null)); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); }); test("when the input value has a valid date and a partial date has been entered, do not call onDateChange on date reset", async () => { const handler = jest.fn(); const { getByTestId } = renderWithTheme( <DateInput defaultValue={new Date(2021, 0, 1)} onDateChange={handler} data-testid="date" /> ); act(() => { getByTestId("date").focus(); }); backspace(getByTestId("date"), 3); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(getByTestId("date")).toHaveValue("Fri, Jan 1, 2021")); await waitFor(() => expect(handler).not.toHaveBeenCalled()); }); test("when the input value has a valid date and a malformed date has been entered, do not call onDateChange", async () => { const handler = jest.fn(); const { getByTestId } = renderWithTheme( <DateInput defaultValue={new Date(2021, 0, 1)} onDateChange={handler} data-testid="date" /> ); act(() => { getByTestId("date").focus(); }); backspace(getByTestId("date"), 6); type(getByTestId("date"), "999999"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(handler).not.toHaveBeenCalled()); }); test("when the input value has a valid date and is focused then blured with the same date, do not call onDateChange", async () => { const handler = jest.fn(); const { getByTestId } = renderWithTheme( <DateInput defaultValue={new Date(2021, 0, 1)} onDateChange={handler} data-testid="date" /> ); act(() => { getByTestId("date").focus(); }); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(handler).not.toHaveBeenCalled()); }); test("when a valid date has been entered and the date exceed the specified min or max value, onDateChange is called with the clamped date before onBlur is called", async () => { const handleDateChange = jest.fn(); const { getByTestId } = renderWithTheme( <DateInput onDateChange={handleDateChange} min={new Date(2021, 0, 1)} data-testid="date" /> ); act(() => { getByTestId("date").focus(); }); type(getByTestId("date"), "01012020"); act(() => { userEvent.click(document.body); }); await waitFor(() => expect(handleDateChange).toHaveBeenLastCalledWith(expect.anything(), new Date(2021, 0, 1))); await waitFor(() => expect(handleDateChange).toHaveBeenCalledTimes(1)); }); test("when a preset is selected, call onDateChange with the preset date", async () => { const handler = jest.fn(); const { container, getByRole } = renderWithTheme( <DateInput presets={[{ text: "Preset 1", date: new Date(2020, 0, 1) }]} onDateChange={handler} /> ); act(() => { userEvent.click(container.querySelector(":scope [aria-label=\"Date presets\"]")); }); await waitFor(() => expect(getByRole("menu")).toBeInTheDocument()); act(() => { userEvent.click(getByRole("menuitemradio")); }); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); await waitFor(() => expect(handler).toHaveBeenCalledWith(expect.anything(), new Date(2020, 0, 1))); }); test("can focus the date input with the focus api", async () => { let refNode: HTMLElement = null; renderWithTheme( <DateInput ref={node => { refNode = node; }} data-testid="date" /> ); act(() => { refNode.focus(); }); await waitFor(() => expect(refNode).toHaveFocus()); }); test("when compact presets are provided, can focus the input with the focus api", async () => { const ref = createRef<HTMLInputElement>(); const { getByPlaceholderText } = renderWithTheme( <DateInput presets={[{ text: "Preset 1", date: new Date(2020, 0, 1) }]} presetsVariant="compact" placeholder="date-input" ref={ref} /> ); act(() => { ref.current.focus(); }); await waitFor(() => expect(getByPlaceholderText("date-input")).toHaveFocus()); }); test("when expanded presets are provided, can focus the input with the focus api", async () => { const ref = createRef<HTMLInputElement>(); const { getByPlaceholderText } = renderWithTheme( <DateInput presets={[{ text: "Preset 1", date: new Date(2020, 0, 1) }]} presetsVariant="expanded" placeholder="date-input" ref={ref} /> ); act(() => { ref.current.focus(); }); await waitFor(() => expect(getByPlaceholderText("date-input")).toHaveFocus()); }); // ***** Refs ***** test("ref is a DOM element", async () => { const ref = createRef<HTMLInputElement>(); renderWithTheme( <DateInput ref={ref} /> ); await waitFor(() => expect(ref.current).not.toBeNull()); expect(ref.current instanceof HTMLElement).toBeTruthy(); expect(ref.current.tagName).toBe("INPUT"); }); test("when compact presets are provided, ref is a DOM element", async () => { const ref = createRef<HTMLInputElement>(); renderWithTheme( <DateInput presets={[{ text: "Preset 1", date: new Date(2020, 0, 1) }]} presetsVariant="compact" ref={ref} /> ); await waitFor(() => expect(ref.current).not.toBeNull()); expect(ref.current instanceof HTMLElement).toBeTruthy(); expect(ref.current.tagName).toBe("DIV"); }); test("when expanded presets are provided, ref is a DOM element", async () => { const ref = createRef<HTMLInputElement>(); renderWithTheme( <DateInput presets={[{ text: "Preset 1", date: new Date(2020, 0, 1) }]} presetsVariant="expanded" ref={ref} /> ); await waitFor(() => expect(ref.current).not.toBeNull()); expect(ref.current instanceof HTMLElement).toBeTruthy(); expect(ref.current.tagName).toBe("DIV"); }); test("when using a callback ref, ref is a DOM element", async () => { let refNode: HTMLElement = null; renderWithTheme( <DateInput ref={node => { refNode = node; }} /> ); await waitFor(() => expect(refNode).not.toBeNull()); expect(refNode instanceof HTMLElement).toBeTruthy(); expect(refNode.tagName).toBe("INPUT"); }); test("set ref once", async () => { const handler = jest.fn(); renderWithTheme( <DateInput ref={handler} /> ); await waitFor(() => expect(handler).toHaveBeenCalledTimes(1)); });
the_stack
import * as vscode from 'vscode' import * as actions from './actions' import { TextDecoder } from 'util' //#endregion /** * ## Command Arguments * * Most commands provided by ModalEdit take arguments. Since command arguments * are stored in objects by-design, we define them as interfaces. * * ### Search Arguments * * Search arguments are documented in the * [README](../README.html#code-modaledit-search-code). */ interface SearchArgs { backwards?: boolean caseSensitive?: boolean wrapAround?: boolean acceptAfter?: number selectTillMatch?: boolean typeAfterAccept?: string typeBeforeNextMatch?: string typeAfterNextMatch?: string typeBeforePreviousMatch?: string typeAfterPreviousMatch?: string } /** * ### Bookmark Arguments * * [Bookmark](../README.html#bookmarks) ID is a user specified string label. * Actual positions are stored in an object that conforms to the `Bookmark` * interface in the `bookmarks` dictionary. */ interface BookmarkArgs { bookmark?: string, select?: boolean } class Bookmark implements vscode.QuickPickItem { public description: string constructor( public label: string, public document: vscode.TextDocument, public position: vscode.Position) { let ln = position.line let col = position.character let text = document.lineAt(ln).text this.description = `Ln ${ln}, Col ${col}: ${text}` } } /** * ### Quick Snippet Arguments * * [Quick snippets](../README.html#quick-snippets) are also stored in an array. * So their IDs are indexes as well. */ interface QuickSnippetArgs { snippet: number } /** * ### Type Normal Keys Arguments * * The [`typeNormalKeys` command](../README.html#invoking-key-bindings) gets the * entered keys as a string. */ interface TypeNormalKeysArgs { keys: string } /** * ### Select Between Arguments * * The `selectBetween` command takes as arguments the strings/regular * expressions which delimit the text to be selected. Both of them are optional, * but in order for the command to do anything one of them needs to be defined. * If the `from` argument is missing, the selection goes from the cursor * position forwards to the `to` string. If the `to` is missing the selection * goes backwards till the `from` string. * * If the `regex` flag is on, `from` and `to` strings are treated as regular * expressions in the search. * * The `inclusive` flag tells if the delimiter strings are included in the * selection or not. By default the delimiter strings are not part of the * selection. Last, the `caseSensitive` flag makes the search case sensitive. * When this flag is missing or false the search is case insensitive. * * By default the search scope is the current line. If you want search inside * the whole document, set the `docScope` flag. */ interface SelectBetweenArgs { from: string to: string regex: boolean inclusive: boolean caseSensitive: boolean docScope: boolean } /** * ## State Variables * * The enabler for modal editing is the `type` event that VS Code provides. It * reroutes the user's key presses to our extension. We store the handler to * this event in the `typeSubscription` variable. */ let typeSubscription: vscode.Disposable | undefined /** * We add two items in the status bar that show the current mode. The main * status bar shows the current state we are in. The secondary status bar shows * additional info such as keys that have been pressed so far and any help * strings defined in key bindings. */ let mainStatusBar: vscode.StatusBarItem let secondaryStatusBar: vscode.StatusBarItem /** * This is the main mode flag that tells if we are in normal mode or insert * mode. */ let normalMode = true /** * The `selecting` flag indicates if we have initiated selection mode. Note that * it is not the only indicator that tells whether a selection is active. */ let selecting = false /** * The `searching` flag tells if `modaledit.search` command is in operation. */ let searching = false /** * Search state variables. */ let searchString: string let searchStartSelections: vscode.Selection[] let searchInfo: string | null = null /** * Current search parameters. */ let searchBackwards = false let searchCaseSensitive = false let searchWrapAround = false let searchAcceptAfter = Number.POSITIVE_INFINITY let searchSelectTillMatch = false let searchTypeAfterAccept: string | undefined let searchTypeBeforeNextMatch: string | undefined let searchTypeAfterNextMatch: string | undefined let searchTypeBeforePreviousMatch: string | undefined let searchTypeAfterPreviousMatch: string | undefined let searchReturnToNormal = true /** * Bookmarks are stored here. */ let bookmarks: { [label: string]: Bookmark } = {} /** * Quick snippets are simply stored in an array of strings. */ let quickSnippets: string[] = [] /** * "Repeat last change" command needs to know when text in editor has changed. * It also needs to save the current and last command key sequence, as well as * the last sequence that caused text to change. */ let textChanged = false let currentKeySequence: string[] = [] let lastKeySequence: string[] = [] let lastChange: string[] = [] /** * ## Command Names * * Since command names are easy to misspell, we define them as constants. */ const toggleId = "modaledit.toggle" const enterNormalId = "modaledit.enterNormal" const enterInsertId = "modaledit.enterInsert" const toggleSelectionId = "modaledit.toggleSelection" const enableSelectionId = "modaledit.enableSelection" const cancelSelectionId = "modaledit.cancelSelection" const cancelMultipleSelectionsId = "modaledit.cancelMultipleSelections" const searchId = "modaledit.search" const cancelSearchId = "modaledit.cancelSearch" const deleteCharFromSearchId = "modaledit.deleteCharFromSearch" const nextMatchId = "modaledit.nextMatch" const previousMatchId = "modaledit.previousMatch" const defineBookmarkId = "modaledit.defineBookmark" const goToBookmarkId = "modaledit.goToBookmark" const showBookmarksId = "modaledit.showBookmarks" const fillSnippetArgsId = "modaledit.fillSnippetArgs" const defineQuickSnippetId = "modaledit.defineQuickSnippet" const insertQuickSnippetId = "modaledit.insertQuickSnippet" const typeNormalKeysId = "modaledit.typeNormalKeys" const selectBetweenId = "modaledit.selectBetween" const repeatLastChangeId = "modaledit.repeatLastChange" const importPresetsId = "modaledit.importPresets" /** * ## Registering Commands * * The commands are registered when the extension is activated (main entry point * calls this function). We also create the status bar item. */ export function register(context: vscode.ExtensionContext) { context.subscriptions.push( vscode.commands.registerCommand(toggleId, toggle), vscode.commands.registerCommand(enterNormalId, enterNormal), vscode.commands.registerCommand(enterInsertId, enterInsert), vscode.commands.registerCommand(toggleSelectionId, toggleSelection), vscode.commands.registerCommand(enableSelectionId, enableSelection), vscode.commands.registerCommand(cancelSelectionId, cancelSelection), vscode.commands.registerCommand(cancelMultipleSelectionsId, cancelMultipleSelections), vscode.commands.registerCommand(searchId, search), vscode.commands.registerCommand(cancelSearchId, cancelSearch), vscode.commands.registerCommand(deleteCharFromSearchId, deleteCharFromSearch), vscode.commands.registerCommand(nextMatchId, nextMatch), vscode.commands.registerCommand(previousMatchId, previousMatch), vscode.commands.registerCommand(defineBookmarkId, defineBookmark), vscode.commands.registerCommand(goToBookmarkId, goToBookmark), vscode.commands.registerCommand(showBookmarksId, showBookmarks), vscode.commands.registerCommand(fillSnippetArgsId, fillSnippetArgs), vscode.commands.registerCommand(defineQuickSnippetId, defineQuickSnippet), vscode.commands.registerCommand(insertQuickSnippetId, insertQuickSnippet), vscode.commands.registerCommand(typeNormalKeysId, typeNormalKeys), vscode.commands.registerCommand(selectBetweenId, selectBetween), vscode.commands.registerCommand(repeatLastChangeId, repeatLastChange), vscode.commands.registerCommand(importPresetsId, importPresets) ) mainStatusBar = vscode.window.createStatusBarItem( vscode.StatusBarAlignment.Left) mainStatusBar.command = toggleId secondaryStatusBar = vscode.window.createStatusBarItem( vscode.StatusBarAlignment.Left) } /** * ## Keyboard Event Handler * * When the user types in normal mode, `onType` handler gets each typed * character one at a time. It calls the `runActionForKey` subroutine to invoke * the action bound to the typed key. In addition, it updates the state * variables needed by the `repeatLastChange` command and the status bar. */ async function onType(event: { text: string }) { if (textChanged) { lastChange = lastKeySequence textChanged = false } currentKeySequence.push(event.text) if (await runActionForKey(event.text)) { lastKeySequence = currentKeySequence currentKeySequence = [] } updateCursorAndStatusBar(vscode.window.activeTextEditor, actions.getHelp()) } /** * Whenever text changes in an active editor, we set a flag. This flag is * examined in the `onType` handler above, and the `lastChange` variable is set * to indicate that the last command that changed editor text. */ export function onTextChanged() { textChanged = true } /** * This helper function just calls the `handleKey` function in the `actions` * module. It checks if we have an active selection or search mode on, and * passes that information to the function. `handleKey` returns `true` if the * key actually invoked a command, or `false` if it was a part of incomplete * key sequence that did not (yet) cause any commands to run. This information * is needed to decide whether the `lastKeySequence` variable is updated. */ async function runActionForKey(key: string): Promise<boolean> { return await actions.handleKey(key, isSelecting(), searching) } /** * ## Mode Switching Commands * * `toggle` switches between normal and insert mode. */ export function toggle() { if (normalMode) enterInsert() else enterNormal() } /** * When entering normal mode, we: * * 1. cancel the search, if it is on, * 2. subscribe to the `type` event, * 3. handle the rest of the mode setup with `setNormalMode` function, and * 4. clear the selection. */ export function enterNormal() { cancelSearch() if (!typeSubscription) typeSubscription = vscode.commands.registerCommand("type", onType) setNormalMode(true) cancelSelection() } /** * Conversely, when entering insert mode, we: * * 1. cancel the search, if it is on (yes, you can use it in insert mode, too), * 2. unsubscribe to the `type` event, * 3. handle the rest of the mode setup with `setNormalMode` function. * * Note that we specifically don't clear the selection. This allows the user * to easily surround selected text with hyphens `'`, parenthesis `(` and `)`, * brackets `[` and `]`, etc. */ export function enterInsert() { cancelSearch() if (typeSubscription) { typeSubscription.dispose() typeSubscription = undefined } setNormalMode(false) } /** * The rest of the state handling is delegated to subroutines that do specific * things. `setNormalMode` sets or resets the VS Code `modaledit.normal` context. * This can be used in "standard" key bindings. Then it sets the `normalMode` * variable and calls the next subroutine which updates cursor and status bar. */ async function setNormalMode(value: boolean): Promise<void> { const editor = vscode.window.activeTextEditor if (editor) { await vscode.commands.executeCommand("setContext", "modaledit.normal", value) normalMode = value updateCursorAndStatusBar(editor) } } /** * This function updates the cursor shape and status bar according to editor * state. It indicates when selection is active or search mode is on. If * so, it shows the search parameters. If no editor is active, we hide the * status bar items. */ export function updateCursorAndStatusBar(editor: vscode.TextEditor | undefined, help?: string) { if (editor) { // Get the style parameters let [style, text, color] = searching ? actions.getSearchStyles() : isSelecting() && normalMode ? actions.getSelectStyles() : normalMode ? actions.getNormalStyles() : actions.getInsertStyles() /** * Update the cursor style. */ editor.options.cursorStyle = style /** * Update the main status bar. */ mainStatusBar.text = searching ? `${text} [${searchBackwards ? "B" : "F" }${searchCaseSensitive ? "S" : ""}]: ${searchString}` : text mainStatusBar.color = color mainStatusBar.show() /** * Update secondary status bar. If there is any keys pressed in the * current sequence, we show them. Also possible help string is shown. * The info given by search command is shown only as long there are * no other messages to show. */ let sec = " " + currentKeySequence.join("") if (help) sec = `${sec} ${help}` if (searchInfo) { if (sec.trim() == "") sec = searchInfo else searchInfo = null } secondaryStatusBar.text = sec secondaryStatusBar.show() } else { mainStatusBar.hide() secondaryStatusBar.hide() } } /** * ## Selection Commands * * `modaledit.cancelSelection` command clears the selection using standard * `cancelSelection` command, but also sets the `selecting` flag to false, and * updates the status bar. It is advisable to use this command instead of the * standard version to keep the state in sync. */ async function cancelSelection(): Promise<void> { if (selecting) { await vscode.commands.executeCommand("cancelSelection") selecting = false updateCursorAndStatusBar(vscode.window.activeTextEditor) } } /** * `modaledit.cancelMultipleSelections`, like `modaledit.cancelSelection` sets * selecting to false and sets the anchor equal to active selection position. * Unlike `modaledit.cancelSelection` it preserves multiple cursors. */ function cancelMultipleSelections() { if (selecting) { let editor = vscode.window.activeTextEditor if (editor) editor.selections = editor.selections.map(sel => new vscode.Selection(sel.active, sel.active)) selecting = false updateCursorAndStatusBar(vscode.window.activeTextEditor) } } /** * `modaledit.toggleSelection` toggles the selection mode on and off. It sets * the selection mode flag and updates the status bar, but also clears the * selection. */ async function toggleSelection(): Promise<void> { let oldSelecting = selecting if (oldSelecting) await vscode.commands.executeCommand("cancelSelection") selecting = !oldSelecting updateCursorAndStatusBar(vscode.window.activeTextEditor) } /** * `modaledit.enableSelection` sets the selecting to true. */ function enableSelection() { selecting = true; updateCursorAndStatusBar(vscode.window.activeTextEditor) } /** * The following helper function actually determines, if a selection is active. * It checks not only the `selecting` flag but also if there is any text * selected in the active editor. */ function isSelecting(): boolean { if (normalMode && selecting) return true selecting = vscode.window.activeTextEditor!.selections.some( selection => !selection.anchor.isEqual(selection.active)) return selecting } /** * Function that sets the selecting flag off. This function is called from one * event. The flag is resetted when the active editor changes. The function that * updates the status bar sets the flag on again, if there are any active * selections. */ export function resetSelecting() { selecting = false } /** * ## Search Commands * * Incremental search is by far the most complicated part of this extension. * Searching overrides both normal and insert modes, and captures the keyboard * until it is done. The following subroutine sets the associated state * variable, the VS Code `modaledit.searching` context, and the status bar. * Since search mode also puts the editor implicitly in the normal mode, we * need to check what was the state when we initiated the search. If we were in * insert mode, we return also there. */ async function setSearching(value: boolean) { searching = value await vscode.commands.executeCommand("setContext", "modaledit.searching", value) updateCursorAndStatusBar(vscode.window.activeTextEditor) if (!(value || searchReturnToNormal)) enterInsert() } /** * This is the main command that not only initiates the search, but also handles * the key presses when search is active. That is why its argument is defined * as an union type. We also use the argument to detect whether we are starting * a new search or adding characters to the active search. */ async function search(args: SearchArgs | string): Promise<void> { let editor = vscode.window.activeTextEditor if (!editor) return if (!args) args = {} if (typeof args == 'object') { /** * If we get an object as argument, we start a new search. We switch * to normal mode, if necessary. Then we initialize the search string * to empty, and store the current selections in the * `searchStartSelections` array. We need an array as the command also * works with multiple cursors. Finally we store the search arguments * in the module level variables. */ searchReturnToNormal = normalMode actions.setLastCommand(searchId) if (!normalMode) enterNormal() setSearching(true) searchString = "" searchStartSelections = editor.selections searchBackwards = args.backwards || false searchCaseSensitive = args.caseSensitive || false searchWrapAround = args.wrapAround || false searchAcceptAfter = args.acceptAfter || Number.POSITIVE_INFINITY searchSelectTillMatch = args.selectTillMatch || false searchTypeAfterAccept = args.typeAfterAccept searchTypeBeforeNextMatch = args.typeBeforeNextMatch searchTypeAfterNextMatch = args.typeAfterNextMatch searchTypeBeforePreviousMatch = args.typeBeforePreviousMatch searchTypeAfterPreviousMatch = args.typeAfterPreviousMatch } else if (args == "\n") /** * If we get an enter character we accept the search. */ await acceptSearch() else { /** * Otherwise we just add the character to the search string and find * the next match. If `acceptAfter` argument is given, and we have a * sufficiently long search string, we accept the search automatically. */ searchString += args highlightMatches(editor, searchStartSelections) if (searchString.length >= searchAcceptAfter) await acceptSearch() } } /** * The actual search functionality is located in this helper function. It is * used by the actual search command plus the commands that jump to next and * previous match. * * The search starts from positions specified by the `selections` argument. If * there are multilple selections (cursors) active, multiple searches are * performed. Each cursor location is considered separately, and the next match * from that position is selected. The function does *not* make sure that found * matches are unique. In case the matches overlap, the number of selections * will decrease. */ function highlightMatches(editor: vscode.TextEditor, selections: vscode.Selection[]) { searchInfo = null if (searchString == "") /** * If search string is empty, we return to the start positions. */ editor.selections = searchStartSelections else { /** * We get the text of the active editor as string. If we have * case-insensitive search, we transform the text to lower case. */ let doc = editor.document let docText = searchCaseSensitive ? doc.getText() : doc.getText().toLowerCase() /** * Next we determine the search target. It is also transformed to * lower case, if search is case-insensitive. */ let target = searchCaseSensitive ? searchString : searchString.toLowerCase() editor.selections = selections.map(sel => { /** * This is the actual search that is performed for each cursor * position. The lambda function returns a new selection for each * active cursor. */ let startOffs = doc.offsetAt(sel.active) /** * Depending on the search direction we find either the * first or the last match from the start offset. */ let offs = searchBackwards ? docText.lastIndexOf(target, startOffs - 1) : docText.indexOf(target, startOffs) if (offs < 0) { if (searchWrapAround) /** * If search string was not found but `wrapAround` argument * was set, we try to find the search string from beginning * or end of the document. If that fails too, we return * the original selection and the cursor will not move. */ offs = searchBackwards ? docText.lastIndexOf(target) : docText.indexOf(target) if (offs < 0) { searchInfo = "Pattern not found" return sel } let limit = (bw: boolean) => bw ? "TOP" : "BOTTOM" searchInfo = `Search hit ${limit(searchBackwards)} continuing at ${ limit(!searchBackwards)}` } /** * If search was successful, we return a new selection to highlight * it. First, we find the start and end position of the match. */ let len = searchString.length let start = doc.positionAt(offs) let end = doc.positionAt(offs + len) /** * If the search direction is backwards, we flip the active and * anchor positions. Normally, the anchor is set to the start and * cursor to the end. Finally, we check if the `selectTillMatch` * argument is set. If so, we move only the active cursor position * and leave the selection start (anchor) as-is. */ let [active, anchor] = searchBackwards ? [start, end] : [end, start] if (searchSelectTillMatch) anchor = sel.anchor return new vscode.Selection(anchor, active) }) } editor.revealRange(editor.selection) } /** * ### Accepting Search * * Accepting the search resets the mode variables. Additionally, if * `typeAfterAccept` argument is set we run the given normal mode commands. */ async function acceptSearch() { setSearching(false) if (searchTypeAfterAccept) await typeNormalKeys({ keys: searchTypeAfterAccept }) } /** * ### Canceling Search * * Canceling search just resets state, and moves the cursor back to the starting * position. */ async function cancelSearch(): Promise<void> { if (searching) { await setSearching(false) let editor = vscode.window.activeTextEditor if (editor) { editor.selections = searchStartSelections editor.revealRange(editor.selection) } } } /** * ### Modifying Search String * * Since we cannot capture the backspace character in normal mode, we have to * hook it some other way. We define a command `modaledit.deleteCharFromSearch` * which deletes the last character from the search string. This command can * then be bound to backspace using the standard keybindings. We only run the * command, if the `modaledit.searching` context is set. Below is an excerpt * of the default keybindings defined in `package.json`. * ```js * { * "key": "Backspace", * "command": "modaledit.deleteCharFromSearch", * "when": "editorTextFocus && modaledit.searching" * } * ``` * Note that we need to also update the status bar to show the modified search * string. The `onType` callback that normally handles this is not getting * called when this command is invoked. */ function deleteCharFromSearch() { let editor = vscode.window.activeTextEditor if (editor && searching && searchString.length > 0) { searchString = searchString.slice(0, searchString.length - 1) highlightMatches(editor, searchStartSelections) updateCursorAndStatusBar(editor) } } /** * ### Finding Previous and Next Match * * Using the `highlightMatches` function finding next and previous match is a * relatively simple task. We basically just restart the search from * the current cursor position(s). * * We also check whether the search parameters include `typeBeforeNextMatch` or * `typeAfterNextMatch` argument. If so, we invoke the user-specified commands * before and/or after we jump to the next match. */ async function nextMatch(): Promise<void> { let editor = vscode.window.activeTextEditor if (editor && searchString) { if (searchTypeBeforeNextMatch) await typeNormalKeys({ keys: searchTypeBeforeNextMatch }) highlightMatches(editor, editor.selections) if (searchTypeAfterNextMatch) await typeNormalKeys({ keys: searchTypeAfterNextMatch }) } } /** * When finding the previous match we flip the search direction but otherwise do * the same routine as in the previous function. */ async function previousMatch(): Promise<void> { let editor = vscode.window.activeTextEditor if (editor && searchString) { if (searchTypeBeforePreviousMatch) await typeNormalKeys({ keys: searchTypeBeforePreviousMatch }) searchBackwards = !searchBackwards highlightMatches(editor, editor.selections) searchBackwards = !searchBackwards if (searchTypeAfterPreviousMatch) await typeNormalKeys({ keys: searchTypeAfterPreviousMatch }) } } /** * ## Bookmarks * * Defining a bookmark is simple. We just store the cursor location and file in * a `Bookmark` object, and store it in the `bookmarks` array. */ function defineBookmark(args?: BookmarkArgs) { let editor = vscode.window.activeTextEditor if (editor) { let label = args?.bookmark?.toString() || '0' let document = editor.document let position = editor.selection.active bookmarks[label] = new Bookmark(label, document, position) } } /** * Jumping to bookmark is also easy, just call the `changeSelection` function * we already defined. It makes sure that selection is visible. */ async function goToBookmark(args?: BookmarkArgs): Promise<void> { let label = args?.bookmark?.toString() || '0' let bm = bookmarks[label] if (bm) { await vscode.window.showTextDocument(bm.document) let editor = vscode.window.activeTextEditor if (editor) { if (args?.select) changeSelection(editor, editor.selection.anchor, bm.position) else changeSelection(editor, bm.position, bm.position) } } } /** * To show the list of bookmarks in the command menu, we provide a new command. */ async function showBookmarks(): Promise<void> { let items = Object.getOwnPropertyNames(bookmarks).map(name => bookmarks[name]) let selected = await vscode.window.showQuickPick(items, { placeHolder: "Select bookmark to jump to", matchOnDescription: true }) if (selected) await goToBookmark({ bookmark: selected.label }) } /** * This helper function changes the selection range in the active editor. It * also makes sure that the selection is visible. */ function changeSelection(editor: vscode.TextEditor, anchor: vscode.Position, active: vscode.Position) { editor.selection = new vscode.Selection(anchor, active) editor.revealRange(editor.selection) } /** * ## Quick Snippets * * Supporting quick snippets is also a pleasantly simple job. First we implement * the `modaledit.fillSnippetArgs` command, which replaces (multi-)selection * ranges with `$1`, `$2`, ... */ async function fillSnippetArgs(): Promise<void> { let editor = vscode.window.activeTextEditor if (editor) { let sel = editor.selections await editor.edit(eb => { for (let i = 0; i < sel.length; i++) eb.replace(sel[i], "$" + (i + 1)) }) } } /** * Defining a snippet just puts the selection into an array. */ function defineQuickSnippet(args?: QuickSnippetArgs) { let editor = vscode.window.activeTextEditor if (editor) quickSnippets[args?.snippet || 0] = editor.document.getText(editor.selection) } /** * Inserting a snippet is done as easily with the built-in command. We enter * insert mode automatically before snippet is expanded. */ async function insertQuickSnippet(args?: QuickSnippetArgs): Promise<void> { let i = args?.snippet || 0 let snippet = quickSnippets[i] if (snippet) { enterInsert() await vscode.commands.executeCommand("editor.action.insertSnippet", { snippet }) } } /** * ## Invoking Commands via Key Bindings * * The last command runs normal mode commands throught their key bindings. * Implementing that is as easy as calling the keyboard handler. */ async function typeNormalKeys(args: TypeNormalKeysArgs): Promise<void> { if (typeof args !== 'object' || typeof (args.keys) !== 'string') throw Error(`${typeNormalKeysId}: Invalid args: ${JSON.stringify(args)}`) for (let i = 0; i < args.keys.length; i++) await runActionForKey(args.keys[i]) } /** * ## Advanced Selection Command * * For selecting ranges of text between two characters (inside parenthesis, for * example) we add the `modaledit.selectBetween` command. See the * [instructions](../README.html#selecting-text-between-delimiters) for the list * of parameters this command provides. */ function selectBetween(args: SelectBetweenArgs) { let editor = vscode.window.activeTextEditor if (!editor) return if (typeof args !== 'object') throw Error(`${selectBetweenId}: Invalid args: ${JSON.stringify(args)}`) let doc = editor.document /** * Get position of cursor and anchor. These positions might be in "reverse" * order (cursor lies before anchor), so we need to sort them into `lowPos` * and `highPos` variables and corresponding offset variables. These are * used to determine the search range later on. * * Since `to` or `from` parameter might be missing, we initialize the * `fromOffs` and `toOffs` variables to low and high offsets. They delimit * the range to be selected at the end. */ let cursorPos = editor.selection.active let anchorPos = editor.selection.anchor let [highPos, lowPos] = cursorPos.isAfterOrEqual(anchorPos) ? [cursorPos, anchorPos] : [anchorPos, cursorPos] let highOffs = doc.offsetAt(highPos) let lowOffs = doc.offsetAt(lowPos) let fromOffs = lowOffs let toOffs = highOffs /** * Next we determine the search range. The `startOffs` marks the starting * offset and `endOffs` the end. Depending on the specified scope these * variables are either set to start/end of the current line or the whole * document. * * In the actual search, we have two main branches: one for the case when * regex search is used and another for the normal text search. */ let startPos = new vscode.Position(args.docScope ? 0 : lowPos.line, 0) let endPos = doc.lineAt(args.docScope ? doc.lineCount - 1 : highPos.line) .range.end let startOffs = doc.offsetAt(startPos) let endOffs = doc.offsetAt(endPos) if (args.regex) { if (args.from) { /** * This branch searches for regex in the `from` parameter starting * from `startPos` continuing until `lowPos`. We need to find the * last occurrence of the regex, so we have to add a global modifier * `g` and iterate through all the matches. In case there are no * matches `fromOffs` gets the same offset as `startOffs` meaning * that the selection will extend to the start of the search scope. */ fromOffs = startOffs let text = doc.getText(new vscode.Range(startPos, lowPos)) let re = new RegExp(args.from, args.caseSensitive ? "g" : "gi") let match: RegExpExecArray | null = null while ((match = re.exec(text)) != null) fromOffs = startOffs + match.index + (args.inclusive ? 0 : match[0].length) } if (args.to) { /** * This block finds the regex in the `to` parameter starting from * the range `[highPos, endPos]`. Since we want to find the first * occurrence, we don't need to iterate over the matches in this * case. */ toOffs = endOffs let text = doc.getText(new vscode.Range(highPos, endPos)) let re = new RegExp(args.to, args.caseSensitive ? undefined : "i") let match = re.exec(text) if (match) toOffs = highOffs + match.index + (args.inclusive ? match[0].length : 0) } } else { /** * This branch does the regular text search. We retrieve the whole * search range as string and use `indexOf` and `lastIndexOf` methods * to find the strings in `to` and `from` parameters. Case insensitivity * is done by converting both the search range and search string to * lowercase. */ let text = doc.getText(new vscode.Range(startPos, endPos)) if (!args.caseSensitive) text = text.toLowerCase() if (args.from) { fromOffs = text.lastIndexOf(args.caseSensitive ? args.from : args.from.toLowerCase(), lowOffs - startOffs) fromOffs = fromOffs < 0 ? startOffs : startOffs + fromOffs + (args.inclusive ? 0 : args.from.length) } if (args.to) { toOffs = text.indexOf(args.caseSensitive ? args.to : args.to.toLowerCase(), highOffs - startOffs) toOffs = toOffs < 0 ? endOffs : startOffs + toOffs + (args.inclusive ? args.to.length : 0) } } if (cursorPos.isAfterOrEqual(anchorPos)) /** * The last thing to do is to select the range from `fromOffs` to * `toOffs`. We want to preserve the direction of the selection. If * it was reserved when this command was called, we flip the variables. */ changeSelection(editor, doc.positionAt(fromOffs), doc.positionAt(toOffs)) else changeSelection(editor, doc.positionAt(toOffs), doc.positionAt(fromOffs)) } /** * ## Repeat Last Change Command * * The `repeatLastChange` command runs the key sequence stored in `lastChange` * variable. Since the command inevitably causes text in the editor to change * (which causes the `textChanged` flag to go high), it has to reset the current * key sequence to prevent the `lastChange` variable from being overwritten next * time the user presses a key. */ async function repeatLastChange(): Promise<void> { for (let i = 0; i < lastChange.length; i++) await runActionForKey(lastChange[i]) currentKeySequence = lastChange } /** * ## Use Preset Keybindings * * This command will overwrite to `keybindings` and `selectbindings` settings * with presets. The presets are stored under the subdirectory named `presets`. * Command scans the directory and shows all the files in a pick list. * Alternatively the user can browse for other file that he/she has anywhere * in the file system. If the user selects a file, its contents will replace * the key binding in the global `settings.json` file. * * The presets can be defined as JSON or JavaScript. The code checks the file * extension and surrounds JSON with parenthesis. Then it can evaluate the * contents of the file as JavaScript. This allows to use non-standard JSON * files that include comments. Or, if the user likes to define the whole * shebang in code, he/she just has to make sure that the code evaluates to an * object that has `keybindings` and/or `selectbindings` properties. */ async function importPresets() { const browse = "Browse..." let presetsPath = vscode.extensions.getExtension("johtela.vscode-modaledit")! .extensionPath + "/presets" let fs = vscode.workspace.fs let presets = (await fs.readDirectory(vscode.Uri.file(presetsPath))) .map(t => t[0]) presets.push(browse) let choice = await vscode.window.showQuickPick(presets, { placeHolder: "Warning: Selecting a preset will override current " + "keybindings in global 'settings.json'" }) if (choice) { let uri = vscode.Uri.file(presetsPath + "/" + choice) if (choice == browse) { let userPreset = await vscode.window.showOpenDialog({ openLabel: "Import presets", filters: { JavaScript: ["js"], JSON: ["json", "jsonc"], }, canSelectFiles: true, canSelectFolders: false, canSelectMany: false }) if (!userPreset) return uri = userPreset[0] } try { let js = new TextDecoder("utf-8").decode(await fs.readFile(uri)) if (uri.fsPath.match(/jsonc?$/)) js = `(${js})` let preset = eval(js) let config = vscode.workspace.getConfiguration("modaledit") if (!(preset.keybindings || preset.selectbindings)) throw new Error( `Could not find "keybindings" or "selectbindings" in ${uri}`) if (preset.keybindings) config.update("keybindings", preset.keybindings, true) if (preset.selectbindings) config.update("selectbindings", preset.selectbindings, true) vscode.window.showInformationMessage( "ModalEdit: Keybindings imported.") } catch (e) { vscode.window.showWarningMessage("ModalEdit: Bindings not imported.", `${e}`) } } }
the_stack
import { mXparserConstants } from '../mXparserConstants'; /** * Variadic functions (n parameters)- mXparserConstants tokens definition. * * @author <b>Mariusz Gromada</b><br> * <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br> * <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br> * * @version 4.1.0 * @class */ export class FunctionVariadic { public static TYPE_ID: number = 7; public static TYPE_DESC: string = "Variadic Function"; public static IFF_ID: number = 1; public static MIN_ID: number = 2; public static MAX_ID: number = 3; public static CONT_FRAC_ID: number = 4; public static CONT_POL_ID: number = 5; public static GCD_ID: number = 6; public static LCM_ID: number = 7; public static SUM_ID: number = 8; public static PROD_ID: number = 9; public static AVG_ID: number = 10; public static VAR_ID: number = 11; public static STD_ID: number = 12; public static RND_LIST_ID: number = 13; public static COALESCE_ID: number = 14; public static OR_ID: number = 15; public static AND_ID: number = 16; public static XOR_ID: number = 17; public static ARGMIN_ID: number = 18; public static ARGMAX_ID: number = 19; public static MEDIAN_ID: number = 20; public static MODE_ID: number = 21; public static BASE_ID: number = 22; public static NDIST_ID: number = 23; public static IFF_STR: string = "iff"; public static MIN_STR: string = "min"; public static MAX_STR: string = "max"; public static CONT_FRAC_STR: string = "ConFrac"; public static CONT_POL_STR: string = "ConPol"; public static GCD_STR: string = "gcd"; public static LCM_STR: string = "lcm"; public static SUM_STR: string = "add"; public static PROD_STR: string = "multi"; public static AVG_STR: string = "mean"; public static VAR_STR: string = "var"; public static STD_STR: string = "std"; public static RND_LIST_STR: string = "rList"; public static COALESCE_STR: string = "coalesce"; public static OR_STR: string = "or"; public static AND_STR: string = "and"; public static XOR_STR: string = "xor"; public static ARGMIN_STR: string = "argmin"; public static ARGMAX_STR: string = "argmax"; public static MEDIAN_STR: string = "med"; public static MODE_STR: string = "mode"; public static BASE_STR: string = "base"; public static NDIST_STR: string = "ndist"; public static IFF_SYN: string = "iff( cond-1, expr-1; ... ; cond-n, expr-n )"; public static MIN_SYN: string = "min(a1, ..., an)"; public static MAX_SYN: string = "max(a1, ..., an)"; public static CONT_FRAC_SYN: string = "ConFrac(a1, ..., an)"; public static CONT_POL_SYN: string = "ConPol(a1, ..., an)"; public static GCD_SYN: string = "gcd(a1, ..., an)"; public static LCM_SYN: string = "lcm(a1, ..., an)"; public static SUM_SYN: string = "add(a1, ..., an)"; public static PROD_SYN: string = "multi(a1, ..., an)"; public static AVG_SYN: string = "mean(a1, ..., an)"; public static VAR_SYN: string = "var(a1, ..., an)"; public static STD_SYN: string = "std(a1, ..., an)"; public static RND_LIST_SYN: string = "rList(a1, ..., an)"; public static COALESCE_SYN: string = "coalesce(a1, ..., an)"; public static OR_SYN: string = "or(a1, ..., an)"; public static AND_SYN: string = "and(a1, ..., an)"; public static XOR_SYN: string = "xor(a1, ..., an)"; public static ARGMIN_SYN: string = "argmin(a1, ..., an)"; public static ARGMAX_SYN: string = "argmax(a1, ..., an)"; public static MEDIAN_SYN: string = "med(a1, ..., an)"; public static MODE_SYN: string = "mode(a1, ..., an)"; public static BASE_SYN: string = "base(b, d1, ..., dn)"; public static NDIST_SYN: string = "ndist(v1, ..., vn)"; public static IFF_DESC: string = "If function"; public static MIN_DESC: string = "Minimum function"; public static MAX_DESC: string = "Maximum function"; public static CONT_FRAC_DESC: string = "Continued fraction"; public static CONT_POL_DESC: string = "Continued polynomial"; public static GCD_DESC: string = "Greatest common divisor"; public static LCM_DESC: string = "Least common multiple"; public static SUM_DESC: string = "Summation operator"; public static PROD_DESC: string = "Multiplication"; public static AVG_DESC: string = "Mean / average value"; public static VAR_DESC: string = "Bias-corrected sample variance"; public static STD_DESC: string = "Bias-corrected sample standard deviation"; public static RND_LIST_DESC: string = "Random number from given list of numbers"; public static COALESCE_DESC: string = "Returns the first non-NaN value"; public static OR_DESC: string = "Logical disjunction (OR) - variadic"; public static AND_DESC: string = "Logical conjunction (AND) - variadic"; public static XOR_DESC: string = "Exclusive or (XOR) - variadic"; public static ARGMIN_DESC: string = "Arguments / indices of the minima"; public static ARGMAX_DESC: string = "Arguments / indices of the maxima"; public static MEDIAN_DESC: string = "The sample median"; public static MODE_DESC: string = "Mode - the value that appears most often"; public static BASE_DESC: string = "Returns number in given numeral system base represented by list of digits"; public static NDIST_DESC: string = "Number of distinct values"; public static IFF_SINCE: string; public static IFF_SINCE_$LI$(): string { if (FunctionVariadic.IFF_SINCE == null) { FunctionVariadic.IFF_SINCE = mXparserConstants.NAMEv10; } return FunctionVariadic.IFF_SINCE; } public static MIN_SINCE: string; public static MIN_SINCE_$LI$(): string { if (FunctionVariadic.MIN_SINCE == null) { FunctionVariadic.MIN_SINCE = mXparserConstants.NAMEv10; } return FunctionVariadic.MIN_SINCE; } public static MAX_SINCE: string; public static MAX_SINCE_$LI$(): string { if (FunctionVariadic.MAX_SINCE == null) { FunctionVariadic.MAX_SINCE = mXparserConstants.NAMEv10; } return FunctionVariadic.MAX_SINCE; } public static CONT_FRAC_SINCE: string; public static CONT_FRAC_SINCE_$LI$(): string { if (FunctionVariadic.CONT_FRAC_SINCE == null) { FunctionVariadic.CONT_FRAC_SINCE = mXparserConstants.NAMEv10; } return FunctionVariadic.CONT_FRAC_SINCE; } public static CONT_POL_SINCE: string; public static CONT_POL_SINCE_$LI$(): string { if (FunctionVariadic.CONT_POL_SINCE == null) { FunctionVariadic.CONT_POL_SINCE = mXparserConstants.NAMEv10; } return FunctionVariadic.CONT_POL_SINCE; } public static GCD_SINCE: string; public static GCD_SINCE_$LI$(): string { if (FunctionVariadic.GCD_SINCE == null) { FunctionVariadic.GCD_SINCE = mXparserConstants.NAMEv10; } return FunctionVariadic.GCD_SINCE; } public static LCM_SINCE: string; public static LCM_SINCE_$LI$(): string { if (FunctionVariadic.LCM_SINCE == null) { FunctionVariadic.LCM_SINCE = mXparserConstants.NAMEv10; } return FunctionVariadic.LCM_SINCE; } public static SUM_SINCE: string; public static SUM_SINCE_$LI$(): string { if (FunctionVariadic.SUM_SINCE == null) { FunctionVariadic.SUM_SINCE = mXparserConstants.NAMEv24; } return FunctionVariadic.SUM_SINCE; } public static PROD_SINCE: string; public static PROD_SINCE_$LI$(): string { if (FunctionVariadic.PROD_SINCE == null) { FunctionVariadic.PROD_SINCE = mXparserConstants.NAMEv24; } return FunctionVariadic.PROD_SINCE; } public static AVG_SINCE: string; public static AVG_SINCE_$LI$(): string { if (FunctionVariadic.AVG_SINCE == null) { FunctionVariadic.AVG_SINCE = mXparserConstants.NAMEv24; } return FunctionVariadic.AVG_SINCE; } public static VAR_SINCE: string; public static VAR_SINCE_$LI$(): string { if (FunctionVariadic.VAR_SINCE == null) { FunctionVariadic.VAR_SINCE = mXparserConstants.NAMEv24; } return FunctionVariadic.VAR_SINCE; } public static STD_SINCE: string; public static STD_SINCE_$LI$(): string { if (FunctionVariadic.STD_SINCE == null) { FunctionVariadic.STD_SINCE = mXparserConstants.NAMEv24; } return FunctionVariadic.STD_SINCE; } public static RND_LIST_SINCE: string; public static RND_LIST_SINCE_$LI$(): string { if (FunctionVariadic.RND_LIST_SINCE == null) { FunctionVariadic.RND_LIST_SINCE = mXparserConstants.NAMEv30; } return FunctionVariadic.RND_LIST_SINCE; } public static COALESCE_SINCE: string; public static COALESCE_SINCE_$LI$(): string { if (FunctionVariadic.COALESCE_SINCE == null) { FunctionVariadic.COALESCE_SINCE = mXparserConstants.NAMEv41; } return FunctionVariadic.COALESCE_SINCE; } public static OR_SINCE: string; public static OR_SINCE_$LI$(): string { if (FunctionVariadic.OR_SINCE == null) { FunctionVariadic.OR_SINCE = mXparserConstants.NAMEv41; } return FunctionVariadic.OR_SINCE; } public static AND_SINCE: string; public static AND_SINCE_$LI$(): string { if (FunctionVariadic.AND_SINCE == null) { FunctionVariadic.AND_SINCE = mXparserConstants.NAMEv41; } return FunctionVariadic.AND_SINCE; } public static XOR_SINCE: string; public static XOR_SINCE_$LI$(): string { if (FunctionVariadic.XOR_SINCE == null) { FunctionVariadic.XOR_SINCE = mXparserConstants.NAMEv41; } return FunctionVariadic.XOR_SINCE; } public static ARGMIN_SINCE: string; public static ARGMIN_SINCE_$LI$(): string { if (FunctionVariadic.ARGMIN_SINCE == null) { FunctionVariadic.ARGMIN_SINCE = mXparserConstants.NAMEv41; } return FunctionVariadic.ARGMIN_SINCE; } public static ARGMAX_SINCE: string; public static ARGMAX_SINCE_$LI$(): string { if (FunctionVariadic.ARGMAX_SINCE == null) { FunctionVariadic.ARGMAX_SINCE = mXparserConstants.NAMEv41; } return FunctionVariadic.ARGMAX_SINCE; } public static MEDIAN_SINCE: string; public static MEDIAN_SINCE_$LI$(): string { if (FunctionVariadic.MEDIAN_SINCE == null) { FunctionVariadic.MEDIAN_SINCE = mXparserConstants.NAMEv41; } return FunctionVariadic.MEDIAN_SINCE; } public static MODE_SINCE: string; public static MODE_SINCE_$LI$(): string { if (FunctionVariadic.MODE_SINCE == null) { FunctionVariadic.MODE_SINCE = mXparserConstants.NAMEv41; } return FunctionVariadic.MODE_SINCE; } public static BASE_SINCE: string; public static BASE_SINCE_$LI$(): string { if (FunctionVariadic.BASE_SINCE == null) { FunctionVariadic.BASE_SINCE = mXparserConstants.NAMEv41; } return FunctionVariadic.BASE_SINCE; } public static NDIST_SINCE: string; public static NDIST_SINCE_$LI$(): string { if (FunctionVariadic.NDIST_SINCE == null) { FunctionVariadic.NDIST_SINCE = mXparserConstants.NAMEv41; } return FunctionVariadic.NDIST_SINCE; } } FunctionVariadic["__class"] = "org.mariuszgromada.math.mxparser.parsertokens.FunctionVariadic";
the_stack
import chalk from 'chalk'; import fs from 'fs'; import { MiddlewareConsumer, Module, NestModule, OnModuleInit } from '@nestjs/common'; import mongoose from 'mongoose'; import { GraphQLSchema } from 'graphql'; import { GraphQLModule } from '@nestjs/graphql'; import { SubscriptionsModule } from './graphql/subscriptions/subscriptions.module'; import { SubscriptionsService } from './graphql/subscriptions/subscriptions.service'; import { InvitesModule } from './graphql/invites/invites.module'; import { DevicesModule } from './graphql/devices/devices.module'; import { ConfigModule } from './config/config.module'; import { ProductModule } from './controllers/product/product.module'; import { UsersModule } from './graphql/users/users.module'; import { WarehousesModule } from './graphql/warehouses/warehouses.module'; import { OrdersModule } from './graphql/orders/orders.module'; import { CarriersModule } from './graphql/carriers/carriers.module'; import { ProductsModule } from './graphql/products/products.module'; import Logger from 'bunyan'; import { env } from './env'; import { createEverLogger } from './helpers/Log'; import { CommandBus, EventBus, CqrsModule } from '@nestjs/cqrs'; import { TestController } from './controllers/test.controller'; import { ModuleRef } from '@nestjs/core'; import { GeoLocationsModule } from './graphql/geo-locations/geo-locations.module'; import { SCALARS } from './graphql/scalars'; import { WarehousesProductsModule } from './graphql/warehouses-products/warehouses-products.modules'; import { WarehousesCarriersModule } from './graphql/warehouses-carriers/warehouses-carriers.module'; import { WarehousesOrdersModule } from './graphql/warehouses-orders/warehouses-orders.module'; import { InvitesRequestsModule } from './graphql/invites-requests/invites-requests.module'; import { AuthModule } from './auth/auth.module'; import { AdminsModule } from './graphql/admin/admins.module'; import { DataModule } from './graphql/data/data.module'; import { CarriersOrdersModule } from './graphql/carriers-orders/carriers-orders.module'; import { GeoLocationOrdersModule } from './graphql/geo-locations/orders/geo-location-orders.module'; import { GeoLocationMerchantsModule } from './graphql/geo-locations/merchants/geo-location-merchants.module'; import { ApolloServer } from 'apollo-server-express'; import { ApolloServerPluginLandingPageGraphQLPlayground, ApolloServerPluginLandingPageGraphQLPlaygroundOptions } from 'apollo-server-core'; // See https://www.apollographql.com/docs/apollo-server/migration/ import { makeExecutableSchema } from '@graphql-tools/schema'; // See https://www.graphql-tools.com/docs/migration/migration-from-merge-graphql-schemas import { mergeTypeDefs } from '@graphql-tools/merge'; import { loadFilesSync } from '@graphql-tools/load-files'; import { GetAboutUsHandler } from './services/users'; import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm'; import { ServicesModule } from './services/services.module'; import { ServicesApp } from './services/services.app'; import { CurrencyModule } from './graphql/currency/currency.module'; import { PromotionModule } from './graphql/products/promotions/promotion.module'; import { AppsSettingsModule } from './graphql/apps-settings/apps-settings.module'; type Config = Parameters<typeof mergeTypeDefs>[1]; const mergeTypes = (types: any[], options?: { schemaDefinition?: boolean, all?: boolean } & Partial<Config>) => { const schemaDefinition = options && typeof options.schemaDefinition === 'boolean' ? options.schemaDefinition : true; return mergeTypeDefs(types, { useSchemaDefinition: schemaDefinition, forceSchemaDefinition: schemaDefinition, throwOnConflict: true, commentDescriptions: true, reverseDirectives: true, ...options, }); }; const port = env.GQLPORT; const host = env.API_HOST; const log: Logger = createEverLogger({ name: 'NestJS ApplicationModule', }); // Add here all CQRS command handlers export const CommandHandlers = [GetAboutUsHandler]; // Add here all CQRS event handlers export const EventHandlers = []; const entities = ServicesApp.getEntities(); const isSSL = process.env.DB_SSL_MODE && process.env.DB_SSL_MODE !== 'false'; // let's temporary save Cert in ./tmp/logs folder because we have write access to it let sslCertPath = `${env.LOGS_PATH}/ca-certificate.crt`; if (isSSL) { const base64data = process.env.DB_CA_CERT; const buff = Buffer.from(base64data, 'base64'); const sslCert = buff.toString('ascii'); fs.writeFileSync(sslCertPath, sslCert); } // TODO: put to config const connectTimeoutMS: number = 40000; // TODO: put to config (we also may want to increase it) const poolSize: number = 50; // We creating default connection for TypeORM. // It might be used in every place where we do not explicitly require connection with some name. // For example, we are using connection named "typeorm" inside our repositories const connectionSettings: TypeOrmModuleOptions = { // Note: do not change this connection name, it should be default one! // TODO: put this into settings (it's mongo only during testing of TypeORM integration!) type: 'mongodb', url: env.DB_URI, ssl: isSSL, sslCA: isSSL ? [sslCertPath] : undefined, host: process.env.DB_HOST || 'localhost', username: process.env.DB_USER, password: process.env.DB_PASS, database: process.env.DB_NAME || 'ever_development', port: process.env.DB_PORT ? parseInt(process.env.DB_PORT, 10) : 27017, entities, synchronize: true, useNewUrlParser: true, // autoReconnect: true, // reconnectTries: Number.MAX_VALUE, // poolSize: poolSize, connectTimeoutMS: connectTimeoutMS, logging: true, logger: 'file', //Removes console logging, instead logs all queries in a file ormlogs.log useUnifiedTopology: true, }; @Module({ controllers: [TestController], providers: [...CommandHandlers, ...EventHandlers], imports: [ DataModule, ServicesModule, CqrsModule, AuthModule, AdminsModule, AppsSettingsModule, ConfigModule, // configure TypeORM Connection which will be possible to use inside NestJS (e.g. resolvers) TypeOrmModule.forRoot(connectionSettings), // define which repositories shall be registered in the current scope (each entity will have own repository). // Thanks to that we can inject the XXXXRepository to the NestJS using the @InjectRepository() decorator // NOTE: this could be used inside NestJS only, not inside our services TypeOrmModule.forFeature(entities), SubscriptionsModule.forRoot(env.GQLPORT_SUBSCRIPTIONS), GraphQLModule.forRoot({ typePaths: ['./**/*.graphql'], installSubscriptionHandlers: true, debug: !env.isProd, playground: true, context: ({ req, res }) => ({ req, }), }), InvitesModule, DevicesModule, ProductModule, WarehousesModule, GeoLocationsModule, UsersModule, OrdersModule, CarriersModule, CarriersOrdersModule, ProductsModule, WarehousesProductsModule, WarehousesOrdersModule, WarehousesCarriersModule, InvitesRequestsModule, GeoLocationOrdersModule, GeoLocationMerchantsModule, CurrencyModule, PromotionModule, ], }) export class ApplicationModule implements NestModule, OnModuleInit { constructor( // @Inject(HTTP_SERVER_REF) // private readonly httpServerRef: HttpServer, private readonly subscriptionsService: SubscriptionsService, // Next required for NestJS CQRS (see https://docs.nestjs.com/recipes/cqrs) private readonly moduleRef: ModuleRef, private readonly command$: CommandBus, private readonly event$: EventBus ) {} onModuleInit() { // initialize CQRS this.event$.register(EventHandlers); this.command$.register(CommandHandlers); } configure(consumer: MiddlewareConsumer) { console.log(chalk.green(`Configuring NestJS ApplicationModule`)); // trick for GraphQL vs MongoDB ObjectId type. // See https://github.com/apollographql/apollo-server/issues/1633 and // https://github.com/apollographql/apollo-server/issues/1649#issuecomment-420840287 const { ObjectId } = mongoose.Types; ObjectId.prototype.valueOf = function () { return this.toString(); }; /* Next is code which could be used to manually create GraphQL Server instead of using GraphQLModule.forRoot(...) const schema: GraphQLSchema = this.createSchema(); const server: ApolloServer = this.createServer(schema); // this creates manually GraphQL subscriptions server (over ws connection) this.subscriptionsService.createSubscriptionServer(server); const app: any = this.httpServerRef; const graphqlPath = '/graphql'; server.applyMiddleware({app, path: graphqlPath}); */ log.info(`GraphQL Playground available at http://${host}:${port}/graphql`); console.log(chalk.green(`GraphQL Playground available at http://${host}:${port}/graphql`)); } /* Creates GraphQL Apollo Server manually */ createServer(schema: GraphQLSchema): ApolloServer { const playgroundOptions: ApolloServerPluginLandingPageGraphQLPlaygroundOptions = { endpoint: `http://${host}:${port}/graphql`, subscriptionEndpoint: `ws://${host}:${port}/subscriptions`, settings: { 'editor.theme': 'dark' } }; return new ApolloServer({ schema, context: ({ req, res }) => ({ req, }), plugins: [ ApolloServerPluginLandingPageGraphQLPlayground(playgroundOptions) ] }); } /* Creates GraphQL Schema manually. See also code in https://github.com/nestjs/graphql/blob/master/lib/graphql.module.ts how it's done by Nest */ createSchema(): GraphQLSchema { const graphqlPath = './**/*.graphql'; console.log(`Searching for *.graphql files`); const typesArray = loadFilesSync(graphqlPath); const typeDefs = mergeTypes(typesArray, { all: true }); // we can save all GraphQL types into one file for later usage by other systems // import { writeFileSync } from 'fs'; // writeFileSync('./all.graphql', typeDefs); const schema = makeExecutableSchema({ typeDefs, resolvers: { ...SCALARS, }, }); return schema; } }
the_stack
import BN = require('bn.js') import chai = require('chai') import 'mocha' import { globalState } from '../../src/globalstate' import Block from '../../src/models/Block' import ExternalTransaction, { IJSONExternalTransaction, isExternalTransaction, } from '../../src/models/ExternalTransaction' import InternalTransaction from '../../src/models/InternalTransaction' import Log from '../../src/models/Log' import { toBN } from '../../src/utils' import erc20Abi from '../data/erc20Abi' import IJSONBlockFactory from '../factories/IJSONBlockFactory' import IJSONExternalTransactionFactory from '../factories/IJSONExternalTransactionFactory' import IJSONInternalTransactionFactory from '../factories/IJSONInternalTransactionFactory' import IJSONLogFactory from '../factories/IJSONLogFactory' import MockIngestApi from '../mocks/MockIngestApi' import { expectThrow } from '../utils' const should = chai .use(require('chai-spies')) .use(require('bn-chai')(BN)) .should() const TRANSFER_EVENT_SIGNATURE = '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef' const TRANSFER_FROM_TOPIC = '0x0000000000000000000000000000000000000000000000000000000000000001' const TRANSFER_TO_TOPIC = '0x0000000000000000000000000000000000000000000000000000000000000002' const TRANSFER_FROM = '0x0000000000000000000000000000000000000001' const TRANSFER_TO = '0x0000000000000000000000000000000000000002' const TRANSFER_DATA = '0x000000000000000000000000000000000000000000000006659436cf28180000' const TRANSFER_VALUE = '118000000000000000000' const MOCK_ADDRESS = '0x123' const NUM_INTERNAL_TX = 4 const NUM_LOGS = 4 const NUM_EXT_TX = 2 describe('Models', function () { beforeEach(async function () { globalState.setApi(new MockIngestApi(NUM_LOGS, NUM_INTERNAL_TX)) }) describe('Block', function () { const bnFields = [ 'number', 'nonce', 'difficulty', 'totalDifficulty', 'size', 'gasLimit', 'gasUsed', 'timestamp', ] it('can be constructed', async function () { const blockData = IJSONBlockFactory.build() const block = new Block(blockData) should.exist(block) // test instantiation bnFields.forEach((f) => { block[f].should.be.eq.BN(toBN(blockData[f])) }) }) it('maps externalTransactions to ExternalTransaction', async function () { const blockData = IJSONBlockFactory.build({ transactions: IJSONExternalTransactionFactory.buildList(NUM_EXT_TX), }) const block = new Block(blockData) block.transactions.length.should.equal(NUM_EXT_TX) block.transactions[0].should.be.instanceof(ExternalTransaction) }) it('can load tx receipts', async function () { const blockData = IJSONBlockFactory.build({ transactions: IJSONExternalTransactionFactory.buildList(NUM_EXT_TX), }) const block = new Block(blockData) await block.loadTransactions() block.transactions.length.should.equal(NUM_EXT_TX) block.transactions[0].logs.length.should.equal(NUM_LOGS) }) it('can load all transactions with tracing', async function () { const blockData = IJSONBlockFactory.build({ transactions: IJSONExternalTransactionFactory.buildList(NUM_EXT_TX), }) const block = new Block(blockData) await block.loadAllTransactions() // should still have 4 external txs block.transactions.length.should.equal(NUM_EXT_TX) // each external tx should have 4 internal txs block.allTransactions.length.should.equal(NUM_EXT_TX + (NUM_EXT_TX * NUM_INTERNAL_TX)) }) }) describe('ExternalTransaction', function () { beforeEach(async function () { this.blockData = IJSONBlockFactory.build({ transactions: IJSONExternalTransactionFactory.buildList(NUM_EXT_TX), }) this.block = new Block(this.blockData) }) const bnFields = [ 'nonce', 'blockNumber', 'value', 'gasPrice', 'gas', ] const receiptBNFields = ['cumulativeGasUsed', 'gasUsed', 'status'] it('can be constructed', async function () { const etxData = IJSONExternalTransactionFactory.build() const etx = new ExternalTransaction(this.block, etxData) should.exist(etx) etx.block.should.equal(this.block) bnFields.forEach((f) => etx[f].should.be.eq.BN(toBN(etxData[f]))) etx.index.should.eq.BN(toBN(etxData.transactionIndex)) }) it('can fetch rceipt', async function () { const etxData = IJSONExternalTransactionFactory.build() const etx = new ExternalTransaction(this.block, etxData) await etx.getReceipt() receiptBNFields.forEach((f) => etx[f].should.eq.BN(toBN('0x0'))) etx.logs.length.should.equal(NUM_LOGS) }) it('can fetch internal transactions', async function () { const etxData = IJSONExternalTransactionFactory.build() const etx = new ExternalTransaction(this.block, etxData) await etx.getInternalTransactions() etx.internalTransactions.length.should.equal(NUM_INTERNAL_TX) }) it('throws for improperly formatted info', async function () { const badData: IJSONExternalTransaction = {} as IJSONExternalTransaction const fn = () => new ExternalTransaction(this.block, badData) fn.should.throw() }) context('without tracing', function () { beforeEach(async function () { chai.spy.on(globalState.api, 'traceTransaction', () => { throw new Error() }) }) afterEach(async function () { chai.spy.restore() }) it('swallows error', async function () { const etxData = IJSONExternalTransactionFactory.build() const etx = new ExternalTransaction(this.block, etxData) await expectThrow(etx.getInternalTransactions()) }) }) context('isExternalTransaction()', function () { it('can identify an internal and external transaction', async function () { const etxData = IJSONExternalTransactionFactory.build() const etx = new ExternalTransaction(this.block, etxData) const itxData = IJSONInternalTransactionFactory.build() const itx = new InternalTransaction(etx, itxData) isExternalTransaction(etx).should.equal(true) isExternalTransaction(itx).should.equal(false) }) }) }) describe('InternalTransaction', function () { const TEST_ERROR = '0x1' const TEST_OUTPUT = '0x1' const TEST_GAS_USED = '0x1' beforeEach(async function () { this.etxData = IJSONExternalTransactionFactory.build() this.etx = new ExternalTransaction(this.block, this.etxData) }) // mostly tested as a side effect of the other tests it('should set result if error not available', async function () { const itxData = IJSONInternalTransactionFactory.build({ error: undefined, result: { output: TEST_OUTPUT, gasUsed: '0x1', } }) const itx = new InternalTransaction(this.etx, itxData) itx.result.output.should.equal(TEST_OUTPUT) itx.result.gasUsed.should.eq.BN(toBN(TEST_GAS_USED)) }) it('should set error if available', async function () { const itxData = IJSONInternalTransactionFactory.build({ error: TEST_ERROR }) const itx = new InternalTransaction(this.etx, itxData) should.not.exist(itx.result) itx.error.should.equal(TEST_ERROR) }) }) describe('Log', function () { const bnFields = [ 'logIndex', 'blockNumber', 'transactionIndex', ] beforeEach(async function () { this.blockData = IJSONBlockFactory.build({ transactions: IJSONExternalTransactionFactory.buildList(NUM_EXT_TX), }) this.block = new Block(this.blockData) this.etxData = IJSONExternalTransactionFactory.build() this.etx = new ExternalTransaction(this.block, this.etxData) }) it('can be constructed', async function () { const logData = IJSONLogFactory.build() const log = new Log(this.etx, logData) should.exist(log) log.should.be.instanceof(Log) bnFields.forEach((f) => log[f].should.be.eq.BN(toBN(logData[f]))) }) context('parse()', function () { it('handles no available abi', async function () { const logData = IJSONLogFactory.build() const log = new Log(this.etx, logData) log.parse().should.equal(false) }) it('handles invalid topic length', async function () { const logData = IJSONLogFactory.build({ address: MOCK_ADDRESS, topics: [] }) const log = new Log(this.etx, logData) log.parse().should.equal(false) }) it('handles not-found abi item', async function () { globalState.addABI(MOCK_ADDRESS, []) const logData = IJSONLogFactory.build({ address: MOCK_ADDRESS, topics: ['', ''] }) const log = new Log(this.etx, logData) log.parse().should.equal(false) }) it('handles invalid log', async function () { globalState.addABI(MOCK_ADDRESS, erc20Abi) const logData = IJSONLogFactory.build({ address: MOCK_ADDRESS, topics: [ TRANSFER_EVENT_SIGNATURE, '0xno', '0xno', ], data: '0x0', }) const log = new Log(this.etx, logData) log.parse().should.equal(false) }) it('should be able to parse valid log for abi item', async function () { globalState.addABI(MOCK_ADDRESS, erc20Abi) const logData = IJSONLogFactory.build({ address: MOCK_ADDRESS, topics: [ TRANSFER_EVENT_SIGNATURE, TRANSFER_FROM_TOPIC, TRANSFER_TO_TOPIC, ], data: TRANSFER_DATA, }) const log = new Log(this.etx, logData) log.parse().should.equal(true) log.event.should.equal('Transfer(address,address,uint256)') log.eventName.should.equal('Transfer') log.signature.should.equal(TRANSFER_EVENT_SIGNATURE) const args = log.args as any args.from.should.equal(TRANSFER_FROM) args.to.should.equal(TRANSFER_TO) args.value.should.equal(TRANSFER_VALUE) }) }) }) })
the_stack
module android.text { import Canvas = android.graphics.Canvas; import Paint = android.graphics.Paint; import Rect = android.graphics.Rect; import Path = android.graphics.Path; import LeadingMarginSpan = android.text.style.LeadingMarginSpan; import LeadingMarginSpan2 = android.text.style.LeadingMarginSpan.LeadingMarginSpan2; import LineBackgroundSpan = android.text.style.LineBackgroundSpan; import ParagraphStyle = android.text.style.ParagraphStyle; import ReplacementSpan = android.text.style.ReplacementSpan; import TabStopSpan = android.text.style.TabStopSpan; import Arrays = java.util.Arrays; import Float = java.lang.Float; import System = java.lang.System; import StringBuilder = java.lang.StringBuilder; import MeasuredText = android.text.MeasuredText; import Spanned = android.text.Spanned; import SpanSet = android.text.SpanSet; import TextDirectionHeuristic = android.text.TextDirectionHeuristic; import TextDirectionHeuristics = android.text.TextDirectionHeuristics; import TextLine = android.text.TextLine; import TextPaint = android.text.TextPaint; import TextUtils = android.text.TextUtils; import TextWatcher = android.text.TextWatcher; window.addEventListener('AndroidUILoadFinish', ()=>{//real import now eval(`TextUtils = android.text.TextUtils; MeasuredText = android.text.MeasuredText; `); }); /** * A base class that manages text layout in visual elements on * the screen. * <p>For text that will be edited, use a {@link DynamicLayout}, * which will be updated as the text changes. * For text that will not change, use a {@link StaticLayout}. */ export abstract class Layout { private static NO_PARA_SPANS:ParagraphStyle[] = []; /** * Return how wide a layout must be in order to display the * specified text with one line per paragraph. */ static getDesiredWidth(source:String, paint:TextPaint):number; static getDesiredWidth(source:String, start:number, end:number, paint:TextPaint):number; static getDesiredWidth(...args){ if(args.length==2) return (<any>Layout).getDesiredWidth_2(...args); if(args.length==4) return (<any>Layout).getDesiredWidth_4(...args); } private static getDesiredWidth_2(source:String, paint:TextPaint):number { return Layout.getDesiredWidth(source, 0, source.length, paint); } /** * Return how wide a layout must be in order to display the * specified text slice with one line per paragraph. */ private static getDesiredWidth_4(source:String, start:number, end:number, paint:TextPaint):number { let need:number = 0; let next:number; for (let i:number = start; i <= end; i = next) { next = source.substring(0, end).indexOf('\n', i);//TextUtils.indexOf(source, '\n', i, end); if (next < 0) next = end; // note, omits trailing paragraph char let w:number = Layout.measurePara(paint, source, i, next); if (w > need) need = w; next++; } return need; } /** * Subclasses of Layout use this constructor to set the display text, * width, and other standard properties. * @param text the text to render * @param paint the default paint for the layout. Styles can override * various attributes of the paint. * @param width the wrapping width for the text. * @param align whether to left, right, or center the text. Styles can * override the alignment. * @param textDir default FIRSTSTRONG_LTR * @param spacingMult factor by which to scale the font size to get the * default line spacing * @param spacingAdd amount to add to the default line spacing * * @hide */ constructor(text:String, paint:TextPaint, width:number, align:Layout.Alignment, textDir:TextDirectionHeuristic = TextDirectionHeuristics.FIRSTSTRONG_LTR, spacingMult:number = 1, spacingAdd:number = 0) { if (width < 0) throw Error(`new IllegalArgumentException("Layout: " + width + " < 0")`); // baselineShift and bgColor. We probably should reevaluate bgColor. if (paint != null) { paint.bgColor = 0; paint.baselineShift = 0; } this.mText = text; this.mPaint = paint; this.mWorkPaint = new TextPaint(); this.mWidth = width; this.mAlignment = align; this.mSpacingMult = spacingMult; this.mSpacingAdd = spacingAdd; this.mSpannedText = Spanned.isImplements(text); this.mTextDir = textDir; } /** * Replace constructor properties of this Layout with new ones. Be careful. */ /* package */ replaceWith(text:String, paint:TextPaint, width:number, align:Layout.Alignment, spacingmult:number, spacingadd:number):void { if (width < 0) { throw Error(`new IllegalArgumentException("Layout: " + width + " < 0")`); } this.mText = text; this.mPaint = paint; this.mWidth = width; this.mAlignment = align; this.mSpacingMult = spacingmult; this.mSpacingAdd = spacingadd; this.mSpannedText = Spanned.isImplements(text); } /** * Draw this Layout on the specified canvas, with the highlight path drawn * between the background and the text. * * @param canvas the canvas * @param highlight the path of the highlight or cursor; can be null * @param highlightPaint the paint for the highlight * @param cursorOffsetVertical the amount to temporarily translate the * canvas while rendering the highlight */ draw(canvas:Canvas, highlight:Path=null, highlightPaint:Paint=null, cursorOffsetVertical:number=0):void { const lineRange:number[] = this.getLineRangeForDraw(canvas); let firstLine:number = TextUtils.unpackRangeStartFromLong(lineRange); let lastLine:number = TextUtils.unpackRangeEndFromLong(lineRange); if (lastLine < 0) return; this.drawBackground(canvas, highlight, highlightPaint, cursorOffsetVertical, firstLine, lastLine); this.drawText(canvas, firstLine, lastLine); } /** * @hide */ drawText(canvas:Canvas, firstLine:number, lastLine:number):void { let previousLineBottom:number = this.getLineTop(firstLine); let previousLineEnd:number = this.getLineStart(firstLine); let spans:ParagraphStyle[] = Layout.NO_PARA_SPANS; let spanEnd:number = 0; let paint:TextPaint = this.mPaint; let buf:String = this.mText; let paraAlign:Layout.Alignment = this.mAlignment; let tabStops:Layout.TabStops = null; let tabStopsIsInitialized:boolean = false; let tl:TextLine = TextLine.obtain(); // The baseline is the top of the following line minus the current line's descent. for (let i:number = firstLine; i <= lastLine; i++) { let start:number = previousLineEnd; previousLineEnd = this.getLineStart(i + 1); let end:number = this.getLineVisibleEnd(i, start, previousLineEnd); let ltop:number = previousLineBottom; let lbottom:number = this.getLineTop(i + 1); previousLineBottom = lbottom; let lbaseline:number = lbottom - this.getLineDescent(i); let dir:number = this.getParagraphDirection(i); let left:number = 0; let right:number = this.mWidth; if (this.mSpannedText) { let sp:Spanned = <Spanned> buf; let textLength:number = buf.length; let isFirstParaLine:boolean = (start == 0 || buf.charAt(start - 1) == '\n'); // our problem. if (start >= spanEnd && (i == firstLine || isFirstParaLine)) { spanEnd = sp.nextSpanTransition(start, textLength, ParagraphStyle.type); spans = Layout.getParagraphSpans(sp, start, spanEnd, ParagraphStyle.type); paraAlign = this.mAlignment; //for (let n:number = spans.length - 1; n >= 0; n--) { // if (spans[n] instanceof AlignmentSpan) { // paraAlign = (<AlignmentSpan> spans[n]).getAlignment(); // break; // } //} tabStopsIsInitialized = false; } // Draw all leading margin spans. Adjust left or right according // to the paragraph direction of the line. const length:number = spans.length; for (let n:number = 0; n < length; n++) { if (LeadingMarginSpan.isImpl(spans[n])) { let margin:LeadingMarginSpan = <LeadingMarginSpan> spans[n]; let useFirstLineMargin:boolean = isFirstParaLine; if (LeadingMarginSpan2.isImpl(margin)) { let count:number = (<LeadingMarginSpan2> margin).getLeadingMarginLineCount(); let startLine:number = this.getLineForOffset(sp.getSpanStart(margin)); useFirstLineMargin = i < startLine + count; } if (dir == Layout.DIR_RIGHT_TO_LEFT) { margin.drawLeadingMargin(canvas, paint, right, dir, ltop, lbaseline, lbottom, buf, start, end, isFirstParaLine, this); right -= margin.getLeadingMargin(useFirstLineMargin); } else { margin.drawLeadingMargin(canvas, paint, left, dir, ltop, lbaseline, lbottom, buf, start, end, isFirstParaLine, this); left += margin.getLeadingMargin(useFirstLineMargin); } } } } let hasTabOrEmoji:boolean = this.getLineContainsTab(i); // Can't tell if we have tabs for sure, currently if (hasTabOrEmoji && !tabStopsIsInitialized) { if (tabStops == null) { tabStops = new Layout.TabStops(Layout.TAB_INCREMENT, spans); } else { tabStops.reset(Layout.TAB_INCREMENT, spans); } tabStopsIsInitialized = true; } // Determine whether the line aligns to normal, opposite, or center. let align:Layout.Alignment = paraAlign; if (align == Layout.Alignment.ALIGN_LEFT) { align = (dir == Layout.DIR_LEFT_TO_RIGHT) ? Layout.Alignment.ALIGN_NORMAL : Layout.Alignment.ALIGN_OPPOSITE; } else if (align == Layout.Alignment.ALIGN_RIGHT) { align = (dir == Layout.DIR_LEFT_TO_RIGHT) ? Layout.Alignment.ALIGN_OPPOSITE : Layout.Alignment.ALIGN_NORMAL; } let x:number; if (align == Layout.Alignment.ALIGN_NORMAL) { if (dir == Layout.DIR_LEFT_TO_RIGHT) { x = left; } else { x = right; } } else { let max:number = Math.floor(this.getLineExtent(i, tabStops, false)); if (align == Layout.Alignment.ALIGN_OPPOSITE) { if (dir == Layout.DIR_LEFT_TO_RIGHT) { x = right - max; } else { x = left - max; } } else { // Layout.Alignment.ALIGN_CENTER max = max & ~1; x = (right + left - max) >> 1; } } let directions:Layout.Directions = this.getLineDirections(i); if (directions == Layout.DIRS_ALL_LEFT_TO_RIGHT && !this.mSpannedText && !hasTabOrEmoji) { // XXX: assumes there's nothing additional to be done canvas.drawText_end(buf.toString(), start, end, x, lbaseline, paint); } else { tl.set(paint, buf, start, end, dir, directions, hasTabOrEmoji, tabStops); tl.draw(canvas, x, ltop, lbaseline, lbottom); } } TextLine.recycle(tl); } /** * @hide */ drawBackground(canvas:Canvas, highlight:Path, highlightPaint:Paint, cursorOffsetVertical:number, firstLine:number, lastLine:number):void { // They are evaluated at each line. if (this.mSpannedText) { if (this.mLineBackgroundSpans == null) { this.mLineBackgroundSpans = new SpanSet<LineBackgroundSpan>(LineBackgroundSpan.type); } let buffer:Spanned = <Spanned> this.mText; let textLength:number = buffer.length; this.mLineBackgroundSpans.init(buffer, 0, textLength); if (this.mLineBackgroundSpans.numberOfSpans > 0) { let previousLineBottom:number = this.getLineTop(firstLine); let previousLineEnd:number = this.getLineStart(firstLine); let spans:ParagraphStyle[] = Layout.NO_PARA_SPANS; let spansLength:number = 0; let paint:TextPaint = this.mPaint; let spanEnd:number = 0; const width:number = this.mWidth; for (let i:number = firstLine; i <= lastLine; i++) { let start:number = previousLineEnd; let end:number = this.getLineStart(i + 1); previousLineEnd = end; let ltop:number = previousLineBottom; let lbottom:number = this.getLineTop(i + 1); previousLineBottom = lbottom; let lbaseline:number = lbottom - this.getLineDescent(i); if (start >= spanEnd) { // These should be infrequent, so we'll use this so that // we don't have to check as often. spanEnd = this.mLineBackgroundSpans.getNextTransition(start, textLength); // All LineBackgroundSpans on a line contribute to its background. spansLength = 0; // Duplication of the logic of getParagraphSpans if (start != end || start == 0) { // array instead to reduce memory allocation for (let j:number = 0; j < this.mLineBackgroundSpans.numberOfSpans; j++) { // construction if (this.mLineBackgroundSpans.spanStarts[j] >= end || this.mLineBackgroundSpans.spanEnds[j] <= start) continue; if (spansLength == spans.length) { // The spans array needs to be expanded let newSize:number = (2 * spansLength); let newSpans:ParagraphStyle[] = new Array<ParagraphStyle>(newSize); System.arraycopy(spans, 0, newSpans, 0, spansLength); spans = newSpans; } spans[spansLength++] = this.mLineBackgroundSpans.spans[j]; } } } for (let n:number = 0; n < spansLength; n++) { let lineBackgroundSpan:LineBackgroundSpan = <LineBackgroundSpan> spans[n]; lineBackgroundSpan.drawBackground(canvas, paint, 0, width, ltop, lbaseline, lbottom, buffer, start, end, i); } } } this.mLineBackgroundSpans.recycle(); } // a non-spanned transformation of a spanned editing buffer. if (highlight != null) { if (cursorOffsetVertical != 0) canvas.translate(0, cursorOffsetVertical); canvas.drawPath(highlight, highlightPaint); if (cursorOffsetVertical != 0) canvas.translate(0, -cursorOffsetVertical); } } /** * @param canvas * @return The range of lines that need to be drawn, possibly empty. * @hide */ getLineRangeForDraw(canvas:Canvas):number[] { let dtop:number, dbottom:number; { if (!canvas.getClipBounds(Layout.sTempRect)) { // Negative range end used as a special flag return TextUtils.packRangeInLong(0, -1); } dtop = Layout.sTempRect.top; dbottom = Layout.sTempRect.bottom; } const top:number = Math.max(dtop, 0); const bottom:number = Math.min(this.getLineTop(this.getLineCount()), dbottom); if (top >= bottom) return TextUtils.packRangeInLong(0, -1); return TextUtils.packRangeInLong(this.getLineForVertical(top), this.getLineForVertical(bottom)); } /** * Return the start position of the line, given the left and right bounds * of the margins. * * @param line the line index * @param left the left bounds (0, or leading margin if ltr para) * @param right the right bounds (width, minus leading margin if rtl para) * @return the start position of the line (to right of line if rtl para) */ private getLineStartPos(line:number, left:number, right:number):number { // Adjust the point at which to start rendering depending on the // alignment of the paragraph. let align:Layout.Alignment = this.getParagraphAlignment(line); let dir:number = this.getParagraphDirection(line); if (align == Layout.Alignment.ALIGN_LEFT) { align = (dir == Layout.DIR_LEFT_TO_RIGHT) ? Layout.Alignment.ALIGN_NORMAL : Layout.Alignment.ALIGN_OPPOSITE; } else if (align == Layout.Alignment.ALIGN_RIGHT) { align = (dir == Layout.DIR_LEFT_TO_RIGHT) ? Layout.Alignment.ALIGN_OPPOSITE : Layout.Alignment.ALIGN_NORMAL; } let x:number; if (align == Layout.Alignment.ALIGN_NORMAL) { if (dir == Layout.DIR_LEFT_TO_RIGHT) { x = left; } else { x = right; } } else { let tabStops:Layout.TabStops = null; if (this.mSpannedText && this.getLineContainsTab(line)) { let spanned:Spanned = <Spanned> this.mText; let start:number = this.getLineStart(line); let spanEnd:number = spanned.nextSpanTransition(start, spanned.length, TabStopSpan.type); let tabSpans:TabStopSpan[] = Layout.getParagraphSpans<TabStopSpan>(spanned, start, spanEnd, TabStopSpan.type); if (tabSpans.length > 0) { tabStops = new Layout.TabStops(Layout.TAB_INCREMENT, tabSpans); } } let max:number = Math.floor(this.getLineExtent(line, tabStops, false)); if (align == Layout.Alignment.ALIGN_OPPOSITE) { if (dir == Layout.DIR_LEFT_TO_RIGHT) { x = right - max; } else { // max is negative here x = left - max; } } else { // Layout.Alignment.ALIGN_CENTER max = max & ~1; x = (left + right - max) >> 1; } } return x; } /** * Return the text that is displayed by this Layout. */ getText():String { return this.mText; } /** * Return the base Paint properties for this layout. * Do NOT change the paint, which may result in funny * drawing for this layout. */ getPaint():TextPaint { return this.mPaint; } /** * Return the width of this layout. */ getWidth():number { return this.mWidth; } /** * Return the width to which this Layout is ellipsizing, or * {@link #getWidth} if it is not doing anything special. */ getEllipsizedWidth():number { return this.mWidth; } /** * Increase the width of this layout to the specified width. * Be careful to use this only when you know it is appropriate&mdash; * it does not cause the text to reflow to use the full new width. */ increaseWidthTo(wid:number):void { if (wid < this.mWidth) { throw Error(`new RuntimeException("attempted to reduce Layout width")`); } this.mWidth = wid; } /** * Return the total height of this layout. */ getHeight():number { return this.getLineTop(this.getLineCount()); } /** * Return the base alignment of this layout. */ getAlignment():Layout.Alignment { return this.mAlignment; } /** * Return what the text height is multiplied by to get the line height. */ getSpacingMultiplier():number { return this.mSpacingMult; } /** * Return the number of units of leading that are added to each line. */ getSpacingAdd():number { return this.mSpacingAdd; } /** * Return the heuristic used to determine paragraph text direction. * @hide */ getTextDirectionHeuristic():TextDirectionHeuristic { return this.mTextDir; } /** * Return the number of lines of text in this layout. */ abstract getLineCount():number ; /** * Return the baseline for the specified line (0&hellip;getLineCount() - 1) * If bounds is not null, return the top, left, right, bottom extents * of the specified line in it. * @param line which line to examine (0..getLineCount() - 1) * @param bounds Optional. If not null, it returns the extent of the line * @return the Y-coordinate of the baseline */ getLineBounds(line:number, bounds:Rect):number { if (bounds != null) { // ??? bounds.left = 0; bounds.top = this.getLineTop(line); // ??? bounds.right = this.mWidth; bounds.bottom = this.getLineTop(line + 1); } return this.getLineBaseline(line); } /** * Return the vertical position of the top of the specified line * (0&hellip;getLineCount()). * If the specified line is equal to the line count, returns the * bottom of the last line. */ abstract getLineTop(line:number):number ; /** * Return the descent of the specified line(0&hellip;getLineCount() - 1). */ abstract getLineDescent(line:number):number ; /** * Return the text offset of the beginning of the specified line ( * 0&hellip;getLineCount()). If the specified line is equal to the line * count, returns the length of the text. */ abstract getLineStart(line:number):number ; /** * Returns the primary directionality of the paragraph containing the * specified line, either 1 for left-to-right lines, or -1 for right-to-left * lines (see {@link #DIR_LEFT_TO_RIGHT}, {@link #DIR_RIGHT_TO_LEFT}). */ abstract getParagraphDirection(line:number):number ; /** * Returns whether the specified line contains one or more * characters that need to be handled specially, like tabs * or emoji. */ abstract getLineContainsTab(line:number):boolean ; /** * Returns the directional run information for the specified line. * The array alternates counts of characters in left-to-right * and right-to-left segments of the line. * * <p>NOTE: this is inadequate to support bidirectional text, and will change. */ abstract getLineDirections(line:number):Layout.Directions ; /** * Returns the (negative) number of extra pixels of ascent padding in the * top line of the Layout. */ abstract getTopPadding():number ; /** * Returns the number of extra pixels of descent padding in the * bottom line of the Layout. */ abstract getBottomPadding():number ; /** * Returns true if the character at offset and the preceding character * are at different run levels (and thus there's a split caret). * @param offset the offset * @return true if at a level boundary * @hide */ isLevelBoundary(offset:number):boolean { let line:number = this.getLineForOffset(offset); let dirs:Layout.Directions = this.getLineDirections(line); if (dirs == Layout.DIRS_ALL_LEFT_TO_RIGHT || dirs == Layout.DIRS_ALL_RIGHT_TO_LEFT) { return false; } let runs:number[] = dirs.mDirections; let lineStart:number = this.getLineStart(line); let lineEnd:number = this.getLineEnd(line); if (offset == lineStart || offset == lineEnd) { let paraLevel:number = this.getParagraphDirection(line) == 1 ? 0 : 1; let runIndex:number = offset == lineStart ? 0 : runs.length - 2; return ((runs[runIndex + 1] >>> Layout.RUN_LEVEL_SHIFT) & Layout.RUN_LEVEL_MASK) != paraLevel; } offset -= lineStart; for (let i:number = 0; i < runs.length; i += 2) { if (offset == runs[i]) { return true; } } return false; } /** * Returns true if the character at offset is right to left (RTL). * @param offset the offset * @return true if the character is RTL, false if it is LTR */ isRtlCharAt(offset:number):boolean { let line:number = this.getLineForOffset(offset); let dirs:Layout.Directions = this.getLineDirections(line); if (dirs == Layout.DIRS_ALL_LEFT_TO_RIGHT) { return false; } if (dirs == Layout.DIRS_ALL_RIGHT_TO_LEFT) { return true; } let runs:number[] = dirs.mDirections; let lineStart:number = this.getLineStart(line); for (let i:number = 0; i < runs.length; i += 2) { let start:number = lineStart + (runs[i] & Layout.RUN_LENGTH_MASK); // corresponding of the last run if (offset >= start) { let level:number = (runs[i + 1] >>> Layout.RUN_LEVEL_SHIFT) & Layout.RUN_LEVEL_MASK; return ((level & 1) != 0); } } // Should happen only if the offset is "out of bounds" return false; } private primaryIsTrailingPrevious(offset:number):boolean { let line:number = this.getLineForOffset(offset); let lineStart:number = this.getLineStart(line); let lineEnd:number = this.getLineEnd(line); let runs:number[] = this.getLineDirections(line).mDirections; let levelAt:number = -1; for (let i:number = 0; i < runs.length; i += 2) { let start:number = lineStart + runs[i]; let limit:number = start + (runs[i + 1] & Layout.RUN_LENGTH_MASK); if (limit > lineEnd) { limit = lineEnd; } if (offset >= start && offset < limit) { if (offset > start) { // Previous character is at same level, so don't use trailing. return false; } levelAt = (runs[i + 1] >>> Layout.RUN_LEVEL_SHIFT) & Layout.RUN_LEVEL_MASK; break; } } if (levelAt == -1) { // Offset was limit of line. levelAt = this.getParagraphDirection(line) == 1 ? 0 : 1; } // At level boundary, check previous level. let levelBefore:number = -1; if (offset == lineStart) { levelBefore = this.getParagraphDirection(line) == 1 ? 0 : 1; } else { offset -= 1; for (let i:number = 0; i < runs.length; i += 2) { let start:number = lineStart + runs[i]; let limit:number = start + (runs[i + 1] & Layout.RUN_LENGTH_MASK); if (limit > lineEnd) { limit = lineEnd; } if (offset >= start && offset < limit) { levelBefore = (runs[i + 1] >>> Layout.RUN_LEVEL_SHIFT) & Layout.RUN_LEVEL_MASK; break; } } } return levelBefore < levelAt; } /** * Get the primary horizontal position for the specified text offset, but * optionally clamp it so that it doesn't exceed the width of the layout. * @hide */ getPrimaryHorizontal(offset:number, clamped=false):number { let trailing:boolean = this.primaryIsTrailingPrevious(offset); return this.getHorizontal(offset, trailing, clamped); } /** * Get the secondary horizontal position for the specified text offset, but * optionally clamp it so that it doesn't exceed the width of the layout. * @hide */ getSecondaryHorizontal(offset:number, clamped=false):number { let trailing:boolean = this.primaryIsTrailingPrevious(offset); return this.getHorizontal(offset, !trailing, clamped); } private getHorizontal(offset:number, trailing:boolean, clamped:boolean):number { let line:number = this.getLineForOffset(offset); return this.getHorizontal_4(offset, trailing, line, clamped); } private getHorizontal_4(offset:number, trailing:boolean, line:number, clamped:boolean):number { let start:number = this.getLineStart(line); let end:number = this.getLineEnd(line); let dir:number = this.getParagraphDirection(line); let hasTabOrEmoji:boolean = this.getLineContainsTab(line); let directions:Layout.Directions = this.getLineDirections(line); let tabStops:Layout.TabStops = null; if (hasTabOrEmoji && Spanned.isImplements(this.mText)) { // Just checking this line should be good enough, tabs should be // consistent across all lines in a paragraph. let tabs:TabStopSpan[] = Layout.getParagraphSpans<TabStopSpan>(<Spanned> this.mText, start, end, TabStopSpan.type); if (tabs.length > 0) { // XXX should reuse tabStops = new Layout.TabStops(Layout.TAB_INCREMENT, tabs); } } let tl:TextLine = TextLine.obtain(); tl.set(this.mPaint, this.mText, start, end, dir, directions, hasTabOrEmoji, tabStops); let wid:number = tl.measure(offset - start, trailing, null); TextLine.recycle(tl); if (clamped && wid > this.mWidth) { wid = this.mWidth; } let left:number = this.getParagraphLeft(line); let right:number = this.getParagraphRight(line); return this.getLineStartPos(line, left, right) + wid; } /** * Get the leftmost position that should be exposed for horizontal * scrolling on the specified line. */ getLineLeft(line:number):number { let dir:number = this.getParagraphDirection(line); let align:Layout.Alignment = this.getParagraphAlignment(line); if (align == Layout.Alignment.ALIGN_LEFT) { return 0; } else if (align == Layout.Alignment.ALIGN_NORMAL) { if (dir == Layout.DIR_RIGHT_TO_LEFT) return this.getParagraphRight(line) - this.getLineMax(line); else return 0; } else if (align == Layout.Alignment.ALIGN_RIGHT) { return this.mWidth - this.getLineMax(line); } else if (align == Layout.Alignment.ALIGN_OPPOSITE) { if (dir == Layout.DIR_RIGHT_TO_LEFT) return 0; else return this.mWidth - this.getLineMax(line); } else { /* align == Layout.Alignment.ALIGN_CENTER */ let left:number = this.getParagraphLeft(line); let right:number = this.getParagraphRight(line); let max:number = (Math.floor(this.getLineMax(line))) & ~1; return left + ((right - left) - max) / 2; } } /** * Get the rightmost position that should be exposed for horizontal * scrolling on the specified line. */ getLineRight(line:number):number { let dir:number = this.getParagraphDirection(line); let align:Layout.Alignment = this.getParagraphAlignment(line); if (align == Layout.Alignment.ALIGN_LEFT) { return this.getParagraphLeft(line) + this.getLineMax(line); } else if (align == Layout.Alignment.ALIGN_NORMAL) { if (dir == Layout.DIR_RIGHT_TO_LEFT) return this.mWidth; else return this.getParagraphLeft(line) + this.getLineMax(line); } else if (align == Layout.Alignment.ALIGN_RIGHT) { return this.mWidth; } else if (align == Layout.Alignment.ALIGN_OPPOSITE) { if (dir == Layout.DIR_RIGHT_TO_LEFT) return this.getLineMax(line); else return this.mWidth; } else { /* align == Layout.Alignment.ALIGN_CENTER */ let left:number = this.getParagraphLeft(line); let right:number = this.getParagraphRight(line); let max:number = (Math.floor(this.getLineMax(line))) & ~1; return right - ((right - left) - max) / 2; } } /** * Gets the unsigned horizontal extent of the specified line, including * leading margin indent, but excluding trailing whitespace. */ getLineMax(line:number):number { let margin:number = this.getParagraphLeadingMargin(line); let signedExtent:number = this.getLineExtent(line, false); return margin + signedExtent >= 0 ? signedExtent : -signedExtent; } /** * Gets the unsigned horizontal extent of the specified line, including * leading margin indent and trailing whitespace. */ getLineWidth(line:number):number { let margin:number = this.getParagraphLeadingMargin(line); let signedExtent:number = this.getLineExtent(line, true); return margin + signedExtent >= 0 ? signedExtent : -signedExtent; } private getLineExtent(line:number, full:boolean):number; private getLineExtent(line:number, tabStops:Layout.TabStops, full:boolean):number; private getLineExtent(...args):number{ if(args.length===2) return (<any>this).getLineExtent_2(...args); if(args.length===3) return (<any>this).getLineExtent_3(...args); } /** * Like {@link #getLineExtent(int,TabStops,boolean)} but determines the * tab stops instead of using the ones passed in. * @param line the index of the line * @param full whether to include trailing whitespace * @return the extent of the line */ private getLineExtent_2(line:number, full:boolean):number { let start:number = this.getLineStart(line); let end:number = full ? this.getLineEnd(line) : this.getLineVisibleEnd(line); let hasTabsOrEmoji:boolean = this.getLineContainsTab(line); let tabStops:Layout.TabStops = null; if (hasTabsOrEmoji && Spanned.isImplements(this.mText)) { // Just checking this line should be good enough, tabs should be // consistent across all lines in a paragraph. let tabs:TabStopSpan[] = Layout.getParagraphSpans<TabStopSpan>(<Spanned> this.mText, start, end, TabStopSpan.type); if (tabs.length > 0) { // XXX should reuse tabStops = new Layout.TabStops(Layout.TAB_INCREMENT, tabs); } } let directions:Layout.Directions = this.getLineDirections(line); // Returned directions can actually be null if (directions == null) { return 0; } let dir:number = this.getParagraphDirection(line); let tl:TextLine = TextLine.obtain(); tl.set(this.mPaint, this.mText, start, end, dir, directions, hasTabsOrEmoji, tabStops); let width:number = tl.metrics(null); TextLine.recycle(tl); return width; } /** * Returns the signed horizontal extent of the specified line, excluding * leading margin. If full is false, excludes trailing whitespace. * @param line the index of the line * @param tabStops the tab stops, can be null if we know they're not used. * @param full whether to include trailing whitespace * @return the extent of the text on this line */ private getLineExtent_3(line:number, tabStops:Layout.TabStops, full:boolean):number { let start:number = this.getLineStart(line); let end:number = full ? this.getLineEnd(line) : this.getLineVisibleEnd(line); let hasTabsOrEmoji:boolean = this.getLineContainsTab(line); let directions:Layout.Directions = this.getLineDirections(line); let dir:number = this.getParagraphDirection(line); let tl:TextLine = TextLine.obtain(); tl.set(this.mPaint, this.mText, start, end, dir, directions, hasTabsOrEmoji, tabStops); let width:number = tl.metrics(null); TextLine.recycle(tl); return width; } /** * Get the line number corresponding to the specified vertical position. * If you ask for a position above 0, you get 0; if you ask for a position * below the bottom of the text, you get the last line. */ // FIXME: It may be faster to do a linear search for layouts without many lines. getLineForVertical(vertical:number):number { let high:number = this.getLineCount(), low:number = -1, guess:number; while (high - low > 1) { guess = Math.floor((high + low) / 2); if (this.getLineTop(guess) > vertical) high = guess; else low = guess; } if (low < 0) return 0; else return low; } /** * Get the line number on which the specified text offset appears. * If you ask for a position before 0, you get 0; if you ask for a position * beyond the end of the text, you get the last line. */ getLineForOffset(offset:number):number { let high:number = this.getLineCount(), low:number = -1, guess:number; while (high - low > 1) { guess = Math.floor((high + low) / 2); if (this.getLineStart(guess) > offset) high = guess; else low = guess; } if (low < 0) return 0; else return low; } /** * Get the character offset on the specified line whose position is * closest to the specified horizontal position. */ getOffsetForHorizontal(line:number, horiz:number):number { let max:number = this.getLineEnd(line) - 1; let min:number = this.getLineStart(line); let dirs:Layout.Directions = this.getLineDirections(line); if (line == this.getLineCount() - 1) max++; let best:number = min; let bestdist:number = Math.abs(this.getPrimaryHorizontal(best) - horiz); for (let i:number = 0; i < dirs.mDirections.length; i += 2) { let here:number = min + dirs.mDirections[i]; let there:number = here + (dirs.mDirections[i + 1] & Layout.RUN_LENGTH_MASK); let swap:number = (dirs.mDirections[i + 1] & Layout.RUN_RTL_FLAG) != 0 ? -1 : 1; if (there > max) there = max; let high:number = there - 1 + 1, low:number = here + 1 - 1, guess:number; while (high - low > 1) { guess = Math.floor((high + low) / 2); let adguess:number = this.getOffsetAtStartOf(guess); if (this.getPrimaryHorizontal(adguess) * swap >= horiz * swap) high = guess; else low = guess; } if (low < here + 1) low = here + 1; if (low < there) { low = this.getOffsetAtStartOf(low); let dist:number = Math.abs(this.getPrimaryHorizontal(low) - horiz); let aft:number = TextUtils.getOffsetAfter(this.mText, low); if (aft < there) { let other:number = Math.abs(this.getPrimaryHorizontal(aft) - horiz); if (other < dist) { dist = other; low = aft; } } if (dist < bestdist) { bestdist = dist; best = low; } } let dist:number = Math.abs(this.getPrimaryHorizontal(here) - horiz); if (dist < bestdist) { bestdist = dist; best = here; } } let dist:number = Math.abs(this.getPrimaryHorizontal(max) - horiz); if (dist <= bestdist) { bestdist = dist; best = max; } return best; } /** * Return the text offset after the last character on the specified line. */ getLineEnd(line:number):number { return this.getLineStart(line + 1); } /** * Return the text offset after the last visible character (so whitespace * is not counted) on the specified line. */ private getLineVisibleEnd(line:number, start:number=this.getLineStart(line), end:number=this.getLineStart(line + 1)):number { let text:String = this.mText; let ch:string; if (line == this.getLineCount() - 1) { return end; } for (; end > start; end--) { ch = text.charAt(end - 1); if (ch == '\n') { return end - 1; } if (ch != ' ' && ch != '\t') { break; } } return end; } /** * Return the vertical position of the bottom of the specified line. */ getLineBottom(line:number):number { return this.getLineTop(line + 1); } /** * Return the vertical position of the baseline of the specified line. */ getLineBaseline(line:number):number { // getLineTop(line+1) == getLineTop(line) return this.getLineTop(line + 1) - this.getLineDescent(line); } /** * Get the ascent of the text on the specified line. * The return value is negative to match the Paint.ascent() convention. */ getLineAscent(line:number):number { // getLineTop(line+1) - getLineDescent(line) == getLineBaseLine(line) return this.getLineTop(line) - (this.getLineTop(line + 1) - this.getLineDescent(line)); } getOffsetToLeftOf(offset:number):number { return this.getOffsetToLeftRightOf(offset, true); } getOffsetToRightOf(offset:number):number { return this.getOffsetToLeftRightOf(offset, false); } private getOffsetToLeftRightOf(caret:number, toLeft:boolean):number { let line:number = this.getLineForOffset(caret); let lineStart:number = this.getLineStart(line); let lineEnd:number = this.getLineEnd(line); let lineDir:number = this.getParagraphDirection(line); let lineChanged:boolean = false; let advance:boolean = toLeft == (lineDir == Layout.DIR_RIGHT_TO_LEFT); // if walking off line, look at the line we're headed to if (advance) { if (caret == lineEnd) { if (line < this.getLineCount() - 1) { lineChanged = true; ++line; } else { // at very end, don't move return caret; } } } else { if (caret == lineStart) { if (line > 0) { lineChanged = true; --line; } else { // at very start, don't move return caret; } } } if (lineChanged) { lineStart = this.getLineStart(line); lineEnd = this.getLineEnd(line); let newDir:number = this.getParagraphDirection(line); if (newDir != lineDir) { // unusual case. we want to walk onto the line, but it runs // in a different direction than this one, so we fake movement // in the opposite direction. toLeft = !toLeft; lineDir = newDir; } } let directions:Layout.Directions = this.getLineDirections(line); let tl:TextLine = TextLine.obtain(); // XXX: we don't care about tabs tl.set(this.mPaint, this.mText, lineStart, lineEnd, lineDir, directions, false, null); caret = lineStart + tl.getOffsetToLeftRightOf(caret - lineStart, toLeft); tl = TextLine.recycle(tl); return caret; } private getOffsetAtStartOf(offset:number):number { // zero-width characters, look at callers if (offset == 0) return 0; let text:String = this.mText; let c:number = text.codePointAt(offset); let questionMark = '?'.codePointAt(0); if (c >= questionMark && c <= questionMark) { let c1:number = text.codePointAt(offset - 1); if (c1 >= questionMark && c1 <= questionMark) offset -= 1; } if (this.mSpannedText) { let spans:ReplacementSpan[] = (<Spanned> text).getSpans<ReplacementSpan>(offset, offset, ReplacementSpan.type); for (let i:number = 0; i < spans.length; i++) { let start:number = (<Spanned> text).getSpanStart(spans[i]); let end:number = (<Spanned> text).getSpanEnd(spans[i]); if (start < offset && end > offset) offset = start; } } return offset; } /** * Determine whether we should clamp cursor position. Currently it's * only robust for left-aligned displays. * @hide */ shouldClampCursor(line:number):boolean { // Only clamp cursor position in left-aligned displays. switch(this.getParagraphAlignment(line)) { case Layout.Alignment.ALIGN_LEFT: return true; case Layout.Alignment.ALIGN_NORMAL: return this.getParagraphDirection(line) > 0; default: return false; } } /** * Fills in the specified Path with a representation of a cursor * at the specified offset. This will often be a vertical line * but can be multiple discontinuous lines in text with multiple * directionalities. */ getCursorPath(point:number, dest:Path, editingBuffer:String):void { dest.reset(); //let line:number = this.getLineForOffset(point); //let top:number = this.getLineTop(line); //let bottom:number = this.getLineTop(line + 1); //let clamped:boolean = this.shouldClampCursor(line); //let h1:number = this.getPrimaryHorizontal(point, clamped) - 0.5; //let h2:number = this.isLevelBoundary(point) ? this.getSecondaryHorizontal(point, clamped) - 0.5 : h1; //let caps:number = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SHIFT_ON) | TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_SELECTING); //let fn:number = TextKeyListener.getMetaState(editingBuffer, TextKeyListener.META_ALT_ON); //let dist:number = 0; //if (caps != 0 || fn != 0) { // dist = (bottom - top) >> 2; // if (fn != 0) // top += dist; // if (caps != 0) // bottom -= dist; //} //if (h1 < 0.5) // h1 = 0.5; //if (h2 < 0.5) // h2 = 0.5; //if (Float.compare(h1, h2) == 0) { // dest.moveTo(h1, top); // dest.lineTo(h1, bottom); //} else { // dest.moveTo(h1, top); // dest.lineTo(h1, (top + bottom) >> 1); // dest.moveTo(h2, (top + bottom) >> 1); // dest.lineTo(h2, bottom); //} //if (caps == 2) { // dest.moveTo(h2, bottom); // dest.lineTo(h2 - dist, bottom + dist); // dest.lineTo(h2, bottom); // dest.lineTo(h2 + dist, bottom + dist); //} else if (caps == 1) { // dest.moveTo(h2, bottom); // dest.lineTo(h2 - dist, bottom + dist); // dest.moveTo(h2 - dist, bottom + dist - 0.5); // dest.lineTo(h2 + dist, bottom + dist - 0.5); // dest.moveTo(h2 + dist, bottom + dist); // dest.lineTo(h2, bottom); //} //if (fn == 2) { // dest.moveTo(h1, top); // dest.lineTo(h1 - dist, top - dist); // dest.lineTo(h1, top); // dest.lineTo(h1 + dist, top - dist); //} else if (fn == 1) { // dest.moveTo(h1, top); // dest.lineTo(h1 - dist, top - dist); // dest.moveTo(h1 - dist, top - dist + 0.5); // dest.lineTo(h1 + dist, top - dist + 0.5); // dest.moveTo(h1 + dist, top - dist); // dest.lineTo(h1, top); //} } private addSelection(line:number, start:number, end:number, top:number, bottom:number, dest:Path):void { //TODO selection //let linestart:number = this.getLineStart(line); //let lineend:number = this.getLineEnd(line); //let dirs:Layout.Directions = this.getLineDirections(line); //if (lineend > linestart && this.mText.charAt(lineend - 1) == '\n') // lineend--; //for (let i:number = 0; i < dirs.mDirections.length; i += 2) { // let here:number = linestart + dirs.mDirections[i]; // let there:number = here + (dirs.mDirections[i + 1] & Layout.RUN_LENGTH_MASK); // if (there > lineend) // there = lineend; // if (start <= there && end >= here) { // let st:number = Math.max(start, here); // let en:number = Math.min(end, there); // if (st != en) { // let h1:number = this.getHorizontal_4(st, false, line, false); // let h2:number = this.getHorizontal_4(en, true, line, false); // let left:number = Math.min(h1, h2); // let right:number = Math.max(h1, h2); // dest.addRect(left, top, right, bottom, Path.Direction.CW); // } // } //} } /** * Fills in the specified Path with a representation of a highlight * between the specified offsets. This will often be a rectangle * or a potentially discontinuous set of rectangles. If the start * and end are the same, the returned path is empty. */ getSelectionPath(start:number, end:number, dest:Path):void { dest.reset(); //TODO selection //if (start == end) // return; //if (end < start) { // let temp:number = end; // end = start; // start = temp; //} //let startline:number = this.getLineForOffset(start); //let endline:number = this.getLineForOffset(end); //let top:number = this.getLineTop(startline); //let bottom:number = this.getLineBottom(endline); //if (startline == endline) { // this.addSelection(startline, start, end, top, bottom, dest); //} else { // const width:number = this.mWidth; // this.addSelection(startline, start, this.getLineEnd(startline), top, this.getLineBottom(startline), dest); // if (this.getParagraphDirection(startline) == Layout.DIR_RIGHT_TO_LEFT) // dest.addRect(this.getLineLeft(startline), top, 0, this.getLineBottom(startline), Path.Direction.CW); // else // dest.addRect(this.getLineRight(startline), top, width, this.getLineBottom(startline), Path.Direction.CW); // for (let i:number = startline + 1; i < endline; i++) { // top = this.getLineTop(i); // bottom = this.getLineBottom(i); // dest.addRect(0, top, width, bottom, Path.Direction.CW); // } // top = this.getLineTop(endline); // bottom = this.getLineBottom(endline); // this.addSelection(endline, this.getLineStart(endline), end, top, bottom, dest); // if (this.getParagraphDirection(endline) == Layout.DIR_RIGHT_TO_LEFT) // dest.addRect(width, top, this.getLineRight(endline), bottom, Path.Direction.CW); // else // dest.addRect(0, top, this.getLineLeft(endline), bottom, Path.Direction.CW); //} } /** * Get the alignment of the specified paragraph, taking into account * markup attached to it. */ getParagraphAlignment(line:number):Layout.Alignment { let align:Layout.Alignment = this.mAlignment; //if (this.mSpannedText) { // let sp:Spanned = <Spanned> this.mText; // let spans:AlignmentSpan[] = Layout.getParagraphSpans(sp, this.getLineStart(line), this.getLineEnd(line), AlignmentSpan.class); // let spanLength:number = spans.length; // if (spanLength > 0) { // align = spans[spanLength - 1].getAlignment(); // } //} return align; } /** * Get the left edge of the specified paragraph, inset by left margins. */ getParagraphLeft(line:number):number { let left:number = 0; let dir:number = this.getParagraphDirection(line); if (dir == Layout.DIR_RIGHT_TO_LEFT || !this.mSpannedText) { // leading margin has no impact, or no styles return left; } return this.getParagraphLeadingMargin(line); } /** * Get the right edge of the specified paragraph, inset by right margins. */ getParagraphRight(line:number):number { let right:number = this.mWidth; let dir:number = this.getParagraphDirection(line); if (dir == Layout.DIR_LEFT_TO_RIGHT || !this.mSpannedText) { // leading margin has no impact, or no styles return right; } return right - this.getParagraphLeadingMargin(line); } /** * Returns the effective leading margin (unsigned) for this line, * taking into account LeadingMarginSpan and LeadingMarginSpan2. * @param line the line index * @return the leading margin of this line */ private getParagraphLeadingMargin(line:number):number { if (!this.mSpannedText) { return 0; } let spanned:Spanned = <Spanned> this.mText; let lineStart:number = this.getLineStart(line); let lineEnd:number = this.getLineEnd(line); let spanEnd:number = spanned.nextSpanTransition(lineStart, lineEnd, LeadingMarginSpan.type); let spans:LeadingMarginSpan[] = Layout.getParagraphSpans<LeadingMarginSpan>(spanned, lineStart, spanEnd, LeadingMarginSpan.type); if (spans.length == 0) { // no leading margin span; return 0; } let margin:number = 0; let isFirstParaLine:boolean = lineStart == 0 || spanned.charAt(lineStart - 1) == '\n'; for (let i:number = 0; i < spans.length; i++) { let span:LeadingMarginSpan = spans[i]; let useFirstLineMargin:boolean = isFirstParaLine; if (LeadingMarginSpan2.isImpl(span)) { let spStart:number = spanned.getSpanStart(span); let spanLine:number = this.getLineForOffset(spStart); let count:number = (<LeadingMarginSpan2> span).getLeadingMarginLineCount(); useFirstLineMargin = line < spanLine + count; } margin += span.getLeadingMargin(useFirstLineMargin); } return margin; } /* package */ static measurePara(paint:TextPaint, text:String, start:number, end:number):number { let mt:MeasuredText = MeasuredText.obtain(); let tl:TextLine = TextLine.obtain(); try { mt.setPara(text, start, end, TextDirectionHeuristics.LTR); let directions:Layout.Directions; let dir:number; //if (mt.mEasy) { directions = Layout.DIRS_ALL_LEFT_TO_RIGHT; dir = Layout.DIR_LEFT_TO_RIGHT; //} else { // directions = AndroidBidi.directions(mt.mDir, mt.mLevels, 0, mt.mChars, 0, mt.mLen); // dir = mt.mDir; //} let chars:string = mt.mChars; let len:number = mt.mLen; let hasTabs:boolean = false; let tabStops:Layout.TabStops = null; for (let i:number = 0; i < len; ++i) { if (chars[i] == '\t') { hasTabs = true; if (Spanned.isImplements(text)) { let spanned:Spanned = <Spanned> text; let spanEnd:number = spanned.nextSpanTransition(start, end, TabStopSpan.type); let spans:TabStopSpan[] = Layout.getParagraphSpans<TabStopSpan>(spanned, start, spanEnd, TabStopSpan.type); if (spans.length > 0) { tabStops = new Layout.TabStops(Layout.TAB_INCREMENT, spans); } } break; } } tl.set(paint, text, start, end, dir, directions, hasTabs, tabStops); return tl.metrics(null); } finally { TextLine.recycle(tl); MeasuredText.recycle(mt); } } /** * Returns the position of the next tab stop after h on the line. * * @param text the text * @param start start of the line * @param end limit of the line * @param h the current horizontal offset * @param tabs the tabs, can be null. If it is null, any tabs in effect * on the line will be used. If there are no tabs, a default offset * will be used to compute the tab stop. * @return the offset of the next tab stop. */ /* package */ static nextTab(text:String, start:number, end:number, h:number, tabs:any[]):number { let nh:number = Float.MAX_VALUE; let alltabs:boolean = false; if (Spanned.isImplements(text)) { if (tabs == null) { tabs = Layout.getParagraphSpans(<Spanned> text, start, end, TabStopSpan.type); alltabs = true; } for (let i:number = 0; i < tabs.length; i++) { if (!alltabs) { if (!(TabStopSpan.isImpl(tabs[i]))) continue; } let where:number = (<TabStopSpan> tabs[i]).getTabStop(); if (where < nh && where > h) nh = where; } if (nh != Float.MAX_VALUE) return nh; } return (Math.floor(((h + Layout.TAB_INCREMENT) / Layout.TAB_INCREMENT))) * Layout.TAB_INCREMENT; } protected isSpanned():boolean { return this.mSpannedText; } /** * Returns the same as <code>text.getSpans()</code>, except where * <code>start</code> and <code>end</code> are the same and are not * at the very beginning of the text, in which case an empty array * is returned instead. * <p> * This is needed because of the special case that <code>getSpans()</code> * on an empty range returns the spans adjacent to that range, which is * primarily for the sake of <code>TextWatchers</code> so they will get * notifications when text goes from empty to non-empty. But it also * has the unfortunate side effect that if the text ends with an empty * paragraph, that paragraph accidentally picks up the styles of the * preceding paragraph (even though those styles will not be picked up * by new text that is inserted into the empty paragraph). * <p> * The reason it just checks whether <code>start</code> and <code>end</code> * is the same is that the only time a line can contain 0 characters * is if it is the final paragraph of the Layout; otherwise any line will * contain at least one printing or newline character. The reason for the * additional check if <code>start</code> is greater than 0 is that * if the empty paragraph is the entire content of the buffer, paragraph * styles that are already applied to the buffer will apply to text that * is inserted into it. */ /* package */ static getParagraphSpans<T> (text:Spanned, start:number, end:number, type:any):T[] { if (start == end && start > 0) { return []; } return text.getSpans<T>(start, end, type); } private getEllipsisChar(method:TextUtils.TruncateAt):string { return (method == TextUtils.TruncateAt.END_SMALL) ? Layout.ELLIPSIS_TWO_DOTS[0] : Layout.ELLIPSIS_NORMAL[0]; } private ellipsize(start:number, end:number, line:number, dest:string[], destoff:number, method:TextUtils.TruncateAt):void { let ellipsisCount:number = this.getEllipsisCount(line); if (ellipsisCount == 0) { return; } let ellipsisStart:number = this.getEllipsisStart(line); let linestart:number = this.getLineStart(line); for (let i:number = ellipsisStart; i < ellipsisStart + ellipsisCount; i++) { let c:string; if (i == ellipsisStart) { // ellipsis c = this.getEllipsisChar(method); } else { // 0-width space c = String.fromCharCode(20);// Java: ' ' } let a:number = i + linestart; if (a >= start && a < end) { dest[destoff + a - start] = c; } } } /** * Return the offset of the first character to be ellipsized away, * relative to the start of the line. (So 0 if the beginning of the * line is ellipsized, not getLineStart().) */ abstract getEllipsisStart(line:number):number ; /** * Returns the number of characters to be ellipsized away, or 0 if * no ellipsis is to take place. */ abstract getEllipsisCount(line:number):number ; private mText:String; private mPaint:TextPaint; /* package */ mWorkPaint:TextPaint; private mWidth:number = 0; private mAlignment:Layout.Alignment = Layout.Alignment.ALIGN_NORMAL; private mSpacingMult:number = 0; private mSpacingAdd:number = 0; private static sTempRect:Rect = new Rect(); private mSpannedText:boolean; private mTextDir:TextDirectionHeuristic; private mLineBackgroundSpans:SpanSet<LineBackgroundSpan>; static DIR_LEFT_TO_RIGHT:number = 1; static DIR_RIGHT_TO_LEFT:number = -1; /* package */ static DIR_REQUEST_LTR:number = 1; /* package */ static DIR_REQUEST_RTL:number = -1; /* package */ static DIR_REQUEST_DEFAULT_LTR:number = 2; /* package */ static DIR_REQUEST_DEFAULT_RTL:number = -2; /* package */ static RUN_LENGTH_MASK:number = 0x03ffffff; /* package */ static RUN_LEVEL_SHIFT:number = 26; /* package */ static RUN_LEVEL_MASK:number = 0x3f; /* package */ static RUN_RTL_FLAG:number = 1 << Layout.RUN_LEVEL_SHIFT; private static TAB_INCREMENT:number = 20; //init last /* package */ static DIRS_ALL_LEFT_TO_RIGHT:Layout.Directions; /* package */ static DIRS_ALL_RIGHT_TO_LEFT:Layout.Directions; /* package */ // this is "..." static ELLIPSIS_NORMAL:string[] = [ '…' ]; /* package */ // this is ".." static ELLIPSIS_TWO_DOTS:string[] = [ '‥' ]; } export module Layout{ /* package */ export class TabStops { private mStops:number[]; private mNumStops:number = 0; private mIncrement:number = 0; constructor( increment:number, spans:any[]) { this.reset(increment, spans); } reset(increment:number, spans:any[]):void { this.mIncrement = increment; let ns:number = 0; if (spans != null) { let stops:number[] = this.mStops; for (let o of spans) { if (TabStopSpan.isImpl(o)) { if (stops == null) { stops = androidui.util.ArrayCreator.newNumberArray(10); } else if (ns == stops.length) { let nstops:number[] = androidui.util.ArrayCreator.newNumberArray(ns * 2); for (let i:number = 0; i < ns; ++i) { nstops[i] = stops[i]; } stops = nstops; } stops[ns++] = (<TabStopSpan> o).getTabStop(); } } if (ns > 1) { Arrays.sort(stops, 0, ns); } if (stops != this.mStops) { this.mStops = stops; } } this.mNumStops = ns; } nextTab(h:number):number { let ns:number = this.mNumStops; if (ns > 0) { let stops:number[] = this.mStops; for (let i:number = 0; i < ns; ++i) { let stop:number = stops[i]; if (stop > h) { return stop; } } } return TabStops.nextDefaultStop(h, this.mIncrement); } static nextDefaultStop(h:number, inc:number):number { return (Math.floor(((h + inc) / inc))) * inc; } } /** * Stores information about bidirectional (left-to-right or right-to-left) * text within the layout of a line. */ export class Directions { // Directions represents directional runs within a line of text. // Runs are pairs of ints listed in visual order, starting from the // leading margin. The first int of each pair is the offset from // the first character of the line to the start of the run. The // second int represents both the length and level of the run. // The length is in the lower bits, accessed by masking with // DIR_LENGTH_MASK. The level is in the higher bits, accessed // by shifting by DIR_LEVEL_SHIFT and masking by DIR_LEVEL_MASK. // To simply test for an RTL direction, test the bit using // DIR_RTL_FLAG, if set then the direction is rtl. /* package */ mDirections:number[]; /* package */ constructor( dirs:number[]) { this.mDirections = dirs; } } /* package */ export class Ellipsizer extends String { /* package */ mText:String; /* package */ mLayout:Layout; /* package */ mWidth:number = 0; /* package */ mMethod:TextUtils.TruncateAt; constructor(s:String) { super(s); this.mText = s; } toString():string { //let line1:number = this.mLayout.getLineForOffset(start); //let line2:number = this.mLayout.getLineForOffset(end); let line1:number = this.mLayout.getLineForOffset(0); let line2:number = this.mLayout.getLineForOffset(this.mText.length); let dest = this.mText.split(''); for (let i:number = line1; i <= line2; i++) { this.mLayout.ellipsize(0, this.mText.length, i, dest, 0, this.mMethod); } return dest.join(''); } } /* package */ export class SpannedEllipsizer extends Layout.Ellipsizer implements Spanned { //FIXME no impl span when ellipsizer private mSpanned:Spanned; constructor(display:String) { super(display); this.mSpanned = <Spanned> display; } getSpans<T> (start:number, end:number, type:any):T[] { return this.mSpanned.getSpans<T>(start, end, type); } getSpanStart(tag:any):number { return this.mSpanned.getSpanStart(tag); } getSpanEnd(tag:any):number { return this.mSpanned.getSpanEnd(tag); } getSpanFlags(tag:any):number { return this.mSpanned.getSpanFlags(tag); } nextSpanTransition(start:number, limit:number, type:any):number { return this.mSpanned.nextSpanTransition(start, limit, type); } } export enum Alignment { ALIGN_NORMAL /*() { } */, ALIGN_OPPOSITE /*() { } */, ALIGN_CENTER /*() { } */, /** @hide */ ALIGN_LEFT /*() { } */, /** @hide */ ALIGN_RIGHT /*() { } */ /*; */} } //init after module loaded /* package */ Layout.DIRS_ALL_LEFT_TO_RIGHT = new Layout.Directions( [ 0, Layout.RUN_LENGTH_MASK ]); /* package */ Layout.DIRS_ALL_RIGHT_TO_LEFT = new Layout.Directions( [ 0, Layout.RUN_LENGTH_MASK | Layout.RUN_RTL_FLAG ]); }
the_stack
import { Component } from '@dtinsight/molecule/esm/react'; import type { ITaskResultService } from './taskResultService'; import taskResultService, { createLinkMark, createLog, createTitle } from './taskResultService'; import type { CatalogueDataProps, IOfflineTaskProps, IResponseBodyProps } from '@/interface'; import API from '@/api'; import { checkExist } from '@/utils'; import { TASK_STATUS_FILTERS, TASK_STATUS, TASK_TYPE_ENUM } from '@/constant'; import moment from 'moment'; import { singleton } from 'tsyringe'; export enum EXECUTE_EVENT { onStartRun = 'onStartRun', onEndRun = 'onEndRun', onStop = 'onStop', } /** * 任务执行的结果 */ interface ITaskExecResultProps { /** * 是否需要下载日志 * @deprecated 目前不支持下载功能 */ download: null | string; isContinue: boolean; /** * 需要轮训的接口才有 jobId */ jobId: null | string; /** * 执行异常返回的信息 */ msg: string | null; /** * 执行完成后的结果 */ result: null | any; /** * 当前执行的 sql 语句 */ sqlText: string; status: TASK_STATUS; taskType: TASK_TYPE_ENUM; } const SELECT_TYPE = { SCRIPT: 0, // 脚本 TASK: 1, // 任务 COMPONENT: 2, // 组件 }; /** * 当前执行的任务属性是把目录获取到的数据和 getTaskById 获取到的数据合并起来 */ type ITask = CatalogueDataProps & IOfflineTaskProps; export interface IExecuteService { /** * 执行 sql 任务 * @param currentTabId 当前任务 id * @param task 当前任务 * @param rawParams 执行的参数 * @param sqls 需要执行的 sql 语句 */ execSql: ( currentTabId: number, task: ITask, rawParams: Record<string, any>, sqls: string[], ) => Promise<void>; /** * 停止当前执行的 Sql 任务 * * 目前执行停止之后还需要继续轮训后端状态,所以停止方法调用成功也不主动执行停止操作,而且根据后续轮训状态来执行停止操作 * @param isSilent 静默关闭,不通知任何人(服务器,用户) */ stopSql: (currentTabId: number, currentTabData: ITask, isSilent: boolean) => Promise<void>; /** * 执行数据同步任务 */ execDataSync: (currentTabId: number, params: Record<string, any>) => Promise<boolean>; /** * 停止数据同步任务 * @param isSilent 静默关闭,不通知任何人(服务器,用户) */ stopDataSync: (currentTabId: number, isSilent: boolean) => Promise<void>; onStartRun: (callback: (currentTabId: number) => void) => void; onEndRun: (callback: (currentTabId: number) => void) => void; onStopTab: (callback: (currentTabId: number) => void) => void; } type IExecuteStates = Record<string, void>; @singleton() export default class ExecuteService extends Component<IExecuteStates> implements IExecuteService { private INTERVALS = 1500; protected state: IExecuteStates; /** * 停止信号量,stop执行成功之后,设置信号量,来让所有正在执行中的网络请求知道任务已经无需再继续 */ protected stopSign: Map<number, boolean>; /** * 正在运行中的 jobId,调用stop接口的时候需要使用 */ protected runningSql: Map<number, string>; /** * 储存各个tab的定时器id,用来stop任务时候清楚定时任务 */ protected intervalsStore: Map<number, number>; private taskResultService: ITaskResultService; constructor() { super(); this.state = {}; this.taskResultService = taskResultService; this.stopSign = new Map(); this.runningSql = new Map(); this.intervalsStore = new Map(); } public execSql = ( currentTabId: number, task: ITask, rawParams: Record<string, any>, sqls: string[], ) => { this.stopSign.set(currentTabId, false); this.emit(EXECUTE_EVENT.onStartRun, currentTabId); const key = this.getUniqueKey(task.id); const params = { ...rawParams, uniqueKey: key, }; return this.exec(currentTabId, task, params, sqls, 0); }; public stopSql = (currentTabId: number, currentTabData: ITask, isSilent: boolean) => { this.emit(EXECUTE_EVENT.onStop, currentTabId); if (isSilent) { this.stopSign.set(currentTabId, true); this.taskResultService.appendLogs( currentTabId.toString(), createLog('执行停止', 'warning'), ); if (this.intervalsStore.has(currentTabId)) { window.clearTimeout(this.intervalsStore.get(currentTabId)); this.intervalsStore.delete(currentTabId); } return Promise.resolve(); } this.stopSign.set(currentTabId, true); const jobId = this.runningSql.get(currentTabId); if (!jobId) return Promise.resolve(); // 任务执行 if (checkExist(currentTabData.taskType)) { return API.stopSQLImmediately({ taskId: currentTabData.id, jobId, }).then(() => Promise.resolve()); } // 脚本执行 if (checkExist(currentTabData.type)) { return API.stopScript({ scriptId: currentTabData.id, jobId, }).then(() => Promise.resolve()); } return Promise.resolve(); }; public execDataSync = async (currentTabId: number, params: Record<string, any>) => { this.stopSign.set(currentTabId, false); this.emit(EXECUTE_EVENT.onStartRun, currentTabId); this.taskResultService.clearLogs(currentTabId.toString()); this.taskResultService.appendLogs( currentTabId.toString(), `同步任务【${params.name}】开始执行`, ); const res = await API.execDataSyncImmediately<ITaskExecResultProps>(params); // 执行结果异常的情况下,存在 message if (res && res.code && res.message) { this.taskResultService.appendLogs( currentTabId.toString(), createLog(`${res.message}`, 'error'), ); } // 执行结束 if (!res || (res && res.code !== 1)) { this.taskResultService.appendLogs( currentTabId.toString(), createLog(`请求异常!`, 'error'), ); } if (res && res.code === 1) { this.taskResultService.appendLogs( currentTabId.toString(), createLog(`已经成功发送执行请求...`, 'info'), ); if (res.data && res.data.msg) { this.taskResultService.appendLogs( currentTabId.toString(), createLog(`${res.data.msg}`, this.typeCreate(res.data.status)), ); } // 存在 jobId 则去轮训接口获取后续任务执行的状态 if (res.data && res.data.jobId) { this.runningSql.set(currentTabId, res.data.jobId); return this.selectData( res.data.jobId, currentTabId, { id: currentTabId, taskType: SELECT_TYPE.TASK }, TASK_TYPE_ENUM.SYNC, ).then((result) => { this.emit(EXECUTE_EVENT.onEndRun, currentTabId); return result; }); } this.taskResultService.appendLogs( currentTabId.toString(), createLog(`执行返回结果异常`, 'error'), ); } this.emit(EXECUTE_EVENT.onEndRun, currentTabId); return true; }; public stopDataSync = async (currentTabId: number, isSilent: boolean) => { if (isSilent) { this.stopSign.set(currentTabId, true); this.emit(EXECUTE_EVENT.onStop, currentTabId); this.taskResultService.appendLogs( currentTabId.toString(), createLog('执行停止', 'warning'), ); if (this.intervalsStore.get(currentTabId)) { window.clearTimeout(this.intervalsStore.get(currentTabId)); this.intervalsStore.delete(currentTabId); } return; } const jobId = this.runningSql.get(currentTabId); if (!jobId) return; const res = await API.stopDataSyncImmediately({ jobId }); if (res && res.code === 1) { this.taskResultService.appendLogs( currentTabId.toString(), createLog('执行停止', 'warning'), ); } }; private getUniqueKey = (id: number) => `${id}_${moment().valueOf()}`; /** * 执行一系列 sql 任务 * @param {number} currentTabId 当前任务的 ID * @param {ITask} task 任务对象 * @param {Params} params 额外参数 * @param {Array} sqls 要执行的Sql数组 * @param {Int} index 当前执行的数组下标 */ private exec = ( currentTabId: number, task: ITask, rawParams: Record<string, any>, sqls: string[], index: number, ) => { const params = { ...rawParams }; params.sql = `${sqls[index]}`; params.isEnd = sqls.length === index + 1; if (index === 0) { // 重置当前任务执行的日志信息 taskResultService.clearLogs(currentTabId.toString()); } taskResultService.appendLogs( currentTabId.toString(), createLog(`第${index + 1}条任务开始执行`, 'info'), ); // 任务执行 if (checkExist(task.taskType)) { params.taskId = task.id; return API.execSQLImmediately<ITaskExecResultProps>(params) .then((res) => this.succCall(res, currentTabId, task)) .then((res) => { // 执行结果正常,才会去判断是否继续后续步骤 if (res) { const isContinue = this.judgeIfContinueExec(sqls, index); if (isContinue) { // 继续执行之前判断是否停止 if (this.stopSign.get(currentTabId)) { this.stopSign.set(currentTabId, false); taskResultService.appendLogs( currentTabId.toString(), createLog(`用户主动取消请求!`, 'error'), ); } else { // 继续执行下一条 sql this.exec(currentTabId, task, params, sqls, index + 1); return; } } } this.emit(EXECUTE_EVENT.onEndRun, currentTabId); }); } // 脚本执行 if (checkExist(task.type)) { params.scriptId = task.id; return API.execScript<ITaskExecResultProps>(params) .then((res) => this.succCall(res, currentTabId, task)) .then((res) => { if (res) { const isContinue = this.judgeIfContinueExec(sqls, index); if (isContinue) { // 继续执行之前判断是否停止 if (this.stopSign.get(currentTabId)) { this.stopSign.set(currentTabId, false); taskResultService.appendLogs( currentTabId.toString(), createLog(`用户主动取消请求!`, 'error'), ); } else { // 继续执行下一条 sql this.exec(currentTabId, task, params, sqls, index + 1); } } } }); } // 组件执行 if (checkExist((task as any).componentType)) { params.componentId = task.id; params.componentType = (task as any).componentType; return API.execComponent<ITaskExecResultProps>(params) .then((res) => this.succCall(res, currentTabId, task)) .then((res) => { if (res) { const isContinue = this.judgeIfContinueExec(sqls, index); if (isContinue) { // 继续执行之前判断是否停止 if (this.stopSign.get(currentTabId)) { this.stopSign.set(currentTabId, false); taskResultService.appendLogs( currentTabId.toString(), createLog(`用户主动取消请求!`, 'error'), ); } else { // 继续执行下一条 sql this.exec(currentTabId, task, params, sqls, index + 1); } } } }); } return Promise.resolve(); }; private typeCreate = (status: TASK_STATUS) => status === TASK_STATUS.RUN_FAILED ? 'error' : 'info'; /** * 执行 sql 成功后的回调 * @returns */ private succCall = async ( res: IResponseBodyProps<ITaskExecResultProps>, currentTabId: number, task: ITask, ) => { // 假如已经是停止状态,则弃用结果 if (this.stopSign.get(currentTabId)) { this.stopSign.set(currentTabId, false); taskResultService.appendLogs( currentTabId.toString(), createLog(`用户主动取消请求!`, 'error'), ); return false; } // 如果接口请求执行失败而非 sql 语句执行失败,需要将执行信息输出到日志 Panel if (res && res.code && res.message) { taskResultService.appendLogs( currentTabId.toString(), createLog(`${res.message}`, 'error'), ); } // 如果接口请求执行失败 if (!res || (res && res.code !== 1)) { taskResultService.appendLogs(currentTabId.toString(), createLog(`请求异常!`, 'error')); return false; } if (res && res.code === 1) { // 执行成功后,将执行后的信息输出到日志 Panel if (res.data && res.data.msg) { taskResultService.appendLogs( currentTabId.toString(), createLog(`${res.data.msg}`, this.typeCreate(res.data.status)), ); } // 在立即执行 sql 成功后,显示转化之后的任务信息(sqlText) if (res.data && res.data.sqlText) { taskResultService.appendLogs( currentTabId.toString(), `${createTitle('任务信息')}\n${res.data.sqlText}\n${createTitle('')}`, ); } // 如果存在 jobId,则需要轮训根据 jobId 继续获取后续结果 if (res.data?.jobId) { this.runningSql.set(currentTabId, res.data.jobId); return this.selectData(res.data.jobId, currentTabId, task); } // 不存在jobId,则直接返回结果 this.getDataOver(currentTabId, res); return true; } return false; }; /** * 轮训调用 */ private selectData = ( jobId: string, currentTabId: number, task: Pick<ITask, 'id' | 'taskType'>, taskType: TASK_TYPE_ENUM = TASK_TYPE_ENUM.SPARK_SQL, ) => this.doSelect(jobId, currentTabId, task, taskType); /** * 判断是否继续执行 * @param sqls 需要执行的全部 sqls 数组 * @param index 当前执行的 sql 索引 */ private judgeIfContinueExec = (sqls: string[], index: number) => index < sqls.length - 1; /** * 根据不同的状态输出不同的信息,并进行后续的日志输出以及是否进行 download */ private getDataOver = ( currentTabId: number, res: IResponseBodyProps<ITaskExecResultProps>, jobId?: string, ) => { if (res.data) { this.outputStatus(currentTabId, res.data.status); } if (res.data?.result) { taskResultService.setResult(jobId || currentTabId.toString(), res.data.result); } if (res.data && res.data.download) { taskResultService.appendLogs( currentTabId.toString(), `完整日志下载地址:${createLinkMark({ href: res.data.download, download: '', })}\n`, ); } }; private outputStatus = (currentTabId: number, status: TASK_STATUS, extText?: string) => { for (let i = 0; i < TASK_STATUS_FILTERS.length; i += 1) { if (TASK_STATUS_FILTERS[i].value === status) { taskResultService.appendLogs( currentTabId.toString(), createLog( `${TASK_STATUS_FILTERS[i].text}${extText || ''}`, this.typeCreate(status), ), ); } } }; // cancle状态和faild状态(接口正常,业务异常状态)特殊处理 private abnormal = (currentTabId: number, data: ITaskExecResultProps) => { if (data.status) { this.outputStatus(currentTabId, data.status); } if (data.download) { taskResultService.appendLogs( currentTabId.toString(), `完整日志下载地址:${createLinkMark({ href: data.download, download: '', })}\n`, ); } }; /** * 展示返回结果中的 message */ private showMsg = (currentTabId: number, res: any) => { if (res.message) { taskResultService.appendLogs( currentTabId.toString(), createLog(`${res.message}`, 'error'), ); } if (res.data && res.data.msg) { taskResultService.appendLogs( currentTabId.toString(), createLog(`${res.data.msg}`, this.typeCreate(res.data.status)), ); } }; /** * 数据同步轮训请求 */ private retationRequestSync = (currentTabId: number, data?: ITaskExecResultProps | null) => { if (data) { // 取消重拾请求,改为一次性请求 this.abnormal(currentTabId, data); } }; /** * 获取日志接口 */ private selectRunLog = ( currentTabId: number, jobId: string, task: Pick<ITask, 'id'>, type: TASK_TYPE_ENUM, num: number = 0, ) => { API.selectRunLog<ITaskExecResultProps>({ jobId, taskId: task.id, type, sqlId: null, }).then((res) => { if (this.stopSign.get(currentTabId)) { this.stopSign.set(currentTabId, false); taskResultService.appendLogs( currentTabId.toString(), createLog(`用户主动取消请求!`, 'error'), ); return false; } const { code, data, retryLog } = res; if (code) { this.showMsg(currentTabId, res); } if (code !== 1) { taskResultService.appendLogs( currentTabId.toString(), createLog(`请求异常!`, 'error'), ); } if (data && data.download) { taskResultService.appendLogs( currentTabId.toString(), `完整日志下载地址:${createLinkMark({ href: res.data.download, download: '', })}\n`, ); } if (retryLog && num && num <= 3) { this.selectRunLog(currentTabId, jobId, task, type, num + 1); this.outputStatus( currentTabId, TASK_STATUS.WAIT_RUN, `正在进行第${num + 1}次重试,请等候`, ); } }); }; /** * 获取结果接口 */ private selectExecResultData = ( currentTabId: number, jobId: string, task: Pick<ITask, 'id'>, /** * 即 SELECT_TYPE */ type: number, taskType: TASK_TYPE_ENUM, ) => { return new Promise<void>((resolve) => { API.selectExecResultData( { jobId, taskId: task.id, type, sqlId: null, }, taskType, ) .then((res: IResponseBodyProps<ITaskExecResultProps>) => { if (this.stopSign.get(currentTabId)) { this.stopSign.set(currentTabId, false); taskResultService.appendLogs( currentTabId.toString(), createLog(`用户主动取消请求!`, 'error'), ); return false; } if (res) { if (res.code !== 1) { taskResultService.appendLogs( currentTabId.toString(), createLog(`请求异常!`, 'error'), ); } else if (res.data?.result) { taskResultService.appendLogs( currentTabId.toString(), createLog('获取结果成功', 'info'), ); taskResultService.setResult(jobId.toString(), res.data.result); } } }) .finally(() => { resolve(); }); }); }; /** * 获取执行结果 */ private doSelect = ( jobId: string, currentTabId: number, task: Pick<ITask, 'id' | 'taskType'>, taskType: TASK_TYPE_ENUM, ) => { const isTask = checkExist(task && task.taskType); const type = SELECT_TYPE.TASK; // 同步任务轮训结果 if (taskType && taskType === TASK_TYPE_ENUM.SYNC) { return API.selectExecResultDataSync({ jobId, taskId: task.id, type: isTask ? SELECT_TYPE.TASK : SELECT_TYPE.SCRIPT, sqlId: null, }).then((res: IResponseBodyProps<ITaskExecResultProps>) => { if (this.stopSign.get(currentTabId)) { this.stopSign.set(currentTabId, false); taskResultService.appendLogs( currentTabId.toString(), createLog(`用户主动取消请求!`, 'error'), ); return false; } if (res && res.code) { this.showMsg(currentTabId, res); } // 状态正常 if (res && res.code === 1 && res.data) { switch (res.data.status) { case TASK_STATUS.FINISHED: { // 成功 this.getDataOver(currentTabId, res, jobId); return true; } case TASK_STATUS.RUN_FAILED: { // 失败时,判断msg字段内部是否包含appLogs标示,若有,则直接展示 if (res.data.msg && res.data.msg.indexOf('appLogs') > -1) { this.abnormal(currentTabId, res.data); return true; } // 否则重新执行该请求 this.retationRequestSync(currentTabId, res.data); return false; } case TASK_STATUS.STOPED: { this.abnormal(currentTabId, res.data); return true; } default: { // 正常运行,则再次请求,并记录定时器id return new Promise<boolean>((resolve) => { const timeout = window.setTimeout(() => { // 运行中的数据同步任务不输出日志 if (res.data!.status !== TASK_STATUS.RUNNING) { this.outputStatus(currentTabId, res.data!.status, '.....'); } this.doSelect(jobId, currentTabId, task, taskType).then( (success) => { resolve(success); }, ); }, this.INTERVALS); this.intervalsStore.set(currentTabId, timeout); }); } } } else { taskResultService.appendLogs( currentTabId.toString(), createLog(`请求异常!`, 'error'), ); this.retationRequestSync(currentTabId, res.data); return false; } }); } return API.selectStatus({ jobId, taskId: task.id, type, sqlId: null, }).then((res: IResponseBodyProps<ITaskExecResultProps>) => { if (this.stopSign.get(currentTabId)) { this.stopSign.set(currentTabId, false); taskResultService.appendLogs( currentTabId.toString(), createLog(`用户主动取消请求!`, 'error'), ); return false; } // 状态正常 if (res && res.data && res.code === 1) { switch (res.data.status) { case TASK_STATUS.FINISHED: { this.outputStatus(currentTabId, res.data.status); return this.selectExecResultData( currentTabId, jobId, task, type, taskType, ).then(() => { this.selectRunLog(currentTabId, jobId, task, type); return true; }); } case TASK_STATUS.STOPED: case TASK_STATUS.RUN_FAILED: { this.outputStatus(currentTabId, res.data.status); this.selectRunLog(currentTabId, jobId, task, type); return false; } default: { // 正常运行,则再次请求,并记录定时器id return new Promise<boolean>((resolve) => { this.intervalsStore.set( currentTabId, window.setTimeout(() => { this.outputStatus(currentTabId, res.data!.status, '.....'); this.doSelect(jobId, currentTabId, task, taskType).then( (success) => { resolve(success); }, ); }, this.INTERVALS), ); }); } } } else { taskResultService.appendLogs( currentTabId.toString(), createLog(`请求异常!`, 'error'), ); if (res.data) { this.abnormal(currentTabId, res.data); } return false; } }); }; public onStartRun = (callback: (currentTabId: number) => void) => { this.subscribe(EXECUTE_EVENT.onStartRun, callback); }; public onEndRun = (callback: (currentTabId: number) => void) => { this.subscribe(EXECUTE_EVENT.onEndRun, callback); }; public onStopTab = (callback: (currentTabId: number) => void) => { this.subscribe(EXECUTE_EVENT.onStop, callback); }; }
the_stack
'use strict'; import * as vscode from 'vscode'; import * as fs from 'fs'; import * as path from 'path'; import tinycolor from '@ctrl/tinycolor'; import { chooseScope, showNotification, getInfoProvider } from './extension'; import { getConfig } from './configuration'; import * as theme from './theme'; interface ColorConfig { [index: number]: string; default: string | undefined; theme: string | undefined; settings: { global: string | undefined; workspace: string | undefined; }; } export enum ViewMode { standard = 0, palette = 1, } interface WorkbenchCustomizations { [key: string]: any; } export class ElementProvider implements vscode.TreeDataProvider<any> { private _onDidChangeTreeData: vscode.EventEmitter<any> = new vscode.EventEmitter<any>(); readonly onDidChangeTreeData: vscode.Event<any> = this._onDidChangeTreeData.event; viewMode: ViewMode; colors: any; elementData: any = []; colorConfigs: any; elementItems: any = []; constructor(viewMode: ViewMode) { this.viewMode = viewMode; this.loadElementData(); this.loadColors(); this.loadColorConfigs(); for (const key in this.elementData) { const elementData = this.elementData[key]; const treeItem = new Element( elementData, vscode.TreeItemCollapsibleState.None, this.viewMode, this ); this.elementItems[elementData.fullName] = treeItem; } } refresh(element?: any): void { this.loadColorConfigs(); if (element) { element.update(); this._onDidChangeTreeData.fire(element); } else { for (const key in this.elementItems) { this.elementItems[key].update(); } this._onDidChangeTreeData.fire(null); } } getTreeItem(element: Element): vscode.TreeItem { return element; } getChildren(elementTreeGroup?: any): any { const children: any = []; if (this.viewMode === ViewMode.standard) { if (elementTreeGroup) { for (const key in this.elementItems) { const value = this.elementItems[key]; if (value.elementData.group === elementTreeGroup.label) { children.push(value); } } return children; } else { return this.getStandardViewGroups(); } } if (this.viewMode === ViewMode.palette) { if (elementTreeGroup) { return elementTreeGroup.children; } else { return this.getPaletteViewGroups(); } } } toggleViewMode() { this.viewMode = this.viewMode === ViewMode.standard ? ViewMode.palette : ViewMode.standard; this.refresh(); } private getUserColors() { this.colors = {}; const userColors: any = vscode.workspace.getConfiguration().get('codeui.favoriteColors'); if (userColors) { for (const key in userColors) { const value = userColors[key]; if (isHexidecimal(value)) { this.colors[value] = '$(star) ' + key; } else { showNotification( "user-defined color '" + key + ':' + value + ' is not valid. Refer to the config tooltip' ); } } } } private loadColors(): any { this.getUserColors(); const presetColorsText = fs.readFileSync( path.join(__filename, '..', '..', 'data', 'colors.json'), 'utf8' ); const presetColors = JSON.parse(presetColorsText); for (const key in presetColors) { const value = presetColors[key]; if (!this.colors[key]) { this.colors[key] = value; } } } private loadElementData(): any { const fileText: string = fs.readFileSync( path.join(__filename, '..', '..', 'data', 'vscodeElementsArray.json'), 'utf8' ); const allElementsObject = JSON.parse(fileText); for (const key in allElementsObject) { const value = allElementsObject[key]; this.elementData[value.fullName] = value; } } private loadColorConfigs(): any { const elementNames: string[] = []; for (const key in this.elementData) { const value = this.elementData[key]; elementNames.push(value.fullName); } const defaultConfigs = getDefaultConfigs(); const themeConfigs = getThemeConfigs(); const settingsConfigs = getSettingsConfigs(); this.colorConfigs = appendConfigs( elementNames, defaultConfigs, themeConfigs, settingsConfigs ); function appendConfigs( elementNames: string[], defaultConfigs: any, themeConfigs: any, settingsConfigs: any ): any { const colorConfigurations: any = {}; const config = getConfig(); const currentThemeName = config.getColorThemeName(); for (const key in elementNames) { const element: string = elementNames[key]; const elementColorConfig: ColorConfig = { default: undefined, theme: undefined, settings: { global: undefined, workspace: undefined, }, }; elementColorConfig.default = defaultConfigs[element]; if (themeConfigs) { elementColorConfig.theme = themeConfigs[element]; } if (settingsConfigs) { if (settingsConfigs.globalValue) { elementColorConfig.settings.global = settingsConfigs.globalValue[element]; // resolve theme-specific value if (settingsConfigs.globalValue['[' + currentThemeName + ']']) { const themeSpecificCustomizations = settingsConfigs.globalValue['[' + currentThemeName + ']']; if (themeSpecificCustomizations[element]) { elementColorConfig.settings.global = themeSpecificCustomizations[element]; } } // resolve theme-specific value } if (settingsConfigs.workspaceValue) { elementColorConfig.settings.workspace = settingsConfigs.workspaceValue[element]; // resolve theme-specific value if (settingsConfigs.workspaceValue['[' + currentThemeName + ']']) { const themeSpecificCustomizations = settingsConfigs.workspaceValue['[' + currentThemeName + ']']; if (themeSpecificCustomizations[element]) { elementColorConfig.settings.workspace = themeSpecificCustomizations[element]; } } // resolve theme-specific value } } colorConfigurations[element] = elementColorConfig; } return colorConfigurations; } function getDefaultConfigs() { const fileText: string = fs.readFileSync( path.join(__filename, '..', '..', 'data', 'defaultColors_dark.json'), 'utf8' ); const defaultColorsObject = JSON.parse(fileText); return defaultColorsObject; } function getThemeConfigs() { const currentTheme = theme.getCurrentColorTheme(); const workbenchCustomizations = currentTheme.workbenchColorCustomizations; if (workbenchCustomizations) { return workbenchCustomizations; } else { return {}; } } function getSettingsConfigs() { const configurations: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration(); const workbenchColorCustomizations = configurations.inspect( 'workbench.colorCustomizations' ); if (workbenchColorCustomizations) { return workbenchColorCustomizations; } else { return {}; } } } public getStandardViewGroups(): ElementTreeGroup[] { const elementGroupNames = []; const elementTreeGroups: any = []; for (const key in this.elementItems) { const group = this.elementItems[key].elementData.group; if (elementGroupNames.indexOf(group) < 0) { elementGroupNames.push(group); elementTreeGroups.push( new ElementTreeGroup( group, vscode.TreeItemCollapsibleState.Collapsed, undefined, '', ViewMode.standard ) ); } } return elementTreeGroups; } public getPaletteViewGroups(): ElementTreeGroup[] { const elementColors = []; let elementTreeGroups = []; const colorCount: any = []; for (const key in this.elementItems) { const value = this.elementItems[key].colorConfig; let effectiveColor = getEffectiveColor(value); if (effectiveColor) { effectiveColor = effectiveColor.toLowerCase(); } if (elementColors.indexOf(effectiveColor) < 0) { elementColors.push(effectiveColor); let label = effectiveColor; if (!label) { label = '(unset)'; } const elementTreeGroup = new ElementTreeGroup( label, vscode.TreeItemCollapsibleState.Collapsed, effectiveColor, '', ViewMode.palette ); elementTreeGroup.addChild(this.elementItems[key]); elementTreeGroups.push(elementTreeGroup); } else { elementTreeGroups.find((treeGroup) => { if (treeGroup.label === effectiveColor) { treeGroup.addChild(this.elementItems[key]); } }); } } elementTreeGroups = elementTreeGroups.sort((e1, e2) => { if (e1.children.length > e2.children.length) { return -1; } else { return 1; } }); return elementTreeGroups; } public customize(item: Element | ElementTreeGroup) { const targetElements: Array<any> = []; const colorItems: Array<vscode.QuickPickItem> = []; const customizations: WorkbenchCustomizations = {}; let userColor: string | undefined; // Get preset quickpickItems (colors) for (const key in this.colors) { const value = this.colors[key]; colorItems.push({ label: value, description: key }); } // Parse selected element(s) & if element, pass to InfoProvider const infoProvider = getInfoProvider(); if (item instanceof Element) { targetElements.push(item.elementData.fullName); infoProvider.updateSelectedElement(item); } if (item instanceof ElementTreeGroup) { for (const child of item.children) { targetElements.push(child.elementData.fullName); } } // Get customization value from user vscode.window .showQuickPick([{ label: 'Enter a value...' }, { label: 'Choose a preset...' }]) .then((selection) => { if (selection) { if (selection.label === 'Enter a value...') { vscode.window .showInputBox({ placeHolder: 'eg. #f2f2f2' }) .then((selectedColor) => { if (selectedColor) { userColor = selectedColor; apply(); // Write the customization to settings } }); } if (selection.label === 'Choose a preset...') { vscode.window .showQuickPick(colorItems, { canPickMany: false }) .then((selectedColor) => { if (selectedColor) { userColor = selectedColor.description; apply(); // Write the customization to settings } }); } } }); function apply() { for (const element of targetElements) { customizations[element] = userColor; } ElementProvider.updateWorkbenchColors(customizations); } } public async adjustBrightness(item: Element | ElementTreeGroup) { if (item instanceof Element) { const infoProvider = getInfoProvider(); infoProvider.updateSelectedElement(item); } const darken10 = 'Darken (10%)'; const lighten10 = 'Lighten (10%)'; const darkenCustom = 'Darken (Custom value)'; const lightenCustom = 'Lighten (Custom value)'; const actionSelection = await vscode.window.showQuickPick([ darken10, lighten10, darkenCustom, lightenCustom, ]); if (!actionSelection) { return; } if (actionSelection === lighten10) { lighten(item); } else if (actionSelection === darken10) { darken(item); } else if (actionSelection === lightenCustom) { const lightenCustomValueNumber = await showPercentInput(); if (!lightenCustomValueNumber) { return; } lighten(item, lightenCustomValueNumber); } else if (actionSelection === darkenCustom) { const darkenCustomValueNumber = await showPercentInput(); if (!darkenCustomValueNumber) { return; } darken(item, darkenCustomValueNumber); } async function showPercentInput(): Promise<number | undefined> { const percentString = await vscode.window.showInputBox({ prompt: 'Enter a number (Percent)', validateInput(input: string) { const percentNumber = parseFloat(input); if (!isNaN(percentNumber) && isFinite(percentNumber)) { return ''; } return 'Value is not a valid number.'; }, }); if (percentString) { return parseFloat(percentString); } } function darken(item: Element | ElementTreeGroup, value = 5) { const customizations: WorkbenchCustomizations = {}; if (item instanceof Element) { const darkenedValue = '#' + tinycolor(getEffectiveColor(item.colorConfig)).darken(value).toHex(); customizations[item.elementData.fullName] = darkenedValue; } if (item instanceof ElementTreeGroup) { for (const key in item.children) { const value = item.children[key]; const darkenedValue = '#' + tinycolor(getEffectiveColor(value.colorConfig)).darken(value).toHex(); customizations[value.elementData.fullName] = darkenedValue; } } ElementProvider.updateWorkbenchColors(customizations); } function lighten(item: Element | ElementTreeGroup, value = 5) { const customizations: WorkbenchCustomizations = {}; if (item instanceof Element) { const lightenedValue = '#' + tinycolor(getEffectiveColor(item.colorConfig)).lighten(value).toHex(); customizations[item.elementData.fullName] = lightenedValue; } if (item instanceof ElementTreeGroup) { for (const key in item.children) { const value = item.children[key]; const lightenedValue = '#' + tinycolor(getEffectiveColor(value.colorConfig)).lighten(value).toHex(); customizations[value.elementData.fullName] = lightenedValue; } } ElementProvider.updateWorkbenchColors(customizations); } } public clear(item: Element | ElementTreeGroup) { if (item instanceof Element) { const infoProvider = getInfoProvider(); infoProvider.updateSelectedElement(item); const elementName: string = item.elementData.fullName; ElementProvider.updateWorkbenchColors({ [elementName]: undefined }); } else { const customizations: any = {}; for (const element of item.children) { customizations[element.elementData.fullName] = undefined; ElementProvider.updateWorkbenchColors(customizations); } } } public copy(item: Element): void { if (typeof item.description === 'string') { vscode.env.clipboard.writeText(item.description); showNotification('copied ' + item.description); } } static async updateWorkbenchColors(customizations: WorkbenchCustomizations) { const config = getConfig(); const currentThemeProp = '[' + config.getColorThemeName() + ']'; const scope = await resolveScope(); const scopedCustomizations: any = config.getWorkbenchColorCustomizations(scope); for (const element in customizations) { const value = customizations[element]; if ((await isHexidecimal(value)) || value === undefined) { const targetingMode = config.getTargetingMode(); if (targetingMode === 'themeSpecific') { if (scopedCustomizations[currentThemeProp]) { scopedCustomizations[currentThemeProp][element] = value; } else { scopedCustomizations[currentThemeProp] = {}; scopedCustomizations[currentThemeProp][element] = value; } } else { scopedCustomizations[element] = value; } } else { await showNotification(value + 'is not a valid hex color!'); return; } } await vscode.workspace .getConfiguration() .update('workbench.colorCustomizations', scopedCustomizations, scope); } } export class Element extends vscode.TreeItem { viewMode: any; elementData: any; colorConfig: any; dataProvider: any; constructor( elementData: any, collapsibleState: vscode.TreeItemCollapsibleState, viewMode: ViewMode, dataProvider: vscode.TreeDataProvider<any> ) { super('', collapsibleState); this.elementData = elementData; this.tooltip = elementData.info; this.command = { title: '', command: 'showElementInfo', arguments: [this], }; this.dataProvider = dataProvider; this.update(); } private update(): void { if (this.dataProvider.viewMode === ViewMode.standard) { this.label = this.elementData.groupedName; } if (this.dataProvider.viewMode === ViewMode.palette) { this.label = this.elementData.titleName; } this.colorConfig = this.dataProvider.colorConfigs[this.elementData.fullName]; const effectiveColor = getEffectiveColor(this.colorConfig); if (effectiveColor) { this.description = effectiveColor.toLowerCase(); } else { this.description = '-'; } this.iconPath = this.generateIcon(); } private generateIcon(): string { let iconPath = ''; let svgText = ''; let baseColor = ''; let topColor = ''; const colorConfig = this.colorConfig; // Decides the base color & top color, with only customizations appearing as topcoats if (colorConfig.settings.global && colorConfig.settings.workspace) { baseColor = colorConfig.settings.global; topColor = colorConfig.settings.workspace; } else { for (const item of [colorConfig.default, colorConfig.theme]) { if (item) { baseColor = item; } } for (const item of [colorConfig.settings.global, colorConfig.settings.workspace]) { if (item) { topColor = item; } } } // Load template svg text svgText = fs.readFileSync( path.join(__filename, '..', '..', 'resources', 'swatches', 'swatch.svg'), 'utf8' ); // Insert base color to svg text, change corresponding opacity to 1 from 0 if (baseColor) { svgText = svgText.replace( 'fill:%COLOR1%;fill-opacity:0', 'fill:' + baseColor + ';fill-opacity:1' ); } // Insert top color to svg text,, change corresponding opacity to 1 from 0 if (topColor) { svgText = svgText.replace( '<path style="fill:%COLOR2%;stroke-width:0.83446652;fill-opacity:0', '<path style="fill:' + topColor + ';stroke-width:0.83446652;fill-opacity:1' ); } // Write new svg text to a temp, generated svg file iconPath = path.join( __filename, '..', '..', 'resources', 'swatches', 'generated', 'generated_' + baseColor + '-' + topColor + '.svg' ); fs.writeFileSync(iconPath, svgText); // Return the path return iconPath; } contextValue = 'element'; } export class ElementTreeGroup extends vscode.TreeItem { size: any; children: any = []; color: any; constructor( label: string, collapsibleState: vscode.TreeItemCollapsibleState, color: any, tooltip: string, viewMode: ViewMode ) { super(label, collapsibleState); this.label = label; this.color = color; if (color) { this.iconPath = this.getGeneratedIcon(); } if (viewMode === ViewMode.palette) { this.contextValue = 'paletteGroup'; } if (viewMode === ViewMode.standard) { this.contextValue = 'standardGroup'; } } private getGeneratedIcon(): string { let iconPath = ''; let svgText = ''; let baseColor: any; // Load template svg text svgText = fs.readFileSync( path.join(__filename, '..', '..', 'resources', 'swatches', 'swatch.svg'), 'utf8' ); // Get & apply base color (if any) svgText = svgText.replace( 'fill:%COLOR1%;fill-opacity:0', 'fill:' + this.color + ';fill-opacity:1' ); // Write new svg text to a temp, generated svg file iconPath = path.join( __filename, '..', '..', 'resources', 'swatches', 'generated', 'generated_' + this.color + '.svg' ); fs.writeFileSync(iconPath, svgText); // Return the path return iconPath; } addChild(element: Element): void { this.children.push(element); this.description = this.children.length.toString(); } } function getEffectiveColor(colorConfig: ColorConfig): string | undefined { let effective: string | undefined; for (const item of [ colorConfig.default, colorConfig.theme, colorConfig.settings.global, colorConfig.settings.workspace, ]) { if (item) { effective = item; } } return effective; } function resolveScope(): any { const config = getConfig(); const workspaceRootFolder = config.getWorkspaceRootFolder(); const preferredScope = config.getPreferredScope(); let scope: any; if (workspaceRootFolder) { if (preferredScope === 'alwaysAsk') { scope = chooseScope(workspaceRootFolder); if (!scope) { return; } } else if (preferredScope === 'global') { scope = vscode.ConfigurationTarget.Global; } else if (preferredScope === 'workspace') { scope = scope = vscode.ConfigurationTarget.Workspace; } } else if (!workspaceRootFolder) { scope = vscode.ConfigurationTarget.Global; } return scope; } function isHexidecimal(str: string) { const regexp = /^#[0-9a-fA-F]+$/; if (regexp.test(str)) { return true; } else { return false; } }
the_stack
import { assert } from "./errors"; /** * Returns whether this `RegExp` may match on a string that contains a `\n` * character. * * @see https://tc39.es/ecma262/#sec-regexp-regular-expression-objects */ export function canMatchLineFeed(re: RegExp) { // The functions defined below return an integer >= 0 to indicate "keep // processing at index `i`", and -1 to indicate "a line feed character may be // matched by this RegExp". return groupCanMatchLineFeed(0, re, false) === -1; } function groupCanMatchLineFeed(i: number, re: RegExp, inverse: boolean) { for (const src = re.source; i !== -1 && i < src.length;) { switch (src.charCodeAt(i)) { case 41: // ')' return i + 1; // End of a group we're processing. case 40: // '(' if (src.charCodeAt(i + 1) === 63 /* ? */) { const next = src.charCodeAt(i + 2); if (next === 33 /* ! */) { i = groupCanMatchLineFeed(i + 3, re, !inverse); continue; } else if (next === 61 /* = */ || next === 58 /* : */) { i += 2; } else if (next === 60 /* < */) { i += 3; if (src.charCodeAt(i) === 33 /* ! */) { i = groupCanMatchLineFeed(i + 1, re, !inverse); continue; } else if (src.charCodeAt(i) === 61 /* = */) { i++; } else { while (src.charCodeAt(i) !== 62 /* > */) { i++; } } } else { assert(false); } } i = groupCanMatchLineFeed(i + 1, re, inverse); break; case 92: // '\' i = escapedCharacterCanMatchLineFeed(i + 1, re, inverse); break; case 91: // '[' i = characterSetCanMatchLineFeed(i + 1, re, inverse); break; case 46: // '.' if (re.dotAll || inverse) { return -1; } i++; break; case 43: // '+' case 42: // '*' case 63: // '?' case 124: // '|' i++; break; case 123: // '{' i++; while (src.charCodeAt(i - 1) !== 125 /* } */) { i++; } break; case 93: // ']' case 125: // '}' assert(false); break; case 36: // '$' case 94: // '^' case 10: // '\n' if (!inverse) { return -1; } i++; break; default: if (inverse) { return -1; } i++; break; } } return i; } function isDigit(charCode: number) { return charCode >= 48 /* 0 */ && charCode <= 57 /* 9 */; } function isRange(src: string, i: number, n: number, startInclusive: number, endInclusive: number) { if (i + n >= src.length) { return false; } for (let j = 0; j < n; j++) { const chr = src.charCodeAt(i + j); if (chr < startInclusive || chr > endInclusive) { return false; } } return true; } function isHex(src: string, i: number, n: number) { if (i + n >= src.length) { return false; } for (let j = 0; j < n; j++) { const c = src.charCodeAt(i + j); // '0' '9' 'a' 'f' 'A' 'F' if ((c >= 48 && c <= 57) || (c >= 97 && c <= 102) || (c >= 65 && c <= 70)) { continue; } return false; } return true; } function escapedCharacterCanMatchLineFeed(i: number, re: RegExp, inverse: boolean) { const src = re.source, chr = src.charCodeAt(i); switch (chr) { case 110: // 'n' case 115: // 's' case 66: // 'B' case 68: // 'D' case 87: // 'W' return inverse ? i + 1 : -1; case 48: // '0' if (!isRange(src, i + 1, 2, 48 /* 0 */, 55 /* 7 */)) { return inverse ? -1 : i + 1; } if (src.charCodeAt(i + 1) === 49 /* 1 */ && src.charCodeAt(i + 2) === 50 /* 2 */) { // 012 = 10 = '\n' return inverse ? i + 3 : -1; } return inverse ? -1 : i + 3; case 99: // 'c' const controlCharacter = src.charCodeAt(i + 1); if (controlCharacter === 74 /* J */ || controlCharacter === 106 /* j */) { return inverse ? i + 2 : -1; } return inverse ? -1 : i + 2; case 120: // 'x' if (!isHex(src, i + 1, 2)) { return inverse ? -1 : i + 1; } if (src.charCodeAt(i + 1) === 48 /* 0 */) { const next = src.charCodeAt(i + 2); if (next === 97 /* a */ || next === 65 /* A */) { // 0x0A = 10 = \n return inverse ? i + 3 : -1; } } return inverse ? -1 : i + 3; case 117: // 'u' if (src.charCodeAt(i + 1) === 123 /* { */) { i += 2; let x = 0; for (let ch = src.charCodeAt(i); ch !== 125 /* } */; i++) { const v = ch >= 48 /* 0 */ && ch <= 57 /* 9 */ ? ch - 48 /* 0 */ : ch >= 97 /* a */ && ch <= 102 /* f */ ? 10 + ch - 97 /* a */ : 10 + ch - 65 /* A */; x = x * 16 + v; } if (x === 10 /* \n */) { return inverse ? i + 1 : -1; } return inverse ? -1 : i + 1; } if (!isHex(src, i + 1, 4)) { return inverse ? -1 : i + 1; } if (src.charCodeAt(i + 1) === 48 /* 0 */ && src.charCodeAt(i + 2) === 48 /* 0 */ && src.charCodeAt(i + 3) === 48 /* 0 */) { const next = src.charCodeAt(i + 4); if (next === 97 /* a */ || next === 65 /* A */) { // 0x000A = 10 = \n return inverse ? i + 5 : -1; } } return inverse ? -1 : i + 5; // @ts-ignore case 80: // 'P' if (!re.unicode) { return inverse ? -1 : i + 1; } inverse = !inverse; // fallthrough case 112: // 'p' if (!re.unicode) { return inverse ? -1 : i + 1; } const start = i - 1; i += 2; // Skip over 'p{'. while (src.charCodeAt(i) !== 125 /* } */) { i++; } i++; // Skip over '}'. const testRegExpString = src.slice(start, i), testRegExp = new RegExp(testRegExpString, "u"); if (testRegExp.test("\n")) { return inverse ? i : -1; } return inverse ? -1 : i; default: if (chr > 48 /* 0 */ && chr <= 57 /* 9 */) { // Back-reference is treated by the rest of the processing. i++; while (isDigit(src.charCodeAt(i))) { i++; } return i; } return inverse ? -1 : i + 1; } } function characterSetCanMatchLineFeed(i: number, re: RegExp, inverse: boolean) { const src = re.source, start = i - 1; if (src.charCodeAt(i) === 94 /* ^ */) { if (src.charCodeAt(i + 1) === 93 /* ] */) { return inverse ? i + 2 : -1; } i++; inverse = !inverse; } for (let mayHaveRange = false;;) { switch (src.charCodeAt(i)) { case 93: // ']' if (mayHaveRange) { // The test below handles inversions, so we must toggle `inverse` if we // toggled it earlier. if (src.charCodeAt(start + 2) === 94 /* ^ */) { inverse = !inverse; } const testRegExpString = src.slice(start, i + 1), testRegExp = new RegExp(testRegExpString, re.flags); if (testRegExp.test("\n")) { if (!inverse) { return -1; } } else if (inverse) { return -1; } } return i + 1; case 92: // '\' i = escapedCharacterCanMatchLineFeed(i + 1, re, inverse); if (i === -1) { return -1; } break; case 10: // '\n' if (!inverse) { return -1; } i++; break; case 45: // '-' mayHaveRange = true; break; default: if (inverse) { return -1; } i++; break; } } } const mustBeEscapedToBeStatic = new Uint8Array([..."()[]{}*+?^$."].map((c) => c.charCodeAt(0))), mustNotBeEscapedToBeStatic = new Uint8Array([..."123456789wWdDsSpPbBu"].map((c) => c.charCodeAt(0))); /** * Returns the set of strings that the specified `RegExp` may match. If * `undefined`, this `RegExp` can match dynamic strings. */ export function matchesStaticStrings(re: RegExp) { const alternatives = [] as string[], source = re.source; let alt = ""; for (let i = 0, len = source.length; i < len; i++) { const ch = source.charCodeAt(i); if (ch === 124 /* | */) { if (!alternatives.includes(alt)) { alternatives.push(alt); } alt = ""; } else if (ch === 92 /* \ */) { i++; if (i === source.length) { break; } const next = source.charCodeAt(i); switch (next) { case 110: // n alt += "\n"; break; case 114: // r alt += "\r"; break; case 116: // t alt += "\t"; break; case 102: // f alt += "\f"; break; case 118: // v alt += "\v"; break; case 99: // c const controlCh = source.charCodeAt(i + 1), isUpper = 65 <= controlCh && controlCh <= 90, offset = (isUpper ? 65 /* A */ : 107 /* a */) - 1; alt += String.fromCharCode(controlCh - offset); break; case 48: // 0 if (isRange(source, i + 1, 2, 48 /* 0 */, 55 /* 7 */)) { alt += String.fromCharCode(parseInt(source.substr(i + 1, 2), 8)); i += 2; } else { alt += "\0"; } break; case 120: // x if (isHex(source, i + 1, 2)) { alt += String.fromCharCode(parseInt(source.substr(i + 1, 2), 16)); i += 2; } else { alt += "x"; } break; case 117: // u if (source.charCodeAt(i + 1) === 123 /* { */) { const end = source.indexOf("}", i + 2); if (end === -1) { return; } alt += String.fromCharCode(parseInt(source.slice(i + 2, end), 16)); i = end + 1; } else if (isHex(source, i + 1, 4)) { alt += String.fromCharCode(parseInt(source.substr(i + 1, 4), 16)); i += 4; } else { alt += "u"; } return; default: if (mustNotBeEscapedToBeStatic.indexOf(next) !== -1) { return; } alt += source[i]; break; } } else { if (mustBeEscapedToBeStatic.indexOf(ch) !== -1) { return; } alt += source[i]; } } if (!alternatives.includes(alt)) { alternatives.push(alt); } return alternatives; } export interface Node<To extends Node<To>> { toString(): string; firstCharacter(): CharacterSet | undefined; reverse(state: Node.ReverseState): To; } export namespace Node { export type Inner<T extends Node<any>> = T extends Node<infer R> ? R : never; export interface ReverseState { readonly expression: Expression; readonly reversedGroups: (Group | undefined)[]; } } export class Sequence implements Node<Sequence> { public constructor( public readonly nodes: readonly Sequence.Node[], ) {} public toString() { return this.nodes.join(""); } public reverse(state: Node.ReverseState): Sequence { return new Sequence([...this.nodes.map((n) => n.reverse(state))].reverse()); } public firstCharacter() { for (const node of this.nodes) { const firstCharacter = node.firstCharacter(); if (firstCharacter !== undefined) { return firstCharacter; } } return undefined; } } export namespace Sequence { export type Node = Repeat | Anchor; } export abstract class Disjunction<To extends Node<To>> implements Node<To> { public constructor( public readonly alternatives: readonly Sequence[], ) {} protected prefix() { return "("; } protected suffix() { return ")"; } public toString() { return this.prefix() + this.alternatives.join() + this.suffix(); } public firstCharacter(): CharacterSet | undefined { const firstCharacters = this.alternatives .map((a) => a.firstCharacter()) .filter((x) => x !== undefined) as CharacterSet[]; if (firstCharacters.length === 0) { return undefined; } return firstCharacters[0].merge(...firstCharacters.slice(1)); } public abstract reverse(state: Node.ReverseState): To; } export class Group extends Disjunction<Group | NumericEscape | Backreference> { public constructor( alternatives: readonly Sequence[], public readonly index?: number, public readonly name?: string, ) { super(alternatives); } protected prefix() { if (this.name !== undefined) { return "(?<" + this.name + ">"; } if (this.index === undefined) { return "(?:"; } return "("; } public reverse(state: Node.ReverseState): Group | NumericEscape | Backreference { if (this.index !== undefined && state.reversedGroups[this.index - 1] !== undefined) { return new NumericEscape(this.index); } return new Group( this.alternatives.map((a) => a.reverse(state) as Sequence), this.index, this.name, ); } } export class Raw implements Node<Raw> { public constructor( public readonly string: string, ) {} public toString() { return this.string.replace(/[()[\]{}*+?^$.]/g, "\\$&"); } public reverse() { return new Raw([...this.string].reverse().join()); } public firstCharacter() { return new CharacterSet([this], false); } public static readonly a = new Raw("a"); public static readonly z = new Raw("z"); public static readonly A = new Raw("A"); public static readonly Z = new Raw("Z"); public static readonly _ = new Raw("_"); public static readonly _0 = new Raw("0"); public static readonly _9 = new Raw("9"); public static readonly newLine = new Raw("\n"); } export class CharacterSet implements Node<CharacterSet> { public constructor( public readonly alternatives: readonly CharacterSet.Alternative[], public readonly isNegated: boolean, ) {} public toString() { if (this === CharacterSet.digit) { return "\\d"; } if (this === CharacterSet.notDigit) { return "\\D"; } if (this === CharacterSet.word) { return "\\w"; } if (this === CharacterSet.notWord) { return "\\W"; } if (this === CharacterSet.whitespace) { return "\\s"; } if (this === CharacterSet.notWhitespace) { return "\\S"; } const contents = this.alternatives.map( (c) => Array.isArray(c) ? `${c[0]}-${c[1]}` : c.toString(), ).join(""); return `[${this.isNegated ? "^" : ""}${contents}]`; } public negate() { return new CharacterSet(this.alternatives, !this.isNegated); } public makePositive(hasUnicodeFlag?: boolean) { if (!this.isNegated) { return this; } const characterClasses = [] as CharacterClass[], ranges = [0, hasUnicodeFlag ? 0x10FFFF : 0xFFFF]; for (let alternative of this.alternatives) { if (!Array.isArray(alternative)) { if (alternative instanceof CharacterClass) { characterClasses.push(alternative.negate()); continue; } alternative = [alternative, alternative]; } const [alt0, alt1] = alternative, negStart = alt0 instanceof Raw ? alt0.string.charCodeAt(0) : alt0.value, // S negEnd = alt1 instanceof Raw ? alt1.string.charCodeAt(0) : alt1.value; // E for (let i = 0; i < ranges.length; i += 2) { // Let's consider that the range we need to erase is S -> E, and the // positive range we're erasing from is s -> e. const posStart = ranges[i], // s posEnd = ranges[i + 1]; // e if (negEnd < posStart || negStart > posEnd) { // S E s e or s e S E // ^^^ ^^^ nothing to erase } else if (negStart <= posStart) { // S s ... if (negEnd >= posEnd) { // S s e E // ^^^^^^^ erased ranges.splice(i, 2); i -= 2; } else { // S s E e // ^^^^^ erased, s becomes E + 1 ranges[i] = negEnd + 1; } } else if (negEnd >= posEnd) { // s S e E // ^^^^^ erased, e becomes S - 1 ranges[i + 1] = negStart - 1; } else { // s S E e // ^^^ erase, e becomes S - 1 and a new range is added ranges[i + 1] = negStart - 1; ranges.splice(i + 2, 0, negEnd + 1, posEnd); } } } const alternatives = characterClasses as CharacterSet.Alternative[]; for (let i = 0; i < ranges.length; i += 2) { const rangeStart = ranges[i], rangeEnd = ranges[i + 1]; if (rangeStart === rangeEnd) { alternatives.push(Escaped.fromCharCode(rangeStart)); } else { alternatives.push(Escaped.fromCharCode(rangeStart), Escaped.fromCharCode(rangeEnd)); } } alternatives.push(...characterClasses); return new CharacterSet(alternatives, false); } public merge(...others: readonly CharacterSet[]) { const alternatives = this.makePositive().alternatives.slice() as CharacterSet.Alternative[]; for (const other of others) { for (const alternative of other.makePositive().alternatives) { if (alternatives.indexOf(alternative) === -1) { alternatives.push(alternative); } } } return new CharacterSet(alternatives, false); } public reverse() { return this; } public firstCharacter() { return this; } public static readonly digit = new CharacterSet([[Raw._0, Raw._9]], false); public static readonly word = new CharacterSet( [[Raw._0, Raw._9], [Raw.a, Raw.z], [Raw.A, Raw.Z], Raw._], false); public static readonly whitespace = new CharacterSet( [..."\t\n\v\f\r \u00a0\u2000\u2001\u2002\u2003\u2004\u2005", ..."\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000"].map((c) => new Raw(c)), false); public static readonly notDigit = new CharacterSet(CharacterSet.digit.alternatives, true); public static readonly notWord = new CharacterSet(CharacterSet.word.alternatives, true); public static readonly notWhitespace = new CharacterSet( CharacterSet.whitespace.alternatives, true); } export namespace CharacterSet { export type AlternativeAtom = Raw | Escaped; export type Alternative = AlternativeAtom | CharacterClass | [AlternativeAtom, AlternativeAtom]; } export class Escaped implements Node<Escaped> { public constructor( public readonly type: "x" | "u" | "c" | "0", public readonly value: number, ) {} public toString() { const type = this.type, value = this.value, str = type === "0" ? value.toString(8).padStart(2, "0") : type === "c" ? String.fromCharCode(65 + value) : type === "x" ? value.toString(16).padStart(2, "0") : value <= 0xFFFF ? value.toString(16).padStart(4, "0") : "{" + value.toString(16) + "}"; return "\\" + type + str; } public reverse() { return this; } public firstCharacter() { return new CharacterSet([this], false); } public static fromCharCode(charCode: number) { if (charCode >= 32 && charCode <= 126) { return new Raw(String.fromCharCode(charCode)); } if (charCode < 0xFF) { return new Escaped("x", charCode); } return new Escaped("u", charCode); } } export class Dot implements Node<Dot> { private constructor( public readonly includesNewLine: boolean, ) {} public toString() { return "."; } public reverse() { return this; } public firstCharacter() { return new CharacterSet(this.includesNewLine ? [] : [Raw.newLine], true); } public static readonly includingNewLine = new Dot(true); public static readonly excludingNewLine = new Dot(false); } export class CharacterClass implements Node<CharacterClass> { public constructor( public readonly characterClass: string, public readonly isNegative: boolean, ) {} public toString() { return `\\${this.isNegative ? "P" : "p"}{${this.characterClass}}`; } public negate() { return new CharacterClass(this.characterClass, !this.isNegative); } public reverse() { return this; } public firstCharacter() { return new CharacterSet([this], false); } } const enum AnchorKind { Start, End, Boundary, NotBoundary, } export class Anchor implements Node<Anchor> { private constructor( public readonly kind: Anchor.Kind, public readonly string: string, ) {} public toString() { return this.string; } public reverse() { return this; } public firstCharacter() { return undefined; } public static readonly start = new Anchor(AnchorKind.Start, "^"); public static readonly end = new Anchor(AnchorKind.End, "$"); public static readonly boundary = new Anchor(AnchorKind.Boundary, "\\b"); public static readonly notBoundary = new Anchor(AnchorKind.NotBoundary, "\\B"); } export class Lookaround extends Disjunction<Lookaround> { public constructor( alternatives: readonly Sequence[], public readonly isNegative: boolean, public readonly isLookbehind: boolean, ) { super(alternatives); } protected prefix() { return "(?" + (this.isLookbehind ? "<" : "") + (this.isNegative ? "!" : "="); } public reverse(state: Node.ReverseState) { return new Lookaround( this.alternatives.map((a) => a.reverse(state)), this.isNegative, this.isLookbehind, ); } } export namespace Anchor { export type Kind = AnchorKind; } export class Repeat<T extends Repeat.Node = Repeat.Node> implements Node<Repeat> { public constructor( public readonly node: T, public readonly min?: number, public readonly max?: number, public readonly lazy = false, ) {} public get isStar() { return this.min === undefined && this.max === undefined; } public get isPlus() { return this.min === 1 && this.max === undefined; } public get isOptional() { return this.min === undefined && this.max === 1; } public get isNonRepeated() { return this.min === 1 && this.max === 1 && !this.lazy; } public toString() { const node = this.node.toString(), lazy = this.lazy ? "?" : ""; if (this.isOptional) { return node + "?" + lazy; } if (this.isPlus) { return node + "+" + lazy; } if (this.isStar) { return node + "*" + lazy; } return `${node}{${this.min ?? ""},${this.max ?? ""}}${lazy}`; } public reverse(state: Node.ReverseState): Repeat<Node.Inner<T>> { const reversed = this.node.reverse(state) as any; if (reversed === this.node) { return this as any; } return new Repeat(reversed, this.min, this.max, this.lazy); } public firstCharacter() { return this.node.firstCharacter(); } } export namespace Repeat { export type Node = Group | Lookaround | CharacterSet | Raw | Escaped | CharacterClass | Dot | NumericEscape | Backreference; } export class NumericEscape implements Node<Group | NumericEscape | Backreference> { public constructor( public n: number, ) { assert(n > 0); } public toString() { return "\\" + this.n; } public reverse(state: Node.ReverseState) { const i = this.n - 1; if (i >= state.reversedGroups.length || state.reversedGroups[i] !== undefined) { return this; } const group = state.expression.groups[i]; return state.reversedGroups[i] = new Group( group.alternatives.map((a) => a.reverse(state)), group.index, group.name, ); } public firstCharacter() { return undefined; } } export class Backreference implements Node<Group | NumericEscape | Backreference> { public constructor( public readonly name: string, ) {} public toString() { return "\\k<" + this.name + ">"; } public reverse(state: Node.ReverseState) { const n = state.expression.groups.findIndex((g) => g.name === this.name); assert(n !== -1); if (state.reversedGroups[n] !== undefined) { return this; } const group = state.expression.groups[n]; return state.reversedGroups[n] = new Group( group.alternatives.map((a) => a.reverse(state)), group.index, group.name, ); } public firstCharacter() { return undefined; } } export class Expression extends Disjunction<Expression> { public constructor( public readonly re: RegExp, public readonly groups: readonly Group[], alternatives: readonly Sequence[], ) { super(alternatives); } protected prefix() { return ""; } protected suffix() { return ""; } public reverse(state?: Node.ReverseState) { if (state === undefined) { state = { expression: this, reversedGroups: Array.from(this.groups, () => undefined), }; } const alternatives = this.alternatives.map((a) => a.reverse(state!)), re = new RegExp(alternatives.join(""), this.re.flags); assert(state.reversedGroups.indexOf(undefined) === -1); return new Expression(re, state.reversedGroups as Group[], alternatives); } } export const enum CharCodes { LF = 10, Bang = 33, Dollar = 36, LParen = 40, RParen = 41, Star = 42, Plus = 43, Comma = 44, Minus = 45, Dot = 46, Colon = 58, LAngle = 60, Eq = 61, RAngle = 62, Question = 63, LBracket = 91, Backslash = 92, RBracket = 93, Caret = 94, LCurly = 123, Pipe = 124, RCurly = 125, } /** * Returns the AST of the given `RegExp`. */ export function parse(re: RegExp) { const dummyGroup = new Group([], undefined); const src = re.source, groups = [] as Group[]; let i = 0; function repeat<T extends Repeat.Node>(node: T) { const ch = src.charCodeAt(i); let min: number | undefined, max: number | undefined; if (ch === CharCodes.Star) { i++; min = 0; } else if (ch === CharCodes.Plus) { i++; min = 1; } else if (ch === CharCodes.LCurly) { i++; const start = i; for (;;) { const ch = src.charCodeAt(i++); if (isDigit(ch)) { continue; } if (ch === CharCodes.RCurly) { min = max = +src.slice(start, i - 1); break; } if (ch === CharCodes.Comma) { min = +src.slice(start, i - 1); const end = i; for (;;) { const ch = src.charCodeAt(i++); if (isDigit(ch)) { continue; } if (ch === CharCodes.RCurly) { max = +src.slice(end, i - 1); break; } i = start - 1; return new Repeat(node, 1, 1, false); } break; } i = start - 1; return new Repeat(node, 1, 1, false); } } else if (ch === CharCodes.Question) { i++; min = 0; max = 1; } else { return new Repeat(node, 1, 1, false); } let lazy = false; if (src.charCodeAt(i) === CharCodes.Question) { lazy = true; i++; } return new Repeat(node, min, max, lazy); } function escapedCharacter<InCharSet extends boolean>( inCharSet: InCharSet, ): Raw | CharacterSet | Escaped | CharacterClass | (InCharSet extends true ? never : NumericEscape | Backreference) { switch (src.charCodeAt(i++)) { case 110: // n return new Raw("\n"); case 114: // r return new Raw("\r"); case 116: // t return new Raw("\t"); case 102: // f return new Raw("\f"); case 118: // v return new Raw("\n"); case 119: // w return CharacterSet.word; case 87: // W return CharacterSet.notWord; case 100: // d return CharacterSet.digit; case 68: // D return CharacterSet.notDigit; case 115: // s return CharacterSet.whitespace; case 83: // S return CharacterSet.notWhitespace; case 99: // c const controlCh = src.charCodeAt(i), isUpper = 65 <= controlCh && controlCh <= 90, offset = (isUpper ? 65 /* A */ : 107 /* a */) - 1, value = controlCh - offset; i++; return new Escaped("c", value); case 48: // 0 if (isRange(src, i, 2, 48 /* 0 */, 55 /* 7 */)) { const value = parseInt(src.substr(i, 2), 8); i += 2; return new Escaped("0", value); } else { return new Raw("\0"); } case 120: // x if (isHex(src, i, 2)) { const value = parseInt(src.substr(i, 2), 16); i += 2; return new Escaped("x", value); } else { return new Raw("x"); } case 117: // u if (src.charCodeAt(i) === CharCodes.LCurly) { const end = src.indexOf("}", i + 1); assert(end !== -1); const value = parseInt(src.slice(i + 1, end), 16); i = end + 1; return new Escaped("u", value); } else if (isHex(src, i, 4)) { const value = parseInt(src.substr(i, 4), 16); i += 4; return new Escaped("u", value); } else { return new Raw("u"); } case 112: // p case 80: // P assert(src.charCodeAt(i) === CharCodes.LCurly); const start = i + 1, end = src.indexOf("}", start); assert(end > start); i = end + 1; return new CharacterClass(src.slice(start, end), src.charCodeAt(start - 2) === 80); default: if (!inCharSet && isDigit(src.charCodeAt(i - 1))) { const start = i - 1; while (isDigit(src.charCodeAt(i))) { i++; } return new NumericEscape(+src.slice(start, i)) as any; } if (!inCharSet && src.charCodeAt(i - 1) === 107 /* k */) { assert(src.charCodeAt(i) === CharCodes.LAngle); const start = i + 1, end = src.indexOf(">", start); assert(end > start); i = end + 1; return new Backreference(src.slice(start, end)) as any; } return new Raw(src[i - 1]); } } function characterSet() { const alternatives: CharacterSet.Alternative[] = [], isNegated = src.charCodeAt(i) === CharCodes.Caret; if (isNegated) { i++; } while (i < src.length) { switch (src.charCodeAt(i++)) { case CharCodes.RBracket: return new CharacterSet(alternatives, isNegated); case CharCodes.Backslash: const escaped = escapedCharacter(/* inCharSet= */ true); if (escaped instanceof CharacterSet) { assert(!escaped.isNegated); alternatives.push(...escaped.alternatives); } else { alternatives.push(escaped); } break; case CharCodes.Minus: if (alternatives.length === 0) { alternatives.push(new Raw("-")); continue; } const start = alternatives[alternatives.length - 1]; if (Array.isArray(start) || start instanceof CharacterClass) { alternatives.push(new Raw("-")); continue; } switch (src.charCodeAt(i++)) { case CharCodes.RBracket: alternatives.push(new Raw("-")); return new CharacterSet(alternatives, isNegated); default: const end = src.charCodeAt(i - 1) === CharCodes.Backslash ? escapedCharacter(/* inCharSet= */ true) : new Raw(src[i - 1]); if (end instanceof CharacterSet) { assert(!end.isNegated); alternatives.push(new Raw("-"), ...end.alternatives); } else if (end instanceof CharacterClass) { alternatives.push(new Raw("-"), end); } else { alternatives.push([start, end]); } break; } break; default: alternatives.push(new Raw(src[i - 1])); break; } } assert(false); } function group(): readonly Sequence[] { const alternatives: Sequence[] = [], sequence: Sequence.Node[] = []; while (i < src.length) { switch (src.charCodeAt(i)) { case CharCodes.RParen: i++; return alternatives; case CharCodes.Pipe: i++; alternatives.push(new Sequence(sequence.splice(0))); break; case CharCodes.LParen: if (src.charCodeAt(i + 1) === CharCodes.Question) { const next = src.charCodeAt(i + 2); if (next === CharCodes.Colon) { i += 3; sequence.push(repeat(new Group(group()))); } else if (next === CharCodes.Eq) { i += 3; sequence.push(repeat(new Lookaround(group(), false, false))); } else if (next === CharCodes.Bang) { i += 3; sequence.push(repeat(new Lookaround(group(), true, false))); } else if (next === CharCodes.LAngle) { if (src.charCodeAt(i) === CharCodes.Eq) { i += 4; sequence.push(repeat(new Lookaround(group(), false, true))); } else if (src.charCodeAt(i + 3) === CharCodes.Bang) { i += 4; sequence.push(repeat(new Lookaround(group(), true, true))); } else { i += 3; const start = i, n = groups.push(dummyGroup); while (src.charCodeAt(i) !== CharCodes.RAngle) { i++; } i++; sequence.push(repeat(groups[n - 1] = new Group(group(), n, src.slice(start, i - 2)))); } } else { assert(false); } } else { const n = groups.push(dummyGroup); sequence.push(repeat(groups[n - 1] = new Group(group(), n) as any) as Repeat<Group>); } break; case CharCodes.Backslash: i++; sequence.push(repeat(escapedCharacter(/* inCharSet= */ false))); break; case CharCodes.LBracket: i++; sequence.push(repeat(characterSet())); break; case CharCodes.Dot: i++; sequence.push(repeat(re.dotAll ? Dot.includingNewLine : Dot.excludingNewLine)); break; case CharCodes.Caret: i++; sequence.push(Anchor.start); break; case CharCodes.Dollar: i++; sequence.push(Anchor.end); break; default: if (sequence.length > 0 && (sequence[sequence.length - 1] as Repeat<Raw>).node instanceof Raw && (sequence[sequence.length - 1] as Repeat<Raw>).isNonRepeated) { const prev = (sequence[sequence.length - 1] as Repeat<Raw>).node; sequence[sequence.length - 1] = repeat(new Raw(prev.string + src[i])); } else { sequence.push(repeat(new Raw(src[i]))); } break; } } alternatives.push(new Sequence(sequence)); return alternatives; } return new Expression(re, groups, group()); } /** * Returns the last `RegExp` match in the given text. */ export function execLast(re: RegExp, text: string) { if (text.length > 10_000) { // Execute reversed text on reversed regular expression. const reverseRe = parse(re).reverse().re, match = reverseRe.exec([...text].reverse().join("")); if (match === null) { return null; } // Update match index and input. match.index = text.length - match.index - match[0].length; match.input = text; // Reverse all matched groups so that they go back to their original text. match[0] = text.substr(match.index, match[0].length); for (let i = 1; i < match.length; i++) { match[i] = [...match[i]].reverse().join(""); } if (match.groups !== undefined) { for (const name in match.groups) { match.groups[name] = [...match.groups[name]].reverse().join(""); } } return match; } let lastMatch: RegExpExecArray | undefined, lastMatchIndex = 0; for (;;) { const match = re.exec(text); if (match === null) { break; } if (match[0].length === 0) { throw new Error("RegExp returned empty result"); } lastMatchIndex += match.index + (lastMatch?.[0].length ?? 0); lastMatch = match; text = text.slice(match.index + match[0].length); } if (lastMatch === undefined) { return null; } lastMatch.index = lastMatchIndex; return lastMatch; } /** * Parses a RegExp string with a possible replacement. */ export function parseRegExpWithReplacement(regexp: string) { if (regexp.length < 2 || regexp[0] !== "/") { throw new Error("invalid RegExp"); } let pattern = "", replacement: string | undefined = undefined, flags: string | undefined = undefined; for (let i = 1; i < regexp.length; i++) { const ch = regexp[i]; if (flags !== undefined) { // Parse flags if (!"miguys".includes(ch)) { throw new Error(`unknown RegExp flag "${ch}"`); } flags += ch; } else if (replacement !== undefined) { // Parse replacement string if (ch === "/") { flags = ""; } else if (ch === "\\") { if (i === regexp.length - 1) { throw new Error("unexpected end of RegExp"); } replacement += ch + regexp[++i]; } else { replacement += ch; } } else { // Parse pattern if (ch === "/") { replacement = ""; } else if (ch === "\\") { if (i === regexp.length - 1) { throw new Error("unexpected end of RegExp"); } pattern += ch + regexp[++i]; } else { pattern += ch; } } } if ((flags === undefined || flags === "") && /^[miguys]+$/.test(replacement ?? "")) { flags = replacement; replacement = undefined; } try { return [new RegExp(pattern, flags), replacement] as const; } catch { throw new Error("invalid RegExp"); } } /** * Returns a valid RegExp source allowing a `RegExp` to match the given string. */ export function escapeForRegExp(text: string) { // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#Escaping return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } /** * Returns a `RegExp` that matches if any of the two given `RegExp`s does, and * the index of the "marker group" that will be equal to `""` if the `RegExp` * that matched the input is `b`. */ export function anyRegExp(a: RegExp, b: RegExp) { const flags = [...new Set([...a.flags, ...b.flags])].join(""), aGroups = new RegExp("|" + a.source, a.flags).exec("")!.length - 1, bGroups = new RegExp("|" + b.source, b.flags).exec("")!.length - 1; // Update backreferences in `b` to ensure they point to the right indices. const bSource = replaceUnlessEscaped(b.source, /\\(\d+)/g, (text, n) => { if (n[0] === "0" || +n > bGroups) { return text; } return "\\" + (+n + aGroups); }); return [new RegExp(`(?:${a.source})|(?:${bSource})()`, flags), aGroups + bGroups + 1] as const; } /** * Same as `text.replace(...args)`, but does not replaced escaped characters. */ export function replaceUnlessEscaped(text: string, re: RegExp, replace: (...args: any) => string) { return text.replace(re, (...args) => { const offset = args[args.length - 2], text = args[args.length - 1]; if (isEscaped(text, offset)) { return args[0]; } return replace(...args); }); } /** * Same as `text.replace(...args)`, but does not replaced escaped characters. */ export function matchUnlessEscaped(text: string, re: RegExp) { assert(re.global); for (let match = re.exec(text); match !== null; match = re.exec(text)) { if (!isEscaped(text, match.index)) { return match; } } return null; } function isEscaped(text: string, offset: number) { if (offset === 0) { return false; } let isEscaped = false; for (let i = offset - 1; i >= 0; i--) { if (text[i] === "\\") { isEscaped = !isEscaped; } else { return isEscaped; } } return isEscaped; } /** * Like `String.prototype.split(RegExp)`, but returns the `[start, end]` * indices corresponding to each string of the split. */ export function splitRange(text: string, re: RegExp) { const sections: [start: number, end: number][] = []; for (let start = 0;;) { re.lastIndex = 0; const match = re.exec(text); if (match === null || text.length === 0) { sections.push([start, start + text.length]); return sections; } sections.push([start, start + match.index]); if (match[0].length === 0) { text = text.slice(1); start++; } else { text = text.slice(match.index + match[0].length); start += match.index + match[0].length; } } } /** * Like `RegExp.prototype.exec()`, but returns the `[start, end]` * indices corresponding to each matched result. */ export function execRange(text: string, re: RegExp) { re.lastIndex = 0; const sections: [start: number, end: number, match: RegExpExecArray][] = []; let diff = 0; for (let match = re.exec(text); match !== null && text.length > 0; match = re.exec(text)) { const start = match.index, end = start + match[0].length; sections.push([diff + start, diff + end, match]); text = text.slice(end); diff += end; re.lastIndex = 0; if (start === end) { text = text.slice(1); diff++; } } return sections; }
the_stack
import * as RoutingProxy from "../../../generated/joynr/system/RoutingProxy"; import BrowserAddress = require("../../../generated/joynr/system/RoutingTypes/BrowserAddress"); import ChannelAddress = require("../../../generated/joynr/system/RoutingTypes/ChannelAddress"); import WebSocketAddress = require("../../../generated/joynr/system/RoutingTypes/WebSocketAddress"); import WebSocketClientAddress = require("../../../generated/joynr/system/RoutingTypes/WebSocketClientAddress"); import MulticastWildcardRegexFactory from "../util/MulticastWildcardRegexFactory"; import * as DiagnosticTags from "../../system/DiagnosticTags"; import LoggingManager from "../../system/LoggingManager"; import InProcessAddress from "../inprocess/InProcessAddress"; import JoynrMessage from "../JoynrMessage"; import MessageReplyToAddressCalculator from "../MessageReplyToAddressCalculator"; import JoynrRuntimeException from "../../exceptions/JoynrRuntimeException"; import * as Typing from "../../util/Typing"; import * as UtilInternal from "../../util/UtilInternal"; import MessagingStubFactory = require("../MessagingStubFactory"); import MessageQueue = require("./MessageQueue"); import Address = require("../../../generated/joynr/system/RoutingTypes/Address"); import JoynrCompound = require("../../types/JoynrCompound"); import UdsClientAddress from "../../../generated/joynr/system/RoutingTypes/UdsClientAddress"; import UdsAddress from "../../../generated/joynr/system/RoutingTypes/UdsAddress"; const log = LoggingManager.getLogger("joynr/messaging/routing/MessageRouter"); type RoutingTable = Record<string, Address>; type MulticastSkeletons = Record<string, any>; /* TODO: let WebSocketMulticastAddressCalculator and MqttMulticastAddresscalculator, etc. implement this interface, or create an abstract class for it */ interface MulticastAddressCalculator { calculate: (joynrMessage: JoynrMessage) => Address; } namespace MessageRouter { export interface MessageRouterSettings { routingTable?: RoutingTable; messagingStubFactory: MessagingStubFactory; incomingAddress?: Address; parentMessageRouterAddress?: Address; messageQueue: MessageQueue; initialRoutingTable?: RoutingTable; multicastAddressCalculator: MulticastAddressCalculator; multicastSkeletons: MulticastSkeletons; } } class MessageRouter { private settings: MessageRouter.MessageRouterSettings; private started: boolean = true; private messagesWithoutReplyTo: JoynrMessage[]; private messageReplyToAddressCalculator: MessageReplyToAddressCalculator; private replyToAddress!: string; private multicastReceiversRegistry: any = {}; private multicastSkeletons: MulticastSkeletons; private multicastAddressCalculator: MulticastAddressCalculator; private parentMessageRouterAddress?: Address; private incomingAddress?: Address; private routingTable: RoutingTable; private queuedRemoveMulticastReceiverCalls: any; private queuedAddMulticastReceiverCalls: any; private queuedRemoveNextHopCalls: any; private queuedAddNextHopCalls: any; private messagingStub: any; private routingProxy!: RoutingProxy; private multicastWildcardRegexFactory: MulticastWildcardRegexFactory; /** * Message Router receives a message and forwards it to the correct endpoint, as looked up in the {@link RoutingTable} @constructor * * @param settings the settings object holding dependencies * @param settings.routingTable * @param settings.messagingStubFactory * @param settings.incomingAddress * @param settings.parentMessageRouterAddress * @param settings.messageQueue * @param settings.initialRoutingTable * @param settings.multicastAddressCalculator * @param settings.multicastSkeletons * * @classdesc The <code>MessageRouter</code> is a joynr internal interface. The Message * Router receives messages from Message Receivers, and forwards them along using to the * appropriate Address, either <code>{@link ChannelAddress}</code> for messages being * sent to a joynr channel via HTTP, <code>{@link BrowserAddress}</code> for messages * going to applications running within a seperate browser tab, or * <code>{@link InProcessAddress}</code> for messages going to a dispatcher running * within the same JavaScript scope as the MessageRouter. * * MessageRouter is part of the cluster controller, and is used for * internal messaging only. */ public constructor(settings: MessageRouter.MessageRouterSettings) { this.multicastWildcardRegexFactory = new MulticastWildcardRegexFactory(); this.queuedAddNextHopCalls = []; this.queuedRemoveNextHopCalls = []; this.queuedAddMulticastReceiverCalls = []; this.queuedRemoveMulticastReceiverCalls = []; this.routingTable = settings.initialRoutingTable || {}; this.incomingAddress = settings.incomingAddress; this.parentMessageRouterAddress = settings.parentMessageRouterAddress; this.multicastAddressCalculator = settings.multicastAddressCalculator; this.multicastSkeletons = settings.multicastSkeletons; this.messageReplyToAddressCalculator = new MessageReplyToAddressCalculator({}); this.messagesWithoutReplyTo = []; if (settings.parentMessageRouterAddress !== undefined && settings.incomingAddress === undefined) { throw new Error("incoming address is undefined"); } if (settings.messagingStubFactory === undefined) { throw new Error("messaging stub factory is undefined"); } if (settings.messageQueue === undefined) { throw new Error("messageQueue is undefined"); } this.route = this.route.bind(this); this.settings = settings; } private isReady(): boolean { return this.started; } private addRoutingProxyToParentRoutingTable(): Promise<void> { if (this.routingProxy && this.routingProxy.proxyParticipantId !== undefined) { // isGloballyVisible is false because the routing provider is local const isGloballyVisible = false; return this.addNextHopToParentRoutingTable(this.routingProxy.proxyParticipantId, isGloballyVisible).catch( error => { if (!this.isReady()) { //in this case, the error is expected, e.g. during shut down log.debug( `Adding routingProxy.proxyParticipantId ${ this.routingProxy.proxyParticipantId }failed while the message router is not ready. Error: ${error.message}` ); return; } throw new Error(error); } ); } return Promise.resolve(); } private processQueuedRoutingProxyCalls(): void { let hopIndex, receiverIndex, queuedCall, length; length = this.queuedAddNextHopCalls.length; for (hopIndex = 0; hopIndex < length; hopIndex++) { queuedCall = this.queuedAddNextHopCalls[hopIndex]; if (queuedCall.participantId !== this.routingProxy.proxyParticipantId) { this.addNextHopToParentRoutingTable(queuedCall.participantId, queuedCall.isGloballyVisible) .then(queuedCall.resolve) .catch(queuedCall.reject); } } length = this.queuedRemoveNextHopCalls.length; for (hopIndex = 0; hopIndex < length; hopIndex++) { queuedCall = this.queuedRemoveNextHopCalls[hopIndex]; this.removeNextHop(queuedCall.participantId) .then(queuedCall.resolve) .catch(queuedCall.reject); } length = this.queuedAddMulticastReceiverCalls.length; for (receiverIndex = 0; receiverIndex < length; receiverIndex++) { queuedCall = this.queuedAddMulticastReceiverCalls[receiverIndex]; this.routingProxy .addMulticastReceiver(queuedCall.parameters) .then(queuedCall.resolve) .catch(queuedCall.reject); } length = this.queuedRemoveMulticastReceiverCalls.length; for (receiverIndex = 0; receiverIndex < length; receiverIndex++) { queuedCall = this.queuedRemoveMulticastReceiverCalls[receiverIndex]; this.routingProxy .removeMulticastReceiver(queuedCall.parameters) .then(queuedCall.resolve) .catch(queuedCall.reject); } this.queuedAddNextHopCalls = undefined; this.queuedRemoveNextHopCalls = undefined; this.queuedAddMulticastReceiverCalls = undefined; this.queuedRemoveMulticastReceiverCalls = undefined; } /** * This method is called when no address can be found in the local routing table. * It tries to resolve the next hop from parent router. */ private resolveNextHopInternal(participantId: string): Promise<Address> { const address = (undefined as unknown) as Address; if (this.routingProxy !== undefined) { return this.routingProxy .resolveNextHop({ participantId }) .then(opArgs => { if (opArgs.resolved) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.routingTable[participantId] = this.parentMessageRouterAddress!; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return this.parentMessageRouterAddress!; } throw new Error( `nextHop cannot be resolved, as participant with id ${participantId} is not reachable by parent routing table` ); }); } return Promise.resolve(address as Address); } private containsAddress(array: Address[], address: Address): boolean { //each address class provides an equals method, e.g. InProcessAddress if (array === undefined) { return false; } for (let j = 0; j < array.length; j++) { if ((array[j] as JoynrCompound).equals(address)) { return true; } } return false; } /** * Get the address to which the passed in message should be sent to. * This is a multicast address calculated from the header content of the message. * * @param message the message for which we want to find an address to send it to. * @return the address to send the message to. Will not be null, because if an address can't be determined an exception is thrown. */ private getAddressesForMulticast(joynrMessage: JoynrMessage): Address[] { const result = []; let address; if (!joynrMessage.isReceivedFromGlobal) { address = this.multicastAddressCalculator.calculate(joynrMessage); if (address !== undefined) { result.push(address); } } let multicastIdPattern, receivers; for (multicastIdPattern in this.multicastReceiversRegistry) { if (this.multicastReceiversRegistry.hasOwnProperty(multicastIdPattern)) { if (joynrMessage.to.match(new RegExp(multicastIdPattern)) !== null) { receivers = this.multicastReceiversRegistry[multicastIdPattern]; if (receivers !== undefined) { for (let i = 0; i < receivers.length; i++) { address = this.routingTable[receivers[i]]; if (address !== undefined && !this.containsAddress(result, address)) { result.push(address); } } } } } } return result; } private routeInternalTransmitOnError(error: Error): void { //error while transmitting message log.debug(`Error while transmitting message: ${error}`); //TODO queue message and retry later } /** * Helper function to route a message once the address is known */ private routeInternal(address: Address, joynrMessage: JoynrMessage): Promise<void> { let errorMsg; // Error: The participant is not registered yet. // remote provider participants are registered by capabilitiesDirectory on lookup // local providers are registered by capabilitiesDirectory on register // replyCallers are registered when they are created if (!joynrMessage.isLocalMessage) { try { this.messageReplyToAddressCalculator.setReplyTo(joynrMessage); } catch (error) { this.messagesWithoutReplyTo.push(joynrMessage); errorMsg = `replyTo address could not be set: ${error}. Queuing message.`; log.warn(errorMsg, DiagnosticTags.forJoynrMessage(joynrMessage)); return Promise.resolve(); } } this.messagingStub = this.settings.messagingStubFactory.createMessagingStub(address); if (this.messagingStub === undefined) { errorMsg = `No message receiver found for participantId: ${joynrMessage.to} queuing message.`; log.info(errorMsg, DiagnosticTags.forJoynrMessage(joynrMessage)); // TODO queue message and retry later return Promise.resolve(); } return this.messagingStub.transmit(joynrMessage).catch(this.routeInternalTransmitOnError); } private registerGlobalRoutingEntryIfRequired(joynrMessage: JoynrMessage): void { if (!joynrMessage.isReceivedFromGlobal) { return; } const type = joynrMessage.type; if ( type === JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST || type === JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REQUEST || type === JoynrMessage.JOYNRMESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST || type === JoynrMessage.JOYNRMESSAGE_TYPE_MULTICAST_SUBSCRIPTION_REQUEST ) { try { const replyToAddress = joynrMessage.replyChannelId; if (!UtilInternal.checkNullUndefined(replyToAddress)) { // because the message is received via global transport, isGloballyVisible must be true const isGloballyVisible = true; this.addNextHop( joynrMessage.from, Typing.augmentTypes(JSON.parse(replyToAddress)), isGloballyVisible ); } } catch (e) { log.error(`could not register global Routing Entry: ${e}`); } } } private resolveNextHopAndRoute(participantId: string, joynrMessage: JoynrMessage): Promise<void> { if (this.routingProxy !== undefined) { return this.routingProxy .resolveNextHop({ participantId }) .then(opArgs => { if (opArgs.resolved && this.parentMessageRouterAddress !== undefined) { this.routingTable[participantId] = this.parentMessageRouterAddress; return this.routeInternal(this.parentMessageRouterAddress, joynrMessage); } throw new Error( `nextHop cannot be resolved, as participant with id ${participantId} is not reachable by parent routing table` ); }) .catch((e: Error) => { log.error(e.message); }); } if ( joynrMessage.type === JoynrMessage.JOYNRMESSAGE_TYPE_REPLY || joynrMessage.type === JoynrMessage.JOYNRMESSAGE_TYPE_SUBSCRIPTION_REPLY || joynrMessage.type === JoynrMessage.JOYNRMESSAGE_TYPE_PUBLICATION ) { const errorMsg = `Received message for unknown proxy. Dropping the message. ID: ${joynrMessage.msgId}`; const now = Date.now(); log.warn(`${errorMsg}, expiryDate: ${joynrMessage.expiryDate}, now: ${now}`); return Promise.resolve(); } log.warn( `No message receiver found for participantId: ${joynrMessage.to}. Queuing message.`, DiagnosticTags.forJoynrMessage(joynrMessage) ); // message is queued until the participant is registered this.settings.messageQueue.putMessage(joynrMessage); return Promise.resolve(); } /** * @param newAddress - the address to be used as replyTo address * * @returns void */ public setReplyToAddress(newAddress: string): void { this.replyToAddress = newAddress; this.messageReplyToAddressCalculator.setReplyToAddress(this.replyToAddress); this.messagesWithoutReplyTo.forEach(this.route); } /** * @param participantId * * @returns promise */ public removeNextHop(participantId: string): Promise<any> { if (!this.isReady()) { log.debug("removeNextHop: ignore call as message router is already shut down"); return Promise.reject(new Error("message router is already shut down")); } delete this.routingTable[participantId]; if (this.routingProxy !== undefined) { return this.routingProxy.removeNextHop({ participantId }); } if (this.parentMessageRouterAddress !== undefined) { const deferred = UtilInternal.createDeferred(); this.queuedRemoveNextHopCalls.push({ participantId, resolve: deferred.resolve, reject: deferred.reject }); return deferred.promise; } return Promise.resolve(); } /** * @param participantId * @param isGloballyVisible * * @returns promise */ private addNextHopToParentRoutingTable(participantId: string, isGloballyVisible: boolean): Promise<any> { if (this.incomingAddress instanceof UdsClientAddress) { return this.routingProxy.addNextHop({ participantId, udsClientAddress: this.incomingAddress, isGloballyVisible }); } if (this.incomingAddress instanceof WebSocketClientAddress) { return this.routingProxy.addNextHop({ participantId, webSocketClientAddress: this.incomingAddress, isGloballyVisible }); } if (this.incomingAddress instanceof BrowserAddress) { return this.routingProxy.addNextHop({ participantId, browserAddress: this.incomingAddress, isGloballyVisible }); } if (this.incomingAddress instanceof WebSocketAddress) { return this.routingProxy.addNextHop({ participantId, webSocketAddress: this.incomingAddress, isGloballyVisible }); } if (this.incomingAddress instanceof UdsAddress) { return this.routingProxy.addNextHop({ participantId, udsAddress: this.incomingAddress, isGloballyVisible }); } if (this.incomingAddress instanceof ChannelAddress) { return this.routingProxy.addNextHop({ participantId, channelAddress: this.incomingAddress, isGloballyVisible }); } const errorMsg = `Invalid address type of incomingAddress: ${Typing.getObjectType(this.incomingAddress)}`; log.fatal(errorMsg); return Promise.reject(new JoynrRuntimeException({ detailMessage: errorMsg })); } /** * @param newRoutingProxy - the routing proxy to be set * @returns A+ promise object */ public setRoutingProxy(newRoutingProxy: RoutingProxy): Promise<void> { this.routingProxy = newRoutingProxy; return this.addRoutingProxyToParentRoutingTable().then(() => this.processQueuedRoutingProxyCalls()); } /** * Get replyToAddress from routing proxy * @returns A+ promise object */ public getReplyToAddressFromRoutingProxy(): Promise<string> { if (!this.routingProxy) { return Promise.reject(new Error(`"setRoutingProxy()" has to be called first`)); } return this.routingProxy.replyToAddress.get(); } /** * Get replyToAddress via routing proxy to enable global communication in message router. * @returns A+ promise object */ public configureReplyToAddressFromRoutingProxy(): Promise<void> { return this.getReplyToAddressFromRoutingProxy() .then(address => this.setReplyToAddress(address)) .catch((error: Error) => { throw new Error(`Failed to get replyToAddress from parent router: ${error}`); }); } /** * Looks up an Address for a given participantId (next hop) * * @param participantId * @returns the address of the next hop in the direction of the given * participantId, or undefined if not found */ public resolveNextHop(participantId: string): Promise<Address> { if (!this.isReady()) { log.debug("resolveNextHop: ignore call as message router is already shut down"); return Promise.reject(new Error("message router is already shut down")); } const address = this.routingTable[participantId]; if (address === undefined) { return this.resolveNextHopInternal(participantId); } return Promise.resolve(address); } /** * @param joynrMessage * @returns A+ promise object */ public route(joynrMessage: JoynrMessage): Promise<any> { try { const now = Date.now(); if (now > joynrMessage.expiryDate) { const errorMsg = `Received expired message. Dropping the message. ID: ${joynrMessage.msgId}`; log.warn(`${errorMsg}, expiryDate: ${joynrMessage.expiryDate}, now: ${now}`); return Promise.resolve(); } log.debug(`Route message. ID: ${joynrMessage.msgId}, expiryDate: ${joynrMessage.expiryDate}, now: ${now}`); this.registerGlobalRoutingEntryIfRequired(joynrMessage); if (joynrMessage.type === JoynrMessage.JOYNRMESSAGE_TYPE_MULTICAST) { return Promise.all( this.getAddressesForMulticast(joynrMessage).map((address: Address) => this.routeInternal(address, joynrMessage) ) ); } const participantId = joynrMessage.to; const address = this.routingTable[participantId]; if (address !== undefined) { return this.routeInternal(address, joynrMessage); } return this.resolveNextHopAndRoute(participantId, joynrMessage); } catch (e) { log.error(`MessageRouter.route failed: ${e.message}`); return Promise.resolve(); } } /** * Registers the next hop with this specific participant Id * * @param participantId * @param address the address to register * @param isGloballyVisible * @returns A+ promise object */ public addNextHop(participantId: string, address: Address, isGloballyVisible: boolean): Promise<void> { if (!this.isReady()) { log.debug("addNextHop: ignore call as message router is already shut down"); return Promise.reject(new Error("message router is already shut down")); } // store the address of the participantId in memory this.routingTable[participantId] = address; let promise; if (this.routingProxy !== undefined) { // register remotely promise = this.addNextHopToParentRoutingTable(participantId, isGloballyVisible); } else { promise = Promise.resolve(); } this.participantRegistered(participantId); return promise; } /** * Adds a new receiver for the identified multicasts. * * @param parameters - object containing parameters * @param parameters.multicastId * @param parameters.subscriberParticipantId * @param parameters.providerParticipantId * @returns A+ promise object */ public addMulticastReceiver(parameters: { multicastId: string; subscriberParticipantId: string; providerParticipantId: string; }): Promise<void> { //1. handle call in local router //1.a store receiver in multicastReceiverRegistry const multicastIdPattern = this.multicastWildcardRegexFactory.createIdPattern(parameters.multicastId); const providerAddress = this.routingTable[parameters.providerParticipantId]; if (this.multicastReceiversRegistry[multicastIdPattern] === undefined) { this.multicastReceiversRegistry[multicastIdPattern] = []; //1.b the first receiver for this multicastId -> inform MessagingSkeleton about receiver const skeleton = this.multicastSkeletons[providerAddress._typeName]; if (skeleton !== undefined && skeleton.registerMulticastSubscription !== undefined) { skeleton.registerMulticastSubscription(parameters.multicastId); } } this.multicastReceiversRegistry[multicastIdPattern].push(parameters.subscriberParticipantId); //2. forward call to parent router (if available) if ( this.parentMessageRouterAddress === undefined || providerAddress === undefined || providerAddress instanceof InProcessAddress ) { return Promise.resolve(); } if (this.routingProxy !== undefined) { return this.routingProxy.addMulticastReceiver(parameters); } const deferred = UtilInternal.createDeferred(); this.queuedAddMulticastReceiverCalls.push({ parameters, resolve: deferred.resolve, reject: deferred.reject }); return deferred.promise; } /** * Removes a receiver for the identified multicasts. * * @param parameters - object containing parameters * @param parameters.multicastId * @param parameters.subscriberParticipantId * @param parameters.providerParticipantId * @returns A+ promise object */ public removeMulticastReceiver(parameters: { multicastId: string; subscriberParticipantId: string; providerParticipantId: string; }): Promise<void> { //1. handle call in local router //1.a remove receiver from multicastReceiverRegistry const multicastIdPattern = this.multicastWildcardRegexFactory.createIdPattern(parameters.multicastId); const providerAddress = this.routingTable[parameters.providerParticipantId]; if (this.multicastReceiversRegistry[multicastIdPattern] !== undefined) { const receivers = this.multicastReceiversRegistry[multicastIdPattern]; for (let i = 0; i < receivers.length; i++) { if (receivers[i] === parameters.subscriberParticipantId) { receivers.splice(i, 1); break; } } if (receivers.length === 0) { delete this.multicastReceiversRegistry[multicastIdPattern]; //1.b no receiver anymore for this multicastId -> inform MessagingSkeleton about removed receiver const skeleton = this.multicastSkeletons[providerAddress._typeName]; if (skeleton !== undefined && skeleton.unregisterMulticastSubscription !== undefined) { skeleton.unregisterMulticastSubscription(parameters.multicastId); } } } //2. forward call to parent router (if available) if ( this.parentMessageRouterAddress === undefined || providerAddress === undefined || providerAddress instanceof InProcessAddress ) { return Promise.resolve(); } if (this.routingProxy !== undefined) { return this.routingProxy.removeMulticastReceiver(parameters); } const deferred = UtilInternal.createDeferred(); this.queuedRemoveMulticastReceiverCalls.push({ parameters, resolve: deferred.resolve, reject: deferred.reject }); return deferred.promise; } /** * @param participantId * * @returns void */ public participantRegistered(participantId: string): void { const messageQueue = this.settings.messageQueue.getAndRemoveMessages(participantId); if (messageQueue !== undefined) { let i = messageQueue.length; while (i--) { this.route(messageQueue[i]); } } } /** * Tell the message router that the given participantId is known. The message router * checks internally if an address is already present in the routing table. If not, * it adds the parentMessageRouterAddress to the routing table for this participantId. * * @param participantId * * @returns void */ public setToKnown(participantId: string): void { if (!this.isReady()) { log.debug("setToKnown: ignore call as message router is already shut down"); return; } //if not already set if (this.routingTable[participantId] === undefined) { if (this.parentMessageRouterAddress !== undefined) { this.routingTable[participantId] = this.parentMessageRouterAddress; } } } public hasMulticastReceivers(): boolean { return Object.keys(this.multicastReceiversRegistry).length > 0; } /** * Shutdown the message router */ public shutdown(): void { function rejectCall(call: { reject: Function }): void { call.reject(new Error("Message Router has been shut down")); } if (this.queuedAddNextHopCalls !== undefined) { this.queuedAddNextHopCalls.forEach(rejectCall); this.queuedAddNextHopCalls = []; } if (this.queuedRemoveNextHopCalls !== undefined) { this.queuedRemoveNextHopCalls.forEach(rejectCall); this.queuedRemoveNextHopCalls = []; } if (this.queuedAddMulticastReceiverCalls !== undefined) { this.queuedAddMulticastReceiverCalls.forEach(rejectCall); this.queuedAddMulticastReceiverCalls = []; } if (this.queuedRemoveMulticastReceiverCalls !== undefined) { this.queuedRemoveMulticastReceiverCalls.forEach(rejectCall); this.queuedRemoveMulticastReceiverCalls = []; } this.started = false; this.settings.messageQueue.shutdown(); } } export = MessageRouter;
the_stack
import { SpriteFrame } from "../../cocos/2d/assets/sprite-frame"; import { Sprite } from "../../cocos/2d/components/sprite"; import { assetManager, loader } from "../../cocos/core/asset-manager"; import releaseManager from "../../cocos/core/asset-manager/release-manager"; import { Texture2D } from "../../cocos/core/assets/texture-2d"; import { isValid } from "../../cocos/core/data/object"; import { Scene, Node } from "../../cocos/core/scene-graph"; describe('releaseManager', () => { const libPath = './tests/fixtures/library'; assetManager.init({importBase: libPath, nativeBase: libPath}); test('reference', function () { const tex = new Texture2D(); tex._uuid = 'AAA'; expect(tex.refCount).toBe(0); tex.addRef(); expect(tex.refCount).toBe(1); tex.decRef(false); expect(tex.refCount).toBe(0); }); test('release', function () { const tex = new Texture2D(); tex._uuid = 'AAA'; tex.addRef(); assetManager.assets.add('AAA', tex); expect(isValid(tex, true)).toBeTruthy(); // @ts-ignore releaseManager._free(tex, false); expect(assetManager.assets.count).toBe(1); expect(isValid(tex, true)).toBeTruthy(); assetManager.releaseAsset(tex); expect(assetManager.assets.count).toBe(0); expect(isValid(tex, true)).toBeFalsy(); }); test('release dependencies', function () { const texA = new Texture2D(); texA._uuid = 'AAA'; assetManager.assets.add('AAA', texA); const texB = new Texture2D(); texB._uuid = 'BBB'; texB.addRef(); assetManager.assets.add('BBB', texB); assetManager.dependUtil._depends.add('AAA', {deps: ['BBB']}); // @ts-ignore releaseManager._free(texA); expect(assetManager.assets.count).toBe(0); }); test('release circle reference', function () { const texA = new Texture2D(); texA._uuid = 'AAA'; texA.addRef(); assetManager.assets.add('AAA', texA); const texB = new Texture2D(); texB._uuid = 'BBB'; texB.addRef(); texB.addRef(); assetManager.assets.add('BBB', texB); const texC = new Texture2D(); texC._uuid = 'CCC'; texC.addRef(); assetManager.assets.add('CCC', texC); const texD = new Texture2D(); texD._uuid = 'DDD'; texD.addRef(); assetManager.assets.add('DDD', texD); assetManager.dependUtil._depends.add('AAA', {deps: ['BBB']}); assetManager.dependUtil._depends.add('BBB', {deps: ['CCC']}); assetManager.dependUtil._depends.add('CCC', {deps: ['AAA', 'DDD']}); assetManager.dependUtil._depends.add('DDD', {deps: ['BBB']}); // @ts-ignore releaseManager._free(texA); expect(assetManager.assets.count).toBe(0); }); test('release circle reference2', function () { const texA = new Texture2D(); texA._uuid = 'AAA'; texA.addRef(); assetManager.assets.add('AAA', texA); const texB = new Texture2D(); texB._uuid = 'BBB'; texB.addRef(); texB.addRef(); texB.addRef(); assetManager.assets.add('BBB', texB); const texC = new Texture2D(); texC._uuid = 'CCC'; texC.addRef(); assetManager.assets.add('CCC', texC); const texD = new Texture2D(); texD._uuid = 'DDD'; texD.addRef(); assetManager.assets.add('DDD', texD); assetManager.dependUtil._depends.add('AAA', {deps: ['BBB']}); assetManager.dependUtil._depends.add('BBB', {deps: ['CCC']}); assetManager.dependUtil._depends.add('CCC', {deps: ['AAA', 'DDD']}); assetManager.dependUtil._depends.add('DDD', {deps: ['BBB']}); // @ts-ignore releaseManager._free(texA); expect(assetManager.assets.count).toBe(4); assetManager.releaseAll(); }); test('release circle reference3', function () { const texA = new Texture2D(); texA._uuid = 'AAA'; texA.addRef().addRef(); assetManager.assets.add('AAA', texA); const texB = new Texture2D(); texB._uuid = 'BBB'; texB.addRef().addRef(); assetManager.assets.add('BBB', texB); const texC = new Texture2D(); texC._uuid = 'CCC'; texC.addRef(); assetManager.assets.add('CCC', texC); const texD = new Texture2D(); texD._uuid = 'DDD'; texD.addRef(); assetManager.assets.add('DDD', texD); assetManager.dependUtil._depends.add('AAA', {deps: ['BBB']}); assetManager.dependUtil._depends.add('BBB', {deps: ['CCC', 'DDD']}); assetManager.dependUtil._depends.add('CCC', {deps: ['AAA', 'BBB']}); assetManager.dependUtil._depends.add('DDD', {deps: ['AAA']}); // @ts-ignore releaseManager._free(texA); expect(assetManager.assets.count).toBe(0); }); test('release circle reference4', function () { const texA = new Texture2D(); texA._uuid = 'AAA'; texA.addRef().addRef(); assetManager.assets.add('AAA', texA); const texB = new Texture2D(); texB._uuid = 'BBB'; texB.addRef().addRef().addRef(); assetManager.assets.add('BBB', texB); const texC = new Texture2D(); texC._uuid = 'CCC'; texC.addRef().addRef(); assetManager.assets.add('CCC', texC); const texD = new Texture2D(); texD._uuid = 'DDD'; texD.addRef(); assetManager.assets.add('DDD', texD); assetManager.dependUtil._depends.add('AAA', {deps: ['BBB']}); assetManager.dependUtil._depends.add('BBB', {deps: ['CCC', 'DDD']}); assetManager.dependUtil._depends.add('CCC', {deps: ['AAA', 'BBB']}); assetManager.dependUtil._depends.add('DDD', {deps: ['AAA']}); // @ts-ignore releaseManager._free(texA); expect(assetManager.assets.count).toBe(4); assetManager.releaseAll(); }); test('release circle reference5', function () { const texA = new Texture2D(); texA._uuid = 'AAA'; texA.addRef(); assetManager.assets.add('AAA', texA); const texB = new Texture2D(); texB._uuid = 'BBB'; texB.addRef(); assetManager.assets.add('BBB', texB); const texC = new Texture2D(); texC._uuid = 'CCC'; texC.addRef(); assetManager.assets.add('CCC', texC); const texD = new Texture2D(); texD._uuid = 'DDD'; texD.addRef().addRef(); assetManager.assets.add('DDD', texD); assetManager.dependUtil._depends.add('AAA', {deps: ['DDD', 'BBB']}); assetManager.dependUtil._depends.add('BBB', {deps: ['CCC']}); assetManager.dependUtil._depends.add('CCC', {deps: ['DDD']}); assetManager.dependUtil._depends.add('DDD', {deps: ['AAA']}); // @ts-ignore releaseManager._free(texA); expect(assetManager.assets.count).toBe(0); assetManager.releaseAll(); }); test('AutoRelease', function () { const scene1 = new Scene(''); // @ts-expect-error set private property scene1._id = 'scene 1'; const scene2 = new Scene(''); // @ts-expect-error set private property scene2._id = 'scene 2'; const texA = new Texture2D(); texA._uuid = 'AAA'; texA.addRef(); assetManager.assets.add('AAA', texA); const texB = new Texture2D(); texB._uuid = 'BBB'; texB.addRef().addRef(); assetManager.assets.add('BBB', texB); const texC = new Texture2D(); texC._uuid = 'CCC'; texC.addRef().addRef(); assetManager.assets.add('CCC', texC); const texD = new Texture2D(); texD._uuid = 'DDD'; texD.addRef(); assetManager.assets.add('DDD', texD); assetManager.dependUtil._depends.add('scene 1', {deps: ['AAA', 'BBB', 'CCC', 'DDD']}); assetManager.dependUtil._depends.add('scene 2', {deps: ['BBB', 'CCC']}); releaseManager._autoRelease(scene1, scene2, {}); // @ts-expect-error set private property releaseManager._freeAssets(); expect(assetManager.assets.count).toBe(2); expect(texB.refCount).toBe(1); expect(texC.refCount).toBe(1); assetManager.releaseAll(); }); test('autoRelease_polyfill', function () { const scene1 = new Scene(''); // @ts-expect-error set private property scene1._id = 'scene 1'; const scene2 = new Scene(''); // @ts-expect-error set private property scene2._id = 'scene 2'; const texA = new Texture2D(); texA._uuid = 'AAA'; assetManager.assets.add('AAA', texA); loader.setAutoRelease(texA, true); expect(assetManager.assets.count).toBe(1); releaseManager._autoRelease(scene1, scene2, {}); // @ts-expect-error set private property releaseManager._freeAssets(); expect(assetManager.assets.count).toBe(0); }); test('persistNode', function () { const scene1 = new Scene(''); // @ts-expect-error set private property scene1._id = 'scene 1'; const scene2 = new Scene(''); // @ts-expect-error set private property scene2._id = 'scene 2'; const scene3 = new Scene(''); // @ts-expect-error set private property scene3._id = 'scene 3'; const sp = new SpriteFrame(); sp._uuid = 'AAA'; sp.addRef(); const tex = new Texture2D(); tex.loaded = true; sp.texture = tex; assetManager.assets.add('AAA', sp); const persistNode = new Node(); (persistNode.addComponent(Sprite) as Sprite).spriteFrame = sp; releaseManager._addPersistNodeRef(persistNode); const persistNodes = {}; persistNodes[persistNode.uuid] = persistNode; assetManager.dependUtil._depends.add('scene 1', {deps: ['AAA']}); assetManager.dependUtil._depends.add('scene 2', {deps: []}); releaseManager._autoRelease(scene1, scene2, persistNodes); // @ts-expect-error set private property releaseManager._freeAssets(); expect(assetManager.assets.count).toBe(1); expect(assetManager.assets.get('AAA')).toBe(sp); expect(sp.refCount).toBe(2); releaseManager._removePersistNodeRef(persistNode); expect(sp.refCount).toBe(1); releaseManager._autoRelease(scene2, scene3, {}); // @ts-expect-error set private property releaseManager._freeAssets(); expect(assetManager.assets.count).toBe(0); }); });
the_stack
import { ScoreDisplayConfig } from "~/data/config/overlayConfig"; import ScoreboardConfig from "~/data/scoreboardConfig"; import StateData from "~/data/stateData"; import PlaceholderConversion from "~/PlaceholderConversion"; import IngameScene from "~/scenes/IngameScene"; import TextUtils from "~/util/TextUtils"; import Utils from "~/util/Utils"; import variables from "~/variables"; import { VisualElement } from "./VisualElement"; export default class ScoreboardVisual extends VisualElement { BackgroundRect: Phaser.GameObjects.Rectangle | null = null; BackgroundImage: Phaser.GameObjects.Image | null = null; BackgroundVideo: Phaser.GameObjects.Video | null = null; ImgMask!: Phaser.Display.Masks.BitmapMask; GeoMask!: Phaser.Display.Masks.GeometryMask; MaskImage!: Phaser.GameObjects.Sprite; MaskG!: Phaser.GameObjects.Graphics; ScoreG!: Phaser.GameObjects.Graphics; GameTime: Phaser.GameObjects.Text; CenterIcon: Phaser.GameObjects.Sprite | null = null; BlueTag: Phaser.GameObjects.Text; BlueScoreTemplates: Phaser.Geom.Circle[] = []; BlueScoreText: Phaser.GameObjects.Text | null = null; BlueWins: number = -1; BlueKills: Phaser.GameObjects.Text; BlueTowers: Phaser.GameObjects.Text; BlueGold: Phaser.GameObjects.Text; BlueGoldImage: Phaser.GameObjects.Sprite | null = null; BlueTowerImage: Phaser.GameObjects.Sprite | null = null; BlueDragons: Phaser.GameObjects.Sprite[] = []; BlueIconBackground: Phaser.GameObjects.Sprite | null = null; BlueIconSprite: Phaser.GameObjects.Sprite | null = null; BlueIconName: string = ''; RedTag: Phaser.GameObjects.Text; RedScoreTemplates: Phaser.Geom.Circle[] = []; RedScoreText: Phaser.GameObjects.Text | null = null; RedWins: number = -1; RedKills: Phaser.GameObjects.Text; RedTowers: Phaser.GameObjects.Text; RedGold: Phaser.GameObjects.Text; RedGoldImage: Phaser.GameObjects.Sprite | null = null; RedTowerImage: Phaser.GameObjects.Sprite | null = null; RedDragons: Phaser.GameObjects.Sprite[] = []; RedIconBackground: Phaser.GameObjects.Sprite | null = null; RedIconSprite: Phaser.GameObjects.Sprite | null = null; RedIconName: string = ''; DrakeIconSize: number = 30; DrakeIconOffset: number = 0; ShowScores: boolean = false; TotalGameToWinsNeeded: Record<number, number> = { 5: 3, 3: 2, 2: 2, 1: 1 }; constructor(scene: IngameScene, cfg: ScoreDisplayConfig) { super(scene, cfg.Position, 'score'); this.CreateTextureListeners(); //Mask if (cfg.Background.UseAlpha) { this.MaskImage = scene.make.sprite({ x: cfg.Position.X, y: cfg.Position.Y, key: 'scoreboardMask', add: false }); this.MaskImage.setOrigin(0.5, 0); this.MaskImage.setDisplaySize(cfg.Size.X, cfg.Size.Y); this.ImgMask = this.MaskImage.createBitmapMask(); } else { this.MaskG = scene.make.graphics({}); this.MaskG.fillStyle(0xffffff); this.MaskG.fillRect(cfg.Position.X - (cfg.Size.X / 2), cfg.Position.Y, cfg.Size.X, cfg.Size.Y); this.GeoMask = this.MaskG.createGeometryMask(); } this.ScoreG = this.scene.make.graphics({}, true); this.AddVisualComponent(this.ScoreG); //Background if (cfg.Background.UseVideo) { this.scene.load.video('scoreBgVideo', 'frontend/backgrounds/Score.mp4'); } else if (cfg.Background.UseImage) { this.scene.load.image('scoreBg', 'frontend/backgrounds/Score.png'); } else { this.BackgroundRect = this.scene.add.rectangle(cfg.Position.X, cfg.Position.Y + (cfg.Size.Y / 2), cfg.Size.X, cfg.Size.Y, Phaser.Display.Color.RGBStringToColor(cfg.Background.FallbackColor).color32); this.BackgroundRect.depth = -1; this.BackgroundRect.setMask(ScoreboardVisual.GetConfig()?.Background.UseAlpha ? this.ImgMask : this.GeoMask); this.AddVisualComponent(this.BackgroundRect); } //Game Time this.GameTime = scene.add.text(this.position.X + cfg.TimePosition.X, this.position.Y + cfg.TimePosition.Y, '00:00', { fontFamily: cfg.TimeFont.Name, fontSize: cfg.TimeFont.Size, color: cfg.TimeFont.Color, fontStyle: cfg.TimeFont.Style, align: cfg.TimeFont.Align }); this.GameTime.setOrigin(0.5,0.5); this.GameTime.setAlign(cfg.TimeFont.Align); this.AddVisualComponent(this.GameTime); //Center Icon if (cfg.Misc.ShowCenterIcon) { this.CenterIcon = scene.make.sprite({ x: this.position.X + cfg.Misc.CenterIconPosition.X, y: this.position.Y + cfg.Misc.CenterIconPosition.Y, key: 'scoreCenter', add: true }); this.CenterIcon.setOrigin(0.5,0.5); this.CenterIcon.setDisplaySize(cfg.Misc.CenterIconSize.X, cfg.Misc.CenterIconSize.Y); this.AddVisualComponent(this.CenterIcon); } //Blue Team //Kills this.BlueKills = scene.add.text(this.position.X + cfg.BlueTeam.Kills.Position.X, this.position.Y + cfg.BlueTeam.Kills.Position.Y, '0', { fontFamily: cfg.BlueTeam.Kills.Font.Name, fontSize: cfg.BlueTeam.Kills.Font.Size, color: cfg.BlueTeam.Kills.Font.Color, fontStyle: cfg.BlueTeam.Kills.Font.Style, align: cfg.BlueTeam.Kills.Font.Align }); this.AddVisualComponent(this.BlueKills); if (cfg.BlueTeam.Kills.Font.Align === "right" || cfg.BlueTeam.Kills.Font.Align === "Right") this.BlueKills.setOrigin(1, 0); if (cfg.BlueTeam.Kills.Font.Align === "left" || cfg.BlueTeam.Kills.Font.Align === "Left") this.BlueKills.setOrigin(0, 0); //Towers this.BlueTowers = scene.add.text(this.position.X + cfg.BlueTeam.Towers.Position.X, this.position.Y + cfg.BlueTeam.Towers.Position.Y, '0', { fontFamily: cfg.BlueTeam.Towers.Font.Name, fontSize: cfg.BlueTeam.Towers.Font.Size, fontStyle: cfg.BlueTeam.Towers.Font.Style, align: cfg.BlueTeam.Towers.Font.Align, color: cfg.BlueTeam.Towers.Font.Color, }); this.AddVisualComponent(this.BlueTowers); if (cfg.BlueTeam.Towers.Font.Align === "right" || cfg.BlueTeam.Towers.Font.Align === "Right") this.BlueTowers.setOrigin(1, 0); if (cfg.BlueTeam.Towers.Font.Align === "left" || cfg.BlueTeam.Towers.Font.Align === "Left") this.BlueTowers.setOrigin(0, 0); this.BlueTowerImage = scene.make.sprite({ x: this.position.X + cfg.BlueTeam.Towers.Position.X + cfg.BlueTeam.Towers.Icon.Offset.X, y: this.position.Y + cfg.BlueTeam.Towers.Position.Y + cfg.BlueTeam.Towers.Icon.Offset.Y, key: 'scoreTower', add: true }); this.BlueTowerImage.setDisplaySize(cfg.BlueTeam.Towers.Icon.Size.X, cfg.BlueTeam.Towers.Icon.Size.Y); this.BlueTowerImage.setOrigin(0.5,0.5); this.AddVisualComponent(this.BlueTowerImage); //Gold this.BlueGold = scene.add.text(this.position.X + cfg.BlueTeam.Gold.Position.X, this.position.Y + cfg.BlueTeam.Gold.Position.Y, '2.5k', { fontFamily: cfg.BlueTeam.Gold.Font.Name, fontSize: cfg.BlueTeam.Gold.Font.Size, fontStyle: cfg.BlueTeam.Gold.Font.Style, align: cfg.BlueTeam.Gold.Font.Align, color: cfg.BlueTeam.Gold.Font.Color, }); this.AddVisualComponent(this.BlueGold); if (cfg.BlueTeam.Gold.Font.Align === "right" || cfg.BlueTeam.Gold.Font.Align === "Right") this.BlueGold.setOrigin(1, 0); if (cfg.BlueTeam.Gold.Font.Align === "left" || cfg.BlueTeam.Gold.Font.Align === "Left") this.BlueGold.setOrigin(0, 0); this.BlueGoldImage = scene.make.sprite({ x: this.position.X + cfg.BlueTeam.Gold.Position.X + cfg.BlueTeam.Gold.Icon.Offset.X, y: this.position.Y + cfg.BlueTeam.Gold.Position.Y + cfg.BlueTeam.Gold.Icon.Offset.Y, key: 'scoreGold', add: true }); this.BlueGoldImage.setDisplaySize(cfg.BlueTeam.Gold.Icon.Size.X, cfg.BlueTeam.Gold.Icon.Size.Y); this.BlueGoldImage.setOrigin(0.5,0.5); this.AddVisualComponent(this.BlueGoldImage); this.BlueDragons = []; this.BlueScoreTemplates = []; for (var i = 0; i < 5; i++) { this.BlueScoreTemplates.push(new Phaser.Geom.Circle(this.position.X + cfg.BlueTeam.Score.Position.X + i * cfg.BlueTeam.Score.CircleOffset.X, this.position.Y + cfg.BlueTeam.Score.Position.Y + i * cfg.BlueTeam.Score.CircleOffset.Y, cfg.BlueTeam.Score.CircleRadius)); } //Tag this.BlueTag = scene.add.text(this.position.X + cfg.BlueTeam.Name.Position.X, this.position.Y + cfg.BlueTeam.Name.Position.Y, 'Blue', { fontFamily: cfg.BlueTeam.Name.Font.Name, fontSize: cfg.BlueTeam.Name.Font.Size, fontStyle: cfg.BlueTeam.Name.Font.Style, align: cfg.BlueTeam.Name.Font.Align, color: cfg.BlueTeam.Name.Font.Color, }); this.AddVisualComponent(this.BlueTag); if (cfg.BlueTeam.Name.Font.Align === "right" || cfg.BlueTeam.Name.Font.Align === "Right") this.BlueTag.setOrigin(1, 0); if (cfg.BlueTeam.Name.Font.Align === "left" || cfg.BlueTeam.Name.Font.Align === "Left") this.BlueTag.setOrigin(0, 0); //Icon if (cfg.BlueTeam.Icon.UseBackground) { this.BlueIconBackground = scene.make.sprite({ x: cfg.Position.X + cfg.BlueTeam.Icon.Position.X + cfg.BlueTeam.Icon.BackgroundOffset.X, y: cfg.Position.Y + cfg.BlueTeam.Icon.Position.Y + cfg.BlueTeam.Icon.BackgroundOffset.Y, key: 'scoreBlueIcon', add: true }); this.AddVisualComponent(this.BlueIconBackground); } //Red Team //Kills this.RedKills = scene.add.text(this.position.X + cfg.RedTeam.Kills.Position.X, this.position.Y + cfg.RedTeam.Kills.Position.Y, '0', { fontFamily: cfg.RedTeam.Kills.Font.Name, fontSize: cfg.RedTeam.Kills.Font.Size, fontStyle: cfg.RedTeam.Kills.Font.Style, align: cfg.RedTeam.Kills.Font.Align, color: cfg.RedTeam.Kills.Font.Color, }); this.AddVisualComponent(this.RedKills); if (cfg.RedTeam.Kills.Font.Align === "right" || cfg.RedTeam.Kills.Font.Align === "Right") this.RedKills.setOrigin(1, 0); if (cfg.RedTeam.Kills.Font.Align === "left" || cfg.RedTeam.Kills.Font.Align === "Left") this.RedKills.setOrigin(0, 0); //Towers this.RedTowers = scene.add.text(this.position.X + cfg.RedTeam.Towers.Position.X, this.position.Y + cfg.RedTeam.Towers.Position.Y, '0', { fontFamily: cfg.RedTeam.Towers.Font.Name, fontSize: cfg.RedTeam.Towers.Font.Size, fontStyle: cfg.RedTeam.Towers.Font.Style, align: cfg.RedTeam.Towers.Font.Align, color: cfg.RedTeam.Towers.Font.Color, }); this.AddVisualComponent(this.RedTowers); if (cfg.RedTeam.Towers.Font.Align === "right" || cfg.RedTeam.Towers.Font.Align === "Right") this.RedTowers.setOrigin(1, 0); if (cfg.RedTeam.Towers.Font.Align === "left" || cfg.RedTeam.Towers.Font.Align === "Left") this.RedTowers.setOrigin(0, 0); this.RedTowerImage = scene.make.sprite({ x: this.position.X + cfg.RedTeam.Towers.Position.X + cfg.RedTeam.Towers.Icon.Offset.X, y: this.position.Y + cfg.RedTeam.Towers.Position.Y + cfg.RedTeam.Towers.Icon.Offset.Y, key: 'scoreTower', add: true }); this.RedTowerImage.setDisplaySize(cfg.RedTeam.Towers.Icon.Size.X, cfg.RedTeam.Towers.Icon.Size.Y); this.RedTowerImage.setOrigin(0.5,0.5); this.AddVisualComponent(this.RedTowerImage); //Gold this.RedGold = scene.add.text(this.position.X + cfg.RedTeam.Gold.Position.X, this.position.Y + cfg.RedTeam.Gold.Position.Y, '2.5k', { fontFamily: cfg.RedTeam.Gold.Font.Name, fontSize: cfg.RedTeam.Gold.Font.Size, fontStyle: cfg.RedTeam.Gold.Font.Style, align: cfg.RedTeam.Gold.Font.Align, color: cfg.RedTeam.Gold.Font.Color, }); this.AddVisualComponent(this.RedGold); if (cfg.RedTeam.Gold.Font.Align === "right" || cfg.RedTeam.Gold.Font.Align === "Right") this.RedGold.setOrigin(1, 0); if (cfg.RedTeam.Gold.Font.Align === "left" || cfg.RedTeam.Gold.Font.Align === "Left") this.RedGold.setOrigin(0, 0); this.RedGoldImage = scene.make.sprite({ x: this.position.X + cfg.RedTeam.Gold.Position.X + cfg.RedTeam.Gold.Icon.Offset.X, y: this.position.Y + cfg.RedTeam.Gold.Position.Y + cfg.RedTeam.Gold.Icon.Offset.Y, key: 'scoreGold', add: true }); this.RedGoldImage.setDisplaySize(cfg.RedTeam.Gold.Icon.Size.X, cfg.RedTeam.Gold.Icon.Size.Y); this.RedGoldImage.setOrigin(0.5,0.5); this.AddVisualComponent(this.RedGoldImage); this.RedDragons = []; this.RedScoreTemplates = []; for (var i = 0; i <= 5; i++) { this.RedScoreTemplates.push(new Phaser.Geom.Circle(this.position.X + cfg.RedTeam.Score.Position.X + i * cfg.RedTeam.Score.CircleOffset.X, this.position.Y + cfg.RedTeam.Score.Position.Y + i * cfg.RedTeam.Score.CircleOffset.Y, cfg.RedTeam.Score.CircleRadius)); } //Tag this.RedTag = scene.add.text(this.position.X + cfg.RedTeam.Name.Position.X, this.position.Y + cfg.RedTeam.Name.Position.Y, 'Red', { fontFamily: cfg.RedTeam.Name.Font.Name, fontSize: cfg.RedTeam.Name.Font.Size, fontStyle: cfg.RedTeam.Name.Font.Style, align: cfg.RedTeam.Name.Font.Align, color: cfg.RedTeam.Name.Font.Color, }); this.AddVisualComponent(this.RedTag); if (cfg.RedTeam.Name.Font.Align === "right" || cfg.RedTeam.Name.Font.Align === "Right") this.RedTag.setOrigin(1, 0); if (cfg.RedTeam.Name.Font.Align === "left" || cfg.RedTeam.Name.Font.Align === "Left") this.RedTag.setOrigin(0, 0); //Icon if (cfg.RedTeam.Icon.UseBackground) { this.RedIconBackground = scene.make.sprite({ x: cfg.Position.X + cfg.RedTeam.Icon.Position.X + cfg.RedTeam.Icon.BackgroundOffset.X, y: cfg.Position.Y + cfg.RedTeam.Icon.Position.Y + cfg.RedTeam.Icon.BackgroundOffset.Y, key: 'scoreRedIcon', add: true }); this.AddVisualComponent(this.RedIconBackground); } //Load Resources if (cfg.Background.UseImage || cfg.Background.UseVideo) { this.scene.load.start(); } //Hide Elements on start this.GetActiveVisualComponents().forEach(c => { c.alpha = 0; c.y -= cfg.Size.Y; }); this.Init(); } UpdateValues(state: StateData): void { let scoreConfig = state.scoreboard; if (scoreConfig.GameTime === undefined || scoreConfig.GameTime === null || scoreConfig.GameTime == -1) { if (this.isActive) { this.Stop(); } return; } var timeInSec = Math.round(scoreConfig.GameTime); this.GameTime.text = (Math.floor(timeInSec / 60) >= 10 ? Math.floor(timeInSec / 60) : '0' + Math.floor(timeInSec / 60)) + ':' + (timeInSec % 60 >= 10 ? timeInSec % 60 : '0' + timeInSec % 60); //Update blue team values this.BlueGold.text = Utils.ConvertGold(scoreConfig.BlueTeam.Gold); this.BlueKills.text = scoreConfig.BlueTeam.Kills + ''; this.BlueTowers.text = scoreConfig.BlueTeam.Towers + ''; if (scoreConfig.BlueTeam.Name !== undefined){ this.BlueTag.text = scoreConfig.BlueTeam.Name; if(ScoreboardVisual.GetConfig()?.RedTeam.Name.AdaptiveFontSize) TextUtils.AutoSizeFont(this.RedTag!, ScoreboardVisual.GetConfig()!.RedTeam.Name.MaxSize.X, ScoreboardVisual.GetConfig()!.RedTeam.Name.MaxSize.Y, +ScoreboardVisual.GetConfig()!.RedTeam.Name.Font.Size.replace(/[^\d.-]/g, '')); } else this.BlueTag.text = ''; if (scoreConfig.BlueTeam.Icon !== undefined && scoreConfig.BlueTeam.Icon !== this.BlueIconName) { this.LoadIcon(scoreConfig.BlueTeam.Icon, false); this.BlueIconName = scoreConfig.BlueTeam.Icon; } if (scoreConfig.BlueTeam.Icon === undefined && this.BlueIconName !== '') { this.BlueIconSprite!.destroy(); this.BlueIconSprite = null; this.BlueIconName = ''; } //Update red team values this.RedGold.text = Utils.ConvertGold(scoreConfig.RedTeam.Gold); this.RedKills.text = scoreConfig.RedTeam.Kills + ''; this.RedTowers.text = scoreConfig.RedTeam.Towers + ''; if (scoreConfig.RedTeam.Name !== undefined) { this.RedTag!.text = scoreConfig.RedTeam.Name; if(ScoreboardVisual.GetConfig()?.RedTeam.Name.AdaptiveFontSize) TextUtils.AutoSizeFont(this.RedTag!, ScoreboardVisual.GetConfig()!.RedTeam.Name.MaxSize.X, ScoreboardVisual.GetConfig()!.RedTeam.Name.MaxSize.Y, +ScoreboardVisual.GetConfig()!.RedTeam.Name.Font.Size.replace(/[^\d.-]/g, '')); } else this.RedTag.text = ''; if (scoreConfig.RedTeam.Icon !== undefined && scoreConfig.RedTeam.Icon !== this.RedIconName) { this.LoadIcon(scoreConfig.RedTeam.Icon, true); this.RedIconName = scoreConfig.RedTeam.Icon; } if (scoreConfig.RedTeam.Icon === undefined && this.RedIconName !== '') { this.RedIconSprite!.destroy(); this.RedIconName = ''; this.RedIconSprite = null; } //Update dragons for both teams if (this.isActive && !this.isShowing) { this.UpdateDragons(scoreConfig.BlueTeam.Dragons, false); this.UpdateDragons(scoreConfig.RedTeam.Dragons, true); } //Update scores for both teams if (this.ShowScores && (scoreConfig.BlueTeam.Score === undefined || scoreConfig.RedTeam.Score === undefined)) { this.ScoreG.clear(); this.ShowScores = false; } if (scoreConfig.BlueTeam.Score !== undefined || scoreConfig.RedTeam.Score !== undefined) { if(this.ShowScores === false) { this.ShowScores = true; this.UpdateScores(state, true); } else { this.UpdateScores(state, false); } } if (!this.isActive) { this.Start(); } } UpdateConfig(newConfig: ScoreDisplayConfig): void { //Position this.position = newConfig.Position; //Background if (!newConfig.Background.UseAlpha) { this.MaskG.clear(); this.MaskG.fillStyle(0xffffff); this.MaskG.fillRect(newConfig.Position.X - (newConfig.Size.X / 2), newConfig.Position.Y, newConfig.Size.X, newConfig.Size.Y); } //Background Image if (newConfig.Background.UseImage) { if (this.BackgroundVideo !== undefined && this.BackgroundVideo !== null) { this.RemoveVisualComponent(this.BackgroundVideo); this.BackgroundVideo.destroy(); this.BackgroundVideo = null; this.scene.cache.video.remove('scoreBgVideo'); } if (this.BackgroundRect !== undefined && this.BackgroundRect !== null) { this.RemoveVisualComponent(this.BackgroundRect); this.BackgroundRect.destroy(); this.BackgroundRect = null; } //Load Texture only if it does not already exist if (this.BackgroundImage === null || this.BackgroundImage === undefined) { this.scene.load.image('scoreBg', 'frontend/backgrounds/Score.png'); } } //Background Video else if (newConfig.Background.UseVideo) { if (this.BackgroundRect !== undefined && this.BackgroundRect !== null) { this.RemoveVisualComponent(this.BackgroundRect); this.BackgroundRect.destroy(); this.BackgroundRect = null; } if (this.BackgroundImage !== undefined && this.BackgroundImage !== null) { this.RemoveVisualComponent(this.BackgroundImage); this.BackgroundImage.destroy(); this.BackgroundImage = null; this.scene.textures.remove('scoreBg'); } //Load Video only if it does not already exist if(this.BackgroundVideo === null || this.BackgroundVideo === undefined) { this.scene.load.video('scoreBgVideo', 'frontend/backgrounds/Score.mp4'); } } //Background Color else { if (this.BackgroundImage !== undefined && this.BackgroundImage !== null) { this.RemoveVisualComponent(this.BackgroundImage); this.BackgroundImage.destroy(); this.BackgroundImage = null; this.scene.textures.remove('scoreBg'); } if (this.BackgroundVideo !== undefined && this.BackgroundVideo !== null) { this.RemoveVisualComponent(this.BackgroundVideo); this.BackgroundVideo.destroy(); this.BackgroundVideo = null; this.scene.cache.video.remove('scoreBgVideo'); } if (this.BackgroundRect === null || this.BackgroundRect === undefined) { this.BackgroundRect = this.scene.add.rectangle(newConfig.Position.X, newConfig.Position.Y + (newConfig.Size.Y / 2), newConfig.Size.X, newConfig.Size.Y, Phaser.Display.Color.RGBStringToColor(newConfig.Background.FallbackColor).color, 1); this.BackgroundRect.setMask(ScoreboardVisual.GetConfig()?.Background.UseAlpha ? this.ImgMask : this.GeoMask); this.AddVisualComponent(this.BackgroundRect); if (!this.isActive) { this.BackgroundRect.alpha = 0; } } this.BackgroundRect.setPosition(newConfig.Position.X, newConfig.Position.Y + (newConfig.Size.Y / 2)); this.BackgroundRect.setSize(newConfig.Size.X, newConfig.Size.Y); this.BackgroundRect.setFillStyle(Phaser.Display.Color.RGBStringToColor(newConfig.Background.FallbackColor).color, 1); this.BackgroundRect.setDepth(-1); } //Game Time this.UpdateTextStyle(this.GameTime, newConfig.TimeFont); this.GameTime.setPosition(this.position.X + newConfig.TimePosition.X, this.position.Y + newConfig.TimePosition.Y); //Center Icon if (ScoreboardVisual.GetConfig()?.Misc.ShowCenterIcon && newConfig.Misc.ShowCenterIcon) { //Update Center Icon this.CenterIcon?.setPosition(this.position.X + newConfig.Misc.CenterIconPosition.X, this.position.Y + newConfig.Misc.CenterIconPosition.Y); this.CenterIcon?.setDisplaySize(newConfig.Misc.CenterIconSize.X, newConfig.Misc.CenterIconSize.Y); } else if (ScoreboardVisual.GetConfig()?.Misc.ShowCenterIcon && !newConfig.Misc.ShowCenterIcon) { //Destroy Center Icon this.RemoveVisualComponent(this.CenterIcon); this.CenterIcon?.destroy(); this.CenterIcon = null; } else if (!ScoreboardVisual.GetConfig()?.Misc.ShowCenterIcon && newConfig.Misc.ShowCenterIcon) { //Create Center Icon this.CenterIcon = this.scene.make.sprite({ x: this.position.X + newConfig.Misc.CenterIconPosition.X, y: this.position.Y + newConfig.Misc.CenterIconPosition.Y, key: 'scoreCenter', add: true }); this.CenterIcon.setDisplaySize(newConfig.Misc.CenterIconSize.X, newConfig.Misc.CenterIconSize.Y); this.AddVisualComponent(this.CenterIcon); } //Blue Fonts this.UpdateTextStyle(this.BlueKills, newConfig.BlueTeam.Kills.Font); this.UpdateTextStyle(this.BlueGold, newConfig.BlueTeam.Gold.Font); this.UpdateTextStyle(this.BlueTowers, newConfig.BlueTeam.Towers.Font); this.UpdateTextStyle(this.BlueTag, newConfig.BlueTeam.Name.Font); if (!ScoreboardVisual.GetConfig()?.BlueTeam.Score.UseCircleIcons && this.BlueScoreText !== null) this.UpdateTextStyle(this.BlueScoreText, newConfig.BlueTeam.Score.NumberFont); //Red Fonts this.UpdateTextStyle(this.RedKills, newConfig.RedTeam.Kills.Font); this.UpdateTextStyle(this.RedGold, newConfig.RedTeam.Gold.Font); this.UpdateTextStyle(this.RedTowers, newConfig.RedTeam.Towers.Font); this.UpdateTextStyle(this.RedTag, newConfig.RedTeam.Name.Font); if (!ScoreboardVisual.GetConfig()?.RedTeam.Score.UseCircleIcons && this.RedScoreText !== null) this.UpdateTextStyle(this.RedScoreText, newConfig.RedTeam.Score.NumberFont); //Blue Positions this.BlueKills.setPosition(this.position.X + newConfig.BlueTeam.Kills.Position.X, this.position.Y + newConfig.BlueTeam.Kills.Position.Y); this.BlueTowers.setPosition(this.position.X + newConfig.BlueTeam.Towers.Position.X, this.position.Y + newConfig.BlueTeam.Towers.Position.Y); this.BlueGold.setPosition(this.position.X + newConfig.BlueTeam.Gold.Position.X, this.position.Y + newConfig.BlueTeam.Gold.Position.Y); if (!newConfig.BlueTeam.Score.UseCircleIcons && this.BlueScoreText !== null) this.BlueScoreText?.setPosition(this.position.X + newConfig.BlueTeam.Score.Position.X, this.position.Y + newConfig.BlueTeam.Score.Position.Y); this.BlueTag.setPosition(this.position.X + newConfig.BlueTeam.Name.Position.X, this.position.Y + newConfig.BlueTeam.Name.Position.Y); this.BlueGoldImage?.setPosition(this.position.X + newConfig.BlueTeam.Gold.Position.X + newConfig.BlueTeam.Gold.Icon.Offset.X, this.position.Y + newConfig.BlueTeam.Gold.Position.Y + newConfig.BlueTeam.Gold.Icon.Offset.Y); this.BlueTowerImage?.setPosition(this.position.X + newConfig.BlueTeam.Towers.Position.X + newConfig.BlueTeam.Towers.Icon.Offset.X, this.position.Y + newConfig.BlueTeam.Towers.Position.Y + newConfig.BlueTeam.Towers.Icon.Offset.Y); this.BlueIconSprite?.setPosition(this.position.X + newConfig.BlueTeam.Icon.Position.X, this.position.Y + newConfig.BlueTeam.Icon.Position.Y); //Red Positions this.RedKills.setPosition(this.position.X + newConfig.RedTeam.Kills.Position.X, this.position.Y + newConfig.RedTeam.Kills.Position.Y); this.RedTowers.setPosition(this.position.X + newConfig.RedTeam.Towers.Position.X, this.position.Y + newConfig.RedTeam.Towers.Position.Y); this.RedGold.setPosition(this.position.X + newConfig.RedTeam.Gold.Position.X, this.position.Y + newConfig.RedTeam.Gold.Position.Y); if (!newConfig.RedTeam.Score.UseCircleIcons && this.RedScoreText !== null) this.RedScoreText?.setPosition(this.position.X + newConfig.RedTeam.Score.Position.X, this.position.Y + newConfig.RedTeam.Score.Position.Y); this.RedTag.setPosition(this.position.X + newConfig.RedTeam.Name.Position.X, this.position.Y + newConfig.RedTeam.Name.Position.Y); this.RedGoldImage?.setPosition(this.position.X + newConfig.RedTeam.Gold.Position.X + newConfig.RedTeam.Gold.Icon.Offset.X, this.position.Y + newConfig.RedTeam.Gold.Position.Y + newConfig.RedTeam.Gold.Icon.Offset.Y); this.RedTowerImage?.setPosition(this.position.X + newConfig.RedTeam.Towers.Position.X + newConfig.RedTeam.Towers.Icon.Offset.X, this.position.Y + newConfig.RedTeam.Towers.Position.Y + newConfig.RedTeam.Towers.Icon.Offset.Y); this.RedIconSprite?.setPosition(this.position.X + newConfig.RedTeam.Icon.Position.X, this.position.Y + newConfig.RedTeam.Icon.Position.Y); //Blue Sizes this.BlueTowerImage?.setDisplaySize(newConfig.BlueTeam.Towers.Icon.Size.X, newConfig.BlueTeam.Towers.Icon.Size.Y); this.BlueGoldImage?.setDisplaySize(newConfig.BlueTeam.Gold.Icon.Size.X, newConfig.BlueTeam.Gold.Icon.Size.Y); this.BlueIconSprite?.setDisplaySize(newConfig.BlueTeam.Icon.Size.X, newConfig.BlueTeam.Icon.Size.Y); //Red Sizes this.RedTowerImage?.setDisplaySize(newConfig.RedTeam.Towers.Icon.Size.X, newConfig.RedTeam.Towers.Icon.Size.Y); this.RedGoldImage?.setDisplaySize(newConfig.RedTeam.Gold.Icon.Size.X, newConfig.RedTeam.Gold.Icon.Size.Y); this.RedIconSprite?.setDisplaySize(newConfig.RedTeam.Icon.Size.X, newConfig.RedTeam.Icon.Size.Y); //Blue Icon Background if(newConfig.BlueTeam.Icon.UseBackground && ScoreboardVisual.GetConfig().BlueTeam.Icon.UseBackground) { this.BlueIconBackground?.setPosition(newConfig.Position.X + newConfig.BlueTeam.Icon.Position.X + newConfig.BlueTeam.Icon.BackgroundOffset.X, newConfig.Position.Y + newConfig.BlueTeam.Icon.Position.Y + newConfig.BlueTeam.Icon.BackgroundOffset.Y) } else if(newConfig.BlueTeam.Icon.UseBackground && !ScoreboardVisual.GetConfig().BlueTeam.Icon.UseBackground) { this.BlueIconBackground = this.scene.make.sprite({ x: newConfig.Position.X + newConfig.BlueTeam.Icon.Position.X + newConfig.BlueTeam.Icon.BackgroundOffset.X, y: newConfig.Position.Y + newConfig.BlueTeam.Icon.Position.Y + newConfig.BlueTeam.Icon.BackgroundOffset.Y, key: 'scoreBlueIcon', add: true }); this.AddVisualComponent(this.BlueIconBackground); } else if(!newConfig.BlueTeam.Icon.UseBackground && ScoreboardVisual.GetConfig().BlueTeam.Icon.UseBackground) { this.RemoveVisualComponent(this.BlueIconBackground) } //Red Icon Background if(newConfig.RedTeam.Icon.UseBackground && ScoreboardVisual.GetConfig().RedTeam.Icon.UseBackground) { this.RedIconBackground?.setPosition(newConfig.Position.X + newConfig.RedTeam.Icon.Position.X + newConfig.RedTeam.Icon.BackgroundOffset.X, newConfig.Position.Y + newConfig.RedTeam.Icon.Position.Y + newConfig.RedTeam.Icon.BackgroundOffset.Y) } else if(newConfig.RedTeam.Icon.UseBackground && !ScoreboardVisual.GetConfig().RedTeam.Icon.UseBackground) { this.RedIconBackground = this.scene.make.sprite({ x: newConfig.Position.X + newConfig.RedTeam.Icon.Position.X + newConfig.RedTeam.Icon.BackgroundOffset.X, y: newConfig.Position.Y + newConfig.RedTeam.Icon.Position.Y + newConfig.RedTeam.Icon.BackgroundOffset.Y, key: 'scoreRedIcon', add: true }); this.AddVisualComponent(this.RedIconBackground); } else if(!newConfig.RedTeam.Icon.UseBackground && ScoreboardVisual.GetConfig().RedTeam.Icon.UseBackground) { this.RemoveVisualComponent(this.RedIconBackground) } if (this.scene.state !== null && this.scene.state !== undefined) { //Reset Score Templates this.BlueScoreTemplates = []; this.RedScoreTemplates = []; for (var i = 0; i < 5; i++) { this.BlueScoreTemplates.push(new Phaser.Geom.Circle(this.position.X + newConfig.BlueTeam.Score.Position.X + i * newConfig.BlueTeam.Score.CircleOffset.X, this.position.Y + newConfig.BlueTeam.Score.Position.Y + i * newConfig.BlueTeam.Score.CircleOffset.Y, newConfig.BlueTeam.Score.CircleRadius)); } for (var i = 0; i <= 5; i++) { this.RedScoreTemplates.push(new Phaser.Geom.Circle(this.position.X + newConfig.RedTeam.Score.Position.X + i * newConfig.RedTeam.Score.CircleOffset.X, this.position.Y + newConfig.RedTeam.Score.Position.Y + i * newConfig.RedTeam.Score.CircleOffset.Y, newConfig.RedTeam.Score.CircleRadius)); } //Redraw Scores this.UpdateScores(this.scene.state, true, newConfig); //Drake this.UpdateDragons(this.scene.state.scoreboard.BlueTeam.Dragons, false, newConfig, true); this.UpdateDragons(this.scene.state.scoreboard.RedTeam.Dragons, true, newConfig, true); } if (newConfig.Background.UseImage || newConfig.Background.UseVideo) { console.log('loading assets'); this.scene.load.start(); } if(!this.isActive) { this.GetActiveVisualComponents().forEach(c => { //Hide now visible elements c.alpha = 0; if(c.y > 0) c.y -= newConfig.Size.Y; }); } } static GetConfig(): ScoreDisplayConfig { return IngameScene.Instance.overlayCfg!.Score; } Load(): void { //Load in constructor since there is no reason to queue creation } Start(): void { if (this.isActive || this.isShowing) return; this.isShowing = true; let ctx = this; switch (ScoreboardVisual.GetConfig().Misc.Animation) { case 'none': case 'None': this.GetActiveVisualComponents().forEach(c => { if(c.y < 0) { c.y += ScoreboardVisual.GetConfig()!.Size.Y; } c.alpha = 1; }); this.isShowing = false; this.isActive = true; break; case 'simple': case 'Simple': [this.BackgroundImage, this.BackgroundRect, this.BackgroundVideo, this.GameTime, this.CenterIcon, this.BlueKills, this.RedKills, this.BlueGoldImage, this.RedGoldImage, this.BlueGold, this.RedGold, this.BlueTowerImage, this.RedTowerImage, this.BlueTowers, this.RedTowers, this.BlueTag, this.RedTag, this.ScoreG, this.BlueScoreText, this.RedScoreText, this.BlueIconBackground, this.RedIconBackground].forEach(c => { if(c === null || c === undefined) return; c.alpha = 1; }); this.currentAnimation[0] = this.scene.tweens.add({ targets: [this.BackgroundImage, this.BackgroundRect, this.BackgroundVideo, this.GameTime, this.CenterIcon, this.BlueKills, this.RedKills, this.BlueGoldImage, this.RedGoldImage, this.BlueGold, this.RedGold, this.BlueTowerImage, this.RedTowerImage, this.BlueTowers, this.RedTowers, this.BlueTag, this.RedTag, this.ScoreG, this.BlueScoreText, this.RedScoreText, this.BlueIconBackground, this.RedIconBackground], props: { y: { value: '+=' + ScoreboardVisual.GetConfig().Size.Y, duration: 550, ease: 'Circ.easeOut' } }, paused: false, yoyo: false, duration: 550, onComplete: function() { ctx.isShowing = false; ctx.isActive = true; ctx.currentAnimation = []; } }); this.currentAnimation[1] = this.scene.tweens.add({ targets: [this.BlueIconSprite, this.RedIconSprite].concat(this.BlueDragons).concat(this.RedDragons), props: { alpha: { from: 0, to: 1, duration: 250, ease: 'Circ.easeInOut' } }, paused: false, yoyo: false, delay: 550, duration: 250 }); break; case 'fancy': case 'Fancy': //TODO ScoreboardVisual.GetConfig().Misc.Animation = "Simple"; this.Start(); break; default: break; } } Stop(): void { if(!this.isActive || this.isHiding) { return; } this.isHiding = true; this.isActive = false; let ctx = this; switch (ScoreboardVisual.GetConfig()?.Misc.Animation) { case 'none': case 'None': this.GetActiveVisualComponents().forEach(c => { c.y -= ScoreboardVisual.GetConfig()!.Size.Y; c.alpha = 0; }); this.isHiding = false; break; case 'simple': case 'Simple': this.currentAnimation[0] = this.scene.tweens.add({ targets: [this.BackgroundImage, this.BackgroundRect, this.BackgroundVideo, this.GameTime, this.CenterIcon, this.BlueKills, this.RedKills, this.BlueGoldImage, this.RedGoldImage, this.BlueGold, this.RedGold, this.BlueTowerImage, this.RedTowerImage, this.BlueTowers, this.RedTowers, this.BlueTag, this.RedTag, this.ScoreG, this.BlueScoreText, this.RedScoreText, this.BlueIconBackground, this.RedIconBackground], props: { y: { value: '-=' + ScoreboardVisual.GetConfig().Size.Y, duration: 550, ease: 'Circ.easeIn' } }, paused: false, yoyo: false, duration: 550, delay: 100, onComplete: function () { ctx.isHiding = false; ctx.currentAnimation = []; } }); this.currentAnimation[1] = this.scene.tweens.add({ targets: [this.BlueIconSprite, this.RedIconSprite].concat(this.BlueDragons).concat(this.RedDragons), props: { alpha: { from: 1, to: 0, duration: 250, ease: 'Circ.easeInOut' } }, paused: false, yoyo: false, duration: 100 }); break; case 'fancy': case 'Fancy': //TODO ScoreboardVisual.GetConfig().Misc.Animation = "Simple"; this.Stop(); break; default: break; } } CreateTextureListeners(): void { //Background Image support this.scene.load.on(`filecomplete-image-scoreBg`, () => { this.BackgroundImage = this.scene.make.sprite({ x: ScoreboardVisual.GetConfig()!.Position.X, y: ScoreboardVisual.GetConfig()!.Position.Y, key: 'scoreBg', add: true }); this.BackgroundImage.setOrigin(0.5, 0); this.BackgroundImage.setDepth(-1); this.BackgroundImage.setMask(ScoreboardVisual.GetConfig()?.Background.UseAlpha ? this.ImgMask : this.GeoMask); this.AddVisualComponent(this.BackgroundImage); if (!this.isActive && !this.isShowing) { this.BackgroundImage.alpha = 0; this.BackgroundImage.y -= this.BackgroundImage.displayHeight; } }); //Background Video support this.scene.load.on(`filecomplete-video-scoreBgVideo`, () => { if (this.BackgroundVideo !== undefined && this.BackgroundVideo !== null) { this.RemoveVisualComponent(this.BackgroundVideo); this.BackgroundVideo.destroy(); } // @ts-ignore this.BackgroundVideo = this.scene.add.video(ScoreboardVisual.GetConfig()!.Position.X, ScoreboardVisual.GetConfig()!.Position.Y, 'scoreBgVideo', false, true); this.BackgroundVideo.setOrigin(0.5, 0); this.BackgroundVideo.setMask(ScoreboardVisual.GetConfig()?.Background.UseAlpha ? this.ImgMask : this.GeoMask); this.BackgroundVideo.setLoop(true); this.BackgroundVideo.setDepth(-1); this.BackgroundVideo.play(); this.AddVisualComponent(this.BackgroundVideo); if (!this.isActive && !this.isShowing) { this.BackgroundVideo.alpha = 0; this.BackgroundVideo.y -= this.BackgroundVideo.displayHeight; } }); //Team Icons this.scene.load.on(`filecomplete-image-blue_icon`, () => { this.BlueIconSprite = this.scene.make.sprite({ x: this.position.X + ScoreboardVisual.GetConfig()!.BlueTeam.Icon.Position.X, y: this.position.Y + ScoreboardVisual.GetConfig()!.BlueTeam.Icon.Position.Y, key: 'blue_icon', add: true }); this.BlueIconSprite.displayWidth = ScoreboardVisual.GetConfig()!.BlueTeam.Icon.Size.X; this.BlueIconSprite.displayHeight = ScoreboardVisual.GetConfig()!.BlueTeam.Icon.Size.Y; this.BlueIconSprite.alpha = 0; if(this.isShowing && !this.isActive) { let delay = 550 - this.currentAnimation[0].totalElapsed; this.scene.tweens.add({ targets: this.BlueIconSprite, props: { alpha: { from: 0, to: 1, duration: 1000, ease: 'Circ.easeOut' } }, paused: false, yoyo: false, delay: delay }); } if(this.isActive) { this.BlueIconSprite.alpha = 1; } }); this.scene.load.on(`filecomplete-image-red_icon`, () => { this.RedIconSprite = this.scene.make.sprite({ x: this.position.X + ScoreboardVisual.GetConfig()!.RedTeam.Icon.Position.X, y: this.position.Y + ScoreboardVisual.GetConfig()!.RedTeam.Icon.Position.Y, key: 'red_icon', add: true }); this.RedIconSprite.displayWidth = ScoreboardVisual.GetConfig()!.RedTeam.Icon.Size.X; this.RedIconSprite.displayHeight = ScoreboardVisual.GetConfig()!.RedTeam.Icon.Size.Y; this.RedIconSprite.alpha = 0; if(this.isShowing && !this.isActive) { let delay = 550 - this.currentAnimation[0].totalElapsed; this.scene.tweens.add({ targets: this.RedIconSprite, props: { alpha: { from: 0, to: 1, duration: 1000, ease: 'Circ.easeOut' } }, paused: false, yoyo: false, delay: delay }); } if(this.isActive) { this.RedIconSprite.alpha = 1; } }); } UpdateDragons(dragons: string[], side: boolean, cfg: ScoreDisplayConfig | null = null, force: boolean = false): void { let conf = cfg === null ? ScoreboardVisual.GetConfig()! : cfg; var dragonIcons = side ? this.RedDragons : this.BlueDragons; if (dragons === undefined || dragons === null) { dragonIcons.forEach(oldIcon => { this.RemoveVisualComponent(oldIcon); oldIcon.destroy(); }); } if (force || dragons.length !== dragonIcons.length) { dragonIcons.forEach(oldIcon => { this.RemoveVisualComponent(oldIcon); oldIcon.destroy(); }); dragonIcons = []; var i = 0; dragons.forEach(drakeName => { var toAdd = this.scene.make.sprite({ x: this.position.X + (side ? conf.RedTeam.Drakes.Position.X + i++ * conf.RedTeam.Drakes.Offset.X : conf.BlueTeam.Drakes.Position.X + i++ * conf.BlueTeam.Drakes.Offset.X), y: this.position.Y + (side ? conf.RedTeam.Drakes.Position.Y + i++ * conf.RedTeam.Drakes.Offset.Y : conf.BlueTeam.Drakes.Position.Y + i++ * conf.BlueTeam.Drakes.Offset.Y), key: 'dragon_' + drakeName, add: true }); toAdd.displayHeight = conf.Misc.DrakeIconSize.X; toAdd.displayWidth = conf.Misc.DrakeIconSize.Y; dragonIcons.push(toAdd); this.AddVisualComponent(toAdd); }); if (side) { this.RedDragons = dragonIcons; } else { this.BlueDragons = dragonIcons; } } } UpdateScores(state: StateData, forceUpdate: boolean, cfg: ScoreDisplayConfig | null = null): void { let conf = state.scoreboard; cfg = cfg === null ? ScoreboardVisual.GetConfig()! : cfg; if (forceUpdate || conf.RedTeam.Score !== this.RedWins || conf.BlueTeam.Score !== this.BlueWins) { console.log('[LB] Updating Score display'); let redWins = conf.RedTeam.Score; let blueWins = conf.BlueTeam.Score; this.ScoreG.clear(); this.ScoreG.setDepth(1); if (cfg.BlueTeam.Score.UseCircleIcons) { //Draw blue score icons let color = Phaser.Display.Color.IntegerToColor(variables.fallbackBlue); if (cfg.BlueTeam.Score.UseTeamColor) { if (state.blueColor !== undefined && state.blueColor !== '') { color = Phaser.Display.Color.RGBStringToColor(state.blueColor); this.ScoreG.fillStyle(color.color, 1); this.ScoreG.lineStyle(3, color.color, 1); } } else { this.ScoreG.fillStyle(Phaser.Display.Color.RGBStringToColor(cfg.BlueTeam.Score.FillColor).color, 1); this.ScoreG.lineStyle(3, Phaser.Display.Color.RGBStringToColor(cfg.BlueTeam.Score.StrokeColor).color, 1); } let numIcons = this.TotalGameToWinsNeeded[conf.SeriesGameCount]; this.BlueScoreTemplates.forEach(template => { if (numIcons-- > 0) { if (blueWins-- > 0) { this.ScoreG.fillCircleShape(template); } else { this.ScoreG.strokeCircleShape(template); } } }); } else { this.BlueScoreText!.text = conf.BlueTeam.Score + ''; } if (cfg.RedTeam.Score.UseCircleIcons) { //Draw red score icons let color = Phaser.Display.Color.IntegerToColor(variables.fallbackRed); if (cfg.RedTeam.Score.UseTeamColor) { if (state.redColor !== undefined && state.redColor !== '') { color = Phaser.Display.Color.RGBStringToColor(state.redColor); this.ScoreG.fillStyle(color.color, 1); this.ScoreG.lineStyle(3, color.color, 1); } } else { this.ScoreG.fillStyle(Phaser.Display.Color.RGBStringToColor(cfg.RedTeam.Score.FillColor).color, 1); this.ScoreG.lineStyle(3, Phaser.Display.Color.RGBStringToColor(cfg.RedTeam.Score.StrokeColor).color, 1); } let numIcons = this.TotalGameToWinsNeeded[conf.SeriesGameCount]; this.RedScoreTemplates.forEach(template => { if (numIcons-- > 0) { if (redWins-- > 0) { this.ScoreG.fillCircleShape(template); } else { this.ScoreG.strokeCircleShape(template); } } }); } else { this.RedScoreText!.text = conf.RedTeam.Score + ''; } //update data this.BlueWins = conf.BlueTeam.Score; this.RedWins = conf.RedTeam.Score; } } LoadIcon(iconLoc: string, team: boolean): void { var id = (team ? 'red' : 'blue') + '_icon'; iconLoc = PlaceholderConversion.MakeUrlAbsolute(iconLoc.replace('Cache', '/cache').replace('\\', '/')); if (team) { if (this.RedIconSprite !== undefined && this.RedIconSprite !== null) { this.RemoveVisualComponent(this.RedIconSprite); this.RedIconSprite.destroy(); this.RedIconSprite = null; } } else { if (this.BlueIconSprite !== undefined && this.BlueIconSprite !== null) { this.RemoveVisualComponent(this.BlueIconSprite); this.BlueIconSprite.destroy(); this.BlueIconSprite = null; } } if (this.scene.textures.exists(id)) { this.scene.textures.remove(id); } this.scene.load.image(id, iconLoc); this.scene.load.start(); } }
the_stack
export interface FakeUploadProgress { eventListeners: { progress: any[]; load: any[]; abort: any[]; error: any[]; }; addEventListener(event: string, listener: (e: Event) => any): void; removeEventListener(event: string, listener: (e: Event) => any): void; dispatchEvent(event: Event): void; } export interface FakeXMLHttpRequest { /** * The URL set on the request object. */ url: string; /** * The request method as a string. */ method: string; /** * An object of all request headers, i.e.: */ requestHeaders: any; /** * The request body */ requestBody: string; /** * The request’s status code. * undefined if the request has not been handled (see respond below) */ status: number; /** * Only populated if the respond method is called (see below). */ statusText: string; /** * Whether or not the request is asynchronous. */ async: boolean; /** * Username, if any. */ username: string; /** * Password, if any. */ password: string; withCredentials: boolean; upload: FakeUploadProgress; /** * When using respond, this property is populated with a parsed document if response headers indicate as much (see the spec) */ responseXML: Document; /** * The value of the given response header, if the request has been responded to (see respond). * @param header */ getResponseHeader(header: string): string; /** * All response headers as an object. */ getAllResponseHeaders(): any; /** * Sets response headers (e.g. { "Content-Type": "text/html", ... }, updates the readyState property and fires onreadystatechange. * @param headers */ setResponseHeaders(headers: any): void; /** * Sets the respond body, updates the readyState property and fires onreadystatechange. * Additionally, populates responseXML with a parsed document if response headers indicate as much. */ setResponseBody(body: string): void; /** * Calls the above three methods. */ respond(status: number, headers?: any, body?: string): void; autoRespond(ms: number): void; /** * Simulates a network error on the request. The onerror handler will be called and the status will be 0. */ error(): void; onloadstart(e: Event): void; onprogress(e: Event): void; ontimeout(e: Event): void; onloadend(e: Event): void; onerror(e: Event): void; onabort(e: Event): void; onload(e: Event): void; } export interface FakeServerOptions { /** * When set to true, causes the server to automatically respond to incoming requests after a timeout. * The default timeout is 10ms but you can control it through the autoRespondAfter property. * Note that this feature is intended to help during mockup development, and is not suitable for use in tests. */ autoRespond: boolean; /** * When autoRespond is true, respond to requests after this number of milliseconds. Default is 10. */ autoRespondAfter: number; /** * If set to true, server will find _method parameter in POST body and recognize that as the actual method. * Supports a pattern common to Ruby on Rails applications. For custom HTTP method faking, override server.getHTTPMethod(request). */ fakeHTTPMethods: boolean; /** * If set, the server will respond to every request immediately and synchronously. * This is ideal for faking the server from within a test without having to call server.respond() after each request made in that test. * As this is synchronous and immediate, this is not suitable for simulating actual network latency in tests or mockups. * To simulate network latency with automatic responses, see server.autoRespond and server.autoRespondAfter. */ respondImmediately: boolean; } export interface FakeServer extends FakeServerOptions { lastRequest: FakeXMLHttpRequest | undefined; firstRequest: FakeXMLHttpRequest | undefined; secondRequest: FakeXMLHttpRequest | undefined; thirdRequest: FakeXMLHttpRequest | undefined; /** * Used internally to determine the HTTP method used with the provided request. * By default this method simply returns request.method. * When server.fakeHTTPMethods is true, the method will return the value of the _method parameter if the method is “POST”. * This method can be overridden to provide custom behavior. * @param request */ getHTTPMethod(request: FakeXMLHttpRequest): string; /** * You can inspect the server.requests to verify request ordering, find unmatched requests or check that no requests has been done. * server.requests is an array of all the FakeXMLHttpRequest objects that have been created. */ requests: FakeXMLHttpRequest[]; /** * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""]. * A String representing the response body * An Array with status, headers and response body, e.g. [200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"] * A Function. * Default status is 200 and default headers are none. * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request. * @param body A String representing the response body */ respondWith(body: string): void; /** * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""]. * Default status is 200 and default headers are none. * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request. * @param response An Array with status, headers and response body, e.g. [200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"] */ respondWith(response: any[]): void; /** * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""]. * Default status is 200 and default headers are none. * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request. * @param fn A Function. */ respondWith(fn: (xhr: FakeXMLHttpRequest) => void): void; /** * Responds to all requests to given URL, e.g. /posts/1. */ respondWith(url: string, body: string): void; /** * Responds to all requests to given URL, e.g. /posts/1. */ respondWith(url: string, response: any[]): void; /** * Responds to all requests to given URL, e.g. /posts/1. */ respondWith(url: string, fn: (xhr: FakeXMLHttpRequest) => void): void; /** * Responds to all method requests to the given URL with the given response. * method is an HTTP verb. */ respondWith(method: string, url: string, body: string): void; /** * Responds to all method requests to the given URL with the given response. * method is an HTTP verb. */ respondWith(method: string, url: string, response: any[]): void; /** * Responds to all method requests to the given URL with the given response. * method is an HTTP verb. */ respondWith(method: string, url: string, fn: (xhr: FakeXMLHttpRequest) => void): void; /** * URL may be a regular expression, e.g. /\\/post\\//\\d+ * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: */ respondWith(url: RegExp, body: string): void; /** * URL may be a regular expression, e.g. /\\/post\\//\\d+ * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: */ respondWith(url: RegExp, response: any[]): void; /** * URL may be a regular expression, e.g. /\\/post\\//\\d+ * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: */ respondWith(url: RegExp, fn: (xhr: FakeXMLHttpRequest) => void): void; /** * Responds to all method requests to URLs matching the regular expression. */ respondWith(method: string, url: RegExp, body: string): void; /** * Responds to all method requests to URLs matching the regular expression. */ respondWith(method: string, url: RegExp, response: any[]): void; /** * Responds to all method requests to URLs matching the regular expression. */ respondWith(method: string, url: RegExp, fn: (xhr: FakeXMLHttpRequest) => void): void; respondWith(...args: any[]): void; /** * Causes all queued asynchronous requests to receive a response. * If none of the responses added through respondWith match, the default response is [404, {}, ""]. * Synchronous requests are responded to immediately, so make sure to call respondWith upfront. * If called with arguments, respondWith will be called with those arguments before responding to requests. */ respond(): void; restore(): void; getRequest(): FakeXMLHttpRequest | undefined; reset(): void; resetBehavior(): void; resetHistory(): void; } export interface FakeXMLHttpRequestStatic { new(): FakeXMLHttpRequest; /** * Default false. * When set to true, Sinon will check added filters if certain requests should be “unfaked” */ useFilters: boolean; /** * Add a filter that will decide whether or not to fake a request. * The filter will be called when xhr.open is called, with the exact same arguments (method, url, async, username, password). * If the filter returns true, the request will not be faked. * @param filter */ addFilter(filter: (method: string, url: string, async: boolean, username: string, password: string) => boolean): void; /** * By assigning a function to the onCreate property of the returned object from useFakeXMLHttpRequest() * you can subscribe to newly created FakeXMLHttpRequest objects. See below for the fake xhr object API. * Using this observer means you can still reach objects created by e.g. jQuery.ajax (or other abstractions/frameworks). * @param xhr */ onCreate(xhr: FakeXMLHttpRequest): void; /** * Restore original function(s). */ restore(): void; } export interface FakeServerStatic { create(options?: Partial<FakeServerOptions>): FakeServer; } export interface FakeXHR { useFakeXMLHttpRequest(): FakeXMLHttpRequestStatic; FakeXMLHttpRequest: FakeXMLHttpRequestStatic; } export const fakeServerWithClock: FakeServerStatic; export const fakeServer: FakeServerStatic; export const fakeXhr: FakeXHR;
the_stack
Date: 2018-05-23 05:58:12 Version: 5.10 Tip: To override a DTO option, remove "//" prefix before updating BaseUrl: http://10.0.0.201:8080 //GlobalNamespace: DTOs //MakePropertiesOptional: True //AddServiceStackTypes: True //AddResponseStatus: False //AddImplicitVersion: //AddDescriptionAsComments: True //IncludeTypes: //ExcludeTypes: //DefaultImports: */ export namespace DTOs { export interface IReturn<T> { createResponse(): T; } export interface IReturnVoid { createResponse(): void; } export interface IPost { } // @DataContract export class ResponseError { // @DataMember(Order=1, EmitDefaultValue=false) public errorCode: string; // @DataMember(Order=2, EmitDefaultValue=false) public fieldName: string; // @DataMember(Order=3, EmitDefaultValue=false) public message: string; // @DataMember(Order=4, EmitDefaultValue=false) public meta: { [index: string]: string; }; } // @DataContract export class ResponseStatus { // @DataMember(Order=1) public errorCode: string; // @DataMember(Order=2) public message: string; // @DataMember(Order=3) public stackTrace: string; // @DataMember(Order=4) public errors: ResponseError[]; // @DataMember(Order=5) public meta: { [index: string]: string; }; } export class Query<T> { } export class Basket { public id: string; public customerId: string; public customer: string; public totalItems: number; public totalQuantity: number; public subTotal: number; public created: number; public updated: number; } export class Paged<T> { } export class BasketIndex { public id: string; public customerId: string; public customer: string; public totalItems: number; public totalQuantity: number; public subTotal: number; public created: number; public updated: number; } export class CommandResponse { public roundTripMs: number; public responseStatus: ResponseStatus; } export class DomainCommand { } export class BasketItemIndex { public id: string; public basketId: string; public productId: string; public productPictureContents: string; public productPictureContentType: string; public productName: string; public productDescription: string; public productPrice: number; public quantity: number; public subTotal: number; } export class CatalogBrand { public id: string; public brand: string; } export class CatalogType { public id: string; public type: string; } export class CatalogProduct { public id: string; public name: string; public description: string; public price: number; public catalogTypeId: string; public catalogType: string; public catalogBrandId: string; public catalogBrand: string; public availableStock: number; public restockThreshold: number; public maxStockThreshold: number; public onReorder: boolean; public pictureContents: string; public pictureContentType: string; } export class CatalogProductIndex { public id: string; public name: string; public description: string; public price: number; public catalogTypeId: string; public catalogType: string; public catalogBrandId: string; public catalogBrand: string; public availableStock: number; public restockThreshold: number; public maxStockThreshold: number; public onReorder: boolean; public pictureContents: string; public pictureContentType: string; } export class User { public id: string; public givenName: string; public disabled: boolean; public roles: string[]; public lastLogin: number; } export class StampedCommand { public stamp: number; } export class Location extends StampedCommand { public id: string; public code: string; public description: string; public points: Point[]; } export class Campaign { public id: string; public name: string; public description: string; public start: string; public end: string; public pictureContents: string; public pictureContentType: string; } export class OrderingBuyerIndex { public id: string; public givenName: string; public goodStanding: boolean; public totalSpent: number; public preferredCity: string; public preferredState: string; public preferredCountry: string; public preferredZipCode: string; public preferredPaymentCardholder: string; public preferredPaymentMethod: string; public preferredPaymentExpiration: string; } export class OrderingBuyer { public id: string; public givenName: string; public goodStanding: boolean; public preferredAddressId: string; public preferredPaymentMethodId: string; } export class Address { public id: string; public userName: string; public alias: string; public street: string; public city: string; public state: string; public country: string; public zipCode: string; } export class PaymentMethod { public id: string; public userName: string; public alias: string; public cardNumber: string; public securityNumber: string; public cardholderName: string; public expiration: string; public cardType: string; } export class OrderingOrder { public id: string; public status: string; public statusDescription: string; public userName: string; public buyerName: string; public shippingAddressId: string; public shippingAddress: string; public shippingCityState: string; public shippingZipCode: string; public shippingCountry: string; public billingAddressId: string; public billingAddress: string; public billingCityState: string; public billingZipCode: string; public billingCountry: string; public paymentMethodId: string; public paymentMethod: string; public totalItems: number; public totalQuantity: number; public subTotal: number; public additionalFees: number; public additionalTaxes: number; public total: number; public created: number; public updated: number; public paid: boolean; public items: OrderingOrderItem[]; } export class OrderingOrderIndex { public id: string; public status: string; public statusDescription: string; public userName: string; public buyerName: string; public shippingAddressId: string; public shippingAddress: string; public shippingCity: string; public shippingState: string; public shippingZipCode: string; public shippingCountry: string; public billingAddressId: string; public billingAddress: string; public billingCity: string; public billingState: string; public billingZipCode: string; public billingCountry: string; public paymentMethodId: string; public paymentMethod: string; public totalItems: number; public totalQuantity: number; public subTotal: number; public additional: number; public total: number; public created: number; public updated: number; public paid: boolean; } export class SalesWeekOverWeek { public id: string; public relevancy: number; public dayOfWeek: string; public value: number; } export class SalesByState { public id: string; public relevancy: number; public state: string; public value: number; } export class SalesChart { public id: string; public relevancy: number; public label: string; public value: number; } export class OrderingOrderItem { public id: string; public orderId: string; public productId: string; public productPictureContents: string; public productPictureContentType: string; public productName: string; public productDescription: string; public productPrice: number; public price: number; public quantity: number; public subTotal: number; public additionalFees: number; public additionalTaxes: number; public total: number; } export class ConfigurationStatus { public id: string; public isSetup: boolean; public setupContexts: string[]; } export class Point { public id: string; public locationId: string; public longitude: number; public latitude: number; } export interface ICommand { } export interface IMessage { } // @DataContract export class AuthenticateResponse { // @DataMember(Order=1) public userId: string; // @DataMember(Order=2) public sessionId: string; // @DataMember(Order=3) public userName: string; // @DataMember(Order=4) public displayName: string; // @DataMember(Order=5) public referrerUrl: string; // @DataMember(Order=6) public bearerToken: string; // @DataMember(Order=7) public refreshToken: string; // @DataMember(Order=8) public responseStatus: ResponseStatus; // @DataMember(Order=9) public meta: { [index: string]: string; }; } // @DataContract export class AssignRolesResponse { // @DataMember(Order=1) public allRoles: string[]; // @DataMember(Order=2) public allPermissions: string[]; // @DataMember(Order=3) public responseStatus: ResponseStatus; } // @DataContract export class UnAssignRolesResponse { // @DataMember(Order=1) public allRoles: string[]; // @DataMember(Order=2) public allPermissions: string[]; // @DataMember(Order=3) public responseStatus: ResponseStatus; } // @DataContract export class ConvertSessionToTokenResponse { // @DataMember(Order=1) public meta: { [index: string]: string; }; // @DataMember(Order=2) public accessToken: string; // @DataMember(Order=3) public responseStatus: ResponseStatus; } // @DataContract export class GetAccessTokenResponse { // @DataMember(Order=1) public accessToken: string; // @DataMember(Order=2) public responseStatus: ResponseStatus; } // @DataContract export class RegisterResponse { // @DataMember(Order=1) public userId: string; // @DataMember(Order=2) public sessionId: string; // @DataMember(Order=3) public userName: string; // @DataMember(Order=4) public referrerUrl: string; // @DataMember(Order=5) public bearerToken: string; // @DataMember(Order=6) public refreshToken: string; // @DataMember(Order=7) public responseStatus: ResponseStatus; // @DataMember(Order=8) public meta: { [index: string]: string; }; } export class QueryResponse<T> { public roundTripMs: number; public payload: T; public responseStatus: ResponseStatus; } export class PagedResponse<T> { public roundTripMs: number; public total: number; public records: T[]; public responseStatus: ResponseStatus; } // @Route("/auth") // @Route("/auth/{provider}") // @Route("/authenticate") // @Route("/authenticate/{provider}") // @DataContract export class Authenticate implements IReturn<AuthenticateResponse>, IPost { // @DataMember(Order=1) public provider: string; // @DataMember(Order=2) public state: string; // @DataMember(Order=3) public oauth_token: string; // @DataMember(Order=4) public oauth_verifier: string; // @DataMember(Order=5) public userName: string; // @DataMember(Order=6) public password: string; // @DataMember(Order=7) public rememberMe: boolean; // @DataMember(Order=8) public continue: string; // @DataMember(Order=9) public nonce: string; // @DataMember(Order=10) public uri: string; // @DataMember(Order=11) public response: string; // @DataMember(Order=12) public qop: string; // @DataMember(Order=13) public nc: string; // @DataMember(Order=14) public cnonce: string; // @DataMember(Order=15) public useTokenCookie: boolean; // @DataMember(Order=16) public accessToken: string; // @DataMember(Order=17) public accessTokenSecret: string; // @DataMember(Order=18) public meta: { [index: string]: string; }; public createResponse() { return new AuthenticateResponse(); } public getTypeName() { return 'Authenticate'; } } // @Route("/assignroles") // @DataContract export class AssignRoles implements IReturn<AssignRolesResponse>, IPost { // @DataMember(Order=1) public userName: string; // @DataMember(Order=2) public permissions: string[]; // @DataMember(Order=3) public roles: string[]; public createResponse() { return new AssignRolesResponse(); } public getTypeName() { return 'AssignRoles'; } } // @Route("/unassignroles") // @DataContract export class UnAssignRoles implements IReturn<UnAssignRolesResponse>, IPost { // @DataMember(Order=1) public userName: string; // @DataMember(Order=2) public permissions: string[]; // @DataMember(Order=3) public roles: string[]; public createResponse() { return new UnAssignRolesResponse(); } public getTypeName() { return 'UnAssignRoles'; } } // @Route("/session-to-token") // @DataContract export class ConvertSessionToToken implements IReturn<ConvertSessionToTokenResponse>, IPost { // @DataMember(Order=1) public preserveSession: boolean; public createResponse() { return new ConvertSessionToTokenResponse(); } public getTypeName() { return 'ConvertSessionToToken'; } } // @Route("/access-token") // @DataContract export class GetAccessToken implements IReturn<GetAccessTokenResponse>, IPost { // @DataMember(Order=1) public refreshToken: string; public createResponse() { return new GetAccessTokenResponse(); } public getTypeName() { return 'GetAccessToken'; } } // @Route("/register") // @DataContract export class Register implements IReturn<RegisterResponse>, IPost { // @DataMember(Order=1) public userName: string; // @DataMember(Order=2) public firstName: string; // @DataMember(Order=3) public lastName: string; // @DataMember(Order=4) public displayName: string; // @DataMember(Order=5) public email: string; // @DataMember(Order=6) public password: string; // @DataMember(Order=7) public autoLogin: boolean; // @DataMember(Order=8) public continue: string; public createResponse() { return new RegisterResponse(); } public getTypeName() { return 'Register'; } } /** * Basket */ // @Route("/basket", "GET") // @Api(Description="Basket") export class GetBasket extends Query<Basket> implements IReturn<QueryResponse<Basket>> { public basketId: string; public createResponse() { return new QueryResponse<Basket>(); } public getTypeName() { return 'GetBasket'; } } /** * Basket */ // @Route("/basket/list", "GET") // @Api(Description="Basket") export class ListBaskets extends Paged<BasketIndex> implements IReturn<PagedResponse<BasketIndex>> { public createResponse() { return new PagedResponse<BasketIndex>(); } public getTypeName() { return 'ListBaskets'; } } /** * Basket */ // @Route("/basket", "POST") // @Api(Description="Basket") export class InitiateBasket extends DomainCommand implements IReturn<CommandResponse> { public basketId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'InitiateBasket'; } } /** * Basket */ // @Route("/basket/claim", "POST") // @Api(Description="Basket") export class ClaimBasket extends DomainCommand implements IReturn<CommandResponse> { public basketId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'ClaimBasket'; } } /** * Basket */ // @Route("/basket", "DELETE") // @Api(Description="Basket") export class BasketDestroy extends DomainCommand implements IReturn<CommandResponse> { public basketId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'BasketDestroy'; } } /** * Basket */ // @Route("/basket/item", "GET") // @Api(Description="Basket") export class GetBasketItems extends Paged<BasketItemIndex> implements IReturn<PagedResponse<BasketItemIndex>> { public basketId: string; public createResponse() { return new PagedResponse<BasketItemIndex>(); } public getTypeName() { return 'GetBasketItems'; } } /** * Basket */ // @Route("/basket/item", "POST") // @Api(Description="Basket") export class AddBasketItem extends DomainCommand implements IReturn<CommandResponse> { public basketId: string; public productId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'AddBasketItem'; } } /** * Basket */ // @Route("/basket/item/{ProductId}", "DELETE") // @Api(Description="Basket") export class RemoveBasketItem extends DomainCommand implements IReturn<CommandResponse> { public basketId: string; public productId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'RemoveBasketItem'; } } /** * Basket */ // @Route("/basket/item/{ProductId}/quantity", "POST") // @Api(Description="Basket") export class UpdateBasketItemQuantity extends DomainCommand implements IReturn<CommandResponse> { public basketId: string; public productId: string; public quantity: number; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'UpdateBasketItemQuantity'; } } /** * Catalog */ // @Route("/catalog/brand", "GET") // @Api(Description="Catalog") export class ListCatalogBrands extends Paged<CatalogBrand> implements IReturn<PagedResponse<CatalogBrand>> { public term: string; public limit: number; public id: string; public createResponse() { return new PagedResponse<CatalogBrand>(); } public getTypeName() { return 'ListCatalogBrands'; } } /** * Catalog */ // @Route("/catalog/brand", "POST") // @Api(Description="Catalog") export class AddCatalogBrand extends DomainCommand implements IReturn<CommandResponse> { public brandId: string; public brand: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'AddCatalogBrand'; } } /** * Catalog */ // @Route("/catalog/brand/{BrandId}", "DELETE") // @Api(Description="Catalog") export class RemoveCatalogBrand extends DomainCommand implements IReturn<CommandResponse> { public brandId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'RemoveCatalogBrand'; } } /** * Catalog */ // @Route("/catalog/type", "GET") // @Api(Description="Catalog") export class ListCatalogTypes extends Paged<CatalogType> implements IReturn<PagedResponse<CatalogType>> { public term: string; public limit: number; public id: string; public createResponse() { return new PagedResponse<CatalogType>(); } public getTypeName() { return 'ListCatalogTypes'; } } /** * Catalog */ // @Route("/catalog/type", "POST") // @Api(Description="Catalog") export class AddCatalogType extends DomainCommand implements IReturn<CommandResponse> { public typeId: string; public type: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'AddCatalogType'; } } /** * Catalog */ // @Route("/catalog/type/{TypeId}", "POST") // @Api(Description="Catalog") export class RemoveCatalogType extends DomainCommand implements IReturn<CommandResponse> { public typeId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'RemoveCatalogType'; } } /** * Catalog */ // @Route("/catalog/products/{ProductId}", "GET") // @Api(Description="Catalog") export class GetProduct extends Query<CatalogProduct> implements IReturn<QueryResponse<CatalogProduct>> { public productId: string; public createResponse() { return new QueryResponse<CatalogProduct>(); } public getTypeName() { return 'GetProduct'; } } /** * Catalog */ // @Route("/catalog/products", "GET") // @Api(Description="Catalog") export class ListProducts extends Paged<CatalogProductIndex> implements IReturn<PagedResponse<CatalogProductIndex>> { public createResponse() { return new PagedResponse<CatalogProductIndex>(); } public getTypeName() { return 'ListProducts'; } } /** * Catalog */ // @Route("/catalog", "GET") // @Api(Description="Catalog") export class Catalog extends Paged<CatalogProductIndex> implements IReturn<PagedResponse<CatalogProductIndex>> { public brandId: string; public typeId: string; public search: string; public createResponse() { return new PagedResponse<CatalogProductIndex>(); } public getTypeName() { return 'Catalog'; } } /** * Catalog */ // @Route("/catalog/products", "POST") // @Api(Description="Catalog") export class AddProduct extends DomainCommand implements IReturn<CommandResponse> { public productId: string; public name: string; public price: number; public catalogBrandId: string; public catalogTypeId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'AddProduct'; } } /** * Catalog */ // @Route("/catalog/products/{ProductId}", "DELETE") // @Api(Description="Catalog") export class RemoveProduct extends DomainCommand implements IReturn<CommandResponse> { public productId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'RemoveProduct'; } } /** * Catalog */ // @Route("/catalog/products/{ProductId}/picture", "POST") // @Api(Description="Catalog") export class SetPictureProduct extends DomainCommand implements IReturn<CommandResponse> { public productId: string; public content: string; public contentType: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'SetPictureProduct'; } } /** * Catalog */ // @Route("/catalog/products/{ProductId}/description", "POST") // @Api(Description="Catalog") export class UpdateDescriptionProduct extends DomainCommand implements IReturn<CommandResponse> { public productId: string; public description: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'UpdateDescriptionProduct'; } } /** * Catalog */ // @Route("/catalog/products/{ProductId}/mark", "POST") // @Api(Description="Catalog") export class MarkReordered extends DomainCommand implements IReturn<CommandResponse> { public productId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'MarkReordered'; } } /** * Catalog */ // @Route("/catalog/products/{ProductId}/unmark", "POST") // @Api(Description="Catalog") export class UnMarkReordered extends DomainCommand implements IReturn<CommandResponse> { public productId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'UnMarkReordered'; } } /** * Catalog */ // @Route("/catalog/products/{ProductId}/stock", "POST") // @Api(Description="Catalog") export class UpdateStock extends DomainCommand implements IReturn<CommandResponse> { public productId: string; public stock: number; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'UpdateStock'; } } /** * Catalog */ // @Route("/catalog/products/{ProductId}/price", "POST") // @Api(Description="Catalog") export class UpdatePriceProduct extends DomainCommand implements IReturn<CommandResponse> { public productId: string; public price: number; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'UpdatePriceProduct'; } } /** * Identity */ // @Route("/identity/user", "GET") // @Api(Description="Identity") export class GetIdentity extends Query<User> implements IReturn<QueryResponse<User>> { public createResponse() { return new QueryResponse<User>(); } public getTypeName() { return 'GetIdentity'; } } /** * Identity */ // @Route("/identity/users", "GET") // @Api(Description="Identity") export class GetUsers extends Paged<User> implements IReturn<PagedResponse<User>> { public createResponse() { return new PagedResponse<User>(); } public getTypeName() { return 'GetUsers'; } } /** * Identity */ // @Route("/identity/users", "POST") // @Api(Description="Identity") export class UserRegister extends DomainCommand implements IReturn<CommandResponse> { public givenName: string; public userName: string; public password: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'UserRegister'; } } /** * Identity */ // @Route("/identity/users/{UserName}/name", "POST") // @Api(Description="Identity") export class ChangeName extends DomainCommand implements IReturn<CommandResponse> { public userName: string; public givenName: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'ChangeName'; } } /** * Identity */ // @Route("/identity/users/{UserName}/password", "POST") // @Api(Description="Identity") export class ChangePassword extends DomainCommand implements IReturn<CommandResponse> { public userName: string; public password: string; public newPassword: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'ChangePassword'; } } /** * Identity */ // @Route("/identity/users/{UserName}/enable", "POST") // @Api(Description="Identity") export class UserEnable extends DomainCommand implements IReturn<CommandResponse> { public userName: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'UserEnable'; } } /** * Identity */ // @Route("/identity/users/{UserName}/disable", "POST") // @Api(Description="Identity") export class UserDisable extends DomainCommand implements IReturn<CommandResponse> { public userName: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'UserDisable'; } } /** * Identity */ // @Route("/identity/users/{UserName}/assign", "POST") // @Api(Description="Identity") export class AssignRole extends DomainCommand implements IReturn<CommandResponse> { public userName: string; public roleId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'AssignRole'; } } /** * Identity */ // @Route("/identity/users/{UserName}/revoke", "POST") // @Api(Description="Identity") export class RevokeRole extends DomainCommand implements IReturn<CommandResponse> { public userName: string; public roleId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'RevokeRole'; } } /** * Identity */ // @Route("/identity/roles/{RoleId}/activate", "POST") // @Api(Description="Identity") export class RoleActivate extends DomainCommand implements IReturn<CommandResponse> { public roleId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'RoleActivate'; } } /** * Identity */ // @Route("/identity/roles/{RoleId}/deactivate", "POST") // @Api(Description="Identity") export class RoleDeactivate extends DomainCommand implements IReturn<CommandResponse> { public roleId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'RoleDeactivate'; } } /** * Identity */ // @Route("/identity/roles", "POST") // @Api(Description="Identity") export class RoleDefine extends DomainCommand implements IReturn<CommandResponse> { public roleId: string; public name: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'RoleDefine'; } } /** * Identity */ // @Route("/identity/roles/{RoleId}", "DELETE") // @Api(Description="Identity") export class RoleDestroy extends DomainCommand implements IReturn<CommandResponse> { public roleId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'RoleDestroy'; } } /** * Identity */ // @Route("/identity/roles/{RoleId}/revoke", "POST") // @Api(Description="Identity") export class RoleRevoke extends DomainCommand implements IReturn<CommandResponse> { public roleId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'RoleRevoke'; } } /** * Location */ // @Route("/location", "GET") // @Api(Description="Location") export class ListLocations extends Paged<Location> implements IReturn<PagedResponse<Location>> { public createResponse() { return new PagedResponse<Location>(); } public getTypeName() { return 'ListLocations'; } } /** * Location */ // @Route("/location", "POST") // @Api(Description="Location") export class AddLocation extends DomainCommand implements IReturn<CommandResponse> { public locationId: string; public code: string; public description: string; public parentId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'AddLocation'; } } /** * Location */ // @Route("/location/{LocationId}", "DELETE") // @Api(Description="Location") export class RemoveLocation extends DomainCommand implements IReturn<CommandResponse> { public locationId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'RemoveLocation'; } } /** * Location */ // @Route("/location/{LocationId}/description", "POST") // @Api(Description="Location") export class UpdateDescriptionLocation extends DomainCommand implements IReturn<CommandResponse> { public locationId: string; public description: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'UpdateDescriptionLocation'; } } /** * Location */ // @Route("/location/{LocationId}/point", "POST") // @Api(Description="Location") export class AddPoint extends DomainCommand implements IReturn<CommandResponse> { public locationId: string; public pointId: string; public longitude: number; public latitude: number; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'AddPoint'; } } /** * Location */ // @Route("/location/{LocationId}/point/{PointId}", "DELETE") // @Api(Description="Location") export class RemovePoint extends DomainCommand implements IReturn<CommandResponse> { public locationId: string; public pointId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'RemovePoint'; } } export class GetCampaign extends Query<Campaign> implements IReturn<QueryResponse<Campaign>> { public campaignId: string; public createResponse() { return new QueryResponse<Campaign>(); } public getTypeName() { return 'GetCampaign'; } } export class ListCampaigns extends Paged<Campaign> implements IReturn<PagedResponse<Campaign>> { public createResponse() { return new PagedResponse<Campaign>(); } public getTypeName() { return 'ListCampaigns'; } } /** * Marketing */ // @Route("/campaign/{CampaignId}/description", "POST") // @Api(Description="Marketing") export class ChangeDescriptionCampaign extends DomainCommand implements IReturn<CommandResponse> { public campaignId: string; public description: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'ChangeDescriptionCampaign'; } } /** * Marketing */ // @Route("/campaign", "POST") // @Api(Description="Marketing") export class DefineCampaign extends DomainCommand implements IReturn<CommandResponse> { public campaignId: string; public name: string; public description: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'DefineCampaign'; } } /** * Marketing */ // @Route("/campaign/{CampaignId}/period", "POST") // @Api(Description="Marketing") export class SetPeriodCampaign extends DomainCommand implements IReturn<CommandResponse> { public campaignId: string; public start: string; public end: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'SetPeriodCampaign'; } } /** * Marketing */ // @Route("/campaign/{CampaignId}/picture", "POST") // @Api(Description="Marketing") export class SetPictureCampaign extends DomainCommand implements IReturn<CommandResponse> { public campaignId: string; public pictureUrl: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'SetPictureCampaign'; } } /** * Marketing */ // @Route("/campaign/{CampaignId}/rule", "POST") // @Api(Description="Marketing") export class AddCampaignRule extends DomainCommand implements IReturn<CommandResponse> { public campaignId: string; public ruleId: string; public description: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'AddCampaignRule'; } } /** * Marketing */ // @Route("/campaign/{CampaignId}/rule/{RuleId}", "DELETE") // @Api(Description="Marketing") export class RemoveCampaignRule extends DomainCommand implements IReturn<CommandResponse> { public campaignId: string; public ruleId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'RemoveCampaignRule'; } } /** * Ordering */ // @Route("/buyers", "GET") // @Api(Description="Ordering") export class Buyers extends Paged<OrderingBuyerIndex> implements IReturn<PagedResponse<OrderingBuyerIndex>> { public createResponse() { return new PagedResponse<OrderingBuyerIndex>(); } public getTypeName() { return 'Buyers'; } } /** * Ordering */ // @Route("/buyer", "GET") // @Api(Description="Ordering") export class Buyer extends Query<OrderingBuyer> implements IReturn<QueryResponse<OrderingBuyer>> { public userName: string; public createResponse() { return new QueryResponse<OrderingBuyer>(); } public getTypeName() { return 'Buyer'; } } /** * Ordering */ // @Route("/buyer", "POST") // @Api(Description="Ordering") export class InitiateBuyer extends DomainCommand implements IReturn<CommandResponse> { public createResponse() { return new CommandResponse(); } public getTypeName() { return 'InitiateBuyer'; } } /** * Ordering */ // @Route("/buyer/{UserName}/good", "POST") // @Api(Description="Ordering") export class MarkGoodStanding extends DomainCommand implements IReturn<CommandResponse> { public userName: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'MarkGoodStanding'; } } /** * Ordering */ // @Route("/buyer/{UserName}/suspend", "POST") // @Api(Description="Ordering") export class MarkSuspended extends DomainCommand implements IReturn<CommandResponse> { public userName: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'MarkSuspended'; } } /** * Ordering */ // @Route("/buyer/{UserName}/preferred_address", "POST") // @Api(Description="Ordering") export class SetPreferredAddress extends DomainCommand implements IReturn<CommandResponse> { public addressId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'SetPreferredAddress'; } } /** * Ordering */ // @Route("/buyer/{UserName}/preferred_payment", "POST") // @Api(Description="Ordering") export class SetPreferredPaymentMethod extends DomainCommand implements IReturn<CommandResponse> { public paymentMethodId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'SetPreferredPaymentMethod'; } } /** * Ordering */ // @Route("/buyer/address", "GET") // @Api(Description="Ordering") export class ListAddresses extends Paged<Address> implements IReturn<PagedResponse<Address>> { public term: string; public id: string; public createResponse() { return new PagedResponse<Address>(); } public getTypeName() { return 'ListAddresses'; } } /** * Ordering */ // @Route("/buyer/address", "POST") // @Api(Description="Ordering") export class AddBuyerAddress extends DomainCommand implements IReturn<CommandResponse> { public addressId: string; public alias: string; public street: string; public city: string; public state: string; public country: string; public zipCode: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'AddBuyerAddress'; } } /** * Ordering */ // @Route("/buyer/address/{AddressId}", "DELETE") // @Api(Description="Ordering") export class RemoveBuyerAddress extends DomainCommand implements IReturn<CommandResponse> { public addressId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'RemoveBuyerAddress'; } } /** * Ordering */ // @Route("/buyer/payment_method", "GET") // @Api(Description="Ordering") export class ListPaymentMethods extends Paged<PaymentMethod> implements IReturn<PagedResponse<PaymentMethod>> { public term: string; public id: string; public createResponse() { return new PagedResponse<PaymentMethod>(); } public getTypeName() { return 'ListPaymentMethods'; } } /** * Ordering */ // @Route("/buyer/payment_method", "POST") // @Api(Description="Ordering") export class AddBuyerPaymentMethod extends DomainCommand implements IReturn<CommandResponse> { public paymentMethodId: string; public alias: string; public cardNumber: string; public securityNumber: string; public cardholderName: string; public expiration: string; public cardType: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'AddBuyerPaymentMethod'; } } /** * Ordering */ // @Route("/buyer/payment_method/{PaymentMethodId}", "DELETE") // @Api(Description="Ordering") export class RemoveBuyerPaymentMethod extends DomainCommand implements IReturn<CommandResponse> { public paymentMethodId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'RemoveBuyerPaymentMethod'; } } /** * Ordering */ // @Route("/order/{OrderId}", "GET") // @Api(Description="Ordering") export class GetOrder extends Query<OrderingOrder> implements IReturn<QueryResponse<OrderingOrder>> { public orderId: string; public createResponse() { return new QueryResponse<OrderingOrder>(); } public getTypeName() { return 'GetOrder'; } } /** * Ordering */ // @Route("/order", "GET") // @Api(Description="Ordering") export class BuyerOrders extends Paged<OrderingOrderIndex> implements IReturn<PagedResponse<OrderingOrderIndex>> { public orderStatus: string; public from: string; public to: string; public createResponse() { return new PagedResponse<OrderingOrderIndex>(); } public getTypeName() { return 'BuyerOrders'; } } /** * Ordering */ // @Route("/orders", "GET") // @Api(Description="Ordering") export class ListOrders extends Paged<OrderingOrderIndex> implements IReturn<PagedResponse<OrderingOrderIndex>> { public orderStatus: string; public from: string; public to: string; public createResponse() { return new PagedResponse<OrderingOrderIndex>(); } public getTypeName() { return 'ListOrders'; } } /** * Ordering */ // @Route("/orders/sales_week_over_week", "GET") // @Api(Description="Ordering") export class OrderingSalesWeekOverWeek extends Paged<SalesWeekOverWeek> implements IReturn<PagedResponse<SalesWeekOverWeek>> { public from: string; public to: string; public createResponse() { return new PagedResponse<SalesWeekOverWeek>(); } public getTypeName() { return 'OrderingSalesWeekOverWeek'; } } /** * Ordering */ // @Route("/orders/sales_by_state", "GET") // @Api(Description="Ordering") export class OrderingSalesByState extends Paged<SalesByState> implements IReturn<PagedResponse<SalesByState>> { public from: string; public to: string; public createResponse() { return new PagedResponse<SalesByState>(); } public getTypeName() { return 'OrderingSalesByState'; } } /** * Ordering */ // @Route("/orders/sales", "GET") // @Api(Description="Ordering") export class OrderingSalesChart extends Paged<SalesChart> implements IReturn<PagedResponse<SalesChart>> { public from: string; public to: string; public createResponse() { return new PagedResponse<SalesChart>(); } public getTypeName() { return 'OrderingSalesChart'; } } /** * Ordering */ // @Route("/order/{OrderId}/cancel", "POST") // @Api(Description="Ordering") export class CancelOrder extends DomainCommand implements IReturn<CommandResponse> { public orderId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'CancelOrder'; } } /** * Ordering */ // @Route("/order/{OrderId}/confirm", "POST") // @Api(Description="Ordering") export class ConfirmOrder extends DomainCommand implements IReturn<CommandResponse> { public orderId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'ConfirmOrder'; } } /** * Ordering */ // @Route("/order", "POST") // @Api(Description="Ordering") export class DraftOrder extends DomainCommand implements IReturn<CommandResponse> { public orderId: string; public basketId: string; public billingAddressId: string; public shippingAddressId: string; public paymentMethodId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'DraftOrder'; } } /** * Ordering */ // @Route("/order/{OrderId}/pay", "POST") // @Api(Description="Ordering") export class PayOrder extends DomainCommand implements IReturn<CommandResponse> { public orderId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'PayOrder'; } } /** * Ordering */ // @Route("/order/{OrderId}/ship", "POST") // @Api(Description="Ordering") export class ShipOrder extends DomainCommand implements IReturn<CommandResponse> { public orderId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'ShipOrder'; } } /** * Ordering */ // @Route("/order/{OrderId}/address", "POST") // @Api(Description="Ordering") export class ChangeAddressOrder extends DomainCommand implements IReturn<CommandResponse> { public orderId: string; public shippingId: string; public billingId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'ChangeAddressOrder'; } } /** * Ordering */ // @Route("/order/{OrderId}/payment_method", "POST") // @Api(Description="Ordering") export class ChangePaymentMethodOrder extends DomainCommand implements IReturn<CommandResponse> { public orderId: string; public paymentMethodId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'ChangePaymentMethodOrder'; } } /** * Ordering */ // @Route("/order/{OrderId}/item", "GET") // @Api(Description="Ordering") export class ListOrderItems extends Paged<OrderingOrderItem> implements IReturn<PagedResponse<OrderingOrderItem>> { public orderId: string; public createResponse() { return new PagedResponse<OrderingOrderItem>(); } public getTypeName() { return 'ListOrderItems'; } } /** * Ordering */ // @Route("/order/{OrderId}/item", "POST") // @Api(Description="Ordering") export class AddOrderItem extends DomainCommand implements IReturn<CommandResponse> { public productId: string; public orderId: string; public quantity: number; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'AddOrderItem'; } } /** * Ordering */ // @Route("/order/{OrderId}/item/{ProductId}/price", "POST") // @Api(Description="Ordering") export class OverridePriceOrderItem extends DomainCommand implements IReturn<CommandResponse> { public productId: string; public orderId: string; public price: number; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'OverridePriceOrderItem'; } } /** * Ordering */ // @Route("/order/{OrderId}/item/{ProductId}", "DELETE") // @Api(Description="Ordering") export class RemoveOrderItem extends DomainCommand implements IReturn<CommandResponse> { public productId: string; public orderId: string; public createResponse() { return new CommandResponse(); } public getTypeName() { return 'RemoveOrderItem'; } } /** * Configuration */ // @Route("/configuration/status", "GET") // @Api(Description="Configuration") export class GetStatus extends Query<ConfigurationStatus> implements IReturn<QueryResponse<ConfigurationStatus>> { public createResponse() { return new QueryResponse<ConfigurationStatus>(); } public getTypeName() { return 'GetStatus'; } } /** * Configuration */ // @Route("/configuration/setup/seed", "POST") // @Api(Description="Configuration") export class Seed extends DomainCommand implements IReturn<CommandResponse> { public createResponse() { return new CommandResponse(); } public getTypeName() { return 'Seed'; } } }
the_stack
import { isPlatform } from '@ionic/vue'; import { HTTP } from '@ionic-native/http'; import * as _ from 'lodash'; declare const Buffer: any declare global { interface Window { net: any; } } type Method = "get" | "post" | "put" | "patch" | "head" | "delete" | "options" | "upload" | "download"; type Serializer = "json" | "urlencoded" | "utf8" | "multipart" | "raw" | undefined; let freeSpaceRefreshInterval: any; let sessionStatsRefreshInterval: any; let trackerId=0; class TRPC { sessionToken: any; sessionArguments: any; options: any; lastRequestId: number; useNativePlugin: boolean; persistentData: any; persistentDataValid=false; sessionStats: any; statsHistory: Array<Array<number|null>>=[]; pathMapping: Record<string,string>; constructor() { this.useNativePlugin = (isPlatform("capacitor") && (isPlatform("android") || isPlatform("ios"))) this.lastRequestId = 0; this.pathMapping = {}; } async setServer(options: Record<string, any> = {}, timeout=5): Promise<Record<string, any>> { this.sessionToken=null; this.options = { host:'localhost', path:'/transmission/rpc', port:9091, https:false, timeout:timeout }; for (const [key, value] of Object.entries(options)) { if(value!=""){ this.options[key]=value; } } if(this.options.pathMapping){ this.pathMapping = this.readPathMapping(this.options.pathMapping) } this.setAuthHeader(); this.invalidatePersitentData(); this.sessionArguments = await this.getSession(); this.setFreeSpaceRefreshInterval(); this.setSessionStatsRefreshInterval(); return this.sessionArguments; } readPathMapping(pathMapping: string): Record<string,string> { const result: Record<string,string> = {}; pathMapping.split(/\r?\n/).forEach((pathMap: string) => { const paths = pathMap.match(/^(.+) ?= ?(.+)$/)||[]; for(const key in paths){ if(paths[key]){ if(paths[key].startsWith(' ')){ paths[key]=paths[key].substr(1); } if(paths[key].endsWith(' ')){ paths[key]=paths[key].slice(0, -1); } } } if(paths.length>=3){ result[paths[1]]=paths[2]; } }); return result; } setAuthHeader(): void { if(this.useNativePlugin){ HTTP.setRequestTimeout(this.options.timeout); if(this.options.auth){ HTTP.useBasicAuth(this.options.auth.username,this.options.auth.password); } else { // Reset auth header from previous connection HTTP.useBasicAuth("",""); } } } setFreeSpaceRefreshInterval(): void { clearInterval(freeSpaceRefreshInterval); freeSpaceRefreshInterval = setInterval(async () => { const response = await this.rpcCall("free-space",{path:this.sessionArguments["download-dir"]}) if(response.result=="success"){ this.sessionArguments["download-dir-free-space"]=response.arguments["size-bytes"]; } },60000); } async setSessionStatsRefreshInterval(): Promise<void> { this.statsHistory=[]; clearInterval(sessionStatsRefreshInterval); sessionStatsRefreshInterval = setInterval(() => this.getSessionStats(),10000); await this.getSessionStats(); } async getSession(): Promise<Record<string, any>> { const response = await this.rpcCall("session-get") if(response.arguments){ return response.arguments; } else { return {} } } getSessionArgument(arg: string): Promise<any> { return new Promise( (resolutionFunc,rejectionFunc) => { let count=0; const interval = setInterval(() => { if(this.sessionArguments && typeof this.sessionArguments[arg]!="undefined"){ resolutionFunc(this.sessionArguments[arg]); } else if(count>=100){ clearInterval(interval); rejectionFunc(); } count++; },50); }); } getSessionStats() { return this.rpcCall("session-stats") .then((response) => { this.sessionStats = response.arguments; this.addStatsHistory(this.sessionStats.downloadSpeed,this.sessionStats.uploadSpeed) }) .catch(() => { this.addStatsHistory(null,null); }) } addStatsHistory(downloadSpeed: number|null,uploadSpeed: number|null) { this.statsHistory.push([downloadSpeed,uploadSpeed]); this.statsHistory=this.statsHistory.slice(-30); } setSession(args: Record<string, any>): Promise<Record<string, any>> { return new Promise((resolutionFunc,rejectionFunc) => { this.rpcCall("session-set", args) .then((response) => { for (const key in args) { this.sessionArguments[key]=args[key]; } resolutionFunc(response); }) .catch(() => rejectionFunc()) }); } async getToken(): Promise<string> { let token=""; if(this.sessionToken){ token = this.sessionToken } else { const rep = await this.request("") if(rep.errorMessage){ throw Error(rep.errorMessage); } else if(rep.status==401) { throw Error("Authentication error"); } token = this.readToken(rep); if(token!="") { this.sessionToken=token; } else { throw Error("Unable to reach Transmission Daemon"); } } return token; } readToken(rep: Record<string,any>): string{ let token=""; if(rep.headers && typeof rep.headers['x-transmission-session-id'] !== "undefined"){ token = rep.headers['x-transmission-session-id']; } else if(rep.headers && rep.headers.get && rep.headers.get('x-transmission-session-id')!=null){ token = rep.headers.get('x-transmission-session-id'); } return token; } async getTorrents() { let result: Array<any>=[]; let loadPersistent=false; const args = { fields: [ 'id', 'name', 'percentDone', 'uploadRatio', 'rateDownload', 'rateUpload', 'downloadedEver', 'uploadedEver', 'totalSize', 'addedDate', 'status', 'errorString', 'activityDate', 'sizeWhenDone', 'eta', 'recheckProgress', 'queuePosition' ] } if(!this.persistentDataValid){ loadPersistent=true; args.fields.push('trackers','downloadDir'); } const response = await this.rpcCall("torrent-get", args, true, true); if(response.arguments){ result=response.arguments.torrents if(loadPersistent){ this.readPersitentData(result); } } return result } readPersitentData(details: Array<any>) { let trackers: Array<Record<string,any>> = []; const downloadDirList: Array<string> = []; trackerId=0; for (const torrent of details) { const dir = this.readDownloadDir(torrent.downloadDir) if(!downloadDirList.includes(dir)){ downloadDirList.push(dir) } trackers = this.readTrackers(trackers, torrent.trackers, torrent.id); } downloadDirList.sort(); this.persistentData = { trackers: Object.values(trackers), downloadDir: downloadDirList } this.persistentDataValid = true; } readDownloadDir(downloadDir: string): string { let result = downloadDir //eslint-disable-next-line if(result.match(/[\/\\]$/)){ // Remove last / or \ result = result.substring(0,result.length-1); } return result; } readTrackers(trackers: Array<any>, newTrackers: Array<any>, torrentId: number): Array<any>{ const result: Array<any> = trackers; for(const tracker of newTrackers){ //eslint-disable-next-line const matchs = tracker.announce.match(/^[\w]+:\/\/[\w\d\.-]+/); if(matchs){ const tr = matchs[0]; const data = { id:trackerId, announce:tr, ids:[] } if(!result[data.announce]){ result[data.announce] = data; trackerId++; } if(!result[data.announce].ids.includes(torrentId)){ result[data.announce].ids.push(torrentId) } } } return result; } invalidatePersitentData() { this.persistentDataValid = false; } async getTorrentDetails(id: number) { let result: any={}; const args = { ids:id, fields: [ 'id', 'name', 'percentDone', 'uploadRatio', 'rateDownload', 'rateUpload', 'downloadedEver', 'uploadedEver', 'totalSize', 'addedDate', 'status', 'errorString', 'activityDate', 'sizeWhenDone', 'leftUntilDone', 'downloadDir', 'comment', 'creator', 'dateCreated', 'magnetLink', 'hashString', 'secondsDownloading', 'secondsSeeding', 'pieceCount', 'pieceSize', 'files', 'fileStats', 'doneDate', 'downloadLimit', 'downloadLimited', 'uploadLimit', 'uploadLimited', 'peer-limit', 'seedRatioLimit', 'seedRatioMode', 'seedIdleLimit', 'seedIdleMode', 'bandwidthPriority', 'trackers', 'trackerStats', 'peers', 'recheckProgress' ] } const response = await this.rpcCall("torrent-get", args) if(response.arguments && response.arguments.torrents.length > 0){ result=response.arguments.torrents[0] } else { throw Error("Torrent not found"); } return result; } async torrentAction(action: string, torrentIds: Array<number>, args: Record<string, any> = {}){ if(action=="remove"){ this.invalidatePersitentData(); } return this.rpcCall("torrent-"+action, Object.assign({ids:torrentIds}, args)) } async torrentAdd(args: Record<string, any> = {}){ this.invalidatePersitentData(); return this.rpcCall("torrent-add", args); } async rpcCall(method: string, args: Record<string, any> = {}, retry=true, ignoreError=false) { const argsClone = _.cloneDeep(args); let ret: Record<string, any>={}; const token = await this.getToken() const response = await this.request(method,token,argsClone,ignoreError); if(response.errorMessage){ throw Error(response.errorMessage); } if(response.status){ if(response.status===200){ ret = response.data; } else if(response.status===409){ // Invalid token this.sessionToken=this.readToken(response); if(retry){ // Try with the new token ret = this.rpcCall(method,args,false); } else { throw Error("Invalid token"); } } else { throw Error("HTTP "+response.status); } } if(ret.result && ret.result!="success"){ throw Error(ret.result); } return ret; } async request(action: string, token?: string, args: Record<string, any> = {}, ignoreError=false) { let ret: Record<string, any>={}; const requestId = ++this.lastRequestId; const headers = this.getHeaders(); const requestUrl = this.getRequestUrl(); if(token){ headers["X-Transmission-Session-Id"]=token; } const datas = { method:action, arguments:args, tag:requestId } const options = { method: "post" as Method, headers:headers, serializer:"json" as Serializer, timeout:parseInt(this.options.timeout), data:{}, body:null as string|null } if(this.useNativePlugin){ ret = await this.nativePluginRequest(requestUrl,options,datas); } else if(window.net){ ret = await this.electronRequest(options,datas); } else { ret = await this.browserRequest(requestUrl,options,datas); } // Don't return result if tags doesn't match or server has been changed if((ret.data && ret.data.tag!=requestId) || (ret.url && ret.url!=this.getRequestUrl())){ throw Error(); } // Don't report error if there's a more recent request if(ret.errorMessage && ignoreError && requestId<this.lastRequestId){ throw Error(); } return ret; } async nativePluginRequest(requestUrl: string, options: any, datas: Record<string, any>) { // HTTP request using @ionic-native/http (allow CORS) let result: Record<string, any>={}; options.data = datas await this.timeout(this.options.timeout*1000, HTTP.sendRequest(requestUrl,options)) .then((response) => { result=response as Record<string, any>; }) .catch((error) => { if(error.status){ result=error as Record<string, any>; } else { result.errorMessage=error; } }); if(result.data){ result.data = JSON.parse(result.data) } return result; } async electronRequest(options: any, datas: Record<string, any>) { // HTTP request using Electron net (allow CORS) let result: Record<string, any>={}; Object.assign(options,{ hostname:this.options.host, port:this.options.port, path:this.options.path, protocol:this.options.https ? "https:" : "http:" }) await this.timeout(this.options.timeout*1000, window.net.request(options, datas)) .then((response: any) => { result=response; }) .catch((error) => { if(error.status){ result=error; } else if(error){ result.errorMessage=error; } }); return result; } async browserRequest(requestUrl: string, options: any, datas: Record<string, any>) { // HTTP request using fetch (no CORS) let result: Record<string, any>={}; options.body = JSON.stringify(datas); await this.timeout(this.options.timeout*1000, fetch(requestUrl,options)) .then((response) => { result=response as Record<string, any>; }) .catch((error) => { result.errorMessage=(error=="TypeError: Failed to fetch") ? "Unable to reach host" : error; }); if(result.json && result.ok){ result.data = await result.json(); } return result; } getRequestUrl(): string { let result = this.options.https ? "https":"http"; result += "://"+this.options.host+":"+this.options.port+this.options.path; return result; } getHeaders(headers: any = {}) { if(this.options.auth){ const auth = "Basic "+Buffer.from(this.options.auth.username+':'+this.options.auth.password).toString('base64'); headers["Authorization"]=auth; } headers["Content-Type"]="application/json"; return headers; } timeout(ms: number, promise: Promise<any>) { return new Promise(function(resolve, reject) { setTimeout(function() { reject("Unable to reach host (Timeout)") }, ms) promise.then(resolve, reject) }) } } export const TransmissionRPC = new TRPC();
the_stack
/// <reference types="node" /> import { EventEmitter } from 'events'; declare namespace bearcat { type CallbackFunc = () => void; type ParamClassFunc = () => void; type ConstructorFunction = (...params: any[]) => any; interface BeanPostProcessor { postProcessBeanFactory: CallbackFunc; } interface Bearcat { opts: object; configLocations: string[]; state: number; startTime: number; version: string; applicationContext: ApplicationContext; /** * Bearcat createApp constructor function. * * @param configLocations context path array * @param opts * @param opts.NODE_ENV setup env * @param opts.BEARCAT_ENV setup env * @param opts.NODE_CPATH setup config path * @param opts.BEARCAT_CPATH setup config path * @param opts.BEARCAT_HPATH setup hot reload path(s), usually it is the scan source directory(app by default) * @param opts.BEARCAT_LOGGER setup 'off' to turn off bearcat logger configuration * @param opts.BEARCAT_HOT setup 'on' to turn on bearcat hot code reload * @param opts.BEARCAT_ANNOTATION setup 'off' to turn off bearcat $ based annotation * @param opts.BEARCAT_GLOBAL setup bearcat to be global object * @param opts.BEARCAT_FUNCTION_STRING setup bearcat to use func.toString for $ based annotation * * @return bearcat object * @api public */ createApp(configLocations: string[], opts: object): Bearcat; createApp(opts: object): Bearcat; /** * Bearcat start app. * * @param cb start callback function * @api public */ start(cb?: CallbackFunc): void; /** * Bearcat stop app. * it will stop internal applicationContext, destroy all singletonBeans * * @api public */ stop(): void; /** * Bearcat get beanFactory instance. * * @return beanFactory instance * @api public */ getBeanFactory(): BeanFactory; /** * Bearcat get applicationContext. * * @return applicationContext * @api public */ getApplicationContext(): ApplicationContext; /** * Bearcat get bean from IoC container through meta argument. * * @param meta meta object * @api public */ getBeanByMeta(meta: object): object | null; /** * Bearcat get bean from IoC container through $ annotation function. * * @param func $ annotation function * @api public */ getBeanByFunc(func: ParamClassFunc): object | null; /** * Bearcat add async loading beans, this just add beans needed to be loaded to bearcat. * * Examples: * * bearcat.use(['car']); * bearcat.use('car'); * * @param ids async loading beans id * @api public */ use(ids: string | string[]): void; /** * Bearcat async loading beans. * * @param ids async loading beans id * @param cb callback with loaded bean instances * @api public */ async(ids: string | string[], cb?: CallbackFunc): void; /** * Bearcat add module(bean) to IoC container through $ annotation function. * * @param func $ annotation function * @param context context object * @api public */ module(func: ParamClassFunc, context?: object | null): object | void; /** * Bearcat define module(bean). * * @param id * @param factory function * @param context object * @api public */ define(id: string, factory: ParamClassFunc, context: object | null): void; /** * Bearcat add module(bean) to IoC container through $ annotation function. * * Examples: * * var Car = bearcat.require('car'); * * @param id * @api public */ require(id: string): any; /** * Bearcat get bean from IoC container through beanName or meta argument. * * @param beanName * @return bean * @api public */ getBean(beanName: string | object | ParamClassFunc): object | null; /** * Bearcat get bean constructor function from IoC container through beanName. * * Examples: * * * // through beanName * var Car = bearcat.getFunction("car"); * * * @param beanName * @return bean constructor function * @api public */ getFunction(beanName: string): ConstructorFunction | null; /** * Bearcat get bean constructor function from IoC container through beanName, the same as bearcat.getFunction. * * Examples: * * * // through beanName * var Car = bearcat.getClass("car"); * * * @param beanName * @return bean constructor function * @api public */ getClass(beanName: string): ConstructorFunction | null; /** * Bearcat shim to enable function inherits. * * Examples: * * * bearcat.extend("bus", "car"); * * * @param beanName * @param superBeanName or superBeanName array * @api public */ extend(beanName: string, superBeanName: string | string[]): void; /** * Bearcat call function used for inherits to call super constructor function. * * Examples: * * * bearcat.call("car", this); * * * @param beanName * @param context * @param args * @api public */ call(beanName: string, context?: object | null, ...args: any[]): void; /** * Bearcat get model from bearcat through modelId. * * Examples: * * * // through modelId * var carModel = bearcat.getModel("car"); * * * @param modelId * @return model * @api public */ getModel(modelId: string): object; /** * Bearcat convenient function for using in MVC route mapping. * * Examples: * * * // express * var app = express(); * app.get('/', bearcat.getRoute('bearController', 'index')); * * * @param beanName * @param fnName routeName * @api public */ getRoute(beanName: string, fnName: string): ConstructorFunction; } interface ApplicationContext extends EventEmitter { opts: object; configLocations: string[]; loadBeans: string[]; active: boolean; reloadMap: object; beanFactory: BeanFactory; startUpDate: number; extendBeanMap: object; extendedBeanMap: object; extendBeanCurMap: object; moduleFactory: ModuleFactory; resourceLoader: ResourceLoader; bootStrapLoader: BootStrapLoader; asyncScriptLoader: AsyncScriptLoader; cpath: string; hpath: string; env: string; base: string; beanFactoryPostProcessors: BeanPostProcessor[]; /** * ApplicationContext init. * * @api public */ init(): void; /** * ApplicationContext set container startUpDate. * * @param startUpDate * @api public */ setStartupDate(startUpDate: number): void; /** * ApplicationContext get container startUpDate. * * @return startUpDate * @api public */ getStartupDate(): number; /** * ApplicationContext get resourceLoader. * * @return resourceLoader * @api public */ getResourceLoader(): ResourceLoader; /** * ApplicationContext get asyncScriptLoader. * * @return asyncScriptLoader * @api public */ getAsyncScriptLoader(): AsyncScriptLoader; /** * ApplicationContext get bootStrapLoader. * * @return bootStrapLoader * @api public */ getBootStrapLoader(): BootStrapLoader; /** * ApplicationContext get metaObjects resource from contextPath. * * @param cpath contextPath * @return metaObjects * @api public */ getResource(cpath: string): object; /** * ApplicationContext get contextPath locations. * * @return contextPath locations * @api public */ getConfigLocations(): string[]; /** * ApplicationContext add beanFactoryPostProcessor. * * @param beanFactoryPostProcessor * @api public */ addBeanFactoryPostProcessor(beanFactoryPostProcessor: BeanPostProcessor): void; /** * ApplicationContext get beanFactoryPostProcessors. * * @return beanFactoryPostProcessors * @api public */ getBeanFactoryProcessors(): BeanPostProcessor[]; /** * ApplicationContext do refresh actions. * refresh beanFactory, preIntialize singleton Beans * * @param cb callback function * @api public */ refresh(cb?: CallbackFunc): void; /** * ApplicationContext cancel refresh. * * @api publish */ cancelRefresh(): void; /** * ApplicationContext destroy. * * @api public */ destroy(): void; /** * ApplicationContext check whether applicationContext is active or not. * * @api public */ isActive(): boolean; /** * ApplicationContext getBean through beanName from applicationContext. * * @param beanName * @return beanObject * @api public */ getBean(beanName: string): object; /** * ApplicationContext getBean through metaObject from applicationContext. * * @param meta metaObject * @return beanObject * @api public */ getBeanByMeta(meta: object): object; /** * ApplicationContext getBean through $ annotation function from applicationContext. * * @param func $ annotation function * @return beanObject * @api public */ getBeanByFunc(func: ConstructorFunction): object; /** * ApplicationContext getModel through modelId. * * @param modelId * @return model * @api public */ getModel(modelId: string): object; /** * ApplicationContext getModelDefinition through modelId. * * @param modelId * @return modelDefinition * @api public */ getModelDefinition(modelId: string): object; /** * ApplicationContext get bean contructor function. * * @param beanName * @return bean constructor function * @api public */ getBeanFunction(beanName: string): ConstructorFunction; /** * ApplicationContext extend bean. * * @param beanName * @param superBeanName or superBeanName array * @api public */ extendBean(beanName: string, superBeanName: string | string[]): void; /** * ApplicationContext do extend bean. * * @param beanName * @param superBeanName * @api public */ doExtendBean(beanName: string, superBeanName: string): void; /** * ApplicationContext add module(bean) to IoC container through $ annotation function from applicationContext. * * @param func $ annotation function * @param context * @api public */ module(func: ConstructorFunction, context?: object | null): void; /** * ApplicationContext service locator pattern define module. * * @param id * @param factory factory function * @param context context object * @api public */ define(id: string, factory: ConstructorFunction, context?: object | null): void; /** * ApplicationContext service locator pattern define module. * * @param id * @api public */ require(id: string): any; /** * ApplicationContext add startup loaded bean ids. * * @param ids loaded bean ids * @api public */ use(ids: string[]): void; /** * ApplicationContext async load bean with bean ids. * * @param ids bean ids * @param cb callback function * @api public */ async(ids: string[], cb?: CallbackFunc): void; /** * ApplicationContext check ApplicationContext contains bean or not. * * @param beanName * @return a boolean value that contains bean or not * @api public */ containsBean(beanName: string): boolean; /** * ApplicationContext check bean is a singleton or not. * * @param beanName * @return a boolean value that is a singleton or not * @api public */ isSingleton(beanName: string): boolean; /** * ApplicationContext check bean is a prototype or not. * * @param beanName * @return a boolean value that is a prototype or not * @api public */ isPrototype(beanName: string): boolean; /** * ApplicationContext check ApplicationContext contains beanName beanDefinition or not. * * @param beanName * @return a boolean value that contains beanName beanDefinition or not * @api public */ containsBeanDefinition(beanName: string): boolean; /** * ApplicationContext check whether applicationContext is running or not. * * @return true|false * @api public */ isRunning(): boolean; /** * ApplicationContext close beanFactory. * * @api public */ closeBeanFactory(): void; /** * ApplicationContext check whether applicationContext has beanFactory or not. * * @return true|false * @api public */ hasBeanFactory(): boolean; /** * ApplicationContext getBeanFactory. * * @return beanFactory * @api public */ getBeanFactory(): BeanFactory; /** * ApplicationContext getModuleFactory. * * @return moduleFactory * @api public */ getModuleFactory(): ModuleFactory; /** * ApplicationContext get beanDefinition. * * @param beanName * @return beanDefinition * @api public */ getBeanDefinition(beanName: string): object; /** * ApplicationContext remove beanDefinition from ApplicationContext. * * @param beanName * @api public */ removeBeanDefinition(beanName: string): void; /** * ApplicationContext set env. * * @param env * @api public */ setEnv(env: string): void; /** * ApplicationContext get env. * * @return env * @api public */ getEnv(): string; /** * ApplicationContext set config path. * * @param cpath config path * @api public */ setConfigPath(cpath: string): void; /** * ApplicationContext get config path. * * @return config path * @api public */ getConfigPath(): string; /** * ApplicationContext set hot reload path. * * @param hpath hot reload path * @api public */ setHotPath(hpath: string): void; /** * ApplicationContext get hot reload path. * * @return hpath hot reload path * @api public */ getHotPath(): string; /** * ApplicationContext get base path. * * @return base path * @api public */ getBase(): string; } interface BeanFactory { aspects: object[]; modelMap: object; initCbMap: object; beanCurMap: object; constraints: object; tableModelMap: object; beanFunctions: object; beanDefinitions: object; beanPostProcessors: BeanPostProcessor[]; singletonBeanFactory: SingletonBeanFactory; /** * BeanFactory get bean instance through BeanFactory IoC container. * * @param beanName * @return bean object * @api public */ getBean(beanName: string): object; /** * BeanFactory get bean proxy through BeanFactory IoC container for lazy init bean. * when invoke bean proxy, proxy will invoke getBean to get the target bean * * @param beanName * @return bean proxy object * @api public */ getBeanProxy(beanName: string): object; /** * BeanFactory get model through BeanFactory IoC container. * * @param modelId * @return model proxy object * @api public */ getModelProxy(modelId: string): object; /** * BeanFactory get constraint through BeanFactory IoC container. * * @param cid * @return constraint bean object * @api public */ getConstraint(cid: string): object; /** * BeanFactory set parent bean. * * @param beanName * @return beanDefinition * @api public */ setParentBean(beanName: string): object; /** * BeanFactory register beans through metaObjects into BeanFactory. * * @param metaObjects * @api public */ registerBeans(metaObjects: object): void; /** * BeanFactory register bean through metaObject into BeanFactory. * * @param beanName * @param metaObject * @api public */ registerBean(beanName: string, metaObject: object): void; /** * BeanFactory register model through metaObject into BeanFactory. * * @param beanName bean id * @param modelId model id * @param metaObject * @api public */ registerModel(beanName: string, modelId: string, metaObject: object): void; /** * BeanFactory register constraint through metaObject into BeanFactory. * * @param beanName bean id * @param cid constraint id * @param metaObject * @api public */ registerConstraint(beanName: string, cid: string, metaObject: object): void; /** * BeanFactory instantiating singletion beans in advance. * * @param cb callback function * @api public */ preInstantiateSingletons(cb?: CallbackFunc): void; /** * BeanFactory add beanPostProcessor to BeanFactory. * @param beanPostProcessor * @api public */ addBeanPostProcessor(beanPostProcessor: BeanPostProcessor): void; /** * BeanFactory get beanPostProcessors. * @return beanPostProcessors * @api public */ getBeanPostProcessors(): BeanPostProcessor[]; /** * BeanFactory destroy singletons. * * @api public */ destroySingletons(): void; /** * BeanFactory destroy BeanFactory. * * @api public */ destroyBeanFactory(): void; /** * BeanFactory destroy singleton. * * @param beanName * @api public */ destroySingleton(beanName: string): void; /** * BeanFactory destroy bean. * * @param beanName * @param beanObject * @api public */ destroyBean(beanName: string, beanObject: object): void; /** * BeanFactory check bean is a singleton or not. * * @param beanName * @return true | false * @api public */ isSingleton(beanName: string): boolean; /** * BeanFactory check bean is a prototype or not. * * @param beanName * @return true | false * @api public */ isPrototype(beanName: string): boolean; /** * BeanFactory check BeanFactory contains bean or not. * * @param beanName * @return true | false * @api public */ containsBean(beanName: string): boolean; /** * BeanFactory get bean contructor function. * * @param beanName * @return bean constructor function * @api public */ getBeanFunction(beanName: string): ConstructorFunction; /** * BeanFactory set bean contructor function. * * @param beanName * @param func bean constructor function * @api public */ setBeanFunction(beanName: string, func: ConstructorFunction): void; /** * BeanFactory remove bean contructor function from BeanFactory. * * @param beanName * @api public */ removeFunction(beanName: string): void; /** * BeanFactory get init method. * * @param beanName * @return bean init method * @api public */ getInitCb(beanName: string): CallbackFunc; /** * BeanFactory set init method. * * @param beanName * @param initCb bean init method * @api public */ setInitCb(beanName: string, initCb: CallbackFunc): void; /** * BeanFactory get beanDefinition. * * @param beanName * @return beanDefinition * @api public */ getBeanDefinition(beanName: string): object; /** * BeanFactory get beanDefinitions. * * @return beanDefinitions * @api public */ getBeanDefinitions(): object; /** * BeanFactory remove beanDefinition from BeanFactory. * * @param beanName * @api public */ removeBeanDefinition(beanName: string): void; /** * BeanFactory check BeanFactory contains beanName beanDefinition or not. * * @param beanName * @return true | false * @api public */ containsBeanDefinition(beanName: string): boolean; /** * BeanFactory get aspects. * * @return aspects * @api public */ getAspects(): object[]; /** * BeanFactory get modelDefinition. * * @param modelId * @return modelDefinition * @api public */ getModelDefinition(modelId: string): object; /** * BeanFactory get modelDefinitions. * * @return modelDefinition map * @api public */ getModelDefinitions(): object; /** * BeanFactory get getConstraintDefinition. * * @param cid * @return getConstraintDefinition * @api public */ getConstraintDefinition(cid: string): object; /** * BeanFactory set table model map. * * @param table name * @param modelDefinition * @api public */ setTableModelMap(table: string, modelDefinition: object): void; /** * BeanFactory get modelDefinition by table. * * @param table name * @return modelDefinition * @api public */ getModelDefinitionByTable(table: string): object; } interface SingletonBeanFactory { beanFactory: BeanFactory; singletonObjects: object; /** * SingletonBeanFactory add singleton to SingletonBeanFactory. * * @param beanName * @param beanObject * @api public */ addSingleton(beanName: string, beanObject: object): void; /** * SingletonBeanFactory check SingletonBeanFactory contains singleton or not. * * @param beanName * @return true | false * @api public */ containsSingleton(beanName: string): boolean; /** * SingletonBeanFactory get singleton from SingletonBeanFactory. * * @param beanName * @return singletonObject * @api public */ getSingleton(beanName: string): object; /** * SingletonBeanFactory get all singleton names from SingletonBeanFactory. * * @api public */ getSingletonNames(): string[]; /** * SingletonBeanFactory remove singleton from SingletonBeanFactory. * * @param beanName * @api public */ removeSingleton(beanName: string): void; } interface ModuleFactory { factoryMap: object; moduleMap: object; define(id: string, factory: object): void; require(id: string): any; } interface ResourceLoader { loadPathMap: object; loadPaths: string; /** * ResourceLoader get config loader. * * @return config loader * @api public */ getConfigLoader(): ConfigLoader; /** * ResourceLoader add context load path. * * @param cpath context load path * @api public */ addLoadPath(cpath: string): void; /** * ResourceLoader load metaObjects from context path. * * @param cpath context load path * @return metaObjects * @api public */ load(cpath: string): object; } interface ConfigLoader { /** * ConfigLoader get meta loader. * * @return meta loader * @api public */ getMetaLoader(): MetaLoader; /** * ConfigLoader get meta objects from context path. * * @param cpath context path * @return meta objects * @api public */ getResources(cpath: string): object; /** * ConfigLoader get recursive scan paths and metaObjects in context.json. * * @param cpath context path * @param scanPaths scan paths * @param metaObjects * @api public */ getRecursiveScanPath(cpath: string, scanPaths: string[], metaObjects: object): void; } interface MetaLoader { metaObjects: object; /** * MetaLoader load metaObjects from meta path. * * @param mpath * @return meta objects * @api public */ load(mpath: string): object; /** * MetaLoader set metaObject to beanName. * * @param beanName * @param metaObject * @api public */ setMetaObject(beanName: string, metaObject: object): void; /** * MetaLoader get metaObjects. * * @return metaObjects * @api public */ getMetaObjects(): object; } interface AsyncScriptLoader { cacheModules: object; loaderDir: string; applicationContext: ApplicationContext; /** * AsyncScriptLoader get loaded beans list. * * @return loaded beans * @api public */ getLoadBeans(): object[]; /** * AsyncScriptLoader load beans asynchronously. * * @param ids loaded beans ids * @param cb callback function * @api public */ load(ids: string[], cb?: CallbackFunc): void; /** * AsyncScriptLoader save load script with uri meta. * * @param uri * @param meta * @api public */ save(uri: string, meta: object): void; /** * AsyncScriptLoader register script with id, meta. * * @param id * @param beanMeta * @api public */ module(id: string, beanMeta: object): void; /** * AsyncScriptLoader resolve uri path with refUri. * * @param id * @param refUri * @return resolved path * @api public */ resolve(id: string, refUri: string): string; /** * AsyncScriptLoader resolve deps through bean meta. * * @param beanMeta * @return resolved deps * @api public */ resolveDeps(beanMeta: object): string[]; /** * AsyncScriptLoader get bean path through bean id. * * @param id * @return bean path * @api public */ getPathById(id: string): string; /** * AsyncScriptLoader get script from cache or new. * * @param uri * @param deps id * @return module * @api public */ get(uri: string, deps: string[]): object; /** * AsyncScriptLoader set applicationContext reference. * * @param applicationContext * @api public */ setApplicationContext(applicationContext: ApplicationContext): void; } interface BootStrapLoader { /** * BootStrapLoader load script files. * * @param idPaths * @api public */ load(idPaths: string[]): void; } } declare var bearcat: bearcat.Bearcat; export = bearcat;
the_stack
export const mailchimpSubscribe = 'http://eepurl.com/hb6y4T' const title = 'Risk Tracker Changelog' const shortTitle = 'Changelog' interface Change { date: Date versionNum?: string title?: string spreadsheetURL?: string whatsNew: string instructions?: string } // NOTE: Do not include '/edit' at the end of the URL, because we append different paths like /copy or /template/preview depending on the use case. Do not include a slash at the end of the URL. const changes: Change[] = [ { date: new Date(2021, 8, 18), versionNum: '2.4.1', title: 'Account for vaccines in shared budget reductions', spreadsheetURL: 'https://docs.google.com/spreadsheets/d/1x8OdUOdaZl2tKEHSijPZh_geHVLzIWyaQQGVTtxfoPw', whatsNew: ` * Fix: Shared budget reductions now account for whole-pod vaccines * Fix: Fix missing automatic name generation for two location rows`, instructions: ` 1. **Pod Overview sheet** * Edit cell \`D109\` to contain this formula: <pre><code>=GROCERY_ONE_HOUR_BASIC/MASK_MY_BASIC*VLOOKUP(F109, ACTIVITY_RISK_TABLE_MASK, 2, FALSE)*D104*E109</code></pre> 2. **Locations sheet** * Click on cell \`E9\` and go to *Edit > Copy* * Click above on cell \`E8\` and go to *Edit > Paste* * Click on cell \`E36\` and go to *Edit > Copy* * Click above on cell \`E35\` and go to *Edit > Paste* 3. **Pod Overview sheet:** * Update your version number in cell \`D2\` to 2.4.1 `, }, { date: new Date(2021, 8, 7), versionNum: '2.4', title: 'Increase podmate budgets if everyone is vaccinated', spreadsheetURL: 'https://docs.google.com/spreadsheets/d/1Es4ZzLlNiBSxG5jJsGPUYewrCw2NqB5kDXlNfmdSdD0', whatsNew: ` * New: Increase individual budgets if everyone in the pod is vaccinated since household transmission is less likely. Follows the [formula outlined here](/paper/13-q-and-a#2-if-a-vaccinated-individual-contracts-covid-how-much-less-or-more-likely-is-this-to-result-in-negative-consequences-increased-budget). ([#1013](https://github.com/microCOVID/microCOVID/issues/1013)) * New: Activity Risk now caps at the partner level (60%) instead of the housemate level (40%). ([#1012](https://github.com/microCOVID/microCOVID/issues/1012)) * Bugfix: Handles the case where we don't have vaccination data for a location, and the users selects "Avg local resident (vaccinated)" as the risk profile. ([#1037](https://github.com/microCOVID/microCOVID/issues/1037)) * Bugfix: Corrects the name of the *HEPA filter* location type to include "per hour". ([#968](https://github.com/microCOVID/microCOVID/issues/968)) * Bugfix: Now correctly ignores "environment" when distance is set to "close" ([#1033](https://github.com/microCOVID/microCOVID/issues/1033)) **Note on how the vaccination budget adjustment works:** This feature reduces the impact of other podmate's activities on each persons' budget, since transmission is lower between podmates now that you are all vaccinated. If some people in the pod are not vaccinated or received different types of vaccines, you have two main options. Let these two examples illustrate. * **Example A:** 5 podmates got Pfizer and 1 got J&J. The pod has a 1% annual risk budget. The person who got J&J doesn't mind being exposed to a bit more than 1% per year. So we set this setting to "Pfizer" because most people got Pfizer. This will set individual budgets that, if completely used, will put the housemate with J&J at above 1% risk of getting COVID. In this particular scenario, the podmate with the J&J vaccine may be exposed to up to a 0.07% chance of getting COVID per year. * **Example B:** 5 podmates got Pfizer and 1 got J&J. The pod has a 1% annual risk budget. The person who got J&J definitely wants to stay under the 1% total budget. Therefore, the pod chooses "Johnson & Johnson" for this setting. Everyone doesn't get as much of an increase to their budget, but you all stay under the 1% annual budget. `, instructions: ` 1. **Bugfix to clarify HEPA filter paramters** 1. Go to *Edit > Find & Replace* (it doesn't matter what sheet you are currently viewing) 1. Under **Find** enter: \`flow rate 5x room size\` 1. Under **Replace** enter: \`flow rate 5x room size per hour\` 1. Click **Replace all** 1. Reminder, we have a [air flow calculator](/blog/hepafilters) to determine the flow rate of you air purifier. 1. **Adjusting Activity Risk cap to "Partner" level (60%)** 1. Go to *Edit > Find & Replace* (it doesn't matter what sheet you are currently viewing) 1. Under **Find** enter: <pre><code>IF\\(([a-zA-Z]+\\d+)<>ACTIVITY_TITLE_ONE_TIME, 1E\\+99,[ \\n]*IF\\(OR\\(([a-zA-Z]+\\d+)=ACTIVITY_TITLE_KISSING,[ \\n]*([a-zA-Z]+\\d+)=ACTIVITY_TITLE_CUDDLING\\),[ \\n]*INTERNAL_ACTIVITY!\\$B\\$4,[ \\n]*INTERNAL_ACTIVITY!\\$B\\$3[ \\n]*\\)\\)</code></pre> 1. Under **Replace** enter: <pre><code>PARTNER</code></pre> 1. The **Search using regular expressions** checkbox should be checked 1. The **Also search withing formulas** checkbox should be checked 1. Click **Replace all**. When prompted if you are sure you want to replace all values in all sheets, click **Ok**. (It may take a 10+ seconds to complete. If it was successful, you will see *Replaced 100+ instances of...*) 1. **Bugfix for distance set to "close"** 1. Go to *Edit > Find & Replace* (it doesn't matter what sheet you are currently viewing) 1. Under **Find** enter: <pre><code>AND\\(([a-zA-Z]+\\d+)=ACTIVITY_TITLE_CUDDLING,[ \\n]*([a-zA-Z]+\\d+)=ACTIVITY_TITLE_OUTDOOR\\)</code></pre> 1. Under **Replace** enter: <pre><code>$1=ACTIVITY_TITLE_CUDDLING</code></pre> 1. The **Search using regular expressions** checkbox should be checked 1. The **Also search withing formulas** checkbox should be checked 1. Click **Replace all**. When prompted if you are sure you want to replace all values in all sheets, click **Ok**. (It may take a 10+ seconds to complete. If it was successful, you will see *Replaced 100+ instances of...*) 1. **Bugfix for "Avg local resident (vaccinated)" in locations without vaccinations data** 1. Go to *Edit > Find & Replace* (it doesn't matter what sheet you are currently viewing) 1. Under **Find** enter: <pre><code>=IF\\(ISTEXT\\(([a-zA-Z]+(\\d+))\\), "",[\\n ]+IF\\([\\n ]+ISNUMBER\\(([\\w\\W]*)</code></pre> 1. Under **Replace** enter: <pre><code>=IF(ISTEXT($1), "", IF(AND(OR(T$2="Avg local resident (vaccinated)", T$2="Avg local resident (unvaccinated)"), REGEXMATCH(TO_TEXT(VLOOKUP(PREVALENCE_LOCAL_NAME, LOCATION_TABLE_COMPLETE, 3, FALSE)), "Unknown")), "Error: Vaccination data not available in your region. Please use the 'Avg local resident' risk profile instead", IF(ISNUMBER($3)</code></pre> 1. The **Search using regular expressions** checkbox should be checked 1. The **Also search withing formulas** checkbox should be checked 1. Click **Replace all**. When prompted if you are sure you want to replace all values in all sheets, click **Ok**. (It may take a 10+ seconds to complete. If it was successful, you will see *Replaced 100+ instances of...*) 1. In the **Activity Log** sheet, click on Column N (to highlight the whole column) an go to *Format > Text wrapping > Wrap*. Repeat for the **Custom People** sheet. 1. In the **INTERNAL_PERSON** sheet, click on cell \`B9\` and press *paste* <table style="border: 1px solid #b4bcc2;"> <tr><td>Avg local resident (vaccinated)</td> <td><code>=IF(VLOOKUP(PREVALENCE_LOCAL_NAME, LOCATION_TABLE_COMPLETE, 3, FALSE)="Unknown", "Vaccination data not available in your region, use avg local resident profile instead", 1000000*VLOOKUP(PREVALENCE_LOCAL_NAME, LOCATION_TABLE_COMPLETE, 3, FALSE))</code></td></tr> <tr><td>Avg local resident (unvaccinated)</td> <td><code>=IF(VLOOKUP(PREVALENCE_LOCAL_NAME, LOCATION_TABLE_COMPLETE, 2, FALSE)="Unknown", "Vaccination data not available in your region, use avg local resident profile instead", 1000000*VLOOKUP(PREVALENCE_LOCAL_NAME, LOCATION_TABLE_COMPLETE, 2, FALSE))</code></td></tr> </table> 1. **Pod Overview sheet:** 1. Open the [current spreadsheet](https://docs.google.com/spreadsheets/d/1Es4ZzLlNiBSxG5jJsGPUYewrCw2NqB5kDXlNfmdSdD0) and copy all of \`Row 104\` (Where it says "Adjust budget as though everyone were fully vaccinated with...") to \`Row 104\` in your spreadsheet. 1. Click on \`C104\` then go to *Data > Data validation*. Under *Criteria* set the range to \`=INTERNAL_ACTIVITY!$I$19:$I$32\` then press *Save*. 1. In cell \`C124\` to be <pre><code>=C123/(1+(C122-1)*HOUSEMATE*D104)</code></pre> 1. Update your version number in cell \`D2\` to **2.4** `, }, { date: new Date(2021, 7, 18), versionNum: '2.3', title: 'Add “average vaccinated person”', spreadsheetURL: 'https://docs.google.com/spreadsheets/d/1nlCE-WVIzMEzf9fESE9mD46OIDGnz9yyKTtm49YG2rw', whatsNew: ` * Adds “Avg local resident (vaccinated)” and “Avg local resident (unvaccinated)” as risk profiles you can select.`, instructions: ` 1. **INTERNAL_PERSON sheet** * Highlight and *copy* all 4 of these cells (in the table below) * Click on cell \`B9\` and press *paste* <table style="border: 1px solid #b4bcc2;"> <tr><td>Avg local resident (vaccinated)</td> <td><code>=1000000*VLOOKUP(PREVALENCE_LOCAL_NAME, LOCATION_TABLE_COMPLETE, 3, FALSE)</code></td></tr> <tr><td>Avg local resident (unvaccinated)</td> <td><code>=1000000*VLOOKUP(PREVALENCE_LOCAL_NAME, LOCATION_TABLE_COMPLETE, 2, FALSE)</code></td></tr> </table> 2. **Pod Overview sheet:** * Update your version number in cell \`D2\` to 2.3 3. (Optional, most people can disregard this step) If you care about being able to easily read the % prevalence numbers, then do the following in the 📍 Locations sheet * Change cell \`F5\` to be Unvaccinated average prevalence * Change cell \`G5\` to be Vaccinated average prevalence * Highlight cell \`F6\` through cell \`G30\`. On the toolbar, click the % button to change the formatting to percentages, so you can read the data in those cells. `, }, { date: new Date(2021, 6, 26), title: 'Delta updates', whatsNew: ` The spreadsheet automatically pulls data on transmission rates and vaccine effectiveness from the website. So when we published the updates for the Delta variant, all spreadsheet users automatically got the update. * [See our blog post on the Delta variant](/blog/delta) * [See technical details](/paper/changelog#7262021)`, }, { date: new Date(2021, 4, 28), versionNum: '2.2.5', title: 'Update true infections model & fix budget calculation', spreadsheetURL: 'https://docs.google.com/spreadsheets/d/1HefpIbpD4HIqCzJYJex3_ydZ1j-vWZLI2ksouH0Jbco', whatsNew: ` * Fixed a bug where budgets were over-estimated using an 8-day time frame instead of a 7-day timeframe. * For manual location data: Update the “adjusted prevalence” formula to match the [December 10, 2020 updates](https://covid19-projections.com/estimating-true-infections-revisited/).`, instructions: ` 1. **Pod Overview sheet:** * Change the cell \`C125\` to **7**. (It was previously set to 8). To see row 125, you may need to press the plus button to the left of row 120. 2. **Locations sheet** * This change is only relevant if you’re using manual data entry for locations. (Most people are not.) * Paste into \`M35\` and drag through the end of the column: <pre><code>=IF(K35, (1000 / (DAYS(TODAY(), DAY_0) + 10)) * POWER(IF(OR(I35 >= 0, I35 <= 1), I35, 1), 0.5) + 2, )</code></pre> 3. **Pod Overview sheet:** * Update your version number in cell \`D2\` to **2.2.5** `, }, { date: new Date(2021, 4, 12), versionNum: '2.2.4', title: 'Bugfix - vaccine multiplier not applying properly to some activities', spreadsheetURL: 'https://docs.google.com/spreadsheets/d/1ivoRA8fFGKwm-XoflKFKeWIpRQJVpTFP6W1KN45_tSs', whatsNew: ` * Fixed a bug in the custom people tab where vaccine multiplier wouldn’t apply to every activity row if there was a 0% activity risk`, instructions: ` 1. **Custom People sheet** * Press the plus button above column B to show the hidden columns. * Paste into \`L3\` and drag through the end of the column: <pre><code>=IF(ISTEXT(P3), ROW(), IF(ISNUMBER(E3), MAX(FILTER(L$3:L, L$3:L&lt;ROW(), ISNUMBER(L$3:L))), ""))</pre></code> * Press the minus button above column B to hide the extra columns. \ 2. **Pod Overview sheet:** * Update your version number in cell \`D2\` to **2.2.4** `, }, { date: new Date(2021, 3, 1), versionNum: '2.2.3', title: 'Bugfix - Vaccine time to effectiveness', spreadsheetURL: 'https://docs.google.com/spreadsheets/d/1W3_RxaLrqILJae6Uw-I1D9opP5tKVA694OhdGusNwMs', whatsNew: ` * Changed delay for getting benefits of a vaccine dose to 14 days, consistent with AZ, J&J, and Moderna studies. * (Also, you’ll see the new [Johnson & Johnson vaccine numbers](/paper/13-q-and-a#vaccines-qa) have been automatically added to your spreadsheet since the last release. No action needed.) `, instructions: ` 1. **Custom People sheet** * Paste into \`J3\` and drag through the end of the column: <pre><code>=IF(L3&lt;&gt;"", IF(Q3="", COUNTIF(H3:I3, "&lt;"&TODAY() - 14), COUNTIF(H3:I3, "&lt;"&Q3-14)), )</pre></code> 2. **Activity Log sheet** * Repeat same step as above 3. **Pod Overview sheet:** * Update your version number in cell \`D2\` to **2.2.3** `, }, { date: new Date(2021, 2, 29), versionNum: '2.2.2', title: 'Bugfix - Kissing', spreadsheetURL: 'https://docs.google.com/spreadsheets/d/1aCj6tkxC70sT9WBwLjBYFxbr_eLbAv8FPF-fjrBtdaU', whatsNew: ` * Fixed a bug with kissing receiving a 30% activity risk cap (now 48% as intended) * Matched hourly rate for kissing to Calculator (5x normal rate vs 2x) `, instructions: ` 1. **Activity Log:** * Paste the following into \`F3\` and drag through the end of the column. (You must press the + button above column B to see column F.) <pre><code>=IF( OR( X3="", AND( X3=ACTIVITY_TITLE_ONE_TIME, Y3="", Z3="" ) ), "", MIN( IF(X3&lt;&gt;ACTIVITY_TITLE_ONE_TIME, 1E+99, IF(OR(AD3=ACTIVITY_TITLE_KISSING, AD3=ACTIVITY_TITLE_CUDDLING), INTERNAL_ACTIVITY!$B$4, INTERNAL_ACTIVITY!$B$3 )), VLOOKUP(X3, ACTIVITY_RISK_TABLE_INTERACTION, 2, FALSE) *IF( X3&lt;&gt;ACTIVITY_TITLE_ONE_TIME, 1, IF(AD3=ACTIVITY_TITLE_KISSING, MAX(1, (Y3+Z3/60)), (Y3+Z3/60)) *IF(OR(AA3="", AD3=ACTIVITY_TITLE_KISSING), 1, VLOOKUP( IF(AND(AD3=ACTIVITY_TITLE_CUDDLING, AA3=ACTIVITY_TITLE_OUTDOOR), ACTIVITY_TITLE_INDOOR, AA3), ACTIVITY_RISK_TABLE_ENVIRONMENT, 2, FALSE)) *IF(AD3=ACTIVITY_TITLE_KISSING, 1, IF(AE3="", 1, VLOOKUP(AE3, ACTIVITY_RISK_TABLE_VOICE, 2, FALSE)) *IF(AB3="", 1, VLOOKUP(AB3, ACTIVITY_RISK_TABLE_MASK, 2, FALSE)) *IF(AC3="", 1, VLOOKUP(AC3, ACTIVITY_RISK_TABLE_MASK, 3, FALSE))) *IF(AD3="", 1, VLOOKUP(AD3, ACTIVITY_RISK_TABLE_DISTANCES, 2, FALSE)) )))</pre></code> 2. **Custom People:** * Paste the following into \`F3\` and drag through the end of the column: (You must press the + button above column B to see column F.) <pre><code>=IF( OR( X3="", AND( X3=ACTIVITY_TITLE_ONE_TIME, Y3="", Z3="" ) ), "", MIN( IF(X3&lt;&gt;ACTIVITY_TITLE_ONE_TIME, 1E+99, IF(OR(AD3=ACTIVITY_TITLE_KISSING, AD3=ACTIVITY_TITLE_CUDDLING), INTERNAL_ACTIVITY!$B$4, INTERNAL_ACTIVITY!$B$3 )), VLOOKUP(X3, ACTIVITY_RISK_TABLE_INTERACTION, 2, FALSE) *IF( X3&lt;&gt;ACTIVITY_TITLE_ONE_TIME, 1, IF(AD3=ACTIVITY_TITLE_KISSING, MAX(1, (Y3+Z3/60)), (Y3+Z3/60)) *IF(OR(AA3="", AD3=ACTIVITY_TITLE_KISSING), 1, VLOOKUP( IF(AND(AD3=ACTIVITY_TITLE_CUDDLING, AA3=ACTIVITY_TITLE_OUTDOOR), ACTIVITY_TITLE_ALMOST_OUTDOOR, AA3), ACTIVITY_RISK_TABLE_ENVIRONMENT, 2, FALSE)) *IF(AE3="", 1, VLOOKUP(AE3, ACTIVITY_RISK_TABLE_VOICE, 2, FALSE)) *IF(AB3="", 1, VLOOKUP(AB3, ACTIVITY_RISK_TABLE_MASK, 2, FALSE)) *IF(AC3="", 1, VLOOKUP(AC3, ACTIVITY_RISK_TABLE_MASK, 3, FALSE)) *IF(AD3="", 1, VLOOKUP(AD3, ACTIVITY_RISK_TABLE_DISTANCES, 2, FALSE)) )))</pre></code> 3. **INTERNAL_ACTIVITY:** * Change cell \`F23\` from **2** to **5** 4. **Pod Overview:** * Update your version number in cell \`D2\` to **2.2.2** `, }, { date: new Date(2021, 2, 18), versionNum: '2.2.1', title: 'Bug fixes', spreadsheetURL: 'https://docs.google.com/spreadsheets/d/1lFM0di7j4MaGXbUzbe6GYNeigK1qyl0xuvSxlfIO1us', whatsNew: ` * Fixed a bug that caused vaccines to show up under the wrong podmate in some conditions * Fixed a bug in the Risk to Others Forecast that was showing an erroneously large number * Changed the way version number comparison is checked `, instructions: ` 1. **Activity Log:** * Paste the following into G3 and drag through the end of the column: <pre><code>=IF(L3&lt;&gt;"", IF($P3="", HLOOKUP($L3, '📊 Pod Overview'!$C$20:$X$28, 7, FALSE), HLOOKUP($P3, '📊 Pod Overview'!$C$20:$X$28, 7, FALSE)), )</pre></code> * Paste the following into H3 and drag through the end of the column: <pre><code>=IF(L3&lt;&gt;"", IF($P3="", HLOOKUP($L3, '📊 Pod Overview'!$C$20:$X$28, 8, FALSE), HLOOKUP($P3, '📊 Pod Overview'!$C$20:$X$28, 7, FALSE)), )</pre></code> * Paste the following into I3 and drag through the end of the column <pre><code>=IF(L3&lt;&gt;"", IF($P3="", HLOOKUP($L3, '📊 Pod Overview'!$C$20:$X$28, 9, FALSE), HLOOKUP($P3, '📊 Pod Overview'!$C$20:$X$28, 7, FALSE)), )</pre></code> 2. **Pod Overview:** * Paste the following into C81 (hidden by default in the “← Click plus button to show Risk to Others forecast” expandable section). <pre><code>=IF(NOT(ISTEXT(C$57)), , computeCustomPersonOnDate(INDIRECT("📋 Activity Log!B"&C$23&":B"&C$24-1), INDIRECT("📋 Activity Log!Q"&C$23&":Q"&C$24-1), 2, -1,$B81) )</pre></code> * Drag this through entire section (C81:X100) * Edit cell E2 (which appears to be blank but has a formula in it) to be: <pre><code>=IF(D2&lt;&gt;D3, HYPERLINK("https://docs.google.com/document/d/1iwTFoCS8lOIWWm-ZzcMZ_mPHgA8tHVVA3yhKY23gDu8", "NOTICE: Your spreadsheet is behind the latest version. Please click here for upgrade instructions."), )</pre></code> * Update your version number in cell \`D2\` to **2.2.1** `, }, { date: new Date(2021, 2, 16), versionNum: '2.2', title: 'Vaccines! 🎉 (& additional decay updates)', spreadsheetURL: 'https://docs.google.com/spreadsheets/d/1aCj6tkxC70sT9WBwLjBYFxbr_eLbAv8FPF-fjrBtdaU', whatsNew: ` * **_Vaccines are now supported_** for Pod Members and Custom People! 🎉 * You can read more in the [White Paper explanation of vaccines](/paper/13-q-and-a#vaccines-qa) * Pod Members’ vaccines are set from the pod overview sheet * Custom People’s vaccines are set in column AF-AH of the Custom People sheet * Vaccines require a date for each dose and the brand of vaccine. Risk reduction is calculated individually for each day to maintain integrity of the log from before vaccination. * If you don’t know the vaccine date or type, you can select “Unknown vaccine, unknown date” and the system will automatically apply the lowest efficacy vaccine. * The vaccine efficacy multipliers and “interaction type” multipliers (one-time/housemate/partner) are automatically imported from the microCOVID website, so we can easily update them as new information becomes available. * Your Risk to Others for the last 7 days and next 14 days can be displayed (expandable in the Pod Overview sheet) * Risk from custom people’s activities on a specific date is calculated as of the day you saw them. * Removed the “health care or social worker” and “works from home” person types. [See our rationale for this change here](/paper/13-q-and-a#are-people-who-work-outside-the-home-riskier-than-people-who-work-from-home). `, instructions: ` _Since this is such a large change, these instructions show you how to make a new copy of the spreadsheet and migrate your data over to it._ _Steps_ 1. **Make a copy** of the [latest version of the spreadsheet](https://docs.google.com/spreadsheets/d/1aCj6tkxC70sT9WBwLjBYFxbr_eLbAv8FPF-fjrBtdaU#gid=1845362878) 2. **Podmate names:** Copy-paste the names of each of your podmates (Pod Overview > row 20) 3. **Locations:** Copy-paste your location settings. (Location > B6 through E26) 4. **Custom People data:** Copy-paste the columns from your Custom People sheet (from “Is this a generic person profile that should be adjustable by location?” to “Volume”) 5. **Activity Log data:** Copy-paste the columns from your Activity Log (from “Podmate Name” to “Volume”) 6. Delete your old spreadsheet (File > Move to trash). (Or alternately, you can rename it and make it clear to anyone who opens it that they should go to the new copy.) 7. Notify all your podmates of the new URL. _Less common settings you may also want to migrate:_ 1. Copy-paste your risk budget choice (if it’s something other than default). 2. Copy-paste each of your shared budget reductions (Pod Overview > rows 65-63) _Note: Known Issue with vaccines:_ The vaccine logic will apply your vaccination bonus to your interactions with your podmates slightly before what is strictly accurate (starting 7 days after your vaccination, the sheet will retroactively apply the vaccination multiplier to current microCOVIDs from housemates). The fix for this is too complicated to be deemed worthwhile. * Example: a housemate who gets 100microCOVIDs 6 days after your vaccination will, 8 days after your vaccination, show up as 100 * .3 * .5 * .56 = 8.6 microCOVID instead of 100 * .3 * .5 = 15 microCOVID * Workaround: If you must avoid under-reporting at all costs, enter the date of your vaccine 1 week later than you actually received it. `, }, { date: new Date(2021, 1, 15), versionNum: '2.1', title: 'Manually enter person risk number', spreadsheetURL: 'https://docs.google.com/spreadsheets/d/1-IEwUHHC-V8yzA4R6cShxlev63Ykm0uK61GUL_IynmA', whatsNew: ` * If you know the microCOVID score of the person you’re seeing, you can enter it directly into the “Risk profile” column (instead of selecting an item from the dropdown) `, instructions: ` 1. In the **Pod Activity** Log sheet, press the **+** button on top column B to show the hidden formula columns. 2. Edit cell \`E3\` to contain the following <pre><code>=IF(O3="","", IF(ISNUMBER(O3), O3, MAX( ARBITRARY_MIN_PERSON_RISK, VLOOKUP(O3, PEOPLE_TABLE, 2, FALSE) *IF(OR(P3="", VLOOKUP(O3, PEOPLE_TABLE, 3, FALSE)), 1 + N("Correct for non-default locations"), VLOOKUP(P3, LOCATION_TABLE, 2, FALSE) /PREVALENCE_LOCAL) /MAX(N("Remove delay factor for past weeks"), IF(AND(ISDATE(L3), L3&lt;=LOCATION_DATA_DATE_LAST_UPDATED), VLOOKUP(IF(ISBLANK(P3), PREVALENCE_LOCAL_NAME, P3), LOCATION_TABLE_COMPLETE, 8, FALSE), 1), 1) *IF(Q3,SYMPTOMS_NONE_NOW,1)) ))</pre></code> 3. Drag \`E3\` down to the bottom of the column. 4. Press the **+** button above Column B again to hide the formula columns. 5. Repeat steps 1-4 in the Custom Person sheet. 6. On the **Pod Overview sheet**, change the version number to **2.1** `, }, { date: new Date(2021, 0, 31), versionNum: '2.0', title: 'Version 2.0 release 🎉', spreadsheetURL: 'https://docs.google.com/spreadsheets/d/1-IEwUHHC-V8yzA4R6cShxlev63Ykm0uK61GUL_IynmA', whatsNew: ` * [Read the full details for this release on our blog](/blog/budget) `, instructions: ` **Upgrade note:** It’s not possible to migrate your spreadsheet to version 2. The easiest option is to make a copy of the current version and begin logging your activities there. Future updates will come with migration instructions. `, }, { date: new Date(2021, 0, 31), title: 'Version 1 is being retired', spreadsheetURL: 'https://docs.google.com/spreadsheets/d/1-IEwUHHC-V8yzA4R6cShxlev63Ykm0uK61GUL_IynmA', whatsNew: ` Now that we’re launching [version 2 of the Risk Tracker spreadsheet](/tracker), we are retiring version 1. You can find a copy of [Version 1](https://docs.google.com/spreadsheets/d/1DYIJgjG3H5rwt52NT2TX_m429snmIU-jGw1a8ZODwGQ) here if you need it for any reason. `, }, { date: new Date(2021, 0, 31), title: 'Previous changelog entries', whatsNew: ` Previous changelog entries can be found in the [old risk tracker changelog google doc](https://docs.google.com/document/d/1iwTFoCS8lOIWWm-ZzcMZ_mPHgA8tHVVA3yhKY23gDu8#heading=h.lvpswyvu999r) `, }, ] export const lastUpdated = changes[0].date let content = `See below for each update that has been made to the [Risk Tracker](/tracker) spreadsheet and instructions for how to migrate your copy of the spreadsheet with the latest changes. [Click here to subscribe for notifications about Risk Tracker version updates](${mailchimpSubscribe}). If you have any questions, you can email [tracker@microcovid.org](mailto:tracker@microcovid.org).\n\n` content += changes .map((change) => { // Title // NOTE: If you change the title format, you will likely break the anchor tags on each heading, which may be linked to elsewhere in the system let markdownContent = `## ${change.date.toLocaleDateString()}` if (change.versionNum) { markdownContent += ` (v${change.versionNum})` } if (change.title) { markdownContent += `: ${change.title}` } markdownContent += '\n' // Link if (change.spreadsheetURL) { if (change.versionNum) { markdownContent += `[Direct link to v${change.versionNum} of the spreadsheet](${change.spreadsheetURL})\n\n` } else { markdownContent += `[Direct link to this version of the spreadsheet](${change.spreadsheetURL})\n\n` } } // What's new if (change.whatsNew) { markdownContent += `${change.whatsNew}\n\n` } // Instructions to migrate if (change.instructions) { markdownContent += `**Instructions to manually update your copy of the spreadsheet:**\n${change.instructions}\n\n` } return markdownContent }) .join('\n\n') export const post = { title, shortTitle, content } export default post export const latestRiskTrackerVersion = changes[0].versionNum export const latestRiskTrackerReleaseDate = changes[0].date export const latestRiskTrackerSpreadsheetURL = changes[0].spreadsheetURL
the_stack
import { Component, ViewChildren, QueryList, ElementRef, OnInit } from '@angular/core'; import { Router, NavigationStart, ActivatedRoute } from '@angular/router'; import { DomSanitizer } from '@angular/platform-browser'; import { trigger, transition, style, animate } from '@angular/animations'; import { ServiceFive } from '@ngx-tranalste/core'; import { format } from 'date-fns'; import { fr } from 'date-fns/locale'; import { combineLatest, defer, of } from 'rxjs'; import { catchError, take, filter, map, mergeMap, shareReplay, tap } from 'rxjs/operators'; import { LoadingComponent, ServiceEight, Component61 } from './my-components'; import { Component62 } from '../comp62.component'; import { Component63 } from '../comp63.component' import { serviceThreeOptions, ServiceThree, Component64, Component65 } from './my-components'; import { Component66, Component67 } from './my-components'; import { ServiceFour } from './four.service'; import { serviceOne } from '../one.service'; import { Service61 } from '../sixty-one.service'; import { Service62 } from './sixty-two.service'; import { ServiceEleven } from '../../evleven.service'; @Component({ selector: 'my-page', templateUrl: './my.html', styleUrls: ['./my.scss'], animations: [ trigger('slideIn', [ transition(':enter', [ style({ opacity: 0, maxHeight: '0', overflow: 'hidden', padding: '0 8px' }), animate('.5s', style({ opacity: 1, maxHeight: '250px', padding: '8px' })) ]) ]) ] }) export class Example6Component implements OnInit { get mySelection() { return this.__mySelection; } set mySelection(param) { this.__mySelection = param; const url = `/my.html?` + `nnnAaaa=${this.nnnAaaa}&link=${param.link}`; this.srcIiii = this.sanitize.bypassSecurityTrustResourceUrl(url); // needed for NG context } constructor( private serviceThree: ServiceThree, private sanitize: DomSanitizer, private serviceFour: ServiceFour, private service64: Service61, private serviceOne:  serviceOne, private service8: ServiceEight, private router: Router, private route: ActivatedRoute, private serviceEleven: ServiceEleven, private serviceFive: ServiceFive, private service62: Service62 ) { this.language = service8.language; this.ssssMmmm = service8.ssssMmmm; this.srcIiii = this.sanitize.bypassSecurityTrustResourceUrl('about:blank'); // needed for NG context this.printFooSrc = this.sanitize.bypassSecurityTrustResourceUrl('about:blank'); // needed for NG context } nnnAaaa; ssssMmmm: any; details: any; showPppSss = false; hhhPppp: any; iiiPppAaa: any; iiiPppAaaErr = false; hhhMMmNnn = false; iiiHhhhhppppp: any; iiiHhhhhpppppErr = false; iiiiPppp: any; myError = false; myConfig: any; myConfigErr = false; @ViewChildren('iFrameBill', { read: ElementRef }) iFrameBill: QueryList<any>; today = new Date(); language; defaultTab = 'my-tab'; dateCccBbb; msgBbbb; srcIiii: any; printFooSrc: any; statusOooo; // ERROR (OR) INFO serviceThreeOptionsError: serviceThreeOptions = { showBbbbCccc: false }; __mySelection; errorAaaEeee$ = this.serviceFour.catchError().pipe( tap(e => this.handleError(e)), map(e => !!e) ); foo$ = defer(() => { this.serviceThree.open(LoadingComponent, this.serviceThreeOptionsError); return this.serviceFour.getFooing(); }).pipe( tap(param => { this.details = param; this.dateCccBbb = (<any>param).dateCccBbb; }), catchError(error => of(error)), shareReplay(1) ); bar$ = defer(() => of(this.ssssMmmm)).pipe( map(summary => { const { nnnAaaa, fooStatus, billing, numTttAaa } = summary; return { nnnAaaa, fooStatus, billing, numTttAaa }; }), tap(summary => (this.nnnAaaa = summary.nnnAaaa)), shareReplay() ); fuz$ = defer(() => { this.serviceThree.open(LoadingComponent, this.serviceThreeOptionsError); return this.serviceFour.loadBbbUuuu(); }).pipe( map((userBaz: any) => userBaz.fuz.map(param => { const temp = param.dataFoo; const dataFoo = new Date(temp.replace('-', '/')); return { ...param, dateFoo }; }) ), catchError(error => of(error)), tap(fuz => { if (fuz && fuz.length > 0) { this.mySelection = fuz[0]; } }), shareReplay(1) ); baz$ = combineLatest(this.foo$, this.fuz$).pipe( map(([foo, fuz]) => { if (foo.dateCccBbb && fuz.length === 0) { this.statusOooo = 'INFO'; } else if (foo.error || fuz.error) { this.statusOooo = 'ERROR'; } return this.statusOooo; }) ); showBarXxx$ = combineLatest(this.bar$, this.fuz$, this.foo$).pipe( map(([param1, fuz, foo]) => { if ( param1.numTttAaa !== 1 || (param1.fooStatus.toLowerCase() !== 'open' && bar.fooStatus.toLowerCase() !== 'active') ) { return false; } else { return this.service62.toshowBarXxx(fuz[0].dateFoo, foo.dateCccBbb); } }), catchError(_ => of(false)), tap(show => { this.serviceThree.close(); if (show) { this.setTranslations(); } }) ); ngOnInit() { const qp = tis.route.snapshot.queryParams['qp']; this.defaultTab = qp ? qp : this.defaultTab; this.showPppSss = this.serviceEleven.isFffPppRrrr; if (this.showPppSss) { this.router.events.pipe( take(1), filter(event => event instanceof NavigationStart) ).subscribe(() => { this.serviceEleven.isFffPppRrrr = false; }); } this.service64.getPppIiiAaaa().subscribe( (resp: any) => { const isAaPpIRV = resp && resp.dddPpp && resp.dddPpp.length; if (isAaPpIRV) { this.iiiPppAaa = resp; // for billing page use this.setbbbHhhPTPMessage(); // for billing header values only } else { if (resp.dddPpp && resp.dddPpp.length === 0) { this.hhhMMmNnn = true; } // other business error this.iiiPppAaaErr = true; this.myError = true; } }, error => { this.iiiPppAaaErr = true; this.myError = true; } ); this.serviceOne.getHhhPppp().subscribe(       resp => this.hhhPppp =  resp,       error => console.log('error: ',  error) ); this.serviceFour.getmyConfig().subscribe( resp => this.myConfig = resp, error => this.myConfigErr = true ); } getIiiFooPppBar(event) { // for future event calls to update fooFuz if (event.detail.PId) { this.service64.getIiiFooPppBar(event.detail.PId).subscribe( (resp: any) => { if (resp.fooFuz && resp.fooFuz.length) { this.iiiiPppp = resp; } else { this.myError = true; } }, error => this.myError = true); } } setbbbHhhPTPMessage() { // called on ngInit const ptpID = this.serviceFour.getIdFffHhhP(this.iiiPppAaa); this.service64.getIiiFooPppBar(ptpID).subscribe( (resp: any) => { if (resp.fooFuz && resp.fooFuz.length) { this.iiiHhhhhppppp = resp; } else { this.iiiHhhhhpppppErr = true; } }, error => this.iiiHhhhhpppppErr = true); } setTranslations() { this.serviceFour.getmyType().subscribe(type => { const month = format( this.service62.getCccEchoDtCcc(this.mySelection.issue_date), 'MMMM', this.language === 'fr' ? { ...{ locale: fr } } : {} ); if (type === 'BAR') { this.msgBbbb = this.serviceFive.instant('foo').replace('{{x}}', month); } else { this.msgBbbb = this.serviceFive.instant('bar').replace('{{x}}', month); } }); } doBbbAaaDddd(type: string) { this.serviceThree.open(LoadingComponent, this.serviceThreeOptionsError); this.fetchMee(type).subscribe(); } fetchMee(type) { return this.serviceFour.betSssEeeMee().pipe( mergeMap(param => this.serviceFour.fetchBar(this.mySelection, this.nnnAaaa, type, param).pipe( tap(content => { this.serviceThree.close(); if (content.error) { this.serviceThree.open(Component66, { data: type }); } else { this.serviceFour.doFoo( this.mySelection.id, content, `${this.mySelection.date}-${this.nnnAaaa}-${type}` ); this.serviceThree.open(Component67, { data: type }); } }) ) ) ); } /** Refactor this later */ printBar() { this.serviceThree.open(LoadingComponent, this.serviceThreeOptionsError); this.serviceFour.betSssEeeMee().subscribe(param => { try { const myFooElement = document.getElementById('myFooElement'); myFooElement.focus(); this.serviceThree.close(); myFooElement.onload = () => { const result = (<any>myFooElement).contentWindow.document.execCommand('print', false, null); if (!result) { (<any>myFooElement).contentWindow.print(); } }; this.printFooSrc = this.sanitize.bypassSecurityTrustResourceUrl( this.serviceFour.resolveMyUrl(this.mySelection.link, param, false) ); } catch { this.serviceThree.open(Component61, { data: { content: this.serviceFive.instant('msg') } }); } }); } saveFoo() { this.serviceThree.open(LoadingComponent, this.serviceThreeOptionsError); this.serviceFour.betSssEeeMee().subscribe(encryptStr => { try { const url = this.serviceFour.resolveMyUrl(this.mySelection.link, encryptStr, true); window.open(url, '_blank'); this.serviceThree.close(); } catch { this.serviceThree.open(Component61, { data: { content: this.serviceFive.instant('msg') } }); } }); } setFuz(e: Event) { const frame = this.iFrameBill && this.iFrameBill.first.nativeElement; if (frame && frame.contentDocument && frame.contentDocument.body) { const initialHeight = frame.contentDocument.body.scrollHeight; frame.style.height = initialHeight + 45 + 'px'; let timesRun = 0; // Poll iframe height for change const poll = frame && setInterval(() => { timesRun += 1; if (timesRun > 5) { clearInterval(poll); } else { if (frame && frame.contentDocument && frame.contentDocument.body) { const newHeight = frame.contentDocument.body.scrollHeight; // If height changes after content load then update the height if (newHeight > initialHeight) { frame.style.height = newHeight + 45 + 'px'; } } } }, 500); } else { console.log('Error accessing iframe'); } } schFooClicked($event) { this.defaultTab = 'tab'; } barSelected(event) { this.service64.checkFoo().subscribe((resp: any) => { const foo = { x: true, y: this.details.x, z: resp.x }; resp.x ? this.serviceThree.open(Component63, {data: foo}) : this.checkTyEl(); }, (e) => {this.openFoo(e); }); } checkTyEl() { this.service64.checkEeePppMe1().subscribe((resp: any) => { const data = { x: false, y: this.details.x, z: resp.x }; resp.x ? this.showBar1() : this.serviceThree.open(Component63, {data: data}); }, (e) => {this.openFoo(e); }); } showBar1() { this.service64.getFooLink().subscribe((resp: any) => { const fooLinks = this.service8.language === 'fr' ? resp.x.fr : resp.x.en; const serviceThree: any = this.serviceThree.open(Component62, { data: { x: this.details.x, y: fooLinks }}); serviceThree.foo$.subscribe(resp => { this.saveFuz(res); }); }, (e) => {this.openFoo(e); }); } saveFuz(param) { const x = { y: this.serviceFive.instant('x'), z: this.serviceFive.instant('y') }; this.service64.schedulePTP(param).subscribe((resp: any) => { resp.status ? this.serviceThree.open(Component65, {data: x}) : this.openFoo(); }, (e) => {this.openFoo(e); }); } openFoo(err?) { const x = { y: this.serviceFive.instant('x'), z: this.serviceFive.instant('y') }; this.serviceThree.open(Component64, {data: genericErrorData}); } handleError(e) { if (e.error) { this.statusOooo = 'E'; } } }
the_stack
import fs from 'fs-extra'; import _ from 'lodash'; import path from 'path'; import ts from 'typescript'; import {log} from './logger'; import {fail} from './test-tracker'; import {writeTempFile, matchAndExtract, getTempDir, matchAll} from './utils'; import {CodeSample} from './types'; import {runNode} from './node-runner'; export interface TypeScriptError { line: number; start: number; // inclusive end: number; // exclusive message: string; } export interface TypeScriptTypeAssertion { line: number; type: string; } export interface ConfigBundle { options: ts.CompilerOptions; host: ts.CompilerHost; } const COMMENT_PAT = /^( *\/\/) /; const TILDE_PAT = / (~+)/g; const POST_TILDE_PAT = /\/\/ [~ ]+(?:(.*))?/; const TYPE_ASSERTION_PAT = /\/\/.*[tT]ype is (?:still )?(?:just )?(.*)\.?$/; export function extractExpectedErrors(content: string): TypeScriptError[] { const lines = content.split('\n'); const errors: TypeScriptError[] = []; let lastCodeLine: number; lines.forEach((line, i) => { const comment = matchAndExtract(COMMENT_PAT, line); if (!comment) { lastCodeLine = i; return; } const tildes = matchAll(TILDE_PAT, line); if (tildes.length === 0) { const lastError = errors[errors.length - 1]; if (lastError && lines[lastError.line + 1].startsWith(comment)) { // Presumably this is a continuation of the error. lastError.message += ' ' + line.slice(comment.length).trim(); } return; } const messageMatch = POST_TILDE_PAT.exec(line); const message = (messageMatch ? messageMatch[1] || '' : '').trim(); for (const m of tildes) { const start = m.index + 1; const end = start + m[1].length; errors.push({line: lastCodeLine, start, end, message}); } }); return errors; } function doErrorsOverlap(a: TypeScriptError, b: TypeScriptError) { return a.line === b.line && a.start <= b.end && b.start <= a.end; } function checkMatchingErrors(expectedErrorsIn: TypeScriptError[], actualErrors: TypeScriptError[]) { const expectedErrors = expectedErrorsIn.slice(); const matchedErrors: TypeScriptError[] = []; let anyFailures = false; for (const error of actualErrors) { const i = _.findIndex(expectedErrors, e => doErrorsOverlap(e, error)); if (i >= 0) { const matchedError = expectedErrors.splice(i, 1)[0]; matchedErrors.push(matchedError); log('matched errors:'); log(' expected: ' + matchedError.message); log(' actual: ' + error.message); const posMismatch = []; const dStart = error.start - matchedError.start; const dEnd = error.end - matchedError.end; if (dStart) posMismatch.push(`start: ${dStart}`); if (dEnd) posMismatch.push(`end: ${dEnd}`); if (posMismatch.length) { log(' mismatched error span: ' + posMismatch.join(', ')); } let matchType = ''; let disagree = false; if (error.message === matchedError.message) { matchType = 'perfect'; } else if (!error.message) { matchType = 'empty message'; } else if (error.message.includes(matchedError.message)) { matchType = 'subset'; } else if (matchedError.message.includes('...')) { const parts = matchedError.message.split('...'); const allMatch = _.every(parts, part => error.message.includes(part)); if (allMatch) { matchType = 'match with ...'; } else { disagree = true; } } else { disagree = true; } if (disagree) { log(' error messages could not be matched!'); } else { log(' error messages match: ' + matchType); } } else { const {line, start, end, message} = error; fail(`Unexpected TypeScript error: ${line}:${start}-${end}: ${message}`); anyFailures = true; } } for (const error of expectedErrors) { const {line, start, end, message} = error; fail(`Expected TypeScript error was not produced: ${line}:${start}-${end}: ${message}`); anyFailures = true; } if (expectedErrorsIn.length) { log(`Matched ${matchedErrors.length}/${expectedErrorsIn.length} errors.`); } else if (actualErrors.length === 0) { log(`Code passed type checker.`); } return !anyFailures; } export function hasTypeAssertions(content: string) { const lines = content.split('\n'); return !!_.find(lines, line => TYPE_ASSERTION_PAT.exec(line)); } export function extractTypeAssertions( scanner: ts.Scanner, source: ts.SourceFile, ): TypeScriptTypeAssertion[] { const assertions = [] as TypeScriptTypeAssertion[]; let appliesToPreviousLine = false; let colForContinuation = null; while (scanner.scan() !== ts.SyntaxKind.EndOfFileToken) { const token = scanner.getToken(); if (token === ts.SyntaxKind.WhitespaceTrivia) continue; // ignore leading whitespace. if (token === ts.SyntaxKind.NewLineTrivia) { // an assertion at the start of a line applies to the previous line. appliesToPreviousLine = true; continue; } const pos = scanner.getTokenPos(); const lineChar = source.getLineAndCharacterOfPosition(pos); let {line} = lineChar; const {character} = lineChar; if (token === ts.SyntaxKind.SingleLineCommentTrivia) { const commentText = scanner.getTokenText(); if (character === colForContinuation) { assertions[assertions.length - 1].type += ' ' + commentText.slice(2).trim(); } else { const type = matchAndExtract(TYPE_ASSERTION_PAT, commentText); if (!type) continue; if (appliesToPreviousLine) line -= 1; assertions.push({line, type}); colForContinuation = character; } } else { appliesToPreviousLine = false; colForContinuation = null; } } return assertions; } // Use this to figure out which node you really want: // const debugWalkNode = (node: ts.Node, indent = '') => { // console.log(`${indent}${node.kind}: ${node.getText()}`); // for (const child of node.getChildren()) { // debugWalkNode(child, ' ' + indent); // } // }; /** * Figure out which node we should check the type of. * * For a declaration (`const x = 12`) we want to check the 'x'. * This winds up being the first identifier in the AST. */ export function getNodeForType(node: ts.Node): ts.Node { const findIdentifier = (node: ts.Node): ts.Node | null => { if ( node.kind === ts.SyntaxKind.Identifier || node.kind === ts.SyntaxKind.PropertyAccessExpression || node.kind === ts.SyntaxKind.CallExpression ) { return node; } for (const child of node.getChildren()) { const childId = findIdentifier(child); if (childId) { return childId; } } return null; }; return findIdentifier(node) || node; } export function typesMatch(expected: string, actual: string) { if (expected.endsWith('!')) { expected = expected.slice(0, -1); } if (expected === actual) { return true; } const n = expected.length; return expected.endsWith('...') && actual.slice(0, n - 3) === expected.slice(0, n - 3); } export function checkTypeAssertions( source: ts.SourceFile, checker: ts.TypeChecker, assertions: TypeScriptTypeAssertion[], ) { const numAssertions = assertions.length; let matchedAssertions = 0; let anyFailures = false; // Match assertions to the first node that appears on the line they apply to. const walkTree = (node: ts.Node) => { if ( node.kind !== ts.SyntaxKind.SourceFile && node.kind !== ts.SyntaxKind.SyntaxList && node.kind !== ts.SyntaxKind.Block ) { const pos = node.getEnd(); const {line} = source.getLineAndCharacterOfPosition(pos); const assertionIndex = _.findIndex(assertions, {line}); if (assertionIndex >= 0) { const assertion = assertions[assertionIndex]; const nodeForType = getNodeForType(node); const type = checker.getTypeAtLocation(nodeForType); const actualType = checker.typeToString(type, nodeForType); if (!typesMatch(assertion.type, actualType)) { const testedText = node !== nodeForType ? ` (tested ${nodeForType.getText()})` : ''; fail(`Failed type assertion for ${node.getText()}${testedText}`); log(` Expected: ${assertion.type}`); log(` Actual: ${actualType}`); anyFailures = true; } else { log(`Type assertion match: ${node.getText()} => ${assertion.type}`); matchedAssertions++; } assertions.splice(assertionIndex, 1); } } ts.forEachChild(node, child => { walkTree(child); }); }; walkTree(source); if (assertions.length) { fail('Unable to attach all assertions to nodes'); return false; } else if (numAssertions) { log(` ${matchedAssertions}/${numAssertions} type assertions matched.`); } return !anyFailures; } /** Verify that a TypeScript sample has the expected errors and no others. */ export async function checkTs( content: string, sample: CodeSample, runCode: boolean, config: ConfigBundle, ) { const {id} = sample; const fileName = id + (sample.isTSX ? '.tsx' : `.${sample.language}`); const tsFile = writeTempFile(fileName, content); const sampleDir = getTempDir(); const nodeModulesPath = path.join(sampleDir, 'node_modules'); fs.emptyDirSync(nodeModulesPath); for (const nodeModule of sample.nodeModules) { // For each requested module, look for node_modules in the same directory as the source file // and then march up directories until we find it. // There's probably a better way to do this. let match; const candidates = []; let dir = path.dirname(path.resolve(process.cwd(), sample.sourceFile)); while (true) { const candidate = path.join(dir, 'node_modules', nodeModule); candidates.push(candidate); if (fs.pathExistsSync(candidate)) { match = candidate; break; } const parent = path.dirname(dir); if (parent === dir) { break; } dir = parent; } if (!match) { fail(`Could not find requested node_module ${nodeModule}. See logs for details.`); log('Looked in:\n ' + candidates.join('\n ')); return; } fs.copySync(match, path.join(nodeModulesPath, nodeModule)); } const options: ts.CompilerOptions = { ...config.options, ...sample.tsOptions, }; if (!_.isEmpty(sample.nodeModules)) { options.typeRoots = [path.join(sampleDir, 'node_modules', '@types')]; } const program = ts.createProgram([tsFile], options, config.host); const source = program.getSourceFile(tsFile); if (!source) { fail('Unable to load TS source file'); return; } let diagnostics = ts.getPreEmitDiagnostics(program); if (runCode) { const emitResult = program.emit(); diagnostics = diagnostics.concat(emitResult.diagnostics); if (emitResult.emitSkipped) { fail('Failed to emit JavaScript for TypeScript sample.'); return; } } const expectedErrors = extractExpectedErrors(content); const numLines = content.split('\n').length; const actualErrorsRaw: TypeScriptError[] = diagnostics .map(diagnostic => { const {line, character} = diagnostic.file!.getLineAndCharacterOfPosition(diagnostic.start!); return { line, start: character, end: character + diagnostic.length!, message: ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'), }; }) // sometimes library errors show up as being past the end of the source. .filter(err => err.line < numLines); // There's no way to represent expected errors with identical spans. // Usually these go from least- to most-specific, so just take the last one. const actualErrors = _(actualErrorsRaw) .groupBy(e => `${e.line}:${e.start}-${e.end}`) .mapValues(errs => errs.slice(-1)[0]) .values() .value(); let ok = checkMatchingErrors(expectedErrors, actualErrors); if (hasTypeAssertions(content)) { const languageVersion = config.options.target || ts.ScriptTarget.ES5; const scanner = ts.createScanner( languageVersion, false, source.languageVariant, source.getFullText(), ); const checker = program.getTypeChecker(); const assertions = extractTypeAssertions(scanner, source); ok = ok && checkTypeAssertions(source, checker, assertions); } if (!ok) { log(content); log(`tsconfig options: ${JSON.stringify(options)}`); } if (!runCode) return; const jsFile = tsFile.replace(/\.ts$/, '.js'); if (!fs.existsSync(jsFile)) { fail(`Did not produce JS output in expected place: ${jsFile}`); return; } sample.output = await runNode(jsFile); }
the_stack
import { ref, markRaw, computed, Ref } from 'vue' import { Metamask, MetaMaskProvider, MetaMaskProviderRpcError, } from '../wallets/metamask' import { Walletconnect, WalletConnectProvider } from '../wallets/walletconnect' import { Walletlink, WalletLinkProvider, WalletLinkProviderRpcError, } from '../wallets/walletlink' import { useEthers } from './useEthers' export type WalletProvider = | MetaMaskProvider | WalletConnectProvider | WalletLinkProvider export type ConnectionState = 'none' | 'connecting' | 'connected' export type WalletName = 'none' | 'metamask' | 'walletconnect' | 'walletlink' export type OnConnectedCallback = (provider: WalletProvider) => void export type OnDisconnectCallback = (msg: string) => void export type OnAccountsChangedCallback = (accounts: string[]) => void export type OnChainChangedCallback = (chainId: number) => void export type UseWalletOptions = { library: 'ethers' | 'web3' } // ========================= state ========================= const provider = ref<WalletProvider | null>(null) const status = ref<ConnectionState>('none') const walletName = ref<WalletName>('none') const error = ref('') const onDisconnectCallback = ref<OnDisconnectCallback | null>(null) const onAccountsChangedCallback = ref<OnAccountsChangedCallback | null>(null) const onChainChangedCallback = ref<OnChainChangedCallback | null>(null) export function useWallet(options: UseWalletOptions = { library: 'ethers' }) { const { activate, deactivate } = useEthers() function clear() { provider.value = null status.value = 'none' walletName.value = 'none' error.value = '' onDisconnectCallback.value = null onAccountsChangedCallback.value = null onChainChangedCallback.value = null options.library === 'ethers' && deactivate() } async function connect( _walletName: WalletName, infuraAPI?: string, appName?: string, ) { let _provider: WalletProvider | null = null error.value = '' try { status.value = 'connecting' switch (_walletName) { case 'metamask': _provider = (await Metamask.connect()) as MetaMaskProvider if (!_provider.isConnected) throw new Error('metamask is not connected') break case 'walletconnect': if (!infuraAPI) throw new Error( 'You should provide infuraAPI for connecting WalletConnect', ) _provider = (await Walletconnect.connect( infuraAPI, )) as WalletConnectProvider if (!_provider.connected) throw new Error('walletconnect is not connected') break case 'walletlink': if (!infuraAPI) throw new Error( 'You should provide infuraAPI for connecting WalletLink', ) if (!appName) throw new Error( 'You should provide an app name for connecting WalletLink', ) _provider = (await Walletlink.connect( infuraAPI, appName, )) as WalletLinkProvider if (!_provider.isConnected) throw new Error('walletlink is not connected') break default: throw new Error('Connect Error: wallet name not found') } } catch (err: any) { clear() error.value = `Failed to connect: ${err.message}` return } provider.value = markRaw(_provider) walletName.value = _walletName status.value = 'connected' // EIP-1193 subscriber subscribeDisconnect() subscribeAccountsChanged() subscribeChainChanged() try { options.library === 'ethers' && (await activate(provider.value as WalletProvider)) } catch (err: any) { clear() error.value = `Failed to load data: ${err.message}` return } } async function disconnect() { // note: metamask can't disconnect by provider if (walletName.value === 'walletconnect') { try { await (provider.value as WalletConnectProvider).disconnect() } catch (err: any) { console.error(err.message) } } clear() onDisconnectCallback.value && onDisconnectCallback.value('Disconnect from Dapp') } // ========================= EIP-1193 subscriber ========================= function subscribeDisconnect() { switch (walletName.value) { case 'metamask': ;(provider.value as MetaMaskProvider).on( 'disconnect', (err: MetaMaskProviderRpcError) => { clear() onDisconnectCallback.value && onDisconnectCallback.value(err.message) }, ) break case 'walletconnect': // Q: why it trigger twice when user click disconnect? // source code: https://github.com/WalletConnect/walletconnect-monorepo/blob/0871582be273f8c21bb1351315d649ea47ee70b7/packages/providers/web3-provider/src/index.ts#L277 ;(provider.value as WalletConnectProvider).on( 'disconnect', (code: number, reason: string) => { clear() onDisconnectCallback.value && onDisconnectCallback.value(`${code}: ${reason}`) }, ) break case 'walletlink': ;(provider.value as WalletLinkProvider).on( 'disconnect', (err: WalletLinkProviderRpcError) => { clear() onDisconnectCallback.value && onDisconnectCallback.value(err.message) }, ) break } } function subscribeAccountsChanged() { switch (walletName.value) { case 'metamask': ;(provider.value as MetaMaskProvider).on( 'accountsChanged', async (accounts: string[]) => { try { options.library === 'ethers' && (await activate(provider.value as WalletProvider)) onAccountsChangedCallback.value && onAccountsChangedCallback.value(accounts) } catch (err: any) { error.value = `Failed when changing account: ${err.message}` return } }, ) break case 'walletconnect': ;(provider.value as WalletConnectProvider).on( 'accountsChanged', async (accounts: string[]) => { try { options.library === 'ethers' && (await activate(provider.value as WalletProvider)) onAccountsChangedCallback.value && onAccountsChangedCallback.value(accounts) } catch (err: any) { error.value = `Failed when changing account: ${err.message}` return } }, ) break case 'walletlink': ;(provider.value as WalletLinkProvider).on( 'accountsChanged', async (accounts: string[]) => { try { options.library === 'ethers' && (await activate(provider.value as WalletProvider)) onAccountsChangedCallback.value && onAccountsChangedCallback.value(accounts) } catch (err: any) { error.value = `Failed when changing account: ${err.message}` return } }, ) break } } function subscribeChainChanged() { switch (walletName.value) { case 'metamask': ;(provider.value as MetaMaskProvider).on( 'chainChanged', async (hexChainId: string) => { // Changing network might lead to disconnect so the provider would be deleted. if (!provider.value) { error.value = `Failed when changing chain: missing provider` return } try { const chainId = parseInt(hexChainId, 16) options.library === 'ethers' && (await activate(provider.value as WalletProvider)) onChainChangedCallback.value && onChainChangedCallback.value(chainId) } catch (err: any) { error.value = `Failed when changing chain: ${err.message}` return } }, ) break case 'walletconnect': ;(provider.value as WalletConnectProvider).on( 'chainChanged', async (chainId: number) => { // Changing network might lead to disconnect so the provider would be deleted. if (!provider.value) { error.value = `Failed when changing chain: missing provider` return } try { options.library === 'ethers' && (await activate(provider.value as WalletProvider)) onChainChangedCallback.value && onChainChangedCallback.value(chainId) } catch (err: any) { error.value = `Failed when changing chain: ${err.message}` return } }, ) break case 'walletlink': ;(provider.value as WalletLinkProvider).on( 'chainChanged', async (hexChainId: string) => { // Changing network might lead to disconnect so the provider would be deleted. if (!provider.value) { error.value = `Failed when changing chain: missing provider` return } try { const chainId = parseInt(hexChainId, 16) options.library === 'ethers' && (await activate(provider.value as WalletProvider)) onChainChangedCallback.value && onChainChangedCallback.value(chainId) } catch (err: any) { error.value = `Failed when changing chain: ${err.message}` return } }, ) break } } // ========================= callback ========================= function onDisconnect(callback: OnDisconnectCallback) { onDisconnectCallback.value = callback } function onAccountsChanged(callback: OnAccountsChangedCallback) { onAccountsChangedCallback.value = callback } function onChainChanged(callback: OnChainChangedCallback) { onChainChangedCallback.value = callback } // ========================= getters ========================= const isConnected = computed(() => { if (status.value === 'connected') return true else return false }) return { // state provider: provider as Ref<WalletProvider | null>, status, walletName, error, // getters isConnected, // methods connect, disconnect, // callback onDisconnect, onAccountsChanged, onChainChanged, } }
the_stack
import { BiString, Alignment } from ".."; test("new BiString", () => { expect(() => new BiString(42 as any)).toThrow(TypeError); expect(() => new BiString("fourty-two", 42 as any)).toThrow(TypeError); expect(() => new BiString("fourty-two", "42", 42 as any)).toThrow(TypeError); expect(() => new BiString("fourty-two", "42", new Alignment([ [0, 0], [9, 2], ]))) .toThrow(RangeError); expect(() => new BiString("fourty-two", "42", new Alignment([ [0, 0], [10, 1], ]))) .toThrow(RangeError); new BiString("42"); new BiString("fourty-two", "42"); new BiString("fourty-two", "42", new Alignment([ [0, 0], [6, 1], [7, 1], [10, 2], ])); }); test("BiString.infer", () => { let bs = BiString.infer("test", "test"); expect(bs.equals(new BiString("test"))).toBe(true); bs = BiString.infer("color", "colour"); expect(bs.substring(3, 5).original).toBe("o"); expect(bs.inverse().equals(BiString.infer("colour", "color"))).toBe(true); bs = BiString.infer( "🅃🄷🄴 🅀🅄🄸🄲🄺, 🄱🅁🄾🅆🄽 🦊 🄹🅄🄼🄿🅂 🄾🅅🄴🅁 🅃🄷🄴 🄻🄰🅉🅈 🐶", "the quick brown fox jumps over the lazy dog", ); expect(bs.substring(0, 3).original).toBe("🅃🄷🄴"); expect(bs.substring(0, 3).modified).toBe("the"); expect(bs.substring(4, 9).original).toBe("🅀🅄🄸🄲🄺"); expect(bs.substring(4, 9).modified).toBe("quick"); expect(bs.substring(10, 15).original).toBe("🄱🅁🄾🅆🄽"); expect(bs.substring(10, 15).modified).toBe("brown"); expect(bs.substring(16, 19).original).toBe("🦊"); expect(bs.substring(16, 19).modified).toBe("fox"); expect(bs.substring(20, 25).original).toBe("🄹🅄🄼🄿🅂"); expect(bs.substring(20, 25).modified).toBe("jumps"); expect(bs.substring(40, 43).original).toBe("🐶"); expect(bs.substring(40, 43).modified).toBe("dog"); bs = BiString.infer( "Ṫḧë qüïċḳ, ḅṛöẅṅ 🦊 jüṁṗṡ öṿëṛ ẗḧë ḷäżÿ 🐶", "the quick brown fox jumps over the lazy dog", ); expect(bs.substring(0, 3).equals(new BiString("Ṫḧë", "the", Alignment.identity(3)))).toBe(true); expect(bs.substring(4, 9).equals(new BiString("qüïċḳ", "quick", Alignment.identity(5)))).toBe(true); expect(bs.substring(10, 15).equals(new BiString("ḅṛöẅṅ", "brown", Alignment.identity(5)))).toBe(true); expect(bs.substring(16, 19).original).toBe("🦊"); expect(bs.substring(16, 19).modified).toBe("fox"); expect(bs.substring(20, 25).equals(new BiString("jüṁṗṡ", "jumps", Alignment.identity(5)))).toBe(true); expect(bs.substring(40, 43).original).toBe("🐶"); expect(bs.substring(40, 43).modified).toBe("dog"); bs = BiString.infer("Z̴̡̪̫̖̥̔̿̃̈̏̎͠͝á̸̪̠̖̻̬̖̪̞͙͇̮̠͎̆͋́̐͌̒͆̓l̶͉̭̳̤̬̮̩͎̟̯̜͇̥̠̘͑͐̌͂̄́̀̂̌̈͛̊̄̚͜ģ̸̬̼̞̙͇͕͎̌̾̒̐̿̎̆̿̌̃̏̌́̾̈͘͜o̶̢̭͕͔̩͐ ̴̡̡̜̥̗͔̘̦͉̣̲͚͙̐̈́t̵͈̰̉̀͒̎̈̿̔̄̽͑͝͠ẹ̵̫̲̫̄͜͜x̵͕̳͈̝̤̭̼̼̻͓̿̌̽̂̆̀̀̍̒͐́̈̀̚͝t̸̡̨̥̺̣̟͎̝̬̘̪͔͆́̄̅̚", "Zalgo text"); for (let i = 0; i < bs.length; ++i) { expect(bs.substring(i, i + 1).original.startsWith(bs[i])).toBe(true); } expect(BiString.infer("", "").equals(new BiString(""))).toBe(true); expect(BiString.infer("a", "").equals(new BiString("a", ""))).toBe(true); expect(BiString.infer("", "a").equals(new BiString("", "a"))).toBe(true); }); test("BiString.concat", () => { let bs = new BiString(" ", "").concat( "Hello", new BiString(" ", " "), "world!", new BiString(" ", ""), ); expect(bs.original).toBe(" Hello world! "); expect(bs.modified).toBe("Hello world!"); bs = bs.substring(4, 7); expect(bs.original).toBe("o w"); expect(bs.modified).toBe("o w"); bs = bs.substring(1, 2); expect(bs.original).toBe(" "); expect(bs.modified).toBe(" "); }); test("BiString.indexOf", () => { const bs = new BiString("dysfunction"); expect(bs.indexOf("dis")).toBe(-1); expect(bs.indexOf("fun")).toBe(3); expect(bs.indexOf("n")).toBe(5); expect(bs.indexOf("n", 6)).toBe(10); expect(bs.indexOf("n", 11)).toBe(-1); expect(bs.boundsOf("dis")).toEqual([-1, -1]); expect(bs.boundsOf("fun")).toEqual([3, 6]); expect(bs.boundsOf("n")).toEqual([5, 6]); expect(bs.boundsOf("n", 6)).toEqual([10, 11]); expect(bs.boundsOf("n", 11)).toEqual([-1, -1]); }); test("BiString.lastIndexOf", () => { const bs = new BiString("dysfunction"); expect(bs.lastIndexOf("dis")).toBe(-1); expect(bs.lastIndexOf("fun")).toBe(3); expect(bs.lastIndexOf("n")).toBe(10); expect(bs.lastIndexOf("n", 9)).toBe(5); expect(bs.lastIndexOf("n", 4)).toBe(-1); expect(bs.lastBoundsOf("dis")).toEqual([-1, -1]); expect(bs.lastBoundsOf("fun")).toEqual([3, 6]); expect(bs.lastBoundsOf("n")).toEqual([10, 11]); expect(bs.lastBoundsOf("n", 9)).toEqual([5, 6]); expect(bs.lastBoundsOf("n", 4)).toEqual([-1, -1]); }); test("BiString.{starts,ends}With", () => { const bs = new BiString("Beginning, middle, ending"); expect(bs.startsWith("Begin")).toBe(true); expect(bs.endsWith("ing")).toBe(true); expect(bs.startsWith("ending")).toBe(false); expect(bs.endsWith("Beginning")).toBe(false); }); test("BiString.pad*", () => { const bs = new BiString("Hello world!"); expect(bs.padStart(5).equals(bs)).toBe(true); expect(bs.padEnd(5).equals(bs)).toBe(true); let pad = new BiString("", " "); expect(bs.padStart(16).equals(pad.concat(bs))).toBe(true); expect(bs.padEnd(16).equals(bs.concat(pad))).toBe(true); }); test("BiString.split", () => { let bs = new BiString("The quick, brown fox jumps over the lazy dog"); expect(bs.split()).toEqual([bs]); expect(bs.split("").map(s => s.modified)).toEqual(bs.modified.split("")); expect(bs.split(" ").map(s => s.modified)).toEqual(bs.modified.split(" ")); expect(bs.split(/ /).map(s => s.modified)).toEqual(bs.modified.split(/ /)); expect(bs.split(/ /y).map(s => s.modified)).toEqual(bs.modified.split(/ /y)); expect(bs.split("", 0).map(s => s.modified)).toEqual(bs.modified.split("", 0)); expect(bs.split(" ", 0).map(s => s.modified)).toEqual(bs.modified.split(" ", 0)); expect(bs.split(/ /, 0).map(s => s.modified)).toEqual(bs.modified.split(/ /, 0)); expect(bs.split("", 3).map(s => s.modified)).toEqual(bs.modified.split("", 3)); expect(bs.split(" ", 3).map(s => s.modified)).toEqual(bs.modified.split(" ", 3)); expect(bs.split(/ /, 3).map(s => s.modified)).toEqual(bs.modified.split(/ /, 3)); expect(bs.split("", 20).map(s => s.modified)).toEqual(bs.modified.split("", 20)); expect(bs.split(" ", 20).map(s => s.modified)).toEqual(bs.modified.split(" ", 20)); expect(bs.split(/ /, 20).map(s => s.modified)).toEqual(bs.modified.split(/ /, 20)); bs = new BiString(" The quick, brown fox"); expect(bs.split(" ").map(s => s.modified)).toEqual(bs.modified.split(" ")); expect(bs.split(/ /).map(s => s.modified)).toEqual(bs.modified.split(/ /)); bs = new BiString("The quick, brown fox "); expect(bs.split(" ").map(s => s.modified)).toEqual(bs.modified.split(" ")); expect(bs.split(/ /).map(s => s.modified)).toEqual(bs.modified.split(/ /)); bs = new BiString(" The quick, brown fox "); expect(bs.split(" ").map(s => s.modified)).toEqual(bs.modified.split(" ")); expect(bs.split(/ /).map(s => s.modified)).toEqual(bs.modified.split(/ /)); }); test("BiString.join", () => { const sep = new BiString(" ", ", "); const chunks = new BiString("The quick brown fox").split(" "); const bs = sep.join(chunks); expect(bs.original).toBe("The quick brown fox"); expect(bs.modified).toBe("The, quick, brown, fox"); }); test("BiString.trim{,Start,End}", () => { let bs = new BiString(" Hello world! "); expect(bs.trim().modified).toBe("Hello world!"); expect(bs.trimStart().modified).toBe("Hello world! "); expect(bs.trimEnd().modified).toBe(" Hello world!"); bs = new BiString(" "); expect(bs.trim().modified).toBe(""); expect(bs.trimStart().modified).toBe(""); expect(bs.trimEnd().modified).toBe(""); }); test("BiString.normalize", () => { // "Héllö" -- é is composed but ö has a combining diaeresis let bs = new BiString("H\u00E9llo\u0308").normalize("NFC"); expect(bs.original).toBe("H\u00E9llo\u0308"); expect(bs.modified).toBe("H\u00E9ll\u00F6"); expect(bs.modified).toBe(bs.original.normalize("NFC")); expect(bs.slice(1, 2).equals(new BiString("\u00E9"))).toBe(true); expect(bs.slice(4, 5).equals(new BiString("o\u0308", "\u00F6"))).toBe(true); bs = new BiString("H\u00E9llo\u0308").normalize("NFD"); expect(bs.original).toBe("H\u00E9llo\u0308"); expect(bs.modified).toBe("He\u0301llo\u0308"); expect(bs.modified).toBe(bs.original.normalize("NFD")); expect(bs.slice(1, 3).equals(new BiString("\u00E9", "e\u0301"))).toBe(true); expect(bs.slice(5, 7).original).toBe("o\u0308"); expect(bs.slice(5, 7).modified).toBe("o\u0308"); expect(bs.slice(5, 7).equals(new BiString("o\u0308"))).toBe(true); }); test("BiString.toLowerCase", () => { let bs = new BiString("Hello World").toLowerCase(); let expected = new BiString("Hello World", "hello world", Alignment.identity(11)); expect(bs.equals(expected)).toBe(true); // Odysseus bs = new BiString("ὈΔΥΣΣΕΎΣ").toLowerCase(); expected = new BiString("ὈΔΥΣΣΕΎΣ", "ὀδυσσεύς", Alignment.identity(8)); expect(bs.equals(expected)).toBe(true); // Examples from The Unicode Standard, Version 12.0, Chapter 3.13 bs = new BiString("ᾼΣͅ").toLowerCase(); expected = new BiString("ᾼΣͅ", "ᾳςͅ", Alignment.identity(4)); expect(bs.equals(expected)).toBe(true); bs = new BiString("ͅΣͅ").toLowerCase(); expected = new BiString("ͅΣͅ", "ͅσͅ", Alignment.identity(3)); expect(bs.equals(expected)).toBe(true); bs = new BiString("ᾼΣᾼ").toLowerCase(); expected = new BiString("ᾼΣᾼ", "ᾳσᾳ", Alignment.identity(5)); expect(bs.equals(expected)).toBe(true); bs = new BiString("Σ").toLowerCase(); expected = new BiString("Σ", "σ"); expect(bs.equals(expected)).toBe(true); }); test("BiString.toUpperCase", () => { let bs = new BiString("Hello World").toUpperCase(); let expected = new BiString("Hello World", "HELLO WORLD", Alignment.identity(11)); expect(bs.equals(expected)).toBe(true); bs = new BiString("straße").toUpperCase(); expected = new BiString("stra", "STRA", Alignment.identity(4)).concat( new BiString("ß", "SS"), new BiString("e", "E"), ); expect(bs.equals(expected)).toBe(true); // Odysseus bs = new BiString("Ὀδυσσεύς").toUpperCase(); expected = new BiString("Ὀδυσσεύς", "ὈΔΥΣΣΕΎΣ", Alignment.identity(8)); expect(bs.equals(expected)).toBe(true); }); test("README", () => { let bs = new BiString("𝕿𝖍𝖊 𝖖𝖚𝖎𝖈𝖐, 𝖇𝖗𝖔𝖜𝖓 🦊 𝖏𝖚𝖒𝖕𝖘 𝖔𝖛𝖊𝖗 𝖙𝖍𝖊 𝖑𝖆𝖟𝖞 🐶"); bs = bs.normalize("NFKD"); bs = bs.toLowerCase(); bs = bs.replace("🦊", "fox") bs = bs.replace("🐶", "dog") bs = bs.replace(/[^\w\s]+/g, ""); bs = bs.slice(0, 19); expect(bs.modified).toBe("the quick brown fox"); expect(bs.original).toBe("𝕿𝖍𝖊 𝖖𝖚𝖎𝖈𝖐, 𝖇𝖗𝖔𝖜𝖓 🦊"); });
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { HybridConnections } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { RelayAPI } from "../relayAPI"; import { HybridConnection, HybridConnectionsListByNamespaceNextOptionalParams, HybridConnectionsListByNamespaceOptionalParams, AuthorizationRule, HybridConnectionsListAuthorizationRulesNextOptionalParams, HybridConnectionsListAuthorizationRulesOptionalParams, HybridConnectionsListByNamespaceResponse, HybridConnectionsCreateOrUpdateOptionalParams, HybridConnectionsCreateOrUpdateResponse, HybridConnectionsDeleteOptionalParams, HybridConnectionsGetOptionalParams, HybridConnectionsGetResponse, HybridConnectionsListAuthorizationRulesResponse, HybridConnectionsCreateOrUpdateAuthorizationRuleOptionalParams, HybridConnectionsCreateOrUpdateAuthorizationRuleResponse, HybridConnectionsDeleteAuthorizationRuleOptionalParams, HybridConnectionsGetAuthorizationRuleOptionalParams, HybridConnectionsGetAuthorizationRuleResponse, HybridConnectionsListKeysOptionalParams, HybridConnectionsListKeysResponse, RegenerateAccessKeyParameters, HybridConnectionsRegenerateKeysOptionalParams, HybridConnectionsRegenerateKeysResponse, HybridConnectionsListByNamespaceNextResponse, HybridConnectionsListAuthorizationRulesNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing HybridConnections operations. */ export class HybridConnectionsImpl implements HybridConnections { private readonly client: RelayAPI; /** * Initialize a new instance of the class HybridConnections class. * @param client Reference to the service client */ constructor(client: RelayAPI) { this.client = client; } /** * Lists the hybrid connection within the namespace. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param options The options parameters. */ public listByNamespace( resourceGroupName: string, namespaceName: string, options?: HybridConnectionsListByNamespaceOptionalParams ): PagedAsyncIterableIterator<HybridConnection> { const iter = this.listByNamespacePagingAll( resourceGroupName, namespaceName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByNamespacePagingPage( resourceGroupName, namespaceName, options ); } }; } private async *listByNamespacePagingPage( resourceGroupName: string, namespaceName: string, options?: HybridConnectionsListByNamespaceOptionalParams ): AsyncIterableIterator<HybridConnection[]> { let result = await this._listByNamespace( resourceGroupName, namespaceName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByNamespaceNext( resourceGroupName, namespaceName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByNamespacePagingAll( resourceGroupName: string, namespaceName: string, options?: HybridConnectionsListByNamespaceOptionalParams ): AsyncIterableIterator<HybridConnection> { for await (const page of this.listByNamespacePagingPage( resourceGroupName, namespaceName, options )) { yield* page; } } /** * Authorization rules for a hybrid connection. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param hybridConnectionName The hybrid connection name. * @param options The options parameters. */ public listAuthorizationRules( resourceGroupName: string, namespaceName: string, hybridConnectionName: string, options?: HybridConnectionsListAuthorizationRulesOptionalParams ): PagedAsyncIterableIterator<AuthorizationRule> { const iter = this.listAuthorizationRulesPagingAll( resourceGroupName, namespaceName, hybridConnectionName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listAuthorizationRulesPagingPage( resourceGroupName, namespaceName, hybridConnectionName, options ); } }; } private async *listAuthorizationRulesPagingPage( resourceGroupName: string, namespaceName: string, hybridConnectionName: string, options?: HybridConnectionsListAuthorizationRulesOptionalParams ): AsyncIterableIterator<AuthorizationRule[]> { let result = await this._listAuthorizationRules( resourceGroupName, namespaceName, hybridConnectionName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listAuthorizationRulesNext( resourceGroupName, namespaceName, hybridConnectionName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listAuthorizationRulesPagingAll( resourceGroupName: string, namespaceName: string, hybridConnectionName: string, options?: HybridConnectionsListAuthorizationRulesOptionalParams ): AsyncIterableIterator<AuthorizationRule> { for await (const page of this.listAuthorizationRulesPagingPage( resourceGroupName, namespaceName, hybridConnectionName, options )) { yield* page; } } /** * Lists the hybrid connection within the namespace. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param options The options parameters. */ private _listByNamespace( resourceGroupName: string, namespaceName: string, options?: HybridConnectionsListByNamespaceOptionalParams ): Promise<HybridConnectionsListByNamespaceResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, options }, listByNamespaceOperationSpec ); } /** * Creates or updates a service hybrid connection. This operation is idempotent. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param hybridConnectionName The hybrid connection name. * @param parameters Parameters supplied to create a hybrid connection. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, namespaceName: string, hybridConnectionName: string, parameters: HybridConnection, options?: HybridConnectionsCreateOrUpdateOptionalParams ): Promise<HybridConnectionsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, hybridConnectionName, parameters, options }, createOrUpdateOperationSpec ); } /** * Deletes a hybrid connection. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param hybridConnectionName The hybrid connection name. * @param options The options parameters. */ delete( resourceGroupName: string, namespaceName: string, hybridConnectionName: string, options?: HybridConnectionsDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, hybridConnectionName, options }, deleteOperationSpec ); } /** * Returns the description for the specified hybrid connection. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param hybridConnectionName The hybrid connection name. * @param options The options parameters. */ get( resourceGroupName: string, namespaceName: string, hybridConnectionName: string, options?: HybridConnectionsGetOptionalParams ): Promise<HybridConnectionsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, hybridConnectionName, options }, getOperationSpec ); } /** * Authorization rules for a hybrid connection. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param hybridConnectionName The hybrid connection name. * @param options The options parameters. */ private _listAuthorizationRules( resourceGroupName: string, namespaceName: string, hybridConnectionName: string, options?: HybridConnectionsListAuthorizationRulesOptionalParams ): Promise<HybridConnectionsListAuthorizationRulesResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, hybridConnectionName, options }, listAuthorizationRulesOperationSpec ); } /** * Creates or updates an authorization rule for a hybrid connection. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param hybridConnectionName The hybrid connection name. * @param authorizationRuleName The authorization rule name. * @param parameters The authorization rule parameters. * @param options The options parameters. */ createOrUpdateAuthorizationRule( resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, parameters: AuthorizationRule, options?: HybridConnectionsCreateOrUpdateAuthorizationRuleOptionalParams ): Promise<HybridConnectionsCreateOrUpdateAuthorizationRuleResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, hybridConnectionName, authorizationRuleName, parameters, options }, createOrUpdateAuthorizationRuleOperationSpec ); } /** * Deletes a hybrid connection authorization rule. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param hybridConnectionName The hybrid connection name. * @param authorizationRuleName The authorization rule name. * @param options The options parameters. */ deleteAuthorizationRule( resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, options?: HybridConnectionsDeleteAuthorizationRuleOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, hybridConnectionName, authorizationRuleName, options }, deleteAuthorizationRuleOperationSpec ); } /** * Hybrid connection authorization rule for a hybrid connection by name. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param hybridConnectionName The hybrid connection name. * @param authorizationRuleName The authorization rule name. * @param options The options parameters. */ getAuthorizationRule( resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, options?: HybridConnectionsGetAuthorizationRuleOptionalParams ): Promise<HybridConnectionsGetAuthorizationRuleResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, hybridConnectionName, authorizationRuleName, options }, getAuthorizationRuleOperationSpec ); } /** * Primary and secondary connection strings to the hybrid connection. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param hybridConnectionName The hybrid connection name. * @param authorizationRuleName The authorization rule name. * @param options The options parameters. */ listKeys( resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, options?: HybridConnectionsListKeysOptionalParams ): Promise<HybridConnectionsListKeysResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, hybridConnectionName, authorizationRuleName, options }, listKeysOperationSpec ); } /** * Regenerates the primary or secondary connection strings to the hybrid connection. * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param hybridConnectionName The hybrid connection name. * @param authorizationRuleName The authorization rule name. * @param parameters Parameters supplied to regenerate authorization rule. * @param options The options parameters. */ regenerateKeys( resourceGroupName: string, namespaceName: string, hybridConnectionName: string, authorizationRuleName: string, parameters: RegenerateAccessKeyParameters, options?: HybridConnectionsRegenerateKeysOptionalParams ): Promise<HybridConnectionsRegenerateKeysResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, hybridConnectionName, authorizationRuleName, parameters, options }, regenerateKeysOperationSpec ); } /** * ListByNamespaceNext * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param nextLink The nextLink from the previous successful call to the ListByNamespace method. * @param options The options parameters. */ private _listByNamespaceNext( resourceGroupName: string, namespaceName: string, nextLink: string, options?: HybridConnectionsListByNamespaceNextOptionalParams ): Promise<HybridConnectionsListByNamespaceNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, nextLink, options }, listByNamespaceNextOperationSpec ); } /** * ListAuthorizationRulesNext * @param resourceGroupName Name of the Resource group within the Azure subscription. * @param namespaceName The namespace name * @param hybridConnectionName The hybrid connection name. * @param nextLink The nextLink from the previous successful call to the ListAuthorizationRules method. * @param options The options parameters. */ private _listAuthorizationRulesNext( resourceGroupName: string, namespaceName: string, hybridConnectionName: string, nextLink: string, options?: HybridConnectionsListAuthorizationRulesNextOptionalParams ): Promise<HybridConnectionsListAuthorizationRulesNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, namespaceName, hybridConnectionName, nextLink, options }, listAuthorizationRulesNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listByNamespaceOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.HybridConnectionListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.HybridConnection }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters5, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.hybridConnectionName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.hybridConnectionName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.HybridConnection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.hybridConnectionName ], headerParameters: [Parameters.accept], serializer }; const listAuthorizationRulesOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AuthorizationRuleListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.hybridConnectionName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateAuthorizationRuleOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.AuthorizationRule }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters3, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.authorizationRuleName, Parameters.hybridConnectionName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteAuthorizationRuleOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.authorizationRuleName, Parameters.hybridConnectionName ], headerParameters: [Parameters.accept], serializer }; const getAuthorizationRuleOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AuthorizationRule }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.authorizationRuleName, Parameters.hybridConnectionName ], headerParameters: [Parameters.accept], serializer }; const listKeysOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}/listKeys", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.AccessKeys }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.authorizationRuleName, Parameters.hybridConnectionName ], headerParameters: [Parameters.accept], serializer }; const regenerateKeysOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}/regenerateKeys", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.AccessKeys }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.parameters4, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.authorizationRuleName, Parameters.hybridConnectionName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listByNamespaceNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.HybridConnectionListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName ], headerParameters: [Parameters.accept], serializer }; const listAuthorizationRulesNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AuthorizationRuleListResult }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.namespaceName, Parameters.hybridConnectionName ], headerParameters: [Parameters.accept], serializer };
the_stack
import * as path from 'path'; import * as fs from 'mz/fs'; import {expect} from 'chai'; import './support'; import BuildMonitor from '../src/build-monitor'; import {Observable, Subscription, Subject, Observer} from 'rxjs'; import {TestScheduler} from '@kwonoj/rxjs-testscheduler-compat'; import '../src/custom-rx-operators'; // tslint:disable-next-line:no-var-requires const d = require('debug')('surf-test:build-monitor'); function getSeenRefs(refs: [any]) { return refs.reduce((acc, x) => { acc.add(x.object.sha); return acc; }, new Set<string>()); } describe('the build monitor', function() { beforeEach(async function() { let acc = {}; let fixturesDir = path.join(__dirname, '..', 'fixtures'); for (let name of await fs.readdir(fixturesDir)) { if (!name.match(/^refs.*\.json$/i)) continue; let contents = await fs.readFile(path.join(fixturesDir, name), 'utf8'); acc[name] = JSON.parse(contents.split('\n')[0]); } this.refExamples = acc; this.sched = new TestScheduler(); this.fixture = new BuildMonitor([], '', 2, () => Observable.throw(new Error('no')), undefined, this.sched); }); afterEach(function() { this.fixture.unsubscribe(); }); it('shouldnt run builds in getOrCreateBuild until you subscribe', function() { let buildCount = 0; let runBuildCount = 0; // Scheduling is live this.sched.advanceBy(1000); let buildSubject = new Subject(); this.fixture.runBuild = () => { runBuildCount++; return buildSubject.subUnsub(() => buildCount++); }; d('Initial getOrCreateBuild'); let ref = this.refExamples['refs1.json'][1]; let result = this.fixture.getOrCreateBuild(ref); this.sched.advanceBy(1000); expect(buildCount).to.equal(0); expect(runBuildCount).to.equal(1); d('Subscribing 1x'); result.observable.subscribe(); this.sched.advanceBy(1000); expect(buildCount).to.equal(1); // Double subscribes do nothing d('Subscribing 2x'); result.observable.subscribe(); this.sched.advanceBy(1000); expect(buildCount).to.equal(1); d('Second getOrCreateBuild'); result = this.fixture.getOrCreateBuild(ref); result.observable.subscribe(); this.sched.advanceBy(1000); expect(buildCount).to.equal(1); expect(runBuildCount).to.equal(1); d('Complete the build'); buildSubject.next(''); buildSubject.complete(); d('Third getOrCreateBuild'); result = this.fixture.getOrCreateBuild(ref); result.observable.subscribe(); this.sched.advanceBy(1000); expect(buildCount).to.equal(2); expect(runBuildCount).to.equal(2); }); it('should decide to build new refs from a blank slate', function() { this.fixture.fetchRefs = () => Observable.of(this.refExamples['refs1.json']); let buildCount = 0; this.fixture.runBuild = () => { buildCount++; return Observable.of(''); }; this.fixture.start(); expect(buildCount).to.equal(0); this.sched.advanceBy(30 * 1000); expect(buildCount).to.equal(10); }); it('should decide to build only changed refs', function() { this.fixture.fetchRefs = () => Observable.of(this.refExamples['refs1.json']); let buildCount = 0; this.fixture.runBuild = (ref: any) => { buildCount++; return Observable.of('') .subUnsub(() => d(`Building ${ref.object.sha}`)); }; this.fixture.start(); expect(buildCount).to.equal(0); this.sched.advanceBy(this.fixture.pollInterval + 1000); expect(buildCount).to.equal(10); this.fixture.fetchRefs = () => Observable.of(this.refExamples['refs2.json']); // Move to the next interval, we should only run the one build this.sched.advanceBy(this.fixture.pollInterval); expect(buildCount).to.equal(11); }); it('should only build at a max level of concurrency', function() { let liveBuilds = 0; let completedBuilds = 0; let completedShas = new Set(); this.fixture.runBuild = (ref: any) => { return Observable.of('') .do(() => { if (completedShas.has(ref.object.sha)) d(`Double building! ${ref.object.sha}`); liveBuilds++; d(`Starting build: ${ref.object.sha}`); }) .delay(2 * 1000, this.sched) .do(() => {}, () => {}, () => { liveBuilds--; completedBuilds++; completedShas.add(ref.object.sha); d(`Completing build: ${ref.object.sha}`); }) .publish() .refCount(); }; this.fixture.fetchRefs = () => Observable.of(this.refExamples['refs1.json']); this.fixture.start(); this.sched.advanceBy(this.fixture.pollInterval + 2); expect(liveBuilds).to.equal(2); expect(completedBuilds).to.equal(0); this.sched.advanceBy(this.fixture.pollInterval); expect(liveBuilds).to.equal(2); expect(completedBuilds).to.equal(4); // two builds per 2sec, for 5sec this.sched.advanceBy(30 * 1000); expect(liveBuilds).to.equal(0); expect(completedBuilds).to.equal(10); }); it('shouldnt cancel any builds when we only look at one set of refs', function() { let liveBuilds = 0; let cancelledRefs = new Array<string>(); this.fixture.runBuild = (ref: any) => { let ret = Observable.of('') .do(() => { liveBuilds++; d(`Starting build: ${ref.object.sha}`); }) .delay(2 * 1000, this.sched) .do(() => {}, () => {}, () => { liveBuilds--; d(`Completing build: ${ref.object.sha}`); }) .publish() .refCount(); return Observable.create((subj: Observer<string|{}>) => { let producedItem = false; let disp = ret .do(() => producedItem = true) .subscribe(subj); return new Subscription(() => { disp.unsubscribe(); if (producedItem) return; d(`Canceled ref before it finished! ${ref.object.sha}`); liveBuilds--; cancelledRefs.push(ref.object.sha); }); }); }; this.fixture.fetchRefs = () => Observable.of(this.refExamples['refs1.json']); this.fixture.start(); this.sched.advanceBy(this.fixture.pollInterval + 1000); expect(liveBuilds).to.equal(2); this.sched.advanceBy(1000); expect(liveBuilds).to.equal(2); this.sched.advanceBy(30 * 1000); expect(liveBuilds).to.equal(0); expect(cancelledRefs.length).to.equal(0); }); it.skip('should cancel builds when their refs disappear', function() { let liveBuilds = 0; let cancelledRefs = new Array<string>(); this.fixture.runBuild = (ref: any) => { let ret = Observable.of('') .do(() => { liveBuilds++; d(`Starting build: ${ref.object.sha}`); }) .delay(10 * this.fixture.pollInterval, this.sched) .do(() => {}, () => {}, () => { liveBuilds--; d(`Completing build: ${ref.object.sha}`); }) .publish() .refCount(); return Observable.create((subj: Observer<string|{}>) => { let producedItem = false; let disp = ret .do(() => producedItem = true) .subscribe(subj); return new Subscription(() => { disp.unsubscribe(); if (producedItem) return; d(`Canceled ref before it finished! ${ref.object.sha}`); liveBuilds--; cancelledRefs.push(ref.object.sha); }); }); }; this.fixture.seenCommits = getSeenRefs(this.refExamples['refs1.json']); this.fixture.fetchRefs = () => Observable.of(this.refExamples['refs3.json']); this.fixture.start(); this.sched.advanceBy(this.fixture.pollInterval + 1000); expect(liveBuilds).to.equal(2); this.fixture.fetchRefs = () => Observable.of(this.refExamples['refs4.json']); this.sched.advanceBy(this.fixture.pollInterval + 1000); expect(liveBuilds).to.equal(1); }); it('should cancel builds when their refs change', function() { let liveBuilds = 0; let cancelledRefs = new Array<string>(); this.fixture.runBuild = (ref: any) => { let ret = Observable.of('') .do(() => { liveBuilds++; d(`Starting build: ${ref.object.sha}`); }) .delay(10 * 1000, this.sched) .do(() => {}, () => {}, () => { liveBuilds--; d(`Completing build: ${ref.object.sha}`); }) .publish() .refCount(); return Observable.create((subj: Observer<string|{}>) => { let producedItem = false; let disp = ret .do(() => producedItem = true) .subscribe(subj); return new Subscription(() => { disp.unsubscribe(); if (producedItem) return; d(`Canceled ref before it finished! ${ref.object.sha}`); liveBuilds--; cancelledRefs.push(ref.object.sha); }); }); }; this.fixture.fetchRefs = () => Observable.of(this.refExamples['refs1.json']); this.fixture.start(); this.sched.advanceBy(this.fixture.pollInterval + 1000); expect(liveBuilds).to.equal(2); this.fixture.fetchRefs = () => Observable.of(this.refExamples['refs2.json']); this.sched.advanceBy(this.fixture.pollInterval + 1000); expect(liveBuilds).to.equal(2); }); it('shouldnt die when builds fail', function() { this.fixture.runBuild = () => Observable.throw(new Error('no')); this.fixture.fetchRefs = () => Observable.of(this.refExamples['refs1.json']); this.fixture.start(); this.sched.advanceBy(this.fixture.pollInterval + 1); let ranBuild = false; this.fixture.runBuild = () => { ranBuild = true; return Observable.of(''); }; this.fixture.fetchRefs = () => Observable.of(this.refExamples['refs2.json']); this.sched.advanceBy(this.fixture.pollInterval); expect(ranBuild).to.be.ok; }); });
the_stack
jest.mock('../../node_modules/twilio', () => { // because we don't do a traditional require of twilio but a "project require" we have to mock this differently. const actualTwilio = jest.requireActual('twilio'); const twilio: any = jest.genMockFromModule('twilio'); twilio['twiml'] = actualTwilio.twiml; return twilio; }); import '@twilio-labs/serverless-runtime-types'; import { Request as ExpressRequest, Response as ExpressResponse, } from 'express'; import type { UserAgent } from 'express-useragent'; import { Request as MockRequest } from 'jest-express/lib/request'; import { Response as MockResponse } from 'jest-express/lib/response'; import path from 'path'; import { twiml } from 'twilio'; import { Response } from '../../src/dev-runtime/internal/response'; import { constructContext, constructEvent, constructHeaders, constructGlobalScope, handleError, handleSuccess, isTwiml, } from '../../src/dev-runtime/route'; import { EnvironmentVariablesWithAuth, ServerConfig, } from '../../src/dev-runtime/types'; import { wrapErrorInHtml } from '../../src/dev-runtime/utils/error-html'; import { requireFromProject } from '../../src/dev-runtime/utils/requireFromProject'; import { cleanUpStackTrace } from '../../src/dev-runtime/utils/stack-trace/clean-up'; const { VoiceResponse, MessagingResponse, FaxResponse } = twiml; const mockResponse = new MockResponse() as unknown as ExpressResponse; mockResponse.type = jest.fn(() => mockResponse); function asExpressRequest(req: { query?: {}; body?: {}; rawHeaders?: string[]; cookies?: {}; }): ExpressRequest { return req as unknown as ExpressRequest; } describe('handleError function', () => { test('returns string error', () => { const mockRequest = new MockRequest() as unknown as ExpressRequest; mockRequest['useragent'] = { isDesktop: true, isMobile: false, } as UserAgent; handleError('string error', mockRequest, mockResponse); expect(mockResponse.status).toHaveBeenCalledWith(500); expect(mockResponse.send).toHaveBeenCalledWith('string error'); }); test('handles objects as error argument', () => { const mockRequest = new MockRequest() as unknown as ExpressRequest; mockRequest['useragent'] = { isDesktop: true, isMobile: false, } as UserAgent; handleError({ errorMessage: 'oh no' }, mockRequest, mockResponse); expect(mockResponse.status).toHaveBeenCalledWith(500); expect(mockResponse.send).toHaveBeenCalledWith({ errorMessage: 'oh no' }); }); test('wraps error object for desktop requests', () => { const mockRequest = new MockRequest() as unknown as ExpressRequest; mockRequest['useragent'] = { isDesktop: true, isMobile: false, } as UserAgent; const err = new Error('Failed to execute'); handleError(err, mockRequest, mockResponse); expect(mockResponse.status).toHaveBeenCalledWith(500); expect(mockResponse.send).toHaveBeenCalledWith(wrapErrorInHtml(err)); }); test('wraps error object for mobile requests', () => { const mockRequest = new MockRequest() as unknown as ExpressRequest; mockRequest['useragent'] = { isDesktop: false, isMobile: true, } as UserAgent; const err = new Error('Failed to execute'); handleError(err, mockRequest, mockResponse); expect(mockResponse.status).toHaveBeenCalledWith(500); expect(mockResponse.send).toHaveBeenCalledWith(wrapErrorInHtml(err)); }); test('returns string version of error for other requests', () => { const mockRequest = new MockRequest() as unknown as ExpressRequest; mockRequest['useragent'] = { isDesktop: false, isMobile: false, } as UserAgent; const err = new Error('Failed to execute'); const cleanedupError = cleanUpStackTrace(err); handleError(err, mockRequest, mockResponse); expect(mockResponse.status).toHaveBeenCalledWith(500); expect(mockResponse.send).toHaveBeenCalledWith({ message: 'Failed to execute', name: 'Error', stack: cleanedupError.stack, }); }); }); describe('constructEvent function', () => { test('merges query and body', () => { const event = constructEvent( asExpressRequest({ body: { Body: 'Hello', }, query: { index: 5, }, }) ); expect(event).toEqual({ Body: 'Hello', index: 5, request: { headers: {}, cookies: {} }, }); }); test('overrides query with body', () => { const event = constructEvent( asExpressRequest({ body: { Body: 'Bye', }, query: { Body: 'Hello', From: '+123456789', }, }) ); expect(event).toEqual({ Body: 'Bye', From: '+123456789', request: { headers: {}, cookies: {} }, }); }); test('does not override request', () => { const event = constructEvent( asExpressRequest({ body: { Body: 'Bye', }, query: { request: 'Hello', }, }) ); expect(event).toEqual({ Body: 'Bye', request: 'Hello', }); }); test('handles empty body', () => { const event = constructEvent( asExpressRequest({ body: {}, query: { Body: 'Hello', From: '+123456789', }, }) ); expect(event).toEqual({ Body: 'Hello', From: '+123456789', request: { headers: {}, cookies: {} }, }); }); test('handles empty query', () => { const event = constructEvent( asExpressRequest({ body: { Body: 'Hello', From: '+123456789', }, query: {}, }) ); expect(event).toEqual({ Body: 'Hello', From: '+123456789', request: { headers: {}, cookies: {} }, }); }); test('handles both empty', () => { const event = constructEvent( asExpressRequest({ body: {}, query: {}, }) ); expect(event).toEqual({ request: { headers: {}, cookies: {} } }); }); test('adds headers to request property', () => { const event = constructEvent( asExpressRequest({ body: {}, query: {}, rawHeaders: ['x-test', 'example'], }) ); expect(event).toEqual({ request: { headers: { 'x-test': 'example' }, cookies: {} }, }); }); test('adds cookies to request property', () => { const event = constructEvent( asExpressRequest({ body: {}, query: {}, rawHeaders: [], cookies: { flavour: 'choc chip' }, }) ); expect(event).toEqual({ request: { headers: {}, cookies: { flavour: 'choc chip' } }, }); }); }); describe('constructHeaders function', () => { test('handles undefined', () => { const headers = constructHeaders(); expect(headers).toEqual({}); }); test('handles an empty array', () => { const headers = constructHeaders([]); expect(headers).toEqual({}); }); test('it handles a single header value', () => { const headers = constructHeaders(['x-test', 'hello, world']); expect(headers).toEqual({ 'x-test': 'hello, world' }); }); test('it handles a duplicated header value', () => { const headers = constructHeaders([ 'x-test', 'hello, world', 'x-test', 'ahoy', ]); expect(headers).toEqual({ 'x-test': ['hello, world', 'ahoy'] }); }); test('it handles a duplicated header value multiple times', () => { const headers = constructHeaders([ 'x-test', 'hello, world', 'x-test', 'ahoy', 'x-test', 'third', ]); expect(headers).toEqual({ 'x-test': ['hello, world', 'ahoy', 'third'] }); }); test('it strips restricted headers', () => { const headers = constructHeaders([ 'x-test', 'hello, world', 'I-Twilio-Test', 'nope', ]); expect(headers).toEqual({ 'x-test': 'hello, world' }); }); test('it lowercases and combines header names', () => { const headers = constructHeaders([ 'X-Test', 'hello, world', 'X-test', 'ahoy', 'x-test', 'third', ]); expect(headers).toEqual({ 'x-test': ['hello, world', 'ahoy', 'third'], }); }); test("it doesn't pass on restricted headers", () => { const headers = constructHeaders([ 'I-Twilio-Example', 'example', 'I-T-Example', 'example', 'OT-Example', 'example', 'x-amz-example', 'example', 'via', 'example', 'Referer', 'example.com', 'transfer-encoding', 'example', 'proxy-authorization', 'example', 'proxy-authenticate', 'example', 'x-forwarded-example', 'example', 'x-real-ip', 'example', 'connection', 'example', 'proxy-connection', 'example', 'expect', 'example', 'trailer', 'example', 'upgrade', 'example', 'x-accel-example', 'example', 'x-actual-header', 'this works', ]); expect(headers).toEqual({ 'x-actual-header': 'this works', }); }); }); describe('isTwiml', () => { test('detects Voice TwiML correctly', () => { const twiml = new VoiceResponse(); expect(isTwiml(twiml)).toBeTruthy(); }); test('detects Messaging TwiML correctly', () => { const twiml = new MessagingResponse(); expect(isTwiml(twiml)).toBeTruthy(); }); test('detects Fax TwiML correctly', () => { const twiml = new FaxResponse(); expect(isTwiml(twiml)).toBeTruthy(); }); test('detects invalid object', () => { const notTwiml = new Date(); expect(isTwiml(notTwiml)).toBeFalsy(); const alsoNotTwiml = {}; expect(isTwiml(alsoNotTwiml)).toBeFalsy(); }); }); describe('constructContext function', () => { test('returns correct values', () => { const config = { url: 'http://localhost:8000', env: { ACCOUNT_SID: 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', AUTH_TOKEN: 'authauthauthauthauthauthauthauth', }, baseDir: path.resolve(__dirname, '../../'), } as ServerConfig; const context = constructContext(config, '/test'); expect(context.DOMAIN_NAME).toBe('localhost:8000'); expect(context.PATH).toBe('/test'); expect(context.ACCOUNT_SID).toBe('ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'); expect(context.AUTH_TOKEN).toBe('authauthauthauthauthauthauthauth'); expect(typeof context.getTwilioClient).toBe('function'); }); test('does not override existing PATH values', () => { const env: EnvironmentVariablesWithAuth = { ACCOUNT_SID: 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', AUTH_TOKEN: 'authauthauthauthauthauthauthauth', PATH: '/usr/bin:/bin', }; const config = { url: 'http://localhost:8000', env, baseDir: path.resolve(__dirname, '../../'), } as ServerConfig; const context = constructContext(config, '/test2'); expect(context.PATH).toBe('/usr/bin:/bin'); }); test('does not override existing DOMAIN_NAME values', () => { const env: EnvironmentVariablesWithAuth = { ACCOUNT_SID: 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', AUTH_TOKEN: 'authauthauthauthauthauthauthauth', DOMAIN_NAME: 'hello.world', }; const config = { url: 'http://localhost:8000', env, baseDir: path.resolve(__dirname, '../../'), } as ServerConfig; const context = constructContext(config, '/test2'); expect(context.DOMAIN_NAME).toBe('hello.world'); }); test('getTwilioClient calls twilio constructor', () => { const ACCOUNT_SID = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; const AUTH_TOKEN = 'authauthauthauthauthauthauthauth'; const config = { url: 'http://localhost:8000', env: { ACCOUNT_SID, AUTH_TOKEN }, baseDir: path.resolve(__dirname, '../../'), } as ServerConfig; const context = constructContext(config, '/test'); const twilioFn = requireFromProject(config.baseDir, 'twilio'); context.getTwilioClient(); expect(twilioFn).toHaveBeenCalledWith( 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'authauthauthauthauthauthauthauth', { lazyLoading: true } ); }); }); describe('constructGlobalScope function', () => { const ACCOUNT_SID = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; const AUTH_TOKEN = 'authauthauthauthauthauthauthauth'; let config: ServerConfig; function resetGlobals() { // @ts-ignore global['Twilio'] = undefined; // @ts-ignore global['Runtime'] = undefined; // @ts-ignore global['Response'] = undefined; // @ts-ignore global['twilioClient'] = null; // @ts-ignore global['Functions'] = undefined; } beforeEach(() => { config = { url: 'http://localhost:8000', env: { ACCOUNT_SID, AUTH_TOKEN }, baseDir: path.resolve(__dirname, '../../'), } as ServerConfig; resetGlobals(); }); afterEach(() => { config = {} as ServerConfig; resetGlobals(); }); test('sets the correct global variables', () => { expect(global.Twilio).toBeUndefined(); expect(global.Runtime).toBeUndefined(); expect(global.Response).toBeUndefined(); expect(global.twilioClient).toBeNull(); expect(global.Functions).toBeUndefined(); constructGlobalScope(config); const twilio = requireFromProject(config.baseDir, 'twilio'); expect(global.Twilio).toEqual({ ...twilio, Response }); expect(typeof global.Runtime.getAssets).toBe('function'); expect(typeof global.Runtime.getFunctions).toBe('function'); expect(typeof global.Runtime.getSync).toBe('function'); expect(Response).toEqual(Response); expect(twilioClient).not.toBeNull(); expect(global.Functions).not.toBeUndefined(); }); }); describe('handleSuccess function', () => { test('handles string responses', () => { handleSuccess('Yay', mockResponse); expect(mockResponse.status).toHaveBeenCalledWith(200); expect(mockResponse.send).toHaveBeenCalledWith('Yay'); expect(mockResponse.type).toHaveBeenCalledWith('text/plain'); }); test('handles twiml responses', () => { const twiml = new MessagingResponse(); twiml.message('Hello'); handleSuccess(twiml, mockResponse); expect(mockResponse.status).toHaveBeenCalledWith(200); expect(mockResponse.send).toHaveBeenCalledWith(twiml.toString()); expect(mockResponse.type).toHaveBeenCalledWith('text/xml'); }); test('handles Response instances', () => { const resp = new Response(); resp.setBody({ data: 'Something' }); resp.setStatusCode(418); resp.setHeaders({ 'Content-Type': 'application/json', }); handleSuccess(resp, mockResponse); expect(mockResponse.status).toHaveBeenCalledWith(418); expect(mockResponse.send).toHaveBeenCalledWith({ data: 'Something' }); expect(mockResponse.set).toHaveBeenCalledWith({ 'Content-Type': 'application/json', 'Set-Cookie': [], }); expect(mockResponse.type).not.toHaveBeenCalled(); }); test('sends plain objects', () => { const data = { values: [1, 2, 3] }; handleSuccess(data, mockResponse); expect(mockResponse.status).toHaveBeenCalledWith(200); expect(mockResponse.send).toHaveBeenCalledWith({ values: [1, 2, 3] }); expect(mockResponse.type).not.toHaveBeenCalled(); }); });
the_stack
export = Plyr; export as namespace Plyr; declare class Plyr { /** * Setup a new instance */ static setup(targets: NodeList | HTMLElement | HTMLElement[] | string, options?: Plyr.Options): Plyr[]; /** * Check for support * @param mediaType * @param provider * @param playsInline Whether the player has the playsinline attribute (only applicable to iOS 10+) */ static supported(mediaType?: Plyr.MediaType, provider?: Plyr.Provider, playsInline?: boolean): Plyr.Support; constructor(targets: NodeList | HTMLElement | HTMLElement[] | string, options?: Plyr.Options); /** * Indicates if the current player is HTML5. */ readonly isHTML5: boolean; /** * Indicates if the current player is an embedded player. */ readonly isEmbed: boolean; /** * Indicates if the current player is playing. */ readonly playing: boolean; /** * Indicates if the current player is paused. */ readonly paused: boolean; /** * Indicates if the current player is stopped. */ readonly stopped: boolean; /** * Indicates if the current player has finished playback. */ readonly ended: boolean; /** * Returns a float between 0 and 1 indicating how much of the media is buffered */ readonly buffered: number; /** * Gets or sets the currentTime for the player. The setter accepts a float in seconds. */ currentTime: number; /** * Indicates if the current player is seeking. */ readonly seeking: boolean; /** * Returns the duration for the current media. */ readonly duration: number; /** * Gets or sets the volume for the player. The setter accepts a float between 0 and 1. */ volume: number; /** * Gets or sets the muted state of the player. The setter accepts a boolean. */ muted: boolean; /** * Indicates if the current media has an audio track. */ readonly hasAudio: boolean; /** * Gets or sets the speed for the player. The setter accepts a value in the options specified in your config. Generally the minimum should be 0.5. */ speed: number; /** * Gets or sets the quality for the player. The setter accepts a value from the options specified in your config. */ quality: number; /** * Gets or sets the current loop state of the player. */ loop: boolean; /** * Gets or sets the current source for the player. */ source: Plyr.SourceInfo; /** * Gets or sets the current poster image URL for the player. */ poster: string; /** * Gets or sets the autoplay state of the player. */ autoplay: boolean; /** * Gets or sets the caption track by index. 1 means the track is missing or captions is not active */ currentTrack: number; /** * Gets or sets the preferred captions language for the player. The setter accepts an ISO twoletter language code. Support for the languages is dependent on the captions you include. * If your captions don't have any language data, or if you have multiple tracks with the same language, you may want to use currentTrack instead. */ language: string; /** * Gets or sets the picture-in-picture state of the player. This currently only supported on Safari 10+ on MacOS Sierra+ and iOS 10+. */ pip: boolean; /** * Gets or sets the aspect ratio for embedded players. */ ratio?: string; /** * Access Elements cache */ elements: Plyr.Elements; /** * Returns the current video Provider */ readonly provider: Plyr.Provider; /** * Returns the native API for Vimeo or Youtube players */ readonly embed?: any; readonly fullscreen: Plyr.FullscreenControl; /** * Start playback. * For HTML5 players, play() will return a Promise in some browsers - WebKit and Mozilla according to MDN at time of writing. */ play(): Promise<void> | void; /** * Pause playback. */ pause(): void; /** * Toggle playback, if no parameters are passed, it will toggle based on current status. */ togglePlay(toggle?: boolean): boolean; /** * Stop playback and reset to start. */ stop(): void; /** * Restart playback. */ restart(): void; /** * Rewind playback by the specified seek time. If no parameter is passed, the default seek time will be used. */ rewind(seekTime?: number): void; /** * Fast forward by the specified seek time. If no parameter is passed, the default seek time will be used. */ forward(seekTime?: number): void; /** * Increase volume by the specified step. If no parameter is passed, the default step will be used. */ increaseVolume(step?: number): void; /** * Increase volume by the specified step. If no parameter is passed, the default step will be used. */ decreaseVolume(step?: number): void; /** * Toggle captions display. If no parameter is passed, it will toggle based on current status. */ toggleCaptions(toggle?: boolean): void; /** * Trigger the airplay dialog on supported devices. */ airplay(): void; /** * Toggle the controls (video only). Takes optional truthy value to force it on/off. */ toggleControls(toggle: boolean): void; /** * Add an event listener for the specified event. */ on<K extends keyof Plyr.PlyrEventMap>(event: K, callback: (this: this, event: Plyr.PlyrEventMap[K]) => void): void; /** * Add an event listener for the specified event once. */ once<K extends keyof Plyr.PlyrEventMap>(event: K, callback: (this: this, event: Plyr.PlyrEventMap[K]) => void): void; /** * Remove an event listener for the specified event. */ off<K extends keyof Plyr.PlyrEventMap>(event: K, callback: (this: this, event: Plyr.PlyrEventMap[K]) => void): void; /** * Check support for a mime type. */ supports(type: string): boolean; /** * Destroy lib instance */ destroy(): void; } declare namespace Plyr { type MediaType = 'audio' | 'video'; type Provider = 'html5' | 'youtube' | 'vimeo'; type StandardEventMap = { progress: PlyrEvent; playing: PlyrEvent; play: PlyrEvent; pause: PlyrEvent; timeupdate: PlyrEvent; volumechange: PlyrEvent; seeking: PlyrEvent; seeked: PlyrEvent; ratechange: PlyrEvent; ended: PlyrEvent; enterfullscreen: PlyrEvent; exitfullscreen: PlyrEvent; captionsenabled: PlyrEvent; captionsdisabled: PlyrEvent; languagechange: PlyrEvent; controlshidden: PlyrEvent; controlsshown: PlyrEvent; ready: PlyrEvent; }; // For retrocompatibility, we keep StandadEvent type StandadEvent = keyof Plyr.StandardEventMap; type Html5EventMap = { loadstart: PlyrEvent; loadeddata: PlyrEvent; loadedmetadata: PlyrEvent; canplay: PlyrEvent; canplaythrough: PlyrEvent; stalled: PlyrEvent; waiting: PlyrEvent; emptied: PlyrEvent; cuechange: PlyrEvent; error: PlyrEvent; }; // For retrocompatibility, we keep Html5Event type Html5Event = keyof Plyr.Html5EventMap; type YoutubeEventMap = { statechange: PlyrStateChangeEvent; qualitychange: PlyrEvent; qualityrequested: PlyrEvent; }; // For retrocompatibility, we keep YoutubeEvent type YoutubeEvent = keyof Plyr.YoutubeEventMap; type PlyrEventMap = StandardEventMap & Html5EventMap & YoutubeEventMap; interface FullscreenControl { /** * Indicates if the current player is in fullscreen mode. */ readonly active: boolean; /** * Indicates if the current player has fullscreen enabled. */ readonly enabled: boolean; /** * Enter fullscreen. If fullscreen is not supported, a fallback ""full window/viewport"" is used instead. */ enter(): void; /** * Exit fullscreen. */ exit(): void; /** * Toggle fullscreen. */ toggle(): void; } interface Options { /** * Completely disable Plyr. This would allow you to do a User Agent check or similar to programmatically enable or disable Plyr for a certain UA. Example below. */ enabled?: boolean; /** * Display debugging information in the console */ debug?: boolean; /** * If a function is passed, it is assumed your method will return either an element or HTML string for the controls. Three arguments will be passed to your function; * id (the unique id for the player), seektime (the seektime step in seconds), and title (the media title). See CONTROLS.md for more info on how the html needs to be structured. * Defaults to ['play-large', 'play', 'progress', 'current-time', 'mute', 'volume', 'captions', 'settings', 'pip', 'airplay', 'fullscreen'] */ controls?: string[] | ((id: string, seektime: number, title: string) => unknown) | Element; /** * If you're using the default controls are used then you can specify which settings to show in the menu * Defaults to ['captions', 'quality', 'speed', 'loop'] */ settings?: string[]; /** * Used for internationalization (i18n) of the text within the UI. */ i18n?: any; /** * Load the SVG sprite specified as the iconUrl option (if a URL). If false, it is assumed you are handling sprite loading yourself. */ loadSprite?: boolean; /** * Specify a URL or path to the SVG sprite. See the SVG section for more info. */ iconUrl?: string; /** * Specify the id prefix for the icons used in the default controls (e.g. plyr-play would be plyr). * This is to prevent clashes if you're using your own SVG sprite but with the default controls. * Most people can ignore this option. */ iconPrefix?: string; /** * Specify a URL or path to a blank video file used to properly cancel network requests. */ blankVideo?: string; /** * Autoplay the media on load. This is generally advised against on UX grounds. It is also disabled by default in some browsers. * If the autoplay attribute is present on a <video> or <audio> element, this will be automatically set to true. */ autoplay?: boolean; /** * Only allow one player playing at once. */ autopause?: boolean; /** * The time, in seconds, to seek when a user hits fast forward or rewind. */ seekTime?: number; /** * A number, between 0 and 1, representing the initial volume of the player. */ volume?: number; /** * Whether to start playback muted. If the muted attribute is present on a <video> or <audio> element, this will be automatically set to true. */ muted?: boolean; /** * Click (or tap) of the video container will toggle play/pause. */ clickToPlay?: boolean; /** * Disable right click menu on video to help as very primitive obfuscation to prevent downloads of content. */ disableContextMenu?: boolean; /** * Hide video controls automatically after 2s of no mouse or focus movement, on control element blur (tab out), on playback start or entering fullscreen. * As soon as the mouse is moved, a control element is focused or playback is paused, the controls reappear instantly. */ hideControls?: boolean; /** * Reset the playback to the start once playback is complete. */ resetOnEnd?: boolean; /** * Enable keyboard shortcuts for focused players only or globally */ keyboard?: KeyboardOptions; /** * controls: Display control labels as tooltips on :hover & :focus (by default, the labels are screen reader only). * seek: Display a seek tooltip to indicate on click where the media would seek to. */ tooltips?: TooltipOptions; /** * Specify a custom duration for media. */ duration?: number; /** * Displays the duration of the media on the metadataloaded event (on startup) in the current time display. * This will only work if the preload attribute is not set to none (or is not set at all) and you choose not to display the duration (see controls option). */ displayDuration?: boolean; /** * Display the current time as a countdown rather than an incremental counter. */ invertTime?: boolean; /** * Allow users to click to toggle the above. */ toggleInvert?: boolean; /** * Allows binding of event listeners to the controls before the default handlers. See the defaults.js for available listeners. * If your handler prevents default on the event (event.preventDefault()), the default handler will not fire. */ listeners?: { [key: string]: (error: PlyrEvent) => void }; /** * active: Toggles if captions should be active by default. language: Sets the default language to load (if available). 'auto' uses the browser language. * update: Listen to changes to tracks and update menu. This is needed for some streaming libraries, but can result in unselectable language options). */ captions?: CaptionOptions; /** * enabled: Toggles whether fullscreen should be enabled. fallback: Allow fallback to a full-window solution. * iosNative: whether to use native iOS fullscreen when entering fullscreen (no custom controls) */ fullscreen?: FullScreenOptions; /** * The aspect ratio you want to use for embedded players. */ ratio?: string; /** * enabled: Allow use of local storage to store user settings. key: The key name to use. */ storage?: StorageOptions; /** * selected: The default speed for playback. options: The speed options to display in the UI. YouTube and Vimeo will ignore any options outside of the 0.5-2 range, so options outside of this range will be hidden automatically. */ speed?: SpeedOptions; /** * Currently only supported by YouTube. default is the default quality level, determined by YouTube. options are the options to display. */ quality?: QualityOptions; /** * active: Whether to loop the current video. If the loop attribute is present on a <video> or <audio> element, * this will be automatically set to true This is an object to support future functionality. */ loop?: LoopOptions; /** * enabled: Whether to enable vi.ai ads. publisherId: Your unique vi.ai publisher ID. */ ads?: AdOptions; /** * Vimeo Player Options. */ vimeo?: object; /** * Youtube Player Options. */ youtube?: object; /** * Preview Thumbnails Options. */ previewThumbnails?: PreviewThumbnailsOptions; } interface QualityOptions { default: number; forced?: boolean; onChange?: (quality: number) => void; options: number[]; } interface LoopOptions { active: boolean; } interface AdOptions { enabled: boolean; publisherId: string; } interface SpeedOptions { selected: number; options: number[]; } interface KeyboardOptions { focused?: boolean; global?: boolean; } interface TooltipOptions { controls?: boolean; seek?: boolean; } interface FullScreenOptions { enabled?: boolean; fallback?: boolean | 'force'; allowAudio?: boolean; iosNative?: boolean; } interface CaptionOptions { active?: boolean; language?: string; update?: boolean; } interface StorageOptions { enabled?: boolean; key?: string; } interface PreviewThumbnailsOptions { enabled?: boolean; src?: string | string[]; } export interface Elements { buttons: { airplay?: HTMLButtonElement; captions?: HTMLButtonElement; download?: HTMLButtonElement; fastForward?: HTMLButtonElement; fullscreen?: HTMLButtonElement; mute?: HTMLButtonElement; pip?: HTMLButtonElement; play?: HTMLButtonElement | HTMLButtonElement[]; restart?: HTMLButtonElement; rewind?: HTMLButtonElement; settings?: HTMLButtonElement; }; captions: HTMLElement | null; container: HTMLElement | null; controls: HTMLElement | null; fullscreen: HTMLElement | null; wrapper: HTMLElement | null; } interface SourceInfo { /** * Note: YouTube and Vimeo are currently not supported as audio sources. */ type: MediaType; /** * Title of the new media. Used for the aria-label attribute on the play button, and outer container. YouTube and Vimeo are populated automatically. */ title?: string; /** * This is an array of sources. For HTML5 media, the properties of this object are mapped directly to HTML attributes so more can be added to the object if required. */ sources: Source[]; /** * The URL for the poster image (HTML5 video only). */ poster?: string; /** * An array of track objects. Each element in the array is mapped directly to a track element and any keys mapped directly to HTML attributes so as in the example above, * it will render as <track kind="captions" label="English" srclang="en" src="https://cdn.selz.com/plyr/1.0/example_captions_en.vtt" default> and similar for the French version. * Booleans are converted to HTML5 value-less attributes. */ tracks?: Track[]; } interface Source { /** * The URL of the media file (or YouTube/Vimeo URL). */ src: string; /** * The MIME type of the media file (if HTML5). */ type?: string; provider?: Provider; size?: number; } type TrackKind = 'subtitles' | 'captions' | 'descriptions' | 'chapters' | 'metadata'; interface Track { /** * Indicates how the text track is meant to be used */ kind: TrackKind; /** * Indicates a user-readable title for the track */ label: string; /** * The language of the track text data. It must be a valid BCP 47 language tag. If the kind attribute is set to subtitles, then srclang must be defined. */ srcLang?: string; /** * The URL of the track (.vtt file). */ src: string; default?: boolean; } interface PlyrEvent extends CustomEvent { readonly detail: { readonly plyr: Plyr }; } enum YoutubeState { UNSTARTED = -1, ENDED = 0, PLAYING = 1, PAUSED = 2, BUFFERING = 3, CUED = 5, } interface PlyrStateChangeEvent extends CustomEvent { readonly detail: { readonly plyr: Plyr; readonly code: YoutubeState; }; } interface Support { api: boolean; ui: boolean; } }
the_stack
import "../../../SpecMain"; import { reaction, runInAction } from "mobx"; import i18next from "i18next"; import Cartesian2 from "terriajs-cesium/Source/Core/Cartesian2"; import IonResource from "terriajs-cesium/Source/Core/IonResource"; import Cesium3DTileFeature from "terriajs-cesium/Source/Scene/Cesium3DTileFeature"; import Cesium3DTileset from "terriajs-cesium/Source/Scene/Cesium3DTileset"; import Cesium3DTileStyle from "terriajs-cesium/Source/Scene/Cesium3DTileStyle"; import Cesium3DTileColorBlendMode from "terriajs-cesium/Source/Scene/Cesium3DTileColorBlendMode"; import ShadowMode from "terriajs-cesium/Source/Scene/ShadowMode"; import Cesium3DTilesCatalogItem from "../../../../lib/Models/Catalog/CatalogItems/Cesium3DTilesCatalogItem"; import createStratumInstance from "../../../../lib/Models/Definition/createStratumInstance"; import Terria from "../../../../lib/Models/Terria"; import Matrix4 from "terriajs-cesium/Source/Core/Matrix4"; import HeadingPitchRollTraits from "../../../../lib/Traits/TraitsClasses/HeadingPitchRollTraits"; import LatLonHeightTraits from "../../../../lib/Traits/TraitsClasses/LatLonHeightTraits"; import CommonStrata from "../../../../lib/Models/Definition/CommonStrata"; import Quaternion from "terriajs-cesium/Source/Core/Quaternion"; import Matrix3 from "terriajs-cesium/Source/Core/Matrix3"; import HeadingPitchRoll from "terriajs-cesium/Source/Core/HeadingPitchRoll"; import Cartesian3 from "terriajs-cesium/Source/Core/Cartesian3"; import { OptionsTraits, FilterTraits } from "../../../../lib/Traits/TraitsClasses/Cesium3dTilesTraits"; describe("Cesium3DTilesCatalogItemSpec", function() { let item: Cesium3DTilesCatalogItem; const testUrl = "/test/Cesium3DTiles/tileset.json"; beforeEach(function() { item = new Cesium3DTilesCatalogItem("test", new Terria()); runInAction(() => { item.setTrait("definition", "url", testUrl); }); }); it("should have a type and a typeName", function() { expect(Cesium3DTilesCatalogItem.type).toBe("3d-tiles"); expect(item.type).toBe("3d-tiles"); expect(item.typeName).toBe(i18next.t("models.cesiumTerrain.name3D")); }); it("supports zooming", function() { expect(item.disableZoomTo).toBeFalsy(); }); it("supports show info", function() { expect(item.disableAboutData).toBeFalsy(); }); it("is mappable", function() { expect(item.isMappable).toBeTruthy(); }); describe("showExpressionFromFilters", function() { it("correctly converts filters to show expression", function() { runInAction(() => item.setTrait("definition", "filters", [ createStratumLevelFilter(-2, 11, -1, 10) ]) ); let show: any = item.showExpressionFromFilters; expect(show).toBe( "${feature['stratumlev']} >= -1 && ${feature['stratumlev']} <= 10" ); }); describe("when minimumShown and maximumShown are outside the value range", function() { it("should be undefined", function() { runInAction(() => item.setTrait("definition", "filters", [ createStratumLevelFilter(-2, 11, -2, 11) ]) ); let show: any = item.showExpressionFromFilters; expect(show).toBeUndefined(); }); }); }); describe("cesiumTileStyle", function() { let style: any; beforeEach(function() { runInAction(() => item.setTrait("definition", "style", { color: "vec4(${Height})", show: "${Height} > 30", meta: { description: '"Building id ${id} has height ${Height}."' } }) ); style = item.cesiumTileStyle; }); it("is a Cesium3DTileStyle", function() { expect(style instanceof Cesium3DTileStyle).toBeTruthy(); }); it("creates the style correctly", function() { expect(style.show._expression).toBe("${Height} > 30"); expect(style.color._expression).toBe("vec4(${Height})"); }); describe("when filters are specified", function() { it("adds the filters to the style", function() { runInAction(() => item.setTrait("definition", "filters", [ createStratumLevelFilter(-2, 11, 5, 8) ]) ); style = item.cesiumTileStyle; expect(style.show._expression).toBe(item.showExpressionFromFilters); }); }); }); describe("when loading", function() { describe("if ionAssetId is provided", function() { it("loads the IonResource", async function() { runInAction(() => { item.setTrait("definition", "ionAssetId", 4242); item.setTrait("definition", "ionAccessToken", "fakeToken"); item.setTrait("definition", "ionServer", "fakeServer"); }); spyOn(IonResource, "fromAssetId").and.callThrough(); try { await item.loadMapItems(); } catch {} expect(IonResource.fromAssetId).toHaveBeenCalledWith(4242, { accessToken: "fakeToken", server: "fakeServer" }); }); }); xit("sets the extra options", async function() { runInAction(() => { item.setTrait( "definition", "options", createStratumInstance(OptionsTraits, { maximumScreenSpaceError: 3 }) ); }); try { await item.loadMapItems(); } catch {} expect(item.mapItems[0].maximumScreenSpaceError).toBe(3); }); }); describe("after loading", function() { let dispose: () => void; beforeEach(async function() { try { await item.loadMapItems(); } catch {} // observe mapItems dispose = reaction( () => item.mapItems, () => {} ); }); afterEach(function() { dispose(); }); describe("mapItems", function() { it("has exactly 1 mapItem", function() { expect(item.mapItems.length).toBe(1); }); describe("the mapItem", function() { it("should be a Cesium3DTileset", function() { expect(item.mapItems[0] instanceof Cesium3DTileset).toBeTruthy(); }); describe("the tileset", function() { it("sets `show`", function() { runInAction(() => item.setTrait("definition", "show", false)); expect(item.mapItems[0].show).toBe(false); }); it("sets the shadow mode", function() { runInAction(() => item.setTrait("definition", "shadows", "CAST")); expect(item.mapItems[0].shadows).toBe(ShadowMode.CAST_ONLY); }); it("sets the color blend mode", function() { runInAction(() => { item.setTrait("definition", "colorBlendMode", "REPLACE"); expect(item.mapItems[0].colorBlendMode).toBe( Cesium3DTileColorBlendMode.REPLACE ); }); }); it("sets the color blend amount", function() { runInAction(() => { item.setTrait("user", "colorBlendAmount", 0.42); expect(item.mapItems[0].colorBlendAmount).toBe(0.42); }); }); it("sets the shadow mode", function() { runInAction(() => item.setTrait("definition", "shadows", "CAST")); expect(item.mapItems[0].shadows).toBe(ShadowMode.CAST_ONLY); }); it("sets the style", function() { runInAction(() => item.setTrait("definition", "style", { show: "${ZipCode} === '19341'" }) ); expect(item.mapItems[0].style).toBe((<any>item).cesiumTileStyle); }); // TODO: fix later // describe("when the item is reloaded after destroying the tileset", function() { // it("generates a new tileset", async function() { // const tileset = item.mapItems[0]; // await item.loadMapItems(); // expect(item.mapItems[0] === tileset).toBeTruthy(); // runInAction(() => { // tileset.destroy(); // }); // await item.loadMapItems(); // expect(item.mapItems[0] === tileset).toBeFalsy(); // }); // }); it("sets the rootTransform to IDENTITY", function() { expect( Matrix4.equals(item.mapItems[0].root.transform, Matrix4.IDENTITY) ).toBeTruthy(); }); it("computes a new model matrix from the given transformations", async function() { item.setTrait( CommonStrata.user, "rotation", createStratumInstance(HeadingPitchRollTraits, { heading: 42, pitch: 42, roll: 42 }) ); item.setTrait( CommonStrata.user, "origin", createStratumInstance(LatLonHeightTraits, { latitude: 10, longitude: 10 }) ); item.setTrait(CommonStrata.user, "scale", 5); const modelMatrix = item.mapItems[0].modelMatrix; const rotation = HeadingPitchRoll.fromQuaternion( Quaternion.fromRotationMatrix( Matrix4.getMatrix3(modelMatrix, new Matrix3()) ) ); expect(rotation.heading.toFixed(2)).toBe("-1.85"); expect(rotation.pitch.toFixed(2)).toBe("0.89"); expect(rotation.roll.toFixed(2)).toBe("2.40"); const scale = Matrix4.getScale(modelMatrix, new Cartesian3()); expect(scale.x.toFixed(2)).toEqual("5.00"); expect(scale.y.toFixed(2)).toEqual("5.00"); expect(scale.z.toFixed(2)).toEqual("5.00"); const position = Matrix4.getTranslation( modelMatrix, new Cartesian3() ); expect(position.x.toFixed(2)).toEqual("6186437.07"); expect(position.y.toFixed(2)).toEqual("1090835.77"); expect(position.z.toFixed(2)).toEqual("4081926.10"); }); }); }); }); }); it("correctly builds `Feature` from picked Cesium3DTileFeature", function() { const picked = new Cesium3DTileFeature(); spyOn(picked, "getPropertyNames").and.returnValue([]); const feature = item.buildFeatureFromPickResult(Cartesian2.ZERO, picked); expect(feature).toBeDefined(); if (feature) { expect(feature._cesium3DTileFeature).toBe(picked); } }); it("can change the visibility of a feature", function() { const feature = new Cesium3DTileFeature(); spyOn(feature, "getProperty").and.callFake((prop: string) => { const props: any = { doorNumber: 10, color: "red" }; return props[prop]; }); item.setTrait(CommonStrata.user, "featureIdProperties", [ "doorNumber", "color" ]); item.setFeatureVisibility(feature, false); // @ts-ignore expect(item.style.show.conditions).toEqual([ ['${color} === "red" && ${doorNumber} === 10', false], ["true", true] // fallback rule ]); }); }); function createStratumLevelFilter( minimumValue: number, maximumValue: number, minimumValueShown: number, maximumValueShown: number ) { let filter = createStratumInstance(FilterTraits, { name: "Stratum Level", property: "stratumlev", minimumValue, maximumValue, minimumShown: minimumValueShown, maximumShown: maximumValueShown }); return filter; }
the_stack
interface MockPointerEvent { target?: HTMLElement; type?: string; button?: number; pointerId?: number; pointerType?: string; clientX?: number; clientY?: number; movementX?: number; movementY?: number; altKey?: boolean; ctrlKey?: boolean; metaKey?: boolean; shiftKey?: boolean; buttons?: number[]; [propName: string]: any; } /** * Make a mock PointerEvent. * Many PointerEvent properties are read-only so using real "new PointerEvent()" * is unpractical. */ function eventTemplate(target: HTMLElement): MockPointerEvent { let returnVal = { target, button: 0, preventDefault: () => { }, }; return returnVal; } /** * Simulate PointerEvent in CameraPointersInput instance. */ function simulateEvent(cameraInput: BABYLON.ICameraInput<BABYLON.Camera>, event: MockPointerEvent) { let pointerInfo = {}; switch (event.type) { case "pointerdown": pointerInfo = { type: BABYLON.PointerEventTypes.POINTERDOWN, event }; // Cast "camera" to <any> to relax "private" classification. (<any>cameraInput)._pointerInput(pointerInfo, undefined); break; case "pointerup": pointerInfo = { type: BABYLON.PointerEventTypes.POINTERUP, event }; // Cast "camera" to <any> to relax "private" classification. (<any>cameraInput)._pointerInput(pointerInfo, undefined); break; case "pointermove": pointerInfo = { type: BABYLON.PointerEventTypes.POINTERMOVE, event }; // Cast "camera" to <any> to relax "private" classification. (<any>cameraInput)._pointerInput(pointerInfo, undefined); break; case "blur": // Cast "camera" to <any> to relax "private" classification. (<any>cameraInput)._onLostFocus(); break; case "POINTERDOUBLETAP": // Not a real DOM event. Just a shortcut to trigger // PointerEventTypes.POINTERMOVE on the Input class. pointerInfo = { type: BABYLON.PointerEventTypes.POINTERDOUBLETAP, event }; // Cast "camera" to <any> to relax "private" classification. (<any>cameraInput)._pointerInput(pointerInfo, undefined); break; default: console.error("Invalid pointer event: " + event.type); } } /** * Override the methods of an existing camera to create a stub for testing * BaseCameraPointersInput. * @returns An instance of ArcRotateCameraPointersInput with the interesting * methods stubbed out. */ function StubCameraInput() { // Force our CameraPointersInput instance to type "any" so we can access // protected methods from within this function. let cameraInput: any = <any>new BABYLON.ArcRotateCameraPointersInput(); /** * Reset all counters. */ cameraInput.reset = (): void => { cameraInput.countOnDoubleTap = 0; cameraInput.countOnTouch = 0; cameraInput.countOnMultiTouch = 0; cameraInput.countOnContextMenu = 0; cameraInput.countOnButtonDown = 0; cameraInput.countOnButtonUp = 0; cameraInput.countOnLostFocus = 0; cameraInput.lastOnDoubleTap = undefined; cameraInput.lastOnTouch = undefined; cameraInput.lastOnMultiTouch = undefined; cameraInput.lastOnContextMenu = undefined; cameraInput.lastOnButtonDown = undefined; cameraInput.lastOnButtonUp = undefined; }; cameraInput.reset(); /** * Stub out all mothods we want to test as part of the BaseCameraPointersInput testing. * These stubs keep track of how many times they were called and */ cameraInput.onTouch = (point: BABYLON.Nullable<BABYLON.PointerTouch>, offsetX: number, offsetY: number) => { cameraInput.countOnTouch++; cameraInput.lastOnTouch = { point, offsetX, offsetY }; }; cameraInput.onDoubleTap = (type: string) => { cameraInput.countOnDoubleTap++; cameraInput.lastOnDoubleTap = type; }; cameraInput.onMultiTouch = ( pointA: BABYLON.Nullable<BABYLON.PointerTouch>, pointB: BABYLON.Nullable<BABYLON.PointerTouch>, previousPinchSquaredDistance: number, pinchSquaredDistance: number, previousMultiTouchPanPosition: BABYLON.Nullable<BABYLON.PointerTouch>, multiTouchPanPosition: BABYLON.Nullable<BABYLON.PointerTouch> ) => { cameraInput.countOnMultiTouch++; cameraInput.lastOnMultiTouch = { pointA, pointB, previousPinchSquaredDistance, pinchSquaredDistance, previousMultiTouchPanPosition, multiTouchPanPosition, }; }; cameraInput.onButtonDown = (evt: PointerEvent) => { cameraInput.countOnButtonDown++; let buttonCount = cameraInput.pointB !== null ? 2 : 1; cameraInput.lastOnButtonDown = { evt, buttonCount }; }; cameraInput.onButtonUp = (evt: PointerEvent) => { cameraInput.countOnButtonUp++; let buttonCount = cameraInput.pointA !== null ? 1 : 0; cameraInput.lastOnButtonUp = { evt, buttonCount }; }; cameraInput.onContextMenu = (evt: PointerEvent) => { cameraInput.countOnContextMenu++; cameraInput.lastOnContextMenu = evt; }; cameraInput.onLostFocus = () => { cameraInput.countOnLostFocus++; }; return cameraInput; } /** * Test the things. * The BaseCameraPointersInput class first. */ describe("BaseCameraPointersInput", function () { /** * Sets the timeout of all the tests to 10 seconds. */ this.timeout(10000); before(function (done) { // runs before all tests in this block this.timeout(180000); BABYLONDEVTOOLS.Loader.useDist() .testMode() .load(function () { // Force apply promise polyfill for consistent behavior between // PhantomJS, IE11, and other browsers. BABYLON.PromisePolyfill.Apply(true); done(); }); this._canvas = document.createElement("canvas"); this._engine = new BABYLON.NullEngine(); this._scene = new BABYLON.Scene(this._engine); // Set up an instance of a Camera with the ArcRotateCameraPointersInput. this.camera = new BABYLON.ArcRotateCamera("StubCamera", 0, 0, 0, new BABYLON.Vector3(0, 0, 0), this._scene); this.cameraInput = StubCameraInput(); this.cameraInput.camera = this.camera; this.cameraInput.attachControl(); }); beforeEach(function () { // runs before each test in this block this.cameraInput.reset(); }); describe("one button drag", function () { it('calls "onTouch" method', function () { var event: MockPointerEvent = eventTemplate(<HTMLElement>this._canvas); // Button down. event.type = "pointerdown"; event.clientX = 100; event.clientY = 200; event.button = 0; simulateEvent(this.cameraInput, event); // Button down but no movement events have fired yet. expect(this.cameraInput.countOnTouch).to.equal(0); expect(this.cameraInput.countOnButtonDown).to.equal(1); expect(this.cameraInput.countOnButtonUp).to.equal(0); // Start moving. event.type = "pointermove"; event.button = -1; simulateEvent(this.cameraInput, event); expect(this.cameraInput.countOnTouch).to.equal(1); expect(this.cameraInput.countOnButtonDown).to.equal(1); expect(this.cameraInput.countOnButtonUp).to.equal(0); // Move just started; No value yet. expect(this.cameraInput.lastOnTouch.offsetX).to.equal(0); expect(this.cameraInput.lastOnTouch.offsetY).to.equal(0); // Drag. event.type = "pointermove"; event.clientX = 1000; event.button = -1; simulateEvent(this.cameraInput, event); expect(this.cameraInput.countOnTouch).to.equal(2); expect(this.cameraInput.countOnButtonDown).to.equal(1); expect(this.cameraInput.countOnButtonUp).to.equal(0); // Pointer dragged in X direction. expect(this.cameraInput.lastOnTouch.offsetX).to.above(0); expect(this.cameraInput.lastOnTouch.offsetY).to.equal(0); // Button up. event.type = "pointerup"; event.button = 0; simulateEvent(this.cameraInput, event); expect(this.cameraInput.countOnTouch).to.equal(2); expect(this.cameraInput.countOnButtonDown).to.equal(1); expect(this.cameraInput.countOnButtonUp).to.equal(1); // These callbacks were never called. expect(this.cameraInput.countOnDoubleTap).to.equal(0); expect(this.cameraInput.countOnMultiTouch).to.equal(0); expect(this.cameraInput.countOnContextMenu).to.equal(0); expect(this.cameraInput.countOnLostFocus).to.equal(0); }); it("leaves a clean state allowing repeat calls", function () { var event: MockPointerEvent = eventTemplate(<HTMLElement>this._canvas); // Button down. event.type = "pointerdown"; event.clientX = 100; event.clientY = 200; event.button = 0; simulateEvent(this.cameraInput, event); // Button down but no movement events have fired yet. expect(this.cameraInput.countOnTouch).to.equal(0); expect(this.cameraInput.countOnButtonDown).to.equal(1); expect(this.cameraInput.countOnButtonUp).to.equal(0); // Start moving. event.type = "pointermove"; event.button = -1; simulateEvent(this.cameraInput, event); expect(this.cameraInput.countOnTouch).to.equal(1); expect(this.cameraInput.countOnButtonDown).to.equal(1); expect(this.cameraInput.countOnButtonUp).to.equal(0); // Move just started; No value yet. expect(this.cameraInput.lastOnTouch.offsetX).to.equal(0); expect(this.cameraInput.lastOnTouch.offsetY).to.equal(0); // Drag. event.type = "pointermove"; event.clientX = 1000; event.button = -1; simulateEvent(this.cameraInput, event); expect(this.cameraInput.countOnTouch).to.equal(2); expect(this.cameraInput.countOnButtonDown).to.equal(1); expect(this.cameraInput.countOnButtonUp).to.equal(0); // Pointer dragged in X direction. expect(this.cameraInput.lastOnTouch.offsetX).to.above(0); expect(this.cameraInput.lastOnTouch.offsetY).to.equal(0); // Button up. event.type = "pointerup"; event.button = 0; simulateEvent(this.cameraInput, event); expect(this.cameraInput.countOnTouch).to.equal(2); expect(this.cameraInput.countOnButtonDown).to.equal(1); expect(this.cameraInput.countOnButtonUp).to.equal(1); // Button down for 2nd time. event.type = "pointerdown"; event.clientX = 100; event.clientY = 200; event.button = 0; simulateEvent(this.cameraInput, event); // Button down but no movement events have fired yet. expect(this.cameraInput.countOnTouch).to.equal(2); expect(this.cameraInput.countOnButtonDown).to.equal(2); expect(this.cameraInput.countOnButtonUp).to.equal(1); // Start moving. event.type = "pointermove"; event.button = -1; simulateEvent(this.cameraInput, event); expect(this.cameraInput.countOnTouch).to.equal(3); expect(this.cameraInput.countOnButtonDown).to.equal(2); expect(this.cameraInput.countOnButtonUp).to.equal(1); // Move just started; No value yet. expect(this.cameraInput.lastOnTouch.offsetX).to.equal(0); expect(this.cameraInput.lastOnTouch.offsetY).to.equal(0); // Drag again. event.type = "pointermove"; event.clientY = 2000; event.button = -1; simulateEvent(this.cameraInput, event); expect(this.cameraInput.countOnTouch).to.equal(4); expect(this.cameraInput.countOnButtonDown).to.equal(2); expect(this.cameraInput.countOnButtonUp).to.equal(1); // Pointer dragged in Y direction. expect(this.cameraInput.lastOnTouch.offsetX).to.equal(0); expect(this.cameraInput.lastOnTouch.offsetY).to.above(0); // Button up. event.type = "pointerup"; event.button = 0; simulateEvent(this.cameraInput, event); expect(this.cameraInput.countOnTouch).to.equal(4); expect(this.cameraInput.countOnButtonDown).to.equal(2); expect(this.cameraInput.countOnButtonUp).to.equal(2); // These callbacks were never called. expect(this.cameraInput.countOnDoubleTap).to.equal(0); expect(this.cameraInput.countOnMultiTouch).to.equal(0); expect(this.cameraInput.countOnContextMenu).to.equal(0); expect(this.cameraInput.countOnLostFocus).to.equal(0); }); }); describe("two button drag", function () { it('calls "onMultiTouch" method', function () { var event: MockPointerEvent = eventTemplate(<HTMLElement>this._canvas); // 1st button down. event.type = "pointerdown"; event.pointerType = "touch"; event.clientX = 1000; event.clientY = 200; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Button down but no movement events have fired yet. expect(this.cameraInput.countOnButtonDown).to.equal(1); expect(this.cameraInput.countOnButtonUp).to.equal(0); expect(this.cameraInput.countOnTouch).to.equal(0); expect(this.cameraInput.countOnMultiTouch).to.equal(0); // Start moving before 2nd button has been pressed. event.type = "pointermove"; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Moving with one button down will start a drag. expect(this.cameraInput.countOnButtonDown).to.equal(1); expect(this.cameraInput.countOnButtonUp).to.equal(0); expect(this.cameraInput.countOnTouch).to.equal(1); expect(this.cameraInput.countOnMultiTouch).to.equal(0); // Move X coordinate. event.type = "pointermove"; event.clientX = 1500; event.clientY = 200; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); // One button drag. expect(this.cameraInput.countOnButtonDown).to.equal(1); expect(this.cameraInput.countOnButtonUp).to.equal(0); expect(this.cameraInput.countOnTouch).to.equal(2); expect(this.cameraInput.countOnMultiTouch).to.equal(0); // 2nd button down. (Enter zoom mode.) event.type = "pointerdown"; event.pointerType = "touch"; event.button = 1; event.pointerId = 2; simulateEvent(this.cameraInput, event); // 2nd button down but hasn't moved yet. expect(this.cameraInput.countOnButtonDown).to.equal(2); expect(this.cameraInput.countOnButtonUp).to.equal(0); expect(this.cameraInput.countOnTouch).to.equal(2); expect(this.cameraInput.countOnMultiTouch).to.equal(0); // Start move of 2nd pointer. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2000; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); // Start of drag with 2 buttons down. expect(this.cameraInput.countOnButtonDown).to.equal(2); expect(this.cameraInput.countOnButtonUp).to.equal(0); expect(this.cameraInput.countOnTouch).to.equal(2); expect(this.cameraInput.countOnMultiTouch).to.equal(1); // First time onMultiTouch() is called for a new drag. expect(this.cameraInput.lastOnMultiTouch.pinchSquaredDistance).to.be.above(0); expect(this.cameraInput.lastOnMultiTouch.multiTouchPanPosition).to.not.be.null; // previousPinchSquaredDistance will be null. expect(this.cameraInput.lastOnMultiTouch.previousPinchSquaredDistance).to.be.equal(0); expect(this.cameraInput.lastOnMultiTouch.previousMultiTouchPanPosition).to.be.null; // Move Y coordinate. 2nd point is the one moving. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2500; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); // Moving two button drag. expect(this.cameraInput.countOnButtonDown).to.equal(2); expect(this.cameraInput.countOnButtonUp).to.equal(0); expect(this.cameraInput.countOnTouch).to.equal(2); expect(this.cameraInput.countOnMultiTouch).to.equal(2); // Neither first nor last event in a drag so everything populated. expect(this.cameraInput.lastOnMultiTouch.pinchSquaredDistance).to.be.above(0); expect(this.cameraInput.lastOnMultiTouch.multiTouchPanPosition).to.not.be.null; expect(this.cameraInput.lastOnMultiTouch.previousPinchSquaredDistance).to.be.above(0); expect(this.cameraInput.lastOnMultiTouch.previousMultiTouchPanPosition).to.not.be.null; // Move X and Y coordinate. 1st point is the one moving. event.type = "pointermove"; event.clientX = 1700; event.clientY = 1700; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Moving two button drag. expect(this.cameraInput.countOnButtonDown).to.equal(2); expect(this.cameraInput.countOnButtonUp).to.equal(0); expect(this.cameraInput.countOnTouch).to.equal(2); expect(this.cameraInput.countOnMultiTouch).to.equal(3); // One of the buttons button up. event.type = "pointerup"; event.pointerType = "touch"; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Button up. expect(this.cameraInput.countOnButtonDown).to.equal(2); expect(this.cameraInput.countOnButtonUp).to.equal(1); expect(this.cameraInput.countOnTouch).to.equal(2); expect(this.cameraInput.countOnMultiTouch).to.equal(4); // onMultiTouch() is called one last time when drag ends with null value for // multiTouchPanPosition. expect(this.cameraInput.lastOnMultiTouch.pinchSquaredDistance).to.equal(0); expect(this.cameraInput.lastOnMultiTouch.multiTouchPanPosition).to.be.null; // previousPinchSquaredDistance and previousMultiTouchPanPosition are // populated though. expect(this.cameraInput.lastOnMultiTouch.previousPinchSquaredDistance).to.be.above(0); expect(this.cameraInput.lastOnMultiTouch.previousMultiTouchPanPosition).to.not.be.null; // Move X and Y coordinate of remaining pressed point. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2700; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); // Back to one button drag. expect(this.cameraInput.countOnButtonDown).to.equal(2); expect(this.cameraInput.countOnButtonUp).to.equal(1); expect(this.cameraInput.countOnTouch).to.equal(3); expect(this.cameraInput.countOnMultiTouch).to.equal(4); // Other button button up. (Now moves should have no affect.) event.type = "pointerup"; event.pointerType = "touch"; event.button = 1; event.pointerId = 2; simulateEvent(this.cameraInput, event); // Button up. expect(this.cameraInput.countOnButtonDown).to.equal(2); expect(this.cameraInput.countOnButtonUp).to.equal(2); expect(this.cameraInput.countOnTouch).to.equal(3); expect(this.cameraInput.countOnMultiTouch).to.equal(4); // Move X and Y coordinate. event.type = "pointermove"; event.clientX = 3000; event.clientY = 4000; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Not dragging anymore so no change in callbacks. expect(this.cameraInput.countOnButtonDown).to.equal(2); expect(this.cameraInput.countOnButtonUp).to.equal(2); expect(this.cameraInput.countOnTouch).to.equal(3); expect(this.cameraInput.countOnMultiTouch).to.equal(4); // These callbacks were never called. expect(this.cameraInput.countOnDoubleTap).to.equal(0); expect(this.cameraInput.countOnContextMenu).to.equal(0); expect(this.cameraInput.countOnLostFocus).to.equal(0); }); }); describe("button down then up", function () { it('calls "onButtonDown" and "onButtonUp"', function () { var event: MockPointerEvent = eventTemplate(<HTMLElement>this._canvas); // 1st button down. event.type = "pointerdown"; event.pointerType = "touch"; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(this.cameraInput.countOnButtonDown).to.equal(1); expect(this.cameraInput.countOnButtonUp).to.equal(0); expect(this.cameraInput.lastOnButtonDown.buttonCount).to.be.equal(1); // 2nd button down. event.type = "pointerdown"; event.pointerType = "touch"; event.button = 1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(this.cameraInput.countOnButtonDown).to.equal(2); expect(this.cameraInput.countOnButtonUp).to.equal(0); expect(this.cameraInput.lastOnButtonDown.buttonCount).to.be.equal(2); // One button up. event.type = "pointerup"; event.pointerType = "touch"; event.button = 1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(this.cameraInput.countOnButtonDown).to.equal(2); expect(this.cameraInput.countOnButtonUp).to.equal(1); expect(this.cameraInput.lastOnButtonUp.buttonCount).to.be.equal(1); // Other button up. event.type = "pointerup"; event.pointerType = "touch"; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(this.cameraInput.countOnButtonDown).to.equal(2); expect(this.cameraInput.countOnButtonUp).to.equal(2); expect(this.cameraInput.lastOnButtonUp.buttonCount).to.be.equal(0); // These callbacks were never called. expect(this.cameraInput.countOnTouch).to.equal(0); expect(this.cameraInput.countOnMultiTouch).to.equal(0); expect(this.cameraInput.countOnDoubleTap).to.equal(0); expect(this.cameraInput.countOnContextMenu).to.equal(0); expect(this.cameraInput.countOnLostFocus).to.equal(0); }); it("pointerId of pointerup doesnt match", function () { var event: MockPointerEvent = eventTemplate(<HTMLElement>this._canvas); // 1st button down. event.type = "pointerdown"; event.pointerType = "touch"; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(this.cameraInput.countOnButtonDown).to.equal(1); expect(this.cameraInput.countOnButtonUp).to.equal(0); expect(this.cameraInput.lastOnButtonDown.buttonCount).to.be.equal(1); // 2nd button down. event.type = "pointerdown"; event.pointerType = "touch"; event.button = 1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(this.cameraInput.countOnButtonDown).to.equal(2); expect(this.cameraInput.countOnButtonUp).to.equal(0); expect(this.cameraInput.lastOnButtonDown.buttonCount).to.be.equal(2); // 3rd button down. event.type = "pointerdown"; event.pointerType = "touch"; event.button = 2; event.pointerId = 3; simulateEvent(this.cameraInput, event); // Only 2 buttons are tracked. // onButtonDown() gets called but nothing else changes. expect(this.cameraInput.countOnButtonDown).to.equal(3); expect(this.cameraInput.countOnButtonUp).to.equal(0); expect(this.cameraInput.lastOnButtonDown.buttonCount).to.be.equal(2); // One button up. event.type = "pointerup"; event.pointerType = "touch"; event.button = 1; event.pointerId = 99; simulateEvent(this.cameraInput, event); expect(this.cameraInput.countOnButtonDown).to.equal(3); expect(this.cameraInput.countOnButtonUp).to.equal(1); // Button state gets cleared. No buttons registered as being down. expect(this.cameraInput.lastOnButtonUp.buttonCount).to.be.equal(0); // These callbacks were never called. expect(this.cameraInput.countOnTouch).to.equal(0); expect(this.cameraInput.countOnMultiTouch).to.equal(0); expect(this.cameraInput.countOnDoubleTap).to.equal(0); expect(this.cameraInput.countOnContextMenu).to.equal(0); expect(this.cameraInput.countOnLostFocus).to.equal(0); }); }); }); /** * Test the things. * The ArcRotateCameraInput class. */ describe("ArcRotateCameraInput", function () { /** * Sets the timeout of all the tests to 10 seconds. */ this.timeout(10000); enum ValChange { Increase, Same, Decrease, DontCare, } const interestingValues = ["inertialPanningX", "inertialPanningY", "inertialAlphaOffset", "inertialBetaOffset", "inertialRadiusOffset"]; function resetCameraPos(camera: BABYLON.ArcRotateCamera, cameraCachePos: {}) { camera.alpha = 10; camera.beta = 20; camera.radius = 30; camera.inertialPanningX = 0; camera.inertialPanningY = 0; camera.inertialAlphaOffset = 0; camera.inertialBetaOffset = 0; camera.inertialRadiusOffset = 0; camera._panningMouseButton = 2; camera.useInputToRestoreState = true; camera._useCtrlForPanning = true; interestingValues.forEach((key) => { cameraCachePos[key] = camera[key]; }); } function verifyChanges(camera: BABYLON.ArcRotateCamera, cameraCachePos: {}, toCheck: { [key: string]: ValChange }): boolean { let result = true; interestingValues.forEach((key) => { if (toCheck[key] === undefined) { toCheck[key] = ValChange.Same; } let r = toCheck[key] === ValChange.DontCare || (toCheck[key] === ValChange.Decrease && camera[key] < cameraCachePos[key]) || (toCheck[key] === ValChange.Same && camera[key] === cameraCachePos[key]) || (toCheck[key] === ValChange.Increase && camera[key] > cameraCachePos[key]); if (!r) { console.log(`Incorrect value for ${key}, previous: ${cameraCachePos[key]}, current: ${camera[key]}`); } result = result && r; cameraCachePos[key] = camera[key]; }); if (!result) { displayCamera(camera); } return result; } function displayCamera(camera: BABYLON.ArcRotateCamera): void { let info = { inertialPanningX: camera.inertialPanningX, inertialPanningY: camera.inertialPanningY, inertialAlphaOffset: camera.inertialAlphaOffset, inertialBetaOffset: camera.inertialBetaOffset, inertialRadiusOffset: camera.inertialRadiusOffset, }; console.log(info); } before(function (done) { // runs before all tests in this block this.timeout(180000); BABYLONDEVTOOLS.Loader.useDist() .testMode() .load(function () { // Force apply promise polyfill for consistent behavior between // PhantomJS, IE11, and other browsers. BABYLON.PromisePolyfill.Apply(true); done(); }); this._canvas = document.createElement("canvas"); this._scene = new BABYLON.Scene(new BABYLON.NullEngine()); // Set up an instance of a Camera with the ArcRotateCameraPointersInput. this.camera = new BABYLON.ArcRotateCamera("Camera", 0, 0, 0, new BABYLON.Vector3(0, 0, 0), this._scene); this.cameraInput = new BABYLON.ArcRotateCameraPointersInput(); this.cameraInput.camera = this.camera; this.cameraInput.attachControl(); this.cameraCachePos = {}; }); beforeEach(function () { // runs before each test in this block resetCameraPos(this.camera, this.cameraCachePos); }); describe("Test infrastructure", function () { it("verifyChanges checks Decrease", function () { this.camera.inertialAlphaOffset = 10; this.cameraCachePos.inertialAlphaOffset = 10.001; expect(verifyChanges(this.camera, this.cameraCachePos, { inertialAlphaOffset: ValChange.Decrease })).to.be.true; this.camera.inertialAlphaOffset = 10; this.cameraCachePos.inertialAlphaOffset = 9.999; expect(verifyChanges(this.camera, this.cameraCachePos, { inertialAlphaOffset: ValChange.Decrease })).to.be.false; }); it("verifyChanges checks Same", function () { this.camera.inertialAlphaOffset = 10; this.cameraCachePos.inertialAlphaOffset = 10; expect(verifyChanges(this.camera, this.cameraCachePos, { inertialAlphaOffset: ValChange.Same })).to.be.true; this.camera.inertialAlphaOffset = 10; this.cameraCachePos.inertialAlphaOffset = 10.001; expect(verifyChanges(this.camera, this.cameraCachePos, { inertialAlphaOffset: ValChange.Same })).to.be.false; }); it("verifyChanges checks undefined", function () { // If the 'toCheck' field is undefined, treat is as ValChange.Same. this.camera.inertialAlphaOffset = 10; this.cameraCachePos.inertialAlphaOffset = 10; expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; this.camera.inertialAlphaOffset = 10; this.cameraCachePos.inertialAlphaOffset = 10.001; expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.false; }); it("verifyChanges checks DontCare", function () { this.camera.inertialAlphaOffset = 10; this.cameraCachePos.inertialAlphaOffset = 10; expect(verifyChanges(this.camera, this.cameraCachePos, { inertialAlphaOffset: ValChange.DontCare })).to.be.true; this.camera.inertialAlphaOffset = 10; this.cameraCachePos.inertialAlphaOffset = 1001; expect(verifyChanges(this.camera, this.cameraCachePos, { inertialAlphaOffset: ValChange.DontCare })).to.be.true; }); it("verifyChanges checks Increase", function () { this.camera.inertialAlphaOffset = 10; this.cameraCachePos.inertialAlphaOffset = 9.999; expect(verifyChanges(this.camera, this.cameraCachePos, { inertialAlphaOffset: ValChange.Increase })).to.be.true; this.camera.inertialAlphaOffset = 10; this.cameraCachePos.inertialAlphaOffset = 10.001; expect(verifyChanges(this.camera, this.cameraCachePos, { inertialAlphaOffset: ValChange.Increase })).to.be.false; }); }); describe("one button drag", function () { it("changes inertialAlphaOffset", function () { var event: MockPointerEvent = eventTemplate(<HTMLElement>this._canvas); // Button down. event.type = "pointerdown"; event.clientX = 100; event.clientY = 200; event.button = 0; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Start moving. event.type = "pointermove"; event.button = -1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Move X coordinate. Drag camera. event.type = "pointermove"; event.clientX = 1000; event.button = -1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialAlphaOffset: ValChange.Decrease })).to.be.true; // Button up. Primary button. event.type = "pointerup"; event.button = 0; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; }); it("followed by another one button drag", function () { var event: MockPointerEvent = eventTemplate(<HTMLElement>this._canvas); // Button down. event.type = "pointerdown"; event.clientX = 100; event.clientY = 200; event.button = 0; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Start moving. event.type = "pointermove"; event.button = -1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Move X coordinate. Drag camera. event.type = "pointermove"; event.clientX = 1000; event.button = -1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialAlphaOffset: ValChange.Decrease })).to.be.true; // Button up. Primary button. event.type = "pointerup"; event.button = 0; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // 2nd drag. // Button down. event.type = "pointerdown"; event.clientX = 100; event.clientY = 200; event.button = 0; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Start moving. event.type = "pointermove"; event.button = -1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Move Y coordinate. Drag camera. event.type = "pointermove"; event.clientY = 1000; event.button = -1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialBetaOffset: ValChange.Decrease })).to.be.true; // Button up. Primary button. event.type = "pointerup"; event.button = 0; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; }); it("with Ctrl key changes inertialPanningY", function () { this.cameraInput.panningSensibility = 3; this.cameraInput._useCtrlForPanning = true; var event: MockPointerEvent = eventTemplate(<HTMLElement>this._canvas); // Button down. event.type = "pointerdown"; event.clientX = 100; event.clientY = 200; event.button = 0; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Start moving. event.type = "pointermove"; event.button = -1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Move Y coordinate. Drag camera. (Not panning yet.) event.type = "pointermove"; event.clientY = 1000; event.button = -1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialBetaOffset: ValChange.Decrease })).to.be.true; // Move X coordinate with Ctrl key depressed. Panning now. event.type = "pointermove"; event.clientY = 2000; event.button = -1; event.ctrlKey = true; // Will cause pan motion. simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialPanningY: ValChange.Increase })).to.be.true; // Move X coordinate having released Ctrl. event.type = "pointermove"; event.clientY = 3000; event.button = -1; event.ctrlKey = false; // Will cancel pan motion. simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialBetaOffset: ValChange.Decrease })).to.be.true; // Button up. Primary button. event.type = "pointerup"; event.button = 0; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; }); it("with panningSensibility disabled", function () { this.cameraInput.panningSensibility = 0; var event: MockPointerEvent = eventTemplate(<HTMLElement>this._canvas); // Button down. event.type = "pointerdown"; event.clientX = 100; event.clientY = 200; event.button = 0; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Start moving. event.type = "pointermove"; event.button = -1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Move Y coordinate. Drag camera. event.type = "pointermove"; event.clientY = 1000; event.button = -1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialBetaOffset: ValChange.Decrease })).to.be.true; // Move X coordinate with Ctrl key depressed. // Panning disabled so continue regular drag.. event.type = "pointermove"; event.clientY = 1500; event.button = -1; event.ctrlKey = true; // Will cause pan motion. simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialBetaOffset: ValChange.Decrease })).to.be.true; // Move X coordinate having released Ctrl. event.type = "pointermove"; event.clientY = 3000; event.button = -1; event.ctrlKey = false; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialBetaOffset: ValChange.Decrease })).to.be.true; // Button up. Primary button. event.type = "pointerup"; event.button = 0; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; }); }); describe("two button drag", function () { describe("multiTouchPanAndZoom enabled", function () { it("pinchDeltaPercentage enabled", function () { // Multiple button presses interpreted as "pinch" and "swipe". this.cameraInput.multiTouchPanAndZoom = true; // Zoom changes are a percentage of current value. this.cameraInput.pinchDeltaPercentage = 10; // Panning not enabled. this.cameraInput.panningSensibility = 0; var event: MockPointerEvent = eventTemplate(<HTMLElement>this._canvas); // 1st button down. event.type = "pointerdown"; event.pointerType = "touch"; event.clientX = 1000; event.clientY = 200; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Start moving before 2nd button has been pressed. event.type = "pointermove"; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Move X coordinate. event.type = "pointermove"; event.clientX = 1500; event.clientY = 200; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialAlphaOffset: ValChange.Decrease })).to.be.true; // 2nd button down. (Enter zoom mode.) event.type = "pointerdown"; event.pointerType = "touch"; event.button = 1; event.pointerId = 2; simulateEvent(this.cameraInput, event); // Start move of 2nd pointer. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2000; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Move Y coordinate. 2nd point is the one moving. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2500; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialRadiusOffset: ValChange.Increase })).to.be.true; // Move X + Y coordinate. 1st point is the one moving. event.type = "pointermove"; event.clientX = 1700; event.clientY = 1700; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialRadiusOffset: ValChange.Decrease })).to.be.true; // One of the buttons button up. (Leave zoom mode.) event.type = "pointerup"; event.pointerType = "touch"; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Move X and Y coordinate of remaining pressed point. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2700; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialBetaOffset: ValChange.Decrease })).to.be.true; // Other button button up. (Now moves should have no affect.) event.type = "pointerup"; event.pointerType = "touch"; event.button = 1; event.pointerId = 2; simulateEvent(this.cameraInput, event); // Move X and Y coordinate. event.type = "pointermove"; event.clientX = 3000; event.clientY = 4000; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; }); it("pinchDeltaPercentage disabled", function () { // Multiple button presses interpreted as "pinch" and "swipe". this.cameraInput.multiTouchPanAndZoom = true; // Zoom changes are not a percentage of current value. this.cameraInput.pinchDeltaPercentage = 0; // Panning not enabled. this.cameraInput.panningSensibility = 0; var event: MockPointerEvent = eventTemplate(<HTMLElement>this._canvas); // 1st button down. event.type = "pointerdown"; event.pointerType = "touch"; event.clientX = 1000; event.clientY = 200; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Start moving before 2nd button has been pressed. event.type = "pointermove"; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Move X coordinate. event.type = "pointermove"; event.clientX = 1500; event.clientY = 200; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialAlphaOffset: ValChange.Decrease })).to.be.true; // 2nd button down. (Enter zoom mode.) event.type = "pointerdown"; event.pointerType = "touch"; event.button = 1; event.pointerId = 2; simulateEvent(this.cameraInput, event); // Start move of 2nd pointer. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2000; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Move Y coordinate. 2nd point is the one moving. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2500; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialRadiusOffset: ValChange.Increase })).to.be.true; // Move X + Y coordinate. 1st point is the one moving. event.type = "pointermove"; event.clientX = 1700; event.clientY = 1700; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialRadiusOffset: ValChange.Decrease })).to.be.true; // One of the buttons button up. (Leave zoom mode.) event.type = "pointerup"; event.pointerType = "touch"; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Move X and Y coordinate of remaining pressed point. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2700; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialBetaOffset: ValChange.Decrease })).to.be.true; // Other button button up. (Now moves should have no affect.) event.type = "pointerup"; event.pointerType = "touch"; event.button = 1; event.pointerId = 2; simulateEvent(this.cameraInput, event); // Move X and Y coordinate. event.type = "pointermove"; event.clientX = 3000; event.clientY = 4000; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; }); it("pan on drag", function () { // Multiple button presses interpreted as "pinch" and "swipe". this.cameraInput.multiTouchPanAndZoom = true; // Zoom changes are not a percentage of current value. this.cameraInput.pinchDeltaPercentage = 0; // Panning not enabled. this.cameraInput.panningSensibility = 3; var event: MockPointerEvent = eventTemplate(<HTMLElement>this._canvas); // 1st button down. event.type = "pointerdown"; event.pointerType = "touch"; event.clientX = 1000; event.clientY = 200; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Start moving before 2nd button has been pressed. event.type = "pointermove"; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Move X coordinate. event.type = "pointermove"; event.clientX = 1500; event.clientY = 200; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialAlphaOffset: ValChange.Decrease })).to.be.true; // 2nd button down. (Enter zoom mode.) event.type = "pointerdown"; event.pointerType = "touch"; event.button = 1; event.pointerId = 2; simulateEvent(this.cameraInput, event); // Start move of 2nd pointer. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2000; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Move Y coordinate. 2nd point is the one moving. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2500; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialRadiusOffset: ValChange.Increase, inertialPanningY: ValChange.Increase })).to.be.true; // Move X + Y coordinate. 1st point is the one moving. event.type = "pointermove"; event.clientX = 1700; event.clientY = 1700; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialRadiusOffset: ValChange.Decrease, inertialPanningX: ValChange.Decrease, inertialPanningY: ValChange.Increase })).to.be.true; // One of the buttons button up. (Leave zoom mode.) event.type = "pointerup"; event.pointerType = "touch"; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Move X and Y coordinate of remaining pressed point. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2700; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialBetaOffset: ValChange.Decrease })).to.be.true; // Other button button up. (Now moves should have no affect.) event.type = "pointerup"; event.pointerType = "touch"; event.button = 1; event.pointerId = 2; simulateEvent(this.cameraInput, event); // Move X and Y coordinate. event.type = "pointermove"; event.clientX = 3000; event.clientY = 4000; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; }); }); describe("multiTouchPanAndZoom disabled", function () { it("pinchDeltaPercentage enabled", function () { // Multiple button presses not interpreted as multitouch. this.cameraInput.multiTouchPanAndZoom = false; // Zoom changes are a percentage of current value. this.cameraInput.pinchDeltaPercentage = 10; // Panning not enabled. this.cameraInput.panningSensibility = 3; var event: MockPointerEvent = eventTemplate(<HTMLElement>this._canvas); // 1st button down. event.type = "pointerdown"; event.pointerType = "touch"; event.clientX = 1000; event.clientY = 200; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Start moving before 2nd button has been pressed. event.type = "pointermove"; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Move X coordinate. event.type = "pointermove"; event.clientX = 1500; event.clientY = 200; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialAlphaOffset: ValChange.Decrease })).to.be.true; // 2nd button down. (Enter zoom mode.) event.type = "pointerdown"; event.pointerType = "touch"; event.button = 1; event.pointerId = 2; simulateEvent(this.cameraInput, event); // Start move of 2nd pointer. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2000; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Move Y coordinate. 2nd point is the one moving. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2500; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialRadiusOffset: ValChange.Increase })).to.be.true; // Move X + Y coordinate. 1st point is the one moving. event.type = "pointermove"; event.clientX = 1700; event.clientY = 1700; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialRadiusOffset: ValChange.Decrease })).to.be.true; // One of the buttons button up. (Leave zoom mode.) event.type = "pointerup"; event.pointerType = "touch"; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Move X and Y coordinate of remaining pressed point. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2700; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialBetaOffset: ValChange.Decrease })).to.be.true; // 1st button down again event.type = "pointerdown"; event.pointerType = "touch"; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Start move of 1st button. // This time trigger more than 20 pointermove events without moving more // than pinchToPanMaxDistance to lock into "pan" mode. event.type = "pointermove"; event.clientX = 1000; event.clientY = 1000; event.button = -1; event.pointerId = 1; for (let i = 0; i < 21; i++) { event.clientX++; simulateEvent(this.cameraInput, event); } expect(verifyChanges(this.camera, this.cameraCachePos, { inertialPanningX: ValChange.Decrease })).to.be.true; // Now we are in "pan" mode, we can move 1st pointer larger distances. event.type = "pointermove"; event.clientX = 5000; event.clientY = 5000; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialPanningX: ValChange.Decrease, inertialPanningY: ValChange.Increase })).to.be.true; // One of the buttons button up. (Leave pan mode.) event.type = "pointerup"; event.pointerType = "touch"; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Other button button up. (Now moves should have no affect.) event.type = "pointerup"; event.pointerType = "touch"; event.button = 1; event.pointerId = 2; simulateEvent(this.cameraInput, event); // Move X and Y coordinate. event.type = "pointermove"; event.clientX = 3000; event.clientY = 4000; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; }); it("pinchDeltaPercentage disabled", function () { // Multiple button presses not interpreted as multitouch. this.cameraInput.multiTouchPanAndZoom = false; // Zoom changes are not a percentage of current value. this.cameraInput.pinchDeltaPercentage = 0; // Panning not enabled. this.cameraInput.panningSensibility = 3; var event: MockPointerEvent = eventTemplate(<HTMLElement>this._canvas); // 1st button down. event.type = "pointerdown"; event.pointerType = "touch"; event.clientX = 1000; event.clientY = 200; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Start moving before 2nd button has been pressed. event.type = "pointermove"; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Move X coordinate. event.type = "pointermove"; event.clientX = 1500; event.clientY = 200; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialAlphaOffset: ValChange.Decrease })).to.be.true; // 2nd button down. (Enter zoom mode.) event.type = "pointerdown"; event.pointerType = "touch"; event.button = 1; event.pointerId = 2; simulateEvent(this.cameraInput, event); // Start move of 2nd pointer. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2000; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Move Y coordinate. 2nd point is the one moving. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2500; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialRadiusOffset: ValChange.Increase })).to.be.true; // Move X + Y coordinate. 1st point is the one moving. event.type = "pointermove"; event.clientX = 1700; event.clientY = 1700; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialRadiusOffset: ValChange.Decrease })).to.be.true; // One of the buttons button up. (Leave zoom mode.) event.type = "pointerup"; event.pointerType = "touch"; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Move X and Y coordinate of remaining pressed point. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2700; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialBetaOffset: ValChange.Decrease })).to.be.true; // 1st button down again event.type = "pointerdown"; event.pointerType = "touch"; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Start move of 1st button. // This time trigger more than 20 pointermove events without moving more // than pinchToPanMaxDistance to lock into "pan" mode. event.type = "pointermove"; event.clientX = 1000; event.clientY = 1000; event.button = -1; event.pointerId = 1; for (let i = 0; i < 21; i++) { event.clientX++; simulateEvent(this.cameraInput, event); } expect(verifyChanges(this.camera, this.cameraCachePos, { inertialPanningX: ValChange.Decrease })).to.be.true; // Now we are in "pan" mode, we can move 1st pointer larger distances. event.type = "pointermove"; event.clientX = 5000; event.clientY = 5000; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialPanningX: ValChange.Decrease, inertialPanningY: ValChange.Increase })).to.be.true; // One of the buttons button up. (Leave pan mode.) event.type = "pointerup"; event.pointerType = "touch"; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Other button button up. (Now moves should have no affect.) event.type = "pointerup"; event.pointerType = "touch"; event.button = 1; event.pointerId = 2; simulateEvent(this.cameraInput, event); // Move X and Y coordinate. event.type = "pointermove"; event.clientX = 3000; event.clientY = 4000; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; }); }); }); describe("loose focus", function () { it("cancels drag", function () { // Multiple button presses interpreted as "pinch" and "swipe". this.cameraInput.multiTouchPanAndZoom = true; // Zoom changes are a percentage of current value. this.cameraInput.pinchDeltaPercentage = 10; // Panning not enabled. this.cameraInput.panningSensibility = 0; var event: MockPointerEvent = eventTemplate(<HTMLElement>this._canvas); // 1st button down. event.type = "pointerdown"; event.pointerType = "touch"; event.clientX = 1000; event.clientY = 200; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Start moving before 2nd button has been pressed. event.type = "pointermove"; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Move X coordinate. event.type = "pointermove"; event.clientX = 1500; event.clientY = 200; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialAlphaOffset: ValChange.Decrease })).to.be.true; // Lost focus (<any>this.cameraInput)._onLostFocus(); // Move X + Y coordinate. Should have no affect after loosing focus. event.type = "pointermove"; event.clientX = 1700; event.clientY = 1700; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; }); it("cancels double drag", function () { // Multiple button presses interpreted as "pinch" and "swipe". this.cameraInput.multiTouchPanAndZoom = true; // Zoom changes are a percentage of current value. this.cameraInput.pinchDeltaPercentage = 10; // Panning not enabled. this.cameraInput.panningSensibility = 0; var event: MockPointerEvent = eventTemplate(<HTMLElement>this._canvas); // 1st button down. event.type = "pointerdown"; event.pointerType = "touch"; event.clientX = 1000; event.clientY = 200; event.button = 0; event.pointerId = 1; simulateEvent(this.cameraInput, event); // Start moving before 2nd button has been pressed. event.type = "pointermove"; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Move X coordinate. event.type = "pointermove"; event.clientX = 1500; event.clientY = 200; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialAlphaOffset: ValChange.Decrease })).to.be.true; // 2nd button down. (Enter zoom mode.) event.type = "pointerdown"; event.pointerType = "touch"; event.button = 1; event.pointerId = 2; simulateEvent(this.cameraInput, event); // Start move of 2nd pointer. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2000; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; // Move Y coordinate. 2nd point is the one moving. event.type = "pointermove"; event.clientX = 2000; event.clientY = 2500; event.button = -1; event.pointerId = 2; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, { inertialRadiusOffset: ValChange.Increase })).to.be.true; // Lost focus (<any>this.cameraInput)._onLostFocus(); // Move X + Y coordinate. Should have no affect after loosing focus. event.type = "pointermove"; event.clientX = 1700; event.clientY = 1700; event.button = -1; event.pointerId = 1; simulateEvent(this.cameraInput, event); expect(verifyChanges(this.camera, this.cameraCachePos, {})).to.be.true; }); }); describe("double click", function () { it("doesnt restore save position", function () { // Disable restoring position. this.camera.useInputToRestoreState = false; this.camera.alpha = 10; this.camera.beta = 10; this.camera.radius = 10; this.camera.storeState(); this.camera.alpha = 20; this.camera.beta = 20; this.camera.radius = 20; var event: MockPointerEvent = eventTemplate(<HTMLElement>this._canvas); event.type = "POINTERDOUBLETAP"; simulateEvent(this.cameraInput, event); expect(this.camera.alpha).to.be.equal(20); expect(this.camera.beta).to.be.equal(20); expect(this.camera.radius).to.be.equal(20); }); it("restores save position", function () { // Enable restoring position. this.camera.useInputToRestoreState = true; this.camera.alpha = 10; this.camera.beta = 10; this.camera.radius = 10; this.camera.storeState(); this.camera.alpha = 20; this.camera.beta = 20; this.camera.radius = 20; var event: MockPointerEvent = eventTemplate(<HTMLElement>this._canvas); event.type = "POINTERDOUBLETAP"; simulateEvent(this.cameraInput, event); expect(this.camera.alpha).to.be.equal(10); expect(this.camera.beta).to.be.equal(10); expect(this.camera.radius).to.be.equal(10); }); }); });
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type CommerceSelectShippingOptionInput = { clientMutationId?: string | null; id: string; selectedShippingQuoteId: string; }; export type SelectShippingOptionMutationVariables = { input: CommerceSelectShippingOptionInput; }; export type SelectShippingOptionMutationResponse = { readonly commerceSelectShippingOption: { readonly orderOrError: { readonly __typename: "CommerceOrderWithMutationSuccess"; readonly order?: { readonly lineItems: { readonly edges: ReadonlyArray<{ readonly node: { readonly shippingQuoteOptions: { readonly edges: ReadonlyArray<{ readonly " $fragmentRefs": FragmentRefs<"ShippingQuotes_shippingQuotes">; } | null> | null; } | null; } | null; } | null> | null; } | null; }; readonly error?: { readonly type: string; readonly code: string; readonly data: string | null; }; }; } | null; }; export type SelectShippingOptionMutation = { readonly response: SelectShippingOptionMutationResponse; readonly variables: SelectShippingOptionMutationVariables; }; /* mutation SelectShippingOptionMutation( $input: CommerceSelectShippingOptionInput! ) { commerceSelectShippingOption(input: $input) { orderOrError { __typename ... on CommerceOrderWithMutationSuccess { __typename order { __typename lineItems { edges { node { shippingQuoteOptions { edges { ...ShippingQuotes_shippingQuotes } } id } } } id } } ... on CommerceOrderWithMutationFailure { error { type code data } } } } } fragment ShippingQuotes_shippingQuotes on CommerceShippingQuoteEdge { node { id displayName isSelected price(precision: 2) priceCents } } */ const node: ConcreteRequest = (function(){ var v0 = [ { "defaultValue": null, "kind": "LocalArgument", "name": "input", "type": "CommerceSelectShippingOptionInput!" } ], v1 = [ { "kind": "Variable", "name": "input", "variableName": "input" } ], v2 = { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null }, v3 = { "kind": "InlineFragment", "selections": [ { "alias": null, "args": null, "concreteType": "CommerceApplicationError", "kind": "LinkedField", "name": "error", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "type", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "code", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "data", "storageKey": null } ], "storageKey": null } ], "type": "CommerceOrderWithMutationFailure" }, v4 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }; return { "fragment": { "argumentDefinitions": (v0/*: any*/), "kind": "Fragment", "metadata": null, "name": "SelectShippingOptionMutation", "selections": [ { "alias": null, "args": (v1/*: any*/), "concreteType": "CommerceSelectShippingOptionPayload", "kind": "LinkedField", "name": "commerceSelectShippingOption", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": null, "kind": "LinkedField", "name": "orderOrError", "plural": false, "selections": [ { "kind": "InlineFragment", "selections": [ (v2/*: any*/), { "alias": null, "args": null, "concreteType": null, "kind": "LinkedField", "name": "order", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceLineItemConnection", "kind": "LinkedField", "name": "lineItems", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceLineItemEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceLineItem", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceShippingQuoteConnection", "kind": "LinkedField", "name": "shippingQuoteOptions", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceShippingQuoteEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "ShippingQuotes_shippingQuotes" } ], "storageKey": null } ], "storageKey": null } ], "storageKey": null } ], "storageKey": null } ], "storageKey": null } ], "storageKey": null } ], "type": "CommerceOrderWithMutationSuccess" }, (v3/*: any*/) ], "storageKey": null } ], "storageKey": null } ], "type": "Mutation" }, "kind": "Request", "operation": { "argumentDefinitions": (v0/*: any*/), "kind": "Operation", "name": "SelectShippingOptionMutation", "selections": [ { "alias": null, "args": (v1/*: any*/), "concreteType": "CommerceSelectShippingOptionPayload", "kind": "LinkedField", "name": "commerceSelectShippingOption", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": null, "kind": "LinkedField", "name": "orderOrError", "plural": false, "selections": [ (v2/*: any*/), { "kind": "InlineFragment", "selections": [ (v2/*: any*/), { "alias": null, "args": null, "concreteType": null, "kind": "LinkedField", "name": "order", "plural": false, "selections": [ (v2/*: any*/), { "alias": null, "args": null, "concreteType": "CommerceLineItemConnection", "kind": "LinkedField", "name": "lineItems", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceLineItemEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceLineItem", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceShippingQuoteConnection", "kind": "LinkedField", "name": "shippingQuoteOptions", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceShippingQuoteEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceShippingQuote", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ (v4/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "displayName", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "isSelected", "storageKey": null }, { "alias": null, "args": [ { "kind": "Literal", "name": "precision", "value": 2 } ], "kind": "ScalarField", "name": "price", "storageKey": "price(precision:2)" }, { "alias": null, "args": null, "kind": "ScalarField", "name": "priceCents", "storageKey": null } ], "storageKey": null } ], "storageKey": null } ], "storageKey": null }, (v4/*: any*/) ], "storageKey": null } ], "storageKey": null } ], "storageKey": null }, (v4/*: any*/) ], "storageKey": null } ], "type": "CommerceOrderWithMutationSuccess" }, (v3/*: any*/) ], "storageKey": null } ], "storageKey": null } ] }, "params": { "id": null, "metadata": {}, "name": "SelectShippingOptionMutation", "operationKind": "mutation", "text": "mutation SelectShippingOptionMutation(\n $input: CommerceSelectShippingOptionInput!\n) {\n commerceSelectShippingOption(input: $input) {\n orderOrError {\n __typename\n ... on CommerceOrderWithMutationSuccess {\n __typename\n order {\n __typename\n lineItems {\n edges {\n node {\n shippingQuoteOptions {\n edges {\n ...ShippingQuotes_shippingQuotes\n }\n }\n id\n }\n }\n }\n id\n }\n }\n ... on CommerceOrderWithMutationFailure {\n error {\n type\n code\n data\n }\n }\n }\n }\n}\n\nfragment ShippingQuotes_shippingQuotes on CommerceShippingQuoteEdge {\n node {\n id\n displayName\n isSelected\n price(precision: 2)\n priceCents\n }\n}\n" } }; })(); (node as any).hash = 'b71546b77d6db4f5be7777383c540e4b'; export default node;
the_stack
import { DynamsoftEnums as Dynamsoft } from "./Dynamsoft.Enum"; import { WebTwainEdit } from "./WebTwain.Edit"; export interface WebTwainAcquire extends WebTwainEdit { /** * Start image acquisition. * @param deviceConfiguration Configuration for the acquisition. * @param successCallback A callback function that is executed if the request succeeds. * @param failureCallback A callback function that is executed if the request fails. * @argument errorCode The error code. * @argument errorString The error string. */ AcquireImage( successCallBack?: () => void, failureCallBack?: ( errorCode: number, errorString: string) => void ): void; AcquireImage( deviceConfiguration?: DeviceConfiguration, successCallBack?: () => void, failureCallBack?: ( deviceConfiguration: DeviceConfiguration, errorCode: number, errorString: string) => void ): void; /** * Close the data source (a TWAIN/ICA/SANE device which in most cases is a scanner) to free it to be used by other applications. */ CloseSource(): boolean; /** * Close the data source (a TWAIN/ICA/SANE device which in most cases is a scanner) to free it to be used by other applications. */ CloseSourceAsync(): Promise<boolean>; /** * Disable the data source (a TWAIN/ICA/SANE device which in most cases is a scanner) to stop the acquiring process. If the data source's user interface is displayed, it will be closed. */ DisableSource(): boolean; /** * Enable the data source to start the acquiring process. */ EnableSource(): boolean; /** * Display the TWAIN source's built-in user interface. * @param successCallback A callback function that is executed if the request succeeds. * @param failureCallback A callback function that is executed if the request fails. * @argument errorCode The error code. * @argument errorString The error string. */ EnableSourceUI( successCallBack: () => void, failureCallBack: ( errorCode: number, errorString: string) => void ): void; /** * Load a data source to get it ready to acquire images. */ OpenSource(): boolean; /** * Return all available data sources (scanners, etc.) and optionally all detailed information about them. * @param bIncludeDetails Whether to return more details about the data sources or just their names. */ /** * Load a data source to get it ready to acquire images. */ OpenSourceAsync(): Promise<boolean>; GetSourceNames(bIncludeDetails?: boolean): string[] | SourceDetails[]; /** * Return all available data sources (scanners, etc.) and optionally all detailed information about them. * @param bIncludeDetails Whether to return more details about the data sources or just their names. */ GetSourceNamesAsync(bIncludeDetails: boolean): Promise<string[] | SourceDetails[]>; /** * Bring up the Source Selection User Interface (UI) for the user to choose a data source. * @param successCallback A callback function that is executed if the request succeeds. * @param failureCallback A callback function that is executed if the request fails. * @argument errorCode The error code. * @argument errorString The error string. */ SelectSource( successCallBack?: () => void, failureCallBack?: (errorCode: number, errorString: string) => void ): boolean | void; /** * Bring up the Source Selection User Interface (UI) for the user to choose a data source. * @param successCallback A callback function that is executed if the request succeeds. * @param failureCallback A callback function that is executed if the request fails. * @argument errorCode The error code. * @argument errorString The error string. */ SelectSourceAsync( successCallBack?: () => void, failureCallBack?: (errorCode: number, errorString: string) => void ): Promise<boolean>; /** * Select a data source by its index. * @param index The index of the data source. */ SelectSourceByIndex(index: number): boolean; /** * Select a data source by its index. * @param index The index of the data source. */ SelectSourceByIndexAsync(index: number): Promise<boolean>; /** * Sets a timer which stops the data source opening process once it expires. * @param duration Define the duration of the timer (in milliseconds). */ SetOpenSourceTimeout(duration: number): boolean; /** * Start the acquisition by passing all settings at once. * @param scanSetup Configuration for the acquisition. */ startScan(scanSetup: ScanSetup): Promise<ScanSetup>; /** * Cancels all pending transfers. */ CancelAllPendingTransfers(): boolean; /** * Closes and unloads Data Source Manager. */ CloseSourceManager(): boolean; /** * Closes and unloads Data Source Manager. */ CloseSourceManagerAsync(): Promise<boolean>; /** * Closes the scanning process to release resources on the machine. */ CloseWorkingProcess(): boolean; /** * Ejects the current page and begins scanning the next page in the document feeder. */ FeedPage(): boolean; /** * Get the custom data source data and saves the data in a specified file. * @param fileName The path of the file to save the data source data to. */ GetCustomDSData(fileName: string): boolean; /** * Gets custom DS data and returns it in a base64 string. */ GetCustomDSDataEx(): string; /** * Inspect the current data source and return whether it is a scanner, a webcam, etc. */ GetDeviceType(): number; /** * Get the name of a data source by its index in data source manager source list. * @param index The index of the data source. */ GetSourceNameItems(index: number): string; /** * Load and open data source manager. */ OpenSourceManager(): boolean; /** * Load and open data source manager. */ OpenSourceManagerAsync(): Promise<boolean>; /** * Reset the image layout in the data source. */ ResetImageLayout(): boolean; /** * If called while {IfFeederEnabled} property is true, the data source will return the current page to the input area and return the last page from the output area into the acquisition area. */ RewindPage(): boolean; /** * Sets custom data source data to be used for scanning, the data is stored in a file which can be regarded as a scanning profile. * @param fileName The path of the file. */ SetCustomDSData(fileName: string): boolean; /** * Set custom data source data to be used for scanning, the input is a base64 string. * @param dsDataString The string that contains custom data source data. */ SetCustomDSDataEx(dsDataString: string): boolean; /** * Set the file transfer information to be used in File Transfer mode. * @param fileName The path to transfer the file to. * @param fileFormat The format of the file. */ SetFileXferInfo( fileName: string, fileFormat: Dynamsoft.EnumDWT_FileFormat | number ): boolean; /** * Set the left, top, right, and bottom sides of the image layout * rectangle for the current data source. The image layout rectangle * defines a frame of the data source's scanning area to be acquired. * @param left Specify the rectangle (leftmost coordinate). * @param top Specify the rectangle (topmost coordinate). * @param right Specify the rectangle (rightmost coordinate). * @param bottom Specify the rectangle (bottommost coordinate). */ SetImageLayout( left: number, top: number, right: number, bottom: number ): boolean; /** * Return or set the pixel bit depth for the current value of `PixelType`. */ BitDepth: number; /** * Return or set whether newly acquired images are inserted or appended. */ IfAppendImage: boolean; /** * Return or set whether to close the user interface after all images have been acquired. */ IfDisableSourceAfterAcquire: boolean; /** * Return or set whether to enable duplex scanning (in other words, whether to scan both sides of the paper). */ IfDuplexEnabled: boolean; /** * Return or set whether a data source's Automatic Document Feeder (ADF) is enabled for scanning. */ IfFeederEnabled: boolean; /** * Return or set whether the data source displays the user interface when scanning. */ IfShowUI: boolean; /** * Return or set whether to use TWAIN or ICA protocol on macOS. */ ImageCaptureDriverType: Dynamsoft.EnumDWT_Driver | number; /** * Return or set the page size the data source uses to acquire images. */ PageSize: Dynamsoft.EnumDWT_CapSupportedSizes | number; /** * Return or set the pixel type used when acquiring images. */ PixelType: Dynamsoft.EnumDWT_PixelType | number; /** * Return or set the resolution used when acquiring images. */ Resolution: number; /** * Returns how many data sources are available on the local system. */ readonly SourceCount: number; /** * Return or set the brightness to be used for scanning by the data source. */ Brightness: number; /** * Return or set Contrast to be used for scanning by the data source. */ Contrast: number; /** * Return the device name of current source. */ readonly CurrentSourceName: string; /** * Return a value that indicates the data source status. */ DataSourceStatus: number; /** * Return the name of the default source. */ DefaultSourceName: string; /** * Return whether the source supports duplex. If yes, it further returns the level of duplex the data source supports. */ readonly Duplex: Dynamsoft.EnumDWT_DUPLEX | number; /** * Return or set whether to enable the data source's auto-brightness feature. */ IfAutoBright: boolean; /** * Return or set whether the data source (the scanner) discards blank images during scanning automatically. */ IfAutoDiscardBlankpages: boolean; /** * Return or set whether to enable the data source's automatic document feeding process. */ IfAutoFeed: boolean; /** * Return or set whether to enable the data source's automatic border detection feature. */ IfAutomaticBorderDetection: boolean; /** * Return or set whether to enable the data source's automatic skew correction feature. */ IfAutomaticDeskew: boolean; /** * Return or set whether to enable the data source's automatic document scanning process. */ IfAutoScan: boolean; /** * Return whether or not there are documents loaded in the data source's feeder. */ readonly IfFeederLoaded: boolean; /** * Return whether the Source has a paper sensor that can detect pages on the ADF or Flatbed. */ readonly IfPaperDetectable: boolean; /** * Return or set whether the data source displays a progress indicator during acquisition and transfer. */ IfShowIndicator: boolean; /** * Return whether the data source supports acquisitions with the UI (User Interface) disabled. */ readonly IfUIControllable: boolean; /** * Return or set whether the new TWAIN DSM (data source Manager) is used for acquisitions. The new TWAIN DSM is a DLL called 'TWAINDSM.dll' while the default | old DSM is called 'twain_32.dll'. */ IfUseTwainDSM: boolean; /** * Return the value of the bottom edge of the current image frame (in Unit). */ readonly ImageLayoutFrameBottom: number; /** * Return the value of the left edge of the current image frame (in Unit). */ readonly ImageLayoutFrameLeft: number; /** * Return the value of the right edge of the current image frame (in Unit). */ readonly ImageLayoutFrameRight: number; /** * Return the value of the top edge of the current image frame (in Unit). */ readonly ImageLayoutFrameTop: number; /** * Return the document number of the current image. */ readonly ImageLayoutDocumentNumber: number; /** * Return the page number of the current image. */ readonly ImageLayoutPageNumber: number; /** * Return the bit depth of the current image. */ readonly ImageBitsPerPixel: number; /** * Return the pixel type of the current image. */ readonly ImagePixelType: Dynamsoft.EnumDWT_PixelType | number; /** * Return the length of the current image. */ readonly ImageLength: number; /** * Return the width of the current image. */ readonly ImageWidth: number; /** * Return the horizontal resolution of the current image. */ readonly ImageXResolution: number; /** * Return the vertical resolution of the current image. */ readonly ImageYResolution: number; /** * Return the data of the magnetic data if the data source supports magnetic data recognition. */ readonly MagData: string; /** * Return the type of the magnetic data if the data source supports magnetic data recognition. */ readonly MagType: Dynamsoft.EnumDWT_MagType | number; /** * Return the number of transfers the data source is ready to supply upon demand. */ readonly PendingXfers: number; /** * Return or set the pixel flavor to be used for acquiring images. */ PixelFlavor: number; /** * Return or set the data source's transfer mode. */ TransferMode: Dynamsoft.EnumDWT_TransferMode | number; /** * Return or set the unit of measure for all quantities. */ Unit: Dynamsoft.EnumDWT_UnitType | number; /** * Return and set the number of images your application is willing to accept for each scan job. */ XferCount: number; /** * Gets detailed information about all capabilities of the current data source. * @param successCallback A callback function that is executed if the request succeeds. * @param failureCallback A callback function that is executed if the request fails. * @argument capabilityDetails Detailed information about the specified capabilities. * @argument errorCode The error code. * @argument errorString The error string. */ getCapabilities( succssCallback: (capabilityDetails: CapabilityDetails[]) => void, failureCallback: ( errorCode: number, errorString: string ) => void ): void; /** * Sets up one or multiple capabilities in one call. * @param capabilities A object that describes how to set capabilities. * @param successCallback A callback function that is executed if the request succeeds. * @param failureCallback A callback function that is executed if the request fails. * @argument capabilities The capabilities to set. */ setCapabilities( capabilities: Capabilities, succssCallback: (capabilities: Capabilities) => void, failureCallback: (capabilities: Capabilities) => void ): void; /** * [Deprecation] Specifies the capabiltiy to be negotiated. This is a runtime property. * [Alternative] Use getCapabilities() and setCapabilities() instead. */ Capability: Dynamsoft.EnumDWT_Cap; /** * [Deprecation] Return or set the index (0-based) of * a list to indicate the Current Value when the value of * the CapType property is TWON_ENUMERATION. If the data type * of the capability is String, the list is in CapItemsString property. * For other data types, the list is in CapItems property. This is a runtime property. * [Alternative] Use getCapabilities() and setCapabilities() instead. */ CapCurrentIndex: number; /** * [Deprecation] Return or set the current value in a range when the * value of the CapType property is TWON_RANGE. This is a runtime property. * [Alternative] Use getCapabilities() and setCapabilities() instead. */ CapCurrentValue: number; /** * [Deprecation] Return the index (0-based) of a list to indicate the * Default Value when the value of the CapType property is TWON_ENUMERATION. * If the data type of the capability is String, the list is in CapItemsString property. * For other data types, the list is in CapItems property. This is a runtime, read-only property. * [Alternative] Use getCapabilities() and setCapabilities() instead. */ readonly CapDefaultIndex: number; /** * [Deprecation] Return the default value in a range when the value of the * CapType property is TWON_RANGE. This is a runtime, read-only property. * [Alternative] Use getCapabilities() and setCapabilities() instead. */ CapDefaultValue: number; /** * [Deprecation] Retruns the description for a capability * [Alternative] Use getCapabilities() and setCapabilities() instead. */ CapDescription: string; /** * [Deprecation] Return or set the maximum value in a range when the * value of the CapType property is TWON_RANGE. This is a runtime property. * [Alternative] Use getCapabilities() and setCapabilities() instead. */ CapMaxValue: number; /** * [Deprecation] Return or set the minimum value in a range when the * value of the CapType property is TWON_RANGE. This is a runtime property. * [Alternative] Use getCapabilities() and setCapabilities() instead. */ CapMinValue: number; /** * [Deprecation] Return or set how many items are in the list when the * value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. * For String data type, the list is in CapItemsString property. * For other data types, the list is in CapItems property. * This is a runtime property. * [Alternative] Use getCapabilities() and setCapabilities() instead. */ CapNumItems: number; /** * [Deprecation] Return or set the step size in a range when the value * of the CapType property is TWON_RANGE. This is a runtime property. * [Alternative] Use getCapabilities() and setCapabilities() instead. */ CapStepSize: number; /** * [Deprecation] Return or set the type of capability container used * to exchange capability information between application and source. * This is a runtime property. */ CapType: Dynamsoft.EnumDWT_CapType; /** * [Deprecation] Return or set the value of the capability specified by * Capability property when the value of the CapType property is TWON_ONEVALUE. * This is a runtime property. * [Alternative] Use getCapabilities() and setCapabilities() instead. */ CapValue: number; /** * [Deprecation] Return or set the string value for a capability when the * value of the CapType property is TWON_ONEVALUE. This is a runtime property. * [Alternative] Use getCapabilities() and setCapabilities() instead. */ CapValueString: string; /** * [Deprecation] Return or set the value type for reading the value of a capability. * This is a runtime property. * [Alternative] Use getCapabilities() and setCapabilities() instead. */ CapValueType: number; /** * [Deprecation] Gets information of the capability specified by the Capability property. * [Alternative] Use getCapabilities() and setCapabilities() instead. */ CapGet(): boolean; /** * [Deprecation] Return the Source's current Value for the specified capability. * [Alternative] Use getCapabilities() and setCapabilities() instead. */ CapGetCurrent(): boolean; /** * [Deprecation] Return the Source's Default Value for the specified capability. * This is the Source's preferred default value. * [Alternative] Use getCapabilities() and setCapabilities() instead. */ CapGetDefault(): boolean; /** * [Deprecation] Return the value of the bottom-most edge of the specified frame. * [Alternative] Use getCapabilities() and setCapabilities() instead. * @param index specifies the value of which frame to get. The index is 0-based. */ CapGetFrameBottom(index: number): number; /** * [Deprecation] Return the value (in Unit) of the left-most edge of the specified frame. * [Alternative] Use getCapabilities() and setCapabilities() instead. * @param index specifies the value of which frame to get. The index is 0-based. */ CapGetFrameLeft(index: number): number; /** * [Deprecation] Return the value (in Unit) of the left-most edge of the specified frame. * [Alternative] Use getCapabilities() and setCapabilities() instead. * @param index specifies the value of which frame to get. The index is 0-based. */ CapGetFrameRight(index: number): number; /** * [Deprecation] Return the value (in Unit) of the top-most edge of the specified frame. * [Alternative] Use getCapabilities() and setCapabilities() instead. * @param index specifies the value of which frame to get. The index is 0-based. */ CapGetFrameTop(index: number): number; /** * [Deprecation] Use getCapabilities() and setCapabilities() instead. */ CapGetHelp(index: number): number; /** * [Deprecation] Use getCapabilities() and setCapabilities() instead. */ CapGetLabel(index: number): number; /** * [Deprecation] Use getCapabilities() and setCapabilities() instead. */ CapGetLabels(index: number): number; /** * [Deprecation] Queries whether the Source supports a particular operation on the capability. * [Alternative] Use getCapabilities() and setCapabilities() instead. * @param {Dynamsoft.EnumDWT_MessageType} messageType specifies the type of capability operation. */ CapIfSupported(messageType: Dynamsoft.EnumDWT_MessageType): boolean; /** * [Deprecation] Changes the Current Value of the capability specified by * Capability property back to its power-on value. * [Alternative] Use getCapabilities() and setCapabilities() instead. */ CapReset(): boolean; /** * [Deprecation] Sets the current capability using the container type specified by * CapType property. The current capability is specified by Capability property. * [Alternative] Use getCapabilities() and setCapabilities() instead. */ CapSet(): boolean; /** * [Deprecation] Sets the values of the specified frame. * [Alternative] Use getCapabilities() and setCapabilities() instead. * @param index specifies the values of which frame to set. The index is 0-based. * @param left the value (in Unit) of the left-most edge of the specified frame. * @param top the value (in Unit) of the top-most edge of the specified frame. * @param right the value (in Unit) of the right-most edge of the specified frame. * @param bottom the value (in Unit) of the bottom-most edge of the specified frame. */ CapSetFrame(index: number, left: number, top: number, right: number, bottom: number): boolean; /** * Get the cap item value of the capability specified by Capability property, * when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. * [Alternative] Use getCapabilities() and setCapabilities() instead. * @param index Index is 0-based. It is the index of the cap item. */ GetCapItems(index: number): number; /** * Returns the cap item value of the capability specified by Capability property, * when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. * [Alternative] Use getCapabilities() and setCapabilities() instead. * @param index Index is 0-based. It is the index of the cap item. */ GetCapItemsString(index: number): string; /** * [Deprecation] Set the value of the specified cap item. * @param index Index is 0-based. It is the index of the cap item. * @param newVal For string type, please use CapItemsstring property. */ SetCapItems(index: number, newVal: number): void; /** * [Deprecation] Set the cap item value of the capability specified by Capability property, * when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. * [Alternative] Use getCapabilities() and setCapabilities() instead. * @param index Index is 0-based. It is the index of the cap item. * @param newVal The new value to be set. */ SetCapItemsString(index: number, newVal: string): void; } export interface DeviceConfiguration { /** * Whether to show the built-in User Interface from the device vendor */ IfShowUI?: boolean | undefined; /** * How a pixel is represented. Basically it means whether to scan in color, grey or black & white */ PixelType?: Dynamsoft.EnumDWT_PixelType | number | string | undefined; /** * How detailed is the acquisition. Measured by dots per pixel (DPI) */ Resolution?: number | undefined; /** * Whether to use the document feeder or the flatbed of the device. */ IfFeederEnabled?: boolean | undefined; /** * Whether to scan one side or both sides of each paper. */ IfDuplexEnabled?: boolean | undefined; /** * Whether to close the built-in User Interface after aquisition. Only valid when {IfShowUI} is true. */ IfDisableSourceAfterAcquire?: boolean | undefined; /** * Whether to retrieve information about the image after it's transferred. */ IfGetImageInfo?: boolean | undefined; /** * Whether to retrieve extended information about the image after it's transferred. */ IfGetExtImageInfo?: boolean | undefined; /** * How much extended information is retrieved. Only valid when {IfGetExtImageInfo} is true. */ extendedImageInfoQueryLevel?: number | undefined; } export interface SourceDetails { /** * The driver type which can be "TWAIN" | "ICA" | "SANE" */ DriverType?: string | undefined; /** * Information about the driver if it's DriverType is "ICA" */ DeviceInfo?: any; /** * The name of the data source. E.g. "TWAIN2 FreeImage Software Scanner". */ ProductName?: string | undefined; /** * Whether it is the default source. */ IsDefaultSource?: boolean | undefined; /** * Whether it is the current source. */ IsCurrentSource?: boolean | undefined; /** * The family name of the data source. E.g. "Software Scan". */ ProductFamily?: string | undefined; /** * The manufacturer of the data source. E.g. "TWAIN Working Group". */ Manufacturer?: string | undefined; /** * Supported Groups */ SupportedGroups?: number | undefined; /** * The version of the protocol based on which the data source is developed. */ ProtocolMajor?: number | undefined; ProtocolMinor?: number | undefined; /** * Detailed version of the data source. */ Version?: Version | undefined; } export interface Version { MajorNum?: number | undefined; MinorNum?: number | undefined; Language?: number | undefined; Country?: number | undefined; Info?: string | undefined; } export interface ScanSetup { /** * An id that specifies this specific setup. */ setupId?: string | undefined; /** * Whether to ignore or fail the acquistion when an exception is raised. Set "ignore" or "fail". */ exception?: string | undefined; /** * The name of the data source (the scanner). If not set, the default data source is used. */ scanner?: string | undefined; ui?: { /** * Whether to show the UI of the device. */ bShowUI?: boolean | undefined, /** * Whether to show the indicator of the device. */ bShowIndicator?: boolean | undefined, } | undefined; /** * The TWAIN transfer mode. */ transferMode?: Dynamsoft.EnumDWT_TransferMode | number | undefined; /** * Set how the transfer is done. */ fileXfer?: { /** * Specify the file name (or pattern) for file transfer. * Example: "C:\\WebTWAIN<%06d>.bmp" */ fileName?: string | undefined, /** * Specify the file format. */ fileFormat?: Dynamsoft.EnumDWT_FileFormat | number | undefined, /** * Specify the quality of JPEG files. */ jpegQuality?: number | undefined, /** * Specify the compression type of the file. */ compressionType?: Dynamsoft.EnumDWT_CompressionType | number | undefined } | undefined; /** * Set where the scanned images are inserted. */ insertingIndex?: number | undefined; /** * The profile is a base64 string, if present, it overrides settings and more settings. */ profile?: string | undefined; /** * Basic settings. */ settings?: { /** * "ignore" (default) or "fail". */ exception?: string | undefined, /** * Specify the pixel type. */ pixelType?: Dynamsoft.EnumDWT_PixelType | number | undefined, /** * Specify the resolution. */ resolution?: number | undefined, /** * Whether to enable document feader. */ bFeeder?: boolean | undefined, /** * Whether to enable duplex scan. */ bDuplex?: boolean | undefined } | undefined; moreSettings?: { /** * "ignore" (default) or "fail". */ exception?: string | undefined, /** * Specify the bit depth. */ bitDepth?: number | undefined, /** * Specify the page size. */ pageSize?: Dynamsoft.EnumDWT_CapSupportedSizes | number | undefined, /** * Specify the unit. */ unit?: Dynamsoft.EnumDWT_UnitType | number | undefined, /** * Specify a layout to scan, if present, it'll override pageSize. */ layout?: { left?: number | undefined, top?: number | undefined, right?: number | undefined, bottom?: number | undefined } | undefined, /** * Specify the pixel flavor. */ pixelFlavor?: Dynamsoft.EnumDWT_CapPixelFlavor | number | undefined, /** * Specify Brightness. */ brightness?: number | undefined, /** * Specify contrast. */ contrast?: number | undefined, /** * Specify how many images are transferred per session. */ nXferCount?: number | undefined, /** * Whether to enable automatic blank image detection and removal. */ autoDiscardBlankPages?: boolean | undefined, /** * Whether to enable automatic border detection. */ autoBorderDetection?: boolean | undefined, /** * Whether to enable automatic skew correction. */ autoDeskew?: boolean | undefined, /** * Whether to enable automatic brightness adjustment. */ autoBright?: boolean | undefined } | undefined; /** * A callback triggered before the scan, after the scan and after each page has been transferred. */ funcScanStatus?: ((status: Status) => void) | undefined; /** * Set up how the scanned images are outputted. */ outputSetup?: { /** * Output type. "http" is the only supported type for now. */ type?: string | undefined, /** * Set the output format. */ format?: Dynamsoft.EnumDWT_ImageType | number | undefined, /** * Specify how many times the library will try the output. */ reTries?: number | undefined, /** * Whether to use the FileUploader. */ useUploader?: false | undefined, /** * Whether to upload all images in one HTTP post. */ singlePost?: boolean | undefined, /** * Whether to show a progress bar when outputting. */ showProgressBar?: boolean | undefined, /** * Whether to remove the images after outputting. */ removeAfterOutput?: boolean | undefined, /** * A callback triggered during the outputting. * @argument fileInfo A JSON object that contains the fileName, percentage, statusCode, responseString, etc. */ funcHttpUploadStatus?: ((fileInfo: any) => void) | undefined, /** * Setup for PDF output. */ pdfSetup?: { author?: string | undefined, compression?: Dynamsoft.EnumDWT_PDFCompressionType | number | undefined, creator?: string | undefined, /** * Example: 'D:20181231' */ creationDate?: string | undefined, keyWords?: string | undefined, /** * Example: 'D:20181231' */ modifiedDate?: string | undefined, producer?: string | undefined, subject?: string | undefined, title?: string | undefined, version?: number | undefined, quality?: number | undefined } | undefined, /** * Setup for TIFF output. */ tiffSetup?: { quality?: number | undefined, compression?: Dynamsoft.EnumDWT_TIFFCompressionType | number | undefined, /** * Specify Tiff custom tags. */ tiffTags?: TiffTag[] | undefined } | undefined, /** * Setup for HTTP upload via Post. */ httpParams?: { /** * Target of the request. * Example: "http://dynamsoft.com/receivepost.aspx" */ url?: string | undefined, /** * Custom headers in the form. * Example: {md5: ""} */ headers?: any, /** * Custom form fields. * Example: {"UploadedBy": "Dynamsoft"} */ formFields?: any, /** * The maximum size of a file to be uploaded (in bytes). */ maxSizeLimit?: number | undefined, /** * Specify how many threads (<=4) are to be used. Only valid when {useUploader} is true. */ threads?: number | undefined, /** * Specify the names for the files in the form. * Example: "RemoteName<%06d>" */ remoteName?: string | undefined, /** * Specify the name(s) (pattern) of the uploaded files. * Example: "uploadedFile<%06d>.jpg" */ fileName?: string | undefined } | undefined } | undefined; } export interface Status { bScanCompleted?: boolean | undefined; event?: string | undefined; result?: { currentPageNum?: number | undefined } | undefined; } export interface TiffTag { tagIdentifier?: number | undefined; content?: string | undefined; useBase64Encoding?: boolean | undefined; } /** * Detailed information about a specific capability, */ export interface CapabilityDetails { /** * The Capability. */ capability: ValueAndLabel; /** * The container type of the Capability */ conType: ValueAndLabel; /** * The index for the current value of the Capability */ curIndex: number; /** * The current value of the Capability */ curValue: ValueAndLabel; /** * The index for the default value of the Capability */ defIndex: number; /** * The operation types that are supported by the Capability. Types include {"get", "set", "reset" "getdefault", "getcurrent"} */ query: string[]; /** * The value type of the Capability. Value types include * TWTY_BOOL: 6 * TWTY_FIX32: 7 * TWTY_FRAME: 8 * TWTY_INT8: 0 * TWTY_INT16: 1 * TWTY_INT32: 2 * TWTY_STR32: 9 * TWTY_STR64: 10 * TWTY_STR128: 11 * TWTY_STR255: 12 * TWTY_UINT8: 3 * TWTY_UINT16: 4 * TWTY_int: 5 */ valueType: ValueAndLabel; /** * The available values of the Capability */ values: ValueAndLabel[]; } export interface ValueAndLabel { /** * Numeric representation of the item */ value: Dynamsoft.EnumDWT_Cap | Dynamsoft.EnumDWT_CapType | Dynamsoft.EnumDWT_CapValueType | number; /** * Label or name of the item */ label: string; } export interface Capabilities { /** * Whether to "ignore" or "fail" the request if an exception occurs. This is an overall setting that is inherited by all capabilities. */ exceptition: string; /** * Specifies how to set capabilities */ capabilities: CapabilitySetup[]; } export interface CapabilitySetup { /** * Specify a capability */ capability: Dynamsoft.EnumDWT_Cap | number; /** * The value to set to the capability or the value of the capability after setting. */ curValue: number | string; errorCode?: number | undefined; errorString?: string | undefined; /** * Whether to "ignore" or "fail" the request if an exception occurs when setting this specific capability. */ exception?: string | undefined; }
the_stack
import Editor from '../../editor/index' import { arrForEach, forEach } from '../../utils/util' import post from '../../editor/upload/upload-core' import Progress from '../../editor/upload/progress' type ResImgItemType = string | { url: string; alt?: string; href?: string } export type ResType = { errno: number | string data: ResImgItemType[] } class UploadImg { private editor: Editor constructor(editor: Editor) { this.editor = editor } /** * 往编辑区域插入图片 * @param src 图片地址 */ public insertImg(src: string, alt?: string, href?: string): void { const editor = this.editor const config = editor.config const i18nPrefix = 'validate.' const t = (text: string, prefix: string = i18nPrefix): string => { return editor.i18next.t(prefix + text) } // 设置图片alt const altText = alt ? `alt="${alt}" ` : '' const hrefText = href ? `data-href="${encodeURIComponent(href)}" ` : '' // 先插入图片,无论是否能成功 editor.cmd.do( 'insertHTML', `<img src="${src}" ${altText}${hrefText}style="max-width:100%;" contenteditable="false"/>` ) // 执行回调函数 config.linkImgCallback(src, alt, href) // 加载图片 let img: any = document.createElement('img') img.onload = () => { img = null } img.onerror = () => { config.customAlert( t('插入图片错误'), 'error', `wangEditor: ${t('插入图片错误')},${t('图片链接')} "${src}",${t('下载链接失败')}` ) img = null } img.onabort = () => (img = null) img.src = src } /** * 上传图片 * @param files 文件列表 */ public uploadImg(files: FileList | File[]): void { if (!files.length) { return } const editor = this.editor const config = editor.config // ------------------------------ i18next ------------------------------ const i18nPrefix = 'validate.' const t = (text: string): string => { return editor.i18next.t(i18nPrefix + text) } // ------------------------------ 获取配置信息 ------------------------------ // 服务端地址 let uploadImgServer = config.uploadImgServer // base64 格式 const uploadImgShowBase64 = config.uploadImgShowBase64 // 图片最大体积 const maxSize = config.uploadImgMaxSize const maxSizeM = maxSize / 1024 / 1024 // 一次最多上传图片数量 const maxLength = config.uploadImgMaxLength // 自定义 fileName const uploadFileName = config.uploadFileName // 自定义参数 const uploadImgParams = config.uploadImgParams // 参数拼接到 url 中 const uploadImgParamsWithUrl = config.uploadImgParamsWithUrl // 自定义 header const uploadImgHeaders = config.uploadImgHeaders // 钩子函数 const hooks = config.uploadImgHooks // 上传图片超时时间 const timeout = config.uploadImgTimeout // 跨域带 cookie const withCredentials = config.withCredentials // 自定义上传图片 const customUploadImg = config.customUploadImg if (!customUploadImg) { // 没有 customUploadImg 的情况下,需要如下两个配置才能继续进行图片上传 if (!uploadImgServer && !uploadImgShowBase64) { return } } // ------------------------------ 验证文件信息 ------------------------------ const resultFiles: File[] = [] const errInfos: string[] = [] arrForEach(files, file => { // chrome 低版本 粘贴一张图时files为 [null, File] if (!file) return const name = file.name || file.type.replace('/', '.') // 兼容低版本chrome 没有name const size = file.size // chrome 低版本 name === undefined if (!name || !size) { return } // 将uploadImgAccept数组转换为正则对象 const imgType = editor.config.uploadImgAccept.join('|') const imgTypeRuleStr = `.(${imgType})$` const uploadImgAcceptRule = new RegExp(imgTypeRuleStr, 'i') if (uploadImgAcceptRule.test(name) === false) { // 后缀名不合法,不是图片 errInfos.push(`【${name}】${t('不是图片')}`) return } if (maxSize < size) { // 上传图片过大 errInfos.push(`【${name}】${t('大于')} ${maxSizeM}M`) return } // 验证通过的加入结果列表 resultFiles.push(file) }) // 抛出验证信息 if (errInfos.length) { config.customAlert(`${t('图片验证未通过')}: \n` + errInfos.join('\n'), 'warning') return } // 如果过滤后文件列表为空直接返回 if (resultFiles.length === 0) { config.customAlert(t('传入的文件不合法'), 'warning') return } if (resultFiles.length > maxLength) { config.customAlert(t('一次最多上传') + maxLength + t('张图片'), 'warning') return } // ------------------------------ 自定义上传 ------------------------------ if (customUploadImg && typeof customUploadImg === 'function') { customUploadImg(resultFiles, this.insertImg.bind(this)) // 阻止以下代码执行,重要!!! return } // ------------------------------ 上传图片 ------------------------------ // 添加图片数据 const formData = new FormData() resultFiles.forEach((file: File, index: number) => { let name = uploadFileName || file.name if (resultFiles.length > 1) { // 多个文件时,filename 不能重复 name = name + (index + 1) } formData.append(name, file) }) if (uploadImgServer) { // 添加自定义参数 const uploadImgServerArr = uploadImgServer.split('#') uploadImgServer = uploadImgServerArr[0] const uploadImgServerHash = uploadImgServerArr[1] || '' forEach(uploadImgParams, (key: string, val: string) => { // 因使用者反应,自定义参数不能默认 encode ,由 v3.1.1 版本开始注释掉 // val = encodeURIComponent(val) // 第一,将参数拼接到 url 中 if (uploadImgParamsWithUrl) { if (uploadImgServer.indexOf('?') > 0) { uploadImgServer += '&' } else { uploadImgServer += '?' } uploadImgServer = uploadImgServer + key + '=' + val } // 第二,将参数添加到 formData 中 formData.append(key, val) }) if (uploadImgServerHash) { uploadImgServer += '#' + uploadImgServerHash } // 开始上传 const xhr = post(uploadImgServer, { timeout, formData, headers: uploadImgHeaders, withCredentials: !!withCredentials, beforeSend: xhr => { if (hooks.before) return hooks.before(xhr, editor, resultFiles) }, onTimeout: xhr => { config.customAlert(t('上传图片超时'), 'error') if (hooks.timeout) hooks.timeout(xhr, editor) }, onProgress: (percent, e) => { const progressBar = new Progress(editor) if (e.lengthComputable) { percent = e.loaded / e.total progressBar.show(percent) } }, onError: xhr => { config.customAlert( t('上传图片错误'), 'error', `${t('上传图片错误')},${t('服务器返回状态')}: ${xhr.status}` ) if (hooks.error) hooks.error(xhr, editor) }, onFail: (xhr, resultStr) => { config.customAlert( t('上传图片失败'), 'error', t('上传图片返回结果错误') + `,${t('返回结果')}: ` + resultStr ) if (hooks.fail) hooks.fail(xhr, editor, resultStr) }, onSuccess: (xhr, result: ResType) => { if (hooks.customInsert) { // 自定义插入图片 hooks.customInsert(this.insertImg.bind(this), result, editor) return } if (result.errno != '0') { // 返回格式不对,应该为 { errno: 0, data: [...] } config.customAlert( t('上传图片失败'), 'error', `${t('上传图片返回结果错误')},${t('返回结果')} errno=${result.errno}` ) if (hooks.fail) hooks.fail(xhr, editor, result) return } // 成功,插入图片 const data = result.data data.forEach(link => { if (typeof link === 'string') { this.insertImg(link) } else { this.insertImg(link.url, link.alt, link.href) } }) // 钩子函数 if (hooks.success) hooks.success(xhr, editor, result) }, }) if (typeof xhr === 'string') { // 上传被阻止 config.customAlert(xhr, 'error') } // 阻止以下代码执行,重要!!! return } // ------------------------------ 显示 base64 格式 ------------------------------ if (uploadImgShowBase64) { arrForEach(files, file => { const _this = this const reader = new FileReader() reader.readAsDataURL(file) reader.onload = function () { if (!this.result) return const imgLink = this.result.toString() _this.insertImg(imgLink, imgLink) } }) } } } export default UploadImg
the_stack
import type { DocumentData, DocumentReference, FieldPath, Settings, WhereFilterOp } from '@google-cloud/firestore'; import type { Logger } from 'pino'; import type { Transaction } from './db/transaction'; import type { FirestoreConnectorModel } from './model'; import type { PickReferenceKeys, PopulatedByKeys } from './populate'; export interface Connector { connector: string options: ConnectorOptions settings?: Settings } export interface ConnectorOptions { /** * Indicates whether to connect to a locally running * Firestore emulator instance. * * Defaults to `false`. */ useEmulator?: boolean /** * Indicates whether or not to log the number of * read and write operations for every transaction * that is executed. * * Defaults to `true` for development environments * and `false` otherwise. */ logTransactionStats?: boolean /** * Indicates whether or not to log the details of * every query that is executed. * * Defaults to `false`. */ logQueries?: boolean /** * Designates the document ID to use to store the data * for "singleType" models, or when flattening is enabled. * * Defaults to `"default"`. */ singleId?: string /** * Indicate which models to flatten by RegEx. Matches against the * model's `uid` property. * * Defaults to `false` so that no models are flattened. */ flattenModels?: boolean | string | RegExp | FlattenFn | (string | RegExp | FlattenFn)[] /** * Globally allow queries that are not Firestore native. * These are implemented manually and will have poor performance, * and potentially expensive resource usage. * * Defaults to `false`. */ allowNonNativeQueries?: boolean | string | RegExp | ModelTestFn | (string | RegExp | ModelTestFn)[] /** * If `true`, then IDs are automatically generated and assigned to component instances. * This setting only applies to component models, and has no effect on other models. * * Defaults to `true`. */ ensureComponentIds?: boolean /** * If defined, enforces a maximum limit on the size of all queries. * You can use this to limit out-of-control quota usage. * * Does not apply to flattened collections which use only a single * read operation anyway. * * Defaults to `200`. */ maxQuerySize?: number /** * The field used to build the field that will store the * metadata map which holds the indexes for repeatable and * dynamic-zone components. * * If it is a string, then it will be combined with the component * field as a postfix. If it is a function, then it will be called * with the field of the attribute containing component, and the function * must return the string to be used as the field. * * Defaults to `"$meta"`. */ metadataField?: string | ((attrKey: string) => string) /** * If defined, then overrides the model that is associated with creator fields * such as `"created_by"` and `"updated_by"`. * * Defaults to the build-in Strapi Admin user model, i.e.: `{ modelKey: "user", plugin: "admin" }`. */ creatorUserModel?: string | { model: string, plugin?: string } /** * A hook called before each model is mounted. This can be used to modify any model (particularly useful * for builtin or plugin models), before it is loaded into the Firestore connector. */ beforeMountModel?: ((model: StrapiModel) => void | Promise<void>) /** * A hook called after each model is mounted. Use with caution! */ afterMountModel?: ((model: FirestoreConnectorModel) => void | Promise<void>) } export interface ModelOptions<T extends object, R extends DocumentData = DocumentData> extends StrapiModelOptions { timestamps?: boolean | [string, string] singleId?: string /** * Override connector option per model. * * Defaults to `undefined` (use connector setting). */ logQueries?: boolean /** * Override connector flattening options per model. * `false` to disable. * `true` to enable and use connector's `singleId` for the document ID. * * Defaults to `undefined` (use connector setting). */ flatten?: boolean /** * Override connector setting per model. * * Defaults to `undefined` (use connector setting). */ allowNonNativeQueries?: boolean /** * If defined, nominates a single attribute to be searched when fully-featured * search is disabled because of the `allowNonNativeQueries` setting. */ searchAttribute?: string /** * Override connector setting per model. This setting only affects component models. * * Defaults to `undefined` (use connector setting). */ ensureComponentIds?: boolean /** * Override connector setting per model. * * Defaults to `undefined` (use connector setting). */ maxQuerySize?: number /** * Override connector setting per model. * * Defaults to `undefined` (use connector setting). */ metadataField?: string | ((attrKey: AttributeKey<T>) => string) /** * Converter that is run upon data immediately before it * is stored in Firestore, and immediately after it is * retrieved from Firestore. */ converter?: Converter<T, R> /** * Override connector setting per model. * * Defaults to `undefined` (use connector setting). */ creatorUserModel?: string | { model: string, plugin?: string } /** * Makes this model a virtual model, with the given object acting as the data source. * Virtual models are not stored in Firestore, but the given object acts as the proxy * to fetch and store data in it's entirety. */ virtualDataSource?: DataSource<T> | null /** * A hook that is called inside the transaction whenever an changes. This is called before any change * is committed to the database. If an exception is thrown, then the transaction will be aborted. * Any additional write created by the hook will be committed atomically with this transaction. * * This hook is only called via the query interface (i.e. `strapi.query(...).create(...)` etc). Any operations performed directly using the model's * `runTransaction(...)` interface will bypass this hook. * * Note: This hook may be called multiple times for a single transaction, if the transaction is retried. The result * of transaction may not necessarily be committed to the database, depending on the success of the transaction. * Return a function from this hook, for any code that should be executed only once upon success of the transaction. * * @param previousData The previous value of the entity, or `undefined` if the entity is being created. * @param newData The new value of the entity, or `undefined` if the entity is being deleted. * @param transaction The transaction being run. Can be used to fetch additional entities, or make additional * atomic writes. * @returns The hook may optionally return a function, or a Promise that optionally resolves to a function. * If a promise is returned, it will be awaited before completing the transaction. * If it resolves to a function, this function will be called only once, after the transaction has been * successfully committed. * Any errors thrown by this function will be caught and ignored. * */ onChange?: TransactionOnChangeHook<T> } export type TransactionOnChangeHook<T> = (previousData: T | undefined, newData: T | undefined, transaction: Transaction) => (void | TransactionSuccessHook<T>) | PromiseLike<void | TransactionSuccessHook<T>> export type TransactionSuccessHook<T> = (result: T | undefined) => (void | PromiseLike<void>) export interface DataSource<T extends object> { /** * Indicates whether entries in this data source will have persistent and stable IDs * between server restarts. If `true`, then the connector will allow non-virtual collections * to have dominant references to this virtual collection. */ hasStableIds?: boolean getData(): { [id: string]: T } | Promise<{ [id: string]: T }> setData?(data: { [id: string]: T }): Promise<void> } export interface Converter<T, R extends DocumentData = DocumentData> { toFirestore?: (data: Partial<T>) => R fromFirestore?: (data: R) => T } declare global { const strapi: Strapi interface StrapiModelMap { } } export interface StrapiContext<T extends object = object> { strapi: Strapi modelKey: string model: FirestoreConnectorModel<T> } export interface Strapi { config: { connections: { [c: string]: Connector } hook: any appPath: string } components: StrapiModelRecord models: StrapiModelRecord contentTypes: { [key: string]: StrapiModel } admin: Readonly<StrapiPlugin> plugins: { [key: string]: Readonly<StrapiPlugin> } db: StrapiDatabaseManager connections: { [name: string]: any } log: Logger getModel(modelKey: string, plugin?: string): Readonly<FirestoreConnectorModel> query<K extends keyof StrapiModelMap>(entity: K, plugin?: string): StrapiQuery<StrapiModelMap[K]> query(entity: string, plugin?: string): StrapiQuery } export type StrapiModelRecord = { [modelKey in keyof StrapiModelMap]: Readonly<FirestoreConnectorModel<StrapiModelMap[modelKey]>> }; export interface StrapiDatabaseManager { getModel(name: string, plugin: string | undefined): FirestoreConnectorModel<any> | undefined getModelByAssoc(assoc: StrapiAttribute): FirestoreConnectorModel<any> | undefined getModelByCollectionName(collectionName: string): FirestoreConnectorModel<any> | undefined getModelByGlobalId(globalId: string): FirestoreConnectorModel<any> | undefined } export interface StrapiPlugin { models: StrapiModelRecord } export type AttributeKey<T extends object> = Extract<keyof T, string>; export interface StrapiQuery<T extends object = DocumentData> { model: StrapiModel<T> find<K extends PickReferenceKeys<T>>(params?: any, populate?: K[]): Promise<PopulatedByKeys<T, K>[]> findOne<K extends PickReferenceKeys<T>>(params?: any, populate?: K[]): Promise<PopulatedByKeys<T, K> | null> create<K extends PickReferenceKeys<T>>(values: T, populate?: K[]): Promise<PopulatedByKeys<T, K>> update<K extends PickReferenceKeys<T>>(params: any, values: T, populate?: K[]): Promise<PopulatedByKeys<T, K>> delete<K extends PickReferenceKeys<T>>(params: any, populate?: K[]): Promise<PopulatedByKeys<T, K> | null | (PopulatedByKeys<T, K> | null)[]> count(params?: any): Promise<number> search<K extends PickReferenceKeys<T>>(params: any, populate?: K[]): Promise<PopulatedByKeys<T, K>[]> countSearch(params: any): Promise<number> fetchRelationCounters<K extends PickReferenceKeys<T>>(attribute: K, entitiesIds?: string[]): Promise<RelationCounter[]> } export interface RelationCounter { id: string count: number } export interface StrapiModel<T extends object = object> { connector: string connection: string primaryKey: string primaryKeyType: StrapiAttributeType attributes: { [key: string]: StrapiAttribute } privateAttributes: { [key: string]: StrapiAttribute } collectionName: string kind: 'collectionType' | 'singleType' globalId: string plugin?: string modelName: string modelType?: 'contentType' | 'component' internal?: boolean uid: string orm: string options?: StrapiModelOptions associations: StrapiAssociation<AttributeKey<T>>[] } export interface StrapiModelOptions { timestamps?: boolean | [string, string] populateCreatorFields?: boolean } export type StrapiRelationType = 'oneWay' | 'manyWay' | 'oneToMany' | 'oneToOne' | 'manyToMany' | 'manyToOne' | 'oneToManyMorph' | 'manyToManyMorph' | 'manyMorphToMany' | 'manyMorphToOne' | 'oneMorphToOne' | 'oneMorphToMany'; export type StrapiAttributeType = 'integer' | 'float' | 'decimal' | 'biginteger' | 'string' | 'text' | 'richtext' | 'email' | 'enumeration' | 'uid' | 'date' | 'time' | 'datetime' | 'timestamp' | 'json' | 'boolean' | 'password' | 'dynamiczone' | 'component'; export interface StrapiAttribute { dominant?: boolean via?: string model?: string collection?: string filter?: string plugin?: string autoPopulate?: boolean type?: StrapiAttributeType required?: boolean component?: string components?: string[] repeatable?: boolean min?: number max?: number private?: boolean configurable?: boolean writable?: boolean visible?: boolean index?: true | string | { [key: string]: true | IndexerFn } isMeta?: boolean } export interface IndexerFn { (value: any, component: object): any } export interface FlattenFn<T extends object = any> { (model: StrapiModel<T>): string | boolean | DocumentReference | null | undefined } export interface ModelTestFn<T extends object = any> { (model: StrapiModel<T>): boolean } export interface StrapiAssociation<K extends string = string> { alias: K nature: StrapiRelationType autoPopulate: boolean /** * The `uid` of the target model, or `"*"` if this is * polymorphic. */ targetUid: string type: 'model' | 'collection' collection?: string model?: string dominant?: boolean via?: string plugin?: string filter?: string related?: FirestoreConnectorModel<any>[] tableCollectionName?: string } export interface StrapiFilter { sort?: { field: string, order: 'asc' | 'desc' }[] start?: number, limit?: number, where?: (StrapiWhereFilter | StrapiOrFilter)[] } export type StrapiWhereOperator = 'eq' | 'ne' | 'in' | 'nin' | 'contains' | 'ncontains' | 'containss' | 'ncontainss' | 'lt' | 'lte' | 'gt' | 'gte' | 'null'; export interface StrapiWhereFilter { field: string operator: StrapiWhereOperator value: any } export interface StrapiOrFilter { field?: null operator: 'or' value: StrapiWhereFilter[][] } export interface FirestoreFilter { field: string | FieldPath operator: WhereFilterOp value: any }
the_stack
import { validateCall } from "./validate-call" import { logger } from "../logger" import { createArgument } from "../argument" import { createOption, processGlobalOptions } from "../option" import { registerCompletion } from "../autocomplete" import { Completer } from "../autocomplete/types" import { getOptsMapping } from "../option/mapping" import { isStringValidator, isBoolValidator } from "../validator/utils" import type { Program } from "../program" import { ActionError, NoActionError, BaseError, ValidationSummaryError } from "../error" import { Action, ParserOptions, ParserResult, Option, Argument, CreateArgumentOpts, Configurator, CommandConfig, CreateOptionCommandOpts, } from "../types" import { CustomizedHelpOpts } from "../help/types" import { customizeHelp } from "../help" import { createConfigurator } from "../config" /** * @ignore */ export const PROG_CMD = "__self_cmd" /** * @ignore */ export const HELP_CMD = "help" /** * Command class * */ export class Command { private program: Program private _action?: Action private _lastAddedArgOrOpt?: Argument | Option private _aliases: string[] = [] private _name: string private _config: Configurator<CommandConfig> /** * Command description * * @internal */ readonly description: string /** * Command options array * * @internal */ readonly options: Option[] = [] /** * Command arguments array * * @internal */ readonly args: Argument[] = [] /** * * @param program * @param name * @param description * @internal */ constructor( program: Program, name: string, description: string, config: Partial<CommandConfig> = {}, ) { this.program = program this._name = name this.description = description this._config = createConfigurator({ visible: true, ...config }) } /** * Add one or more aliases so the command can be called by different names. * * @param aliases Command aliases */ alias(...aliases: string[]): Command { this._aliases.push(...aliases) return this } /** * Name getter. Will return an empty string in the program-command context * * @internal */ get name(): string { return this.isProgramCommand() ? "" : this._name } /** * Add an argument to the command. * Synopsis is a string like `<my-argument>` or `[my-argument]`. * Angled brackets (e.g. `<item>`) indicate required input. Square brackets (e.g. `[env]`) indicate optional input. * * Returns the {@link Command} object to facilitate chaining of methods. * * @param synopsis Argument synopsis. * @param description - Argument description. * @param [options] - Optional parameters including validator and default value. */ argument( synopsis: string, description: string, options: CreateArgumentOpts = {}, ): Command { this._lastAddedArgOrOpt = createArgument(synopsis, description, options) this.args.push(this._lastAddedArgOrOpt) return this } /** * Set the corresponding action to execute for this command * * @param action Action to execute */ action(action: Action): Command { this._action = action return this } /** * Allow chaining command() calls. See {@link Program.command}. * */ command( name: string, description: string, config: Partial<CommandConfig> = {}, ): Command { return this.program.command(name, description, config) } /** * Makes the command the default one for the program. */ default(): Command { this.program.defaultCommand = this return this } /** * Checks if the command has the given alias registered. * * @param alias * @internal */ hasAlias(alias: string): boolean { return this._aliases.includes(alias) } /** * Get command aliases. * @internal */ getAliases(): string[] { return this._aliases } /** * @internal */ isProgramCommand(): boolean { return this._name === PROG_CMD } /** * @internal */ isHelpCommand(): boolean { return this._name === HELP_CMD } /** * Hide the command from help. * Shortcut to calling `.configure({ visible: false })`. */ hide(): Command { return this.configure({ visible: false }) } /** * Add an option to the current command. * * @param synopsis Option synopsis like '-f, --force', or '-f, --file \<file\>', or '--with-openssl [path]' * @param description Option description * @param options Additional parameters */ option( synopsis: string, description: string, options: CreateOptionCommandOpts = {}, ): Command { const opt = (this._lastAddedArgOrOpt = createOption(synopsis, description, options)) this.options.push(opt) return this } /** * @internal */ getParserConfig(): Partial<ParserOptions> { const defaults: ParserOptions = { boolean: [], string: [], alias: getOptsMapping(this), autoCast: this.autoCast, variadic: [], ddash: false, } let parserOpts = this.options.reduce((parserOpts, opt) => { if (opt.boolean) { parserOpts.boolean.push(opt.name) } if (isStringValidator(opt.validator)) { parserOpts.string.push(opt.name) } if (opt.variadic) { parserOpts.variadic.push(opt.name) } return parserOpts }, defaults) parserOpts = this.args.reduce((parserOpts, arg, index) => { if (!this.isProgramCommand()) { index++ } if (isBoolValidator(arg.validator)) { parserOpts.boolean.push(index) } if (isStringValidator(arg.validator)) { parserOpts.string.push(index) } if (arg.variadic) { parserOpts.variadic.push(index) } return parserOpts }, parserOpts) return parserOpts } /** * Return a reformated synopsis string * @internal */ get synopsis(): string { const opts = this.options.length ? this.options.some((f) => f.required) ? "<OPTIONS...>" : "[OPTIONS...]" : "" const name = this._name !== PROG_CMD ? " " + this._name : "" return ( this.program.getBin() + name + " " + this.args.map((a) => a.synopsis).join(" ") + " " + opts ).trim() } /** * Customize command help. Can be called multiple times to add more paragraphs and/or sections. * * @param text Help contents * @param options Display options */ help(text: string, options: Partial<CustomizedHelpOpts> = {}): Command { customizeHelp(this, text, options) return this } /** * Configure some behavioral properties. * * @param props properties to set/update */ configure(props: Partial<CommandConfig>): Command { this._config.set(props) return this } /** * Get a configuration property value. * * @internal * @param key Property key to get value for. See {@link CommandConfig}. */ getConfigProperty<K extends keyof CommandConfig>(key: K): CommandConfig[K] { return this._config.get(key) } /** * Get the auto-casting flag. * * @internal */ get autoCast(): boolean { return ( this.getConfigProperty("autoCast") ?? this.program.getConfigProperty("autoCast") ) } /** * Auto-complete */ complete(completer: Completer): Command { if (!this._lastAddedArgOrOpt) { throw new Error( "Caporal setup error: you should only call `.complete()` after .argument() or .option().", ) } registerCompletion(this._lastAddedArgOrOpt, completer) return this } /** * Toggle strict mode. * Shortcut to calling: `.configure({ strictArgsCount: strict, strictOptions: strict }). * By default, strict settings are not defined for commands, and inherit from the * program settings. Calling `.strict(value)` on a command will override the program * settings. * * @param strict boolean enabled flag */ strict(strict = true): Command { return this.configure({ strictArgsCount: strict, strictOptions: strict, }) } /** * Computed strictOptions flag. * * @internal */ get strictOptions(): boolean { return ( this.getConfigProperty("strictOptions") ?? this.program.getConfigProperty("strictOptions") ) } /** * Computed strictArgsCount flag. * * @internal */ get strictArgsCount(): boolean { return ( this.getConfigProperty("strictArgsCount") ?? this.program.getConfigProperty("strictArgsCount") ) } /** * Enable or disable auto casting of arguments & options for the command. * This is basically a shortcut to calling `command.configure({ autoCast: enabled })`. * By default, auto-casting is inherited from the program configuration. * This method allows overriding what's been set on the program level. * * @param enabled */ cast(enabled: boolean): Command { return this.configure({ autoCast: enabled }) } /** * Visible flag * * @internal */ get visible(): boolean { return this.getConfigProperty("visible") } /** * Run the action associated with the command * * @internal */ async run(parsed: Partial<ParserResult>): Promise<unknown> { const data: ParserResult = { args: [], options: {}, line: "", rawOptions: {}, rawArgv: [], ddash: [], ...parsed, } try { // Validate args and options, including global options const result = await validateCall(this, data) const { args, options, ddash, errors } = result // Process any global options const shouldStop = await processGlobalOptions(result, this.program, this) if (shouldStop) { return -1 } if (errors.length) { throw new ValidationSummaryError(this, errors) } if (!this._action) { throw new NoActionError(this) } return await this._action({ args, options, ddash, logger, program: this.program, command: this, }) } catch (err) { const ctor = Object.getPrototypeOf(err).constructor.name throw err instanceof BaseError && ctor !== "Error" ? err : new ActionError(err) } } } /** * Create a new command * * @internal */ export function createCommand( ...args: ConstructorParameters<typeof Command> ): InstanceType<typeof Command> { return new Command(...args) }
the_stack
import {GoogleApis} from './googleapis'; const google = new GoogleApis(); export {google, GoogleApis}; export * as Common from 'googleapis-common'; export * as Auth from 'google-auth-library'; export {abusiveexperiencereport_v1} from './apis/abusiveexperiencereport/v1'; export {acceleratedmobilepageurl_v1} from './apis/acceleratedmobilepageurl/v1'; export {accessapproval_v1} from './apis/accessapproval/v1'; export {accessapproval_v1beta1} from './apis/accessapproval/v1beta1'; export {accesscontextmanager_v1} from './apis/accesscontextmanager/v1'; export {accesscontextmanager_v1beta} from './apis/accesscontextmanager/v1beta'; export {adexchangebuyer_v1_2} from './apis/adexchangebuyer/v1.2'; export {adexchangebuyer_v1_3} from './apis/adexchangebuyer/v1.3'; export {adexchangebuyer_v1_4} from './apis/adexchangebuyer/v1.4'; export {adexchangebuyer2_v2beta1} from './apis/adexchangebuyer2/v2beta1'; export {adexperiencereport_v1} from './apis/adexperiencereport/v1'; export {admin_datatransfer_v1} from './apis/admin/datatransfer_v1'; export {admin_directory_v1} from './apis/admin/directory_v1'; export {admin_reports_v1} from './apis/admin/reports_v1'; export {admob_v1} from './apis/admob/v1'; export {admob_v1beta} from './apis/admob/v1beta'; export {adsense_v1_4} from './apis/adsense/v1.4'; export {adsense_v2} from './apis/adsense/v2'; export {adsensehost_v4_1} from './apis/adsensehost/v4.1'; export {alertcenter_v1beta1} from './apis/alertcenter/v1beta1'; export {analytics_v3} from './apis/analytics/v3'; export {analyticsadmin_v1alpha} from './apis/analyticsadmin/v1alpha'; export {analyticsdata_v1alpha} from './apis/analyticsdata/v1alpha'; export {analyticsdata_v1beta} from './apis/analyticsdata/v1beta'; export {analyticsreporting_v4} from './apis/analyticsreporting/v4'; export {androiddeviceprovisioning_v1} from './apis/androiddeviceprovisioning/v1'; export {androidenterprise_v1} from './apis/androidenterprise/v1'; export {androidmanagement_v1} from './apis/androidmanagement/v1'; export {androidpublisher_v1_1} from './apis/androidpublisher/v1.1'; export {androidpublisher_v1} from './apis/androidpublisher/v1'; export {androidpublisher_v2} from './apis/androidpublisher/v2'; export {androidpublisher_v3} from './apis/androidpublisher/v3'; export {apigateway_v1} from './apis/apigateway/v1'; export {apigateway_v1beta} from './apis/apigateway/v1beta'; export {apikeys_v2} from './apis/apikeys/v2'; export {appengine_v1} from './apis/appengine/v1'; export {appengine_v1alpha} from './apis/appengine/v1alpha'; export {appengine_v1beta} from './apis/appengine/v1beta'; export {appsactivity_v1} from './apis/appsactivity/v1'; export {area120tables_v1alpha1} from './apis/area120tables/v1alpha1'; export {artifactregistry_v1} from './apis/artifactregistry/v1'; export {artifactregistry_v1beta1} from './apis/artifactregistry/v1beta1'; export {artifactregistry_v1beta2} from './apis/artifactregistry/v1beta2'; export {assuredworkloads_v1} from './apis/assuredworkloads/v1'; export {assuredworkloads_v1beta1} from './apis/assuredworkloads/v1beta1'; export {authorizedbuyersmarketplace_v1} from './apis/authorizedbuyersmarketplace/v1'; export {baremetalsolution_v1} from './apis/baremetalsolution/v1'; export {bigquery_v2} from './apis/bigquery/v2'; export {bigqueryconnection_v1beta1} from './apis/bigqueryconnection/v1beta1'; export {bigquerydatatransfer_v1} from './apis/bigquerydatatransfer/v1'; export {bigqueryreservation_v1} from './apis/bigqueryreservation/v1'; export {bigqueryreservation_v1alpha2} from './apis/bigqueryreservation/v1alpha2'; export {bigqueryreservation_v1beta1} from './apis/bigqueryreservation/v1beta1'; export {bigtableadmin_v1} from './apis/bigtableadmin/v1'; export {bigtableadmin_v2} from './apis/bigtableadmin/v2'; export {billingbudgets_v1} from './apis/billingbudgets/v1'; export {billingbudgets_v1beta1} from './apis/billingbudgets/v1beta1'; export {binaryauthorization_v1} from './apis/binaryauthorization/v1'; export {binaryauthorization_v1beta1} from './apis/binaryauthorization/v1beta1'; export {blogger_v2} from './apis/blogger/v2'; export {blogger_v3} from './apis/blogger/v3'; export {books_v1} from './apis/books/v1'; export {calendar_v3} from './apis/calendar/v3'; export {chat_v1} from './apis/chat/v1'; export {chromemanagement_v1} from './apis/chromemanagement/v1'; export {chromepolicy_v1} from './apis/chromepolicy/v1'; export {chromeuxreport_v1} from './apis/chromeuxreport/v1'; export {civicinfo_v2} from './apis/civicinfo/v2'; export {classroom_v1} from './apis/classroom/v1'; export {cloudasset_v1} from './apis/cloudasset/v1'; export {cloudasset_v1beta1} from './apis/cloudasset/v1beta1'; export {cloudasset_v1p1beta1} from './apis/cloudasset/v1p1beta1'; export {cloudasset_v1p4beta1} from './apis/cloudasset/v1p4beta1'; export {cloudasset_v1p5beta1} from './apis/cloudasset/v1p5beta1'; export {cloudasset_v1p7beta1} from './apis/cloudasset/v1p7beta1'; export {cloudbilling_v1} from './apis/cloudbilling/v1'; export {cloudbuild_v1} from './apis/cloudbuild/v1'; export {cloudbuild_v1alpha1} from './apis/cloudbuild/v1alpha1'; export {cloudbuild_v1alpha2} from './apis/cloudbuild/v1alpha2'; export {cloudbuild_v1beta1} from './apis/cloudbuild/v1beta1'; export {cloudchannel_v1} from './apis/cloudchannel/v1'; export {clouddebugger_v2} from './apis/clouddebugger/v2'; export {clouddeploy_v1} from './apis/clouddeploy/v1'; export {clouderrorreporting_v1beta1} from './apis/clouderrorreporting/v1beta1'; export {cloudfunctions_v1} from './apis/cloudfunctions/v1'; export {cloudfunctions_v1beta2} from './apis/cloudfunctions/v1beta2'; export {cloudidentity_v1} from './apis/cloudidentity/v1'; export {cloudidentity_v1beta1} from './apis/cloudidentity/v1beta1'; export {cloudiot_v1} from './apis/cloudiot/v1'; export {cloudkms_v1} from './apis/cloudkms/v1'; export {cloudprofiler_v2} from './apis/cloudprofiler/v2'; export {cloudresourcemanager_v1} from './apis/cloudresourcemanager/v1'; export {cloudresourcemanager_v1beta1} from './apis/cloudresourcemanager/v1beta1'; export {cloudresourcemanager_v2} from './apis/cloudresourcemanager/v2'; export {cloudresourcemanager_v2beta1} from './apis/cloudresourcemanager/v2beta1'; export {cloudresourcemanager_v3} from './apis/cloudresourcemanager/v3'; export {cloudscheduler_v1} from './apis/cloudscheduler/v1'; export {cloudscheduler_v1beta1} from './apis/cloudscheduler/v1beta1'; export {cloudsearch_v1} from './apis/cloudsearch/v1'; export {cloudshell_v1} from './apis/cloudshell/v1'; export {cloudshell_v1alpha1} from './apis/cloudshell/v1alpha1'; export {cloudsupport_v2beta} from './apis/cloudsupport/v2beta'; export {cloudtasks_v2} from './apis/cloudtasks/v2'; export {cloudtasks_v2beta2} from './apis/cloudtasks/v2beta2'; export {cloudtasks_v2beta3} from './apis/cloudtasks/v2beta3'; export {cloudtrace_v1} from './apis/cloudtrace/v1'; export {cloudtrace_v2} from './apis/cloudtrace/v2'; export {cloudtrace_v2beta1} from './apis/cloudtrace/v2beta1'; export {composer_v1} from './apis/composer/v1'; export {composer_v1beta1} from './apis/composer/v1beta1'; export {compute_alpha} from './apis/compute/alpha'; export {compute_beta} from './apis/compute/beta'; export {compute_v1} from './apis/compute/v1'; export {connectors_v1} from './apis/connectors/v1'; export {contactcenterinsights_v1} from './apis/contactcenterinsights/v1'; export {container_v1} from './apis/container/v1'; export {container_v1beta1} from './apis/container/v1beta1'; export {containeranalysis_v1} from './apis/containeranalysis/v1'; export {containeranalysis_v1alpha1} from './apis/containeranalysis/v1alpha1'; export {containeranalysis_v1beta1} from './apis/containeranalysis/v1beta1'; export {content_v2_1} from './apis/content/v2.1'; export {content_v2} from './apis/content/v2'; export {customsearch_v1} from './apis/customsearch/v1'; export {datacatalog_v1} from './apis/datacatalog/v1'; export {datacatalog_v1beta1} from './apis/datacatalog/v1beta1'; export {dataflow_v1b3} from './apis/dataflow/v1b3'; export {datafusion_v1} from './apis/datafusion/v1'; export {datafusion_v1beta1} from './apis/datafusion/v1beta1'; export {datalabeling_v1beta1} from './apis/datalabeling/v1beta1'; export {datamigration_v1} from './apis/datamigration/v1'; export {datamigration_v1beta1} from './apis/datamigration/v1beta1'; export {datapipelines_v1} from './apis/datapipelines/v1'; export {dataproc_v1} from './apis/dataproc/v1'; export {dataproc_v1beta2} from './apis/dataproc/v1beta2'; export {datastore_v1} from './apis/datastore/v1'; export {datastore_v1beta1} from './apis/datastore/v1beta1'; export {datastore_v1beta3} from './apis/datastore/v1beta3'; export {datastream_v1} from './apis/datastream/v1'; export {datastream_v1alpha1} from './apis/datastream/v1alpha1'; export {deploymentmanager_alpha} from './apis/deploymentmanager/alpha'; export {deploymentmanager_v2} from './apis/deploymentmanager/v2'; export {deploymentmanager_v2beta} from './apis/deploymentmanager/v2beta'; export {dfareporting_v3_3} from './apis/dfareporting/v3.3'; export {dfareporting_v3_4} from './apis/dfareporting/v3.4'; export {dfareporting_v3_5} from './apis/dfareporting/v3.5'; export {dialogflow_v2} from './apis/dialogflow/v2'; export {dialogflow_v2beta1} from './apis/dialogflow/v2beta1'; export {dialogflow_v3} from './apis/dialogflow/v3'; export {dialogflow_v3beta1} from './apis/dialogflow/v3beta1'; export {digitalassetlinks_v1} from './apis/digitalassetlinks/v1'; export {discovery_v1} from './apis/discovery/v1'; export {displayvideo_v1} from './apis/displayvideo/v1'; export {displayvideo_v1beta} from './apis/displayvideo/v1beta'; export {displayvideo_v1beta2} from './apis/displayvideo/v1beta2'; export {displayvideo_v1dev} from './apis/displayvideo/v1dev'; export {dlp_v2} from './apis/dlp/v2'; export {dns_v1} from './apis/dns/v1'; export {dns_v1beta2} from './apis/dns/v1beta2'; export {dns_v2beta1} from './apis/dns/v2beta1'; export {docs_v1} from './apis/docs/v1'; export {documentai_v1} from './apis/documentai/v1'; export {documentai_v1beta2} from './apis/documentai/v1beta2'; export {documentai_v1beta3} from './apis/documentai/v1beta3'; export {domains_v1} from './apis/domains/v1'; export {domains_v1alpha2} from './apis/domains/v1alpha2'; export {domains_v1beta1} from './apis/domains/v1beta1'; export {domainsrdap_v1} from './apis/domainsrdap/v1'; export {doubleclickbidmanager_v1_1} from './apis/doubleclickbidmanager/v1.1'; export {doubleclickbidmanager_v1} from './apis/doubleclickbidmanager/v1'; export {doubleclicksearch_v2} from './apis/doubleclicksearch/v2'; export {drive_v2} from './apis/drive/v2'; export {drive_v3} from './apis/drive/v3'; export {driveactivity_v2} from './apis/driveactivity/v2'; export {essentialcontacts_v1} from './apis/essentialcontacts/v1'; export {eventarc_v1} from './apis/eventarc/v1'; export {eventarc_v1beta1} from './apis/eventarc/v1beta1'; export {factchecktools_v1alpha1} from './apis/factchecktools/v1alpha1'; export {fcm_v1} from './apis/fcm/v1'; export {fcmdata_v1beta1} from './apis/fcmdata/v1beta1'; export {file_v1} from './apis/file/v1'; export {file_v1beta1} from './apis/file/v1beta1'; export {firebase_v1beta1} from './apis/firebase/v1beta1'; export {firebaseappcheck_v1beta} from './apis/firebaseappcheck/v1beta'; export {firebasedatabase_v1beta} from './apis/firebasedatabase/v1beta'; export {firebasedynamiclinks_v1} from './apis/firebasedynamiclinks/v1'; export {firebasehosting_v1} from './apis/firebasehosting/v1'; export {firebasehosting_v1beta1} from './apis/firebasehosting/v1beta1'; export {firebaseml_v1} from './apis/firebaseml/v1'; export {firebaseml_v1beta2} from './apis/firebaseml/v1beta2'; export {firebaserules_v1} from './apis/firebaserules/v1'; export {firebasestorage_v1beta} from './apis/firebasestorage/v1beta'; export {firestore_v1} from './apis/firestore/v1'; export {firestore_v1beta1} from './apis/firestore/v1beta1'; export {firestore_v1beta2} from './apis/firestore/v1beta2'; export {fitness_v1} from './apis/fitness/v1'; export {games_v1} from './apis/games/v1'; export {gamesConfiguration_v1configuration} from './apis/gamesConfiguration/v1configuration'; export {gamesManagement_v1management} from './apis/gamesManagement/v1management'; export {gameservices_v1} from './apis/gameservices/v1'; export {gameservices_v1beta} from './apis/gameservices/v1beta'; export {genomics_v1} from './apis/genomics/v1'; export {genomics_v1alpha2} from './apis/genomics/v1alpha2'; export {genomics_v2alpha1} from './apis/genomics/v2alpha1'; export {gkehub_v1} from './apis/gkehub/v1'; export {gkehub_v1alpha} from './apis/gkehub/v1alpha'; export {gkehub_v1alpha2} from './apis/gkehub/v1alpha2'; export {gkehub_v1beta} from './apis/gkehub/v1beta'; export {gkehub_v1beta1} from './apis/gkehub/v1beta1'; export {gmail_v1} from './apis/gmail/v1'; export {gmailpostmastertools_v1} from './apis/gmailpostmastertools/v1'; export {gmailpostmastertools_v1beta1} from './apis/gmailpostmastertools/v1beta1'; export {groupsmigration_v1} from './apis/groupsmigration/v1'; export {groupssettings_v1} from './apis/groupssettings/v1'; export {healthcare_v1} from './apis/healthcare/v1'; export {healthcare_v1beta1} from './apis/healthcare/v1beta1'; export {homegraph_v1} from './apis/homegraph/v1'; export {iam_v1} from './apis/iam/v1'; export {iamcredentials_v1} from './apis/iamcredentials/v1'; export {iap_v1} from './apis/iap/v1'; export {iap_v1beta1} from './apis/iap/v1beta1'; export {ideahub_v1alpha} from './apis/ideahub/v1alpha'; export {ideahub_v1beta} from './apis/ideahub/v1beta'; export {identitytoolkit_v3} from './apis/identitytoolkit/v3'; export {indexing_v3} from './apis/indexing/v3'; export {jobs_v2} from './apis/jobs/v2'; export {jobs_v3} from './apis/jobs/v3'; export {jobs_v3p1beta1} from './apis/jobs/v3p1beta1'; export {jobs_v4} from './apis/jobs/v4'; export {kgsearch_v1} from './apis/kgsearch/v1'; export {language_v1} from './apis/language/v1'; export {language_v1beta1} from './apis/language/v1beta1'; export {language_v1beta2} from './apis/language/v1beta2'; export {libraryagent_v1} from './apis/libraryagent/v1'; export {licensing_v1} from './apis/licensing/v1'; export {lifesciences_v2beta} from './apis/lifesciences/v2beta'; export {localservices_v1} from './apis/localservices/v1'; export {logging_v2} from './apis/logging/v2'; export {managedidentities_v1} from './apis/managedidentities/v1'; export {managedidentities_v1alpha1} from './apis/managedidentities/v1alpha1'; export {managedidentities_v1beta1} from './apis/managedidentities/v1beta1'; export {manufacturers_v1} from './apis/manufacturers/v1'; export {memcache_v1} from './apis/memcache/v1'; export {memcache_v1beta2} from './apis/memcache/v1beta2'; export {metastore_v1alpha} from './apis/metastore/v1alpha'; export {metastore_v1beta} from './apis/metastore/v1beta'; export {ml_v1} from './apis/ml/v1'; export {monitoring_v1} from './apis/monitoring/v1'; export {monitoring_v3} from './apis/monitoring/v3'; export {mybusinessaccountmanagement_v1} from './apis/mybusinessaccountmanagement/v1'; export {mybusinessbusinessinformation_v1} from './apis/mybusinessbusinessinformation/v1'; export {mybusinesslodging_v1} from './apis/mybusinesslodging/v1'; export {mybusinessnotifications_v1} from './apis/mybusinessnotifications/v1'; export {mybusinessplaceactions_v1} from './apis/mybusinessplaceactions/v1'; export {mybusinessverifications_v1} from './apis/mybusinessverifications/v1'; export {networkconnectivity_v1} from './apis/networkconnectivity/v1'; export {networkconnectivity_v1alpha1} from './apis/networkconnectivity/v1alpha1'; export {networkmanagement_v1} from './apis/networkmanagement/v1'; export {networkmanagement_v1beta1} from './apis/networkmanagement/v1beta1'; export {networksecurity_v1} from './apis/networksecurity/v1'; export {networksecurity_v1beta1} from './apis/networksecurity/v1beta1'; export {networkservices_v1} from './apis/networkservices/v1'; export {networkservices_v1beta1} from './apis/networkservices/v1beta1'; export {notebooks_v1} from './apis/notebooks/v1'; export {oauth2_v2} from './apis/oauth2/v2'; export {ondemandscanning_v1} from './apis/ondemandscanning/v1'; export {ondemandscanning_v1beta1} from './apis/ondemandscanning/v1beta1'; export {orgpolicy_v2} from './apis/orgpolicy/v2'; export {osconfig_v1} from './apis/osconfig/v1'; export {osconfig_v1alpha} from './apis/osconfig/v1alpha'; export {osconfig_v1beta} from './apis/osconfig/v1beta'; export {oslogin_v1} from './apis/oslogin/v1'; export {oslogin_v1alpha} from './apis/oslogin/v1alpha'; export {oslogin_v1beta} from './apis/oslogin/v1beta'; export {pagespeedonline_v5} from './apis/pagespeedonline/v5'; export {paymentsresellersubscription_v1} from './apis/paymentsresellersubscription/v1'; export {people_v1} from './apis/people/v1'; export {playablelocations_v3} from './apis/playablelocations/v3'; export {playcustomapp_v1} from './apis/playcustomapp/v1'; export {plus_v1} from './apis/plus/v1'; export {policyanalyzer_v1} from './apis/policyanalyzer/v1'; export {policyanalyzer_v1beta1} from './apis/policyanalyzer/v1beta1'; export {policysimulator_v1} from './apis/policysimulator/v1'; export {policysimulator_v1beta1} from './apis/policysimulator/v1beta1'; export {policytroubleshooter_v1} from './apis/policytroubleshooter/v1'; export {policytroubleshooter_v1beta} from './apis/policytroubleshooter/v1beta'; export {poly_v1} from './apis/poly/v1'; export {privateca_v1} from './apis/privateca/v1'; export {privateca_v1beta1} from './apis/privateca/v1beta1'; export {prod_tt_sasportal_v1alpha1} from './apis/prod_tt_sasportal/v1alpha1'; export {pubsub_v1} from './apis/pubsub/v1'; export {pubsub_v1beta1a} from './apis/pubsub/v1beta1a'; export {pubsub_v1beta2} from './apis/pubsub/v1beta2'; export {pubsublite_v1} from './apis/pubsublite/v1'; export {realtimebidding_v1} from './apis/realtimebidding/v1'; export {realtimebidding_v1alpha} from './apis/realtimebidding/v1alpha'; export {recaptchaenterprise_v1} from './apis/recaptchaenterprise/v1'; export {recommendationengine_v1beta1} from './apis/recommendationengine/v1beta1'; export {recommender_v1} from './apis/recommender/v1'; export {recommender_v1beta1} from './apis/recommender/v1beta1'; export {redis_v1} from './apis/redis/v1'; export {redis_v1beta1} from './apis/redis/v1beta1'; export {remotebuildexecution_v1} from './apis/remotebuildexecution/v1'; export {remotebuildexecution_v1alpha} from './apis/remotebuildexecution/v1alpha'; export {remotebuildexecution_v2} from './apis/remotebuildexecution/v2'; export {reseller_v1} from './apis/reseller/v1'; export {resourcesettings_v1} from './apis/resourcesettings/v1'; export {retail_v2} from './apis/retail/v2'; export {retail_v2alpha} from './apis/retail/v2alpha'; export {retail_v2beta} from './apis/retail/v2beta'; export {run_v1} from './apis/run/v1'; export {run_v1alpha1} from './apis/run/v1alpha1'; export {run_v1beta1} from './apis/run/v1beta1'; export {runtimeconfig_v1} from './apis/runtimeconfig/v1'; export {runtimeconfig_v1beta1} from './apis/runtimeconfig/v1beta1'; export {safebrowsing_v4} from './apis/safebrowsing/v4'; export {sasportal_v1alpha1} from './apis/sasportal/v1alpha1'; export {script_v1} from './apis/script/v1'; export {searchconsole_v1} from './apis/searchconsole/v1'; export {secretmanager_v1} from './apis/secretmanager/v1'; export {secretmanager_v1beta1} from './apis/secretmanager/v1beta1'; export {securitycenter_v1} from './apis/securitycenter/v1'; export {securitycenter_v1beta1} from './apis/securitycenter/v1beta1'; export {securitycenter_v1beta2} from './apis/securitycenter/v1beta2'; export {securitycenter_v1p1alpha1} from './apis/securitycenter/v1p1alpha1'; export {securitycenter_v1p1beta1} from './apis/securitycenter/v1p1beta1'; export {serviceconsumermanagement_v1} from './apis/serviceconsumermanagement/v1'; export {serviceconsumermanagement_v1beta1} from './apis/serviceconsumermanagement/v1beta1'; export {servicecontrol_v1} from './apis/servicecontrol/v1'; export {servicecontrol_v2} from './apis/servicecontrol/v2'; export {servicedirectory_v1} from './apis/servicedirectory/v1'; export {servicedirectory_v1beta1} from './apis/servicedirectory/v1beta1'; export {servicemanagement_v1} from './apis/servicemanagement/v1'; export {servicenetworking_v1} from './apis/servicenetworking/v1'; export {servicenetworking_v1beta} from './apis/servicenetworking/v1beta'; export {serviceusage_v1} from './apis/serviceusage/v1'; export {serviceusage_v1beta1} from './apis/serviceusage/v1beta1'; export {sheets_v4} from './apis/sheets/v4'; export {siteVerification_v1} from './apis/siteVerification/v1'; export {slides_v1} from './apis/slides/v1'; export {smartdevicemanagement_v1} from './apis/smartdevicemanagement/v1'; export {sourcerepo_v1} from './apis/sourcerepo/v1'; export {spanner_v1} from './apis/spanner/v1'; export {speech_v1} from './apis/speech/v1'; export {speech_v1p1beta1} from './apis/speech/v1p1beta1'; export {speech_v2beta1} from './apis/speech/v2beta1'; export {sql_v1beta4} from './apis/sql/v1beta4'; export {sqladmin_v1} from './apis/sqladmin/v1'; export {sqladmin_v1beta4} from './apis/sqladmin/v1beta4'; export {storage_v1} from './apis/storage/v1'; export {storage_v1beta2} from './apis/storage/v1beta2'; export {storagetransfer_v1} from './apis/storagetransfer/v1'; export {streetviewpublish_v1} from './apis/streetviewpublish/v1'; export {sts_v1} from './apis/sts/v1'; export {sts_v1beta} from './apis/sts/v1beta'; export {tagmanager_v1} from './apis/tagmanager/v1'; export {tagmanager_v2} from './apis/tagmanager/v2'; export {tasks_v1} from './apis/tasks/v1'; export {testing_v1} from './apis/testing/v1'; export {texttospeech_v1} from './apis/texttospeech/v1'; export {texttospeech_v1beta1} from './apis/texttospeech/v1beta1'; export {toolresults_v1beta3} from './apis/toolresults/v1beta3'; export {tpu_v1} from './apis/tpu/v1'; export {tpu_v1alpha1} from './apis/tpu/v1alpha1'; export {tpu_v2alpha1} from './apis/tpu/v2alpha1'; export {trafficdirector_v2} from './apis/trafficdirector/v2'; export {transcoder_v1beta1} from './apis/transcoder/v1beta1'; export {translate_v2} from './apis/translate/v2'; export {translate_v3} from './apis/translate/v3'; export {translate_v3beta1} from './apis/translate/v3beta1'; export {vault_v1} from './apis/vault/v1'; export {vectortile_v1} from './apis/vectortile/v1'; export {verifiedaccess_v1} from './apis/verifiedaccess/v1'; export {versionhistory_v1} from './apis/versionhistory/v1'; export {videointelligence_v1} from './apis/videointelligence/v1'; export {videointelligence_v1beta2} from './apis/videointelligence/v1beta2'; export {videointelligence_v1p1beta1} from './apis/videointelligence/v1p1beta1'; export {videointelligence_v1p2beta1} from './apis/videointelligence/v1p2beta1'; export {videointelligence_v1p3beta1} from './apis/videointelligence/v1p3beta1'; export {vision_v1} from './apis/vision/v1'; export {vision_v1p1beta1} from './apis/vision/v1p1beta1'; export {vision_v1p2beta1} from './apis/vision/v1p2beta1'; export {vmmigration_v1} from './apis/vmmigration/v1'; export {vmmigration_v1alpha1} from './apis/vmmigration/v1alpha1'; export {webfonts_v1} from './apis/webfonts/v1'; export {webmasters_v3} from './apis/webmasters/v3'; export {webrisk_v1} from './apis/webrisk/v1'; export {websecurityscanner_v1} from './apis/websecurityscanner/v1'; export {websecurityscanner_v1alpha} from './apis/websecurityscanner/v1alpha'; export {websecurityscanner_v1beta} from './apis/websecurityscanner/v1beta'; export {workflowexecutions_v1} from './apis/workflowexecutions/v1'; export {workflowexecutions_v1beta} from './apis/workflowexecutions/v1beta'; export {workflows_v1} from './apis/workflows/v1'; export {workflows_v1beta} from './apis/workflows/v1beta'; export {youtube_v3} from './apis/youtube/v3'; export {youtubeAnalytics_v1} from './apis/youtubeAnalytics/v1'; export {youtubeAnalytics_v2} from './apis/youtubeAnalytics/v2'; export {youtubereporting_v1} from './apis/youtubereporting/v1';
the_stack
import { assertNever, assertNodeKind } from "./assert"; import {} from "./error"; import { ErrorCodes, SynthError } from "./error-code"; import { CallExpr, Expr, FunctionExpr, Identifier } from "./expression"; import { isArgument, isArrayLiteralExpr, isBinaryExpr, isBlockStmt, isBooleanLiteralExpr, isBreakStmt, isCallExpr, isCatchClause, isComputedPropertyNameExpr, isConditionExpr, isContinueStmt, isDoStmt, isElementAccessExpr, isErr, isExprStmt, isForInStmt, isForOfStmt, isFunctionDecl, isFunctionExpr, isIdentifier, isIfStmt, isNativeFunctionDecl, isNewExpr, isNullLiteralExpr, isNumberLiteralExpr, isObjectLiteralExpr, isParameterDecl, isPropAccessExpr, isPropAssignExpr, isReferenceExpr, isReturnStmt, isSpreadAssignExpr, isSpreadElementExpr, isStringLiteralExpr, isTemplateExpr, isThrowStmt, isTryStmt, isTypeOfExpr, isUnaryExpr, isUndefinedLiteralExpr, isVariableStmt, isWhileStmt, } from "./guards"; import { findIntegration, IntegrationImpl } from "./integration"; import { FunctionlessNode } from "./node"; import { Stmt } from "./statement"; import { AnyFunction, isInTopLevelScope } from "./util"; // https://velocity.apache.org/engine/devel/user-guide.html#conditionals // https://cwiki.apache.org/confluence/display/VELOCITY/CheckingForNull // https://velocity.apache.org/engine/devel/user-guide.html#set export function isVTL(a: any): a is VTL { return (a as VTL | undefined)?.kind === VTL.ContextName; } export abstract class VTL { static readonly ContextName = "Velocity Template"; readonly kind = VTL.ContextName; private readonly statements: string[] = []; private varIt = 0; constructor(...statements: string[]) { this.statements.push(...statements); } public toVTL(): string { return this.statements.join("\n"); } public add(...statements: string[]) { this.statements.push(...statements); } protected newLocalVarName(): `$v${string}` { return `$v${(this.varIt += 1)}`; } public str(value: string) { return `'${value}'`; } /** * Converts a variable {@link reference} to JSON using the built-in `$util.toJson` intrinsic function. * * @param reference variable reference * @returns VTL expression which yields a JSON string of the variable {@link reference}. */ public json(reference: string): string { return `$util.toJson(${reference})`; } /** * Evaluates an {@link expr} with the `$util.qr` statement. * * @param expr expression string to evaluate quietly (i.e. without emitting to output) . */ public qr(expr: string): void { this.add(`$util.qr(${expr})`); } /** * Add a statement which sets the variable {@link reference} to the value of the {@link expr}. * * @param reference the name of the variable to set * @param expr the value to set the variable to */ public set(reference: string, expr: Expr | string): string { this.add( `#set(${reference} = ${ typeof expr === "string" ? expr : this.eval(expr) })` ); return reference; } /** * Stores the {@link expr} in a new variable with a uniquely generated name. * * @param expr the expression * @returns the variable name that contains the value. */ public var(expr: string | Expr): string { return this.set(this.newLocalVarName(), expr); } /** * The put method on an object. * * $var.put("name", "value") * * @param objVar should be a variable referencing an object. * @param name should be a quoted string or variable that represents the name to set in the object * @param expr should be a quoted string or a variable that represents the value to set */ public put(objVar: string, name: string, expr: string | Expr) { this.qr( `${objVar}.put(${name}, ${ typeof expr === "string" ? expr : this.eval(expr) })` ); } /** * The putAll method on an object. * * $var.putAll($otherObj) * * @param objVar should be a variable referencing an object. * @param expr should be a variable that represents an object to merge with the expression */ public putAll(objVar: string, expr: Expr) { this.qr(`${objVar}.putAll(${this.eval(expr)})`); } /** * Evaluate and return an {@link expr}. * * @param expr expression to evaluate * @returns a `#return` VTL expression. */ public return(expr: string | Expr): void { if (typeof expr === "string") { this.add(`#return(${expr})`); } else { return this.return(this.eval(expr)); } } /** * Call a service API. The Call expression will be evaluated and JSON will be rendered * to the Velocity Template output. This JSON payload will be passed to the * service-to-service integration, e.g. a Dynamo API request. * * ```json * #set($payload = { * "operation": "GetItem", * "key": $util.toJson($util.toDynamoDB($key)), * }) * $util.toJson($payload) * ``` * @param call */ public call(call: CallExpr): void { this.add(this.eval(call)); } /** * Configure the integration between this VTL template and a target service. * @param target the target service to integrate with. * @param call the CallExpr representing the integration logic */ protected abstract integrate( target: IntegrationImpl<AnyFunction> | undefined, call: CallExpr ): string; protected abstract dereference(id: Identifier): string; /** * Evaluate an {@link Expr} or {@link Stmt} by emitting statements to this VTL template and * return a variable reference to the evaluated value. * * @param node the {@link Expr} or {@link Stmt} to evaluate. * @returns a variable reference to the evaluated value */ public eval(node?: Expr, returnVar?: string): string; public eval(node: Stmt, returnVar?: string): void; public eval(node?: FunctionlessNode, returnVar?: string): string | void { if (!node) { return "$null"; } if (isArrayLiteralExpr(node)) { if (node.items.find(isSpreadElementExpr) === undefined) { return `[${node.items.map((item) => this.eval(item)).join(", ")}]`; } else { // contains a spread, e.g. [...i], so we will store in a variable const list = this.var("[]"); for (const item of node.items) { if (isSpreadElementExpr(item)) { this.qr(`${list}.addAll(${this.eval(item.expr)})`); } else { // we use addAll because `list.push(item)` is pared as `list.push(...[item])` // - i.e. the compiler passes us an ArrayLiteralExpr even if there is one arg this.qr(`${list}.add(${this.eval(item)})`); } } return list; } } else if (isBinaryExpr(node)) { if (node.op === "in") { throw new SynthError( ErrorCodes.Unexpected_Error, "Expected the `in` binary operator to be re-written before this point" ); } else if (node.op === "=") { return `#set(${this.eval(node.left)} ${node.op} ${this.eval( node.right )})`; } // VTL fails to evaluate binary expressions inside an object put e.g. $obj.put('x', 1 + 1) // a workaround is to use a temp variable. return this.var( `${this.eval(node.left)} ${node.op} ${this.eval(node.right)}` ); } else if (isBlockStmt(node)) { for (const stmt of node.statements) { this.eval(stmt); } return undefined; } else if (isBooleanLiteralExpr(node)) { return `${node.value}`; } else if (isBreakStmt(node)) { return this.add("#break"); } else if (isCallExpr(node)) { const serviceCall = findIntegration(node); if (serviceCall) { return this.integrate(serviceCall, node); } else if ( // If the parent is a propAccessExpr isPropAccessExpr(node.expr) && (node.expr.name === "map" || node.expr.name === "forEach" || node.expr.name === "reduce") ) { if (node.expr.name === "map" || node.expr.name == "forEach") { // list.map(item => ..) // list.map((item, idx) => ..) // list.forEach(item => ..) // list.forEach((item, idx) => ..) const newList = node.expr.name === "map" ? this.var("[]") : undefined; const [value, index, array] = getMapForEachArgs(node); // Try to flatten any maps before this operation // returns the first variable to be used in the foreach of this operation (may be the `value`) const list = this.flattenListMapOperations( node.expr.expr, value, (firstVariable, list) => { this.add(`#foreach(${firstVariable} in ${list})`); }, // If array is present, do not flatten the map, this option immediately evaluates the next expression !!array ); // Render the body const tmp = this.renderMapOrForEachBody( node, list, // the return location will be generated undefined, index, array ); // Add the final value to the array if (node.expr.name === "map") { this.qr(`${newList}.add(${tmp})`); } this.add("#end"); return newList ?? "$null"; } else if (node.expr.name === "reduce") { // list.reduce((result: string[], next) => [...result, next], []); // list.reduce((result, next) => [...result, next]); const fn = assertNodeKind<FunctionExpr>( node.getArgument("callbackfn")?.expr, "FunctionExpr" ); const initialValue = node.getArgument("initialValue")?.expr; // (previousValue: string[], currentValue: string, currentIndex: number, array: string[]) const previousValue = fn.parameters[0]?.name ? `$${fn.parameters[0].name}` : this.newLocalVarName(); const currentValue = fn.parameters[1]?.name ? `$${fn.parameters[1].name}` : this.newLocalVarName(); const currentIndex = fn.parameters[2]?.name ? `$${fn.parameters[2].name}` : undefined; const array = fn.parameters[3]?.name ? `$${fn.parameters[3].name}` : undefined; // create a new local variable name to hold the initial/previous value // this is because previousValue may not be unique and isn't contained within the loop const previousTmp = this.newLocalVarName(); const list = this.flattenListMapOperations( node.expr.expr, currentValue, (firstVariable, list) => { if (initialValue !== undefined) { this.set(previousTmp, initialValue); } else { this.add(`#if(${list}.isEmpty())`); this.add( "$util.error('Reduce of empty array with no initial value')" ); this.add("#end"); } this.add(`#foreach(${firstVariable} in ${list})`); }, // If array is present, do not flatten maps before the reduce, this option immediately evaluates the next expression !!array ); if (currentIndex) { this.add(`#set(${currentIndex} = $foreach.index)`); } if (array) { this.add(`#set(${array} = ${list})`); } const body = () => { // set previousValue variable name to avoid remapping this.set(previousValue, previousTmp); const tmp = this.newLocalVarName(); for (const stmt of fn.body.statements) { this.eval(stmt, tmp); } // set the previous temp to be used later this.set(previousTmp, `${tmp}`); this.add("#end"); }; if (initialValue === undefined) { this.add("#if($foreach.index == 0)"); this.set(previousTmp, currentValue); this.add("#else"); body(); this.add("#end"); } else { body(); } return previousTmp; } // this is an array map, forEach, reduce call } return `${this.eval(node.expr)}(${Object.values(node.args) .map((arg) => this.eval(arg)) .join(", ")})`; } else if (isConditionExpr(node)) { const val = this.newLocalVarName(); this.add(`#if(${this.eval(node.when)})`); this.set(val, node.then); this.add("#else"); this.set(val, node._else); this.add("#end"); return val; } else if (isIfStmt(node)) { this.add(`#if(${this.eval(node.when)})`); this.eval(node.then); if (node._else) { this.add("#else"); this.eval(node._else); } this.add("#end"); return undefined; } else if (isExprStmt(node)) { if (isBinaryExpr(node.expr) && node.expr.op === "=") { return this.add(this.eval(node.expr)); } return this.qr(this.eval(node.expr)); } else if (isForInStmt(node) || isForOfStmt(node)) { this.add( `#foreach($${node.variableDecl.name} in ${this.eval(node.expr)}${ isForInStmt(node) ? ".keySet()" : "" })` ); this.eval(node.body); this.add("#end"); return undefined; } else if (isFunctionDecl(node) || isNativeFunctionDecl(node)) { // there should never be nested functions } else if (isFunctionExpr(node)) { return this.eval(node.body); } else if (isIdentifier(node)) { return this.dereference(node); } else if (isNewExpr(node)) { throw new Error("NewExpr is not supported by Velocity Templates"); } else if (isPropAccessExpr(node)) { let name = node.name; if (name === "push" && isCallExpr(node.parent)) { // this is a push to an array, rename to 'addAll' // addAll because the var-args are converted to an ArrayLiteralExpr name = "addAll"; } return `${this.eval(node.expr)}.${name}`; } else if (isElementAccessExpr(node)) { return `${this.eval(node.expr)}[${this.eval(node.element)}]`; } else if (isNullLiteralExpr(node) || isUndefinedLiteralExpr(node)) { return "$null"; } else if (isNumberLiteralExpr(node)) { return node.value.toString(10); } else if (isObjectLiteralExpr(node)) { const obj = this.var("{}"); for (const prop of node.properties) { if (isPropAssignExpr(prop)) { const name = isIdentifier(prop.name) ? this.str(prop.name.name) : this.eval(prop.name); this.put(obj, name, prop.expr); } else if (isSpreadAssignExpr(prop)) { this.putAll(obj, prop.expr); } else { assertNever(prop); } } return obj; } else if (isComputedPropertyNameExpr(node)) { return this.eval(node.expr); } else if ( isParameterDecl(node) || isReferenceExpr(node) || isPropAssignExpr(node) ) { throw new Error(`cannot evaluate Expr kind: '${node.kind}'`); } else if (isReturnStmt(node)) { if (returnVar) { this.set(returnVar, node.expr ?? "$null"); } else { this.set("$context.stash.return__val", node.expr ?? "$null"); this.add("#set($context.stash.return__flag = true)"); this.add("#return($context.stash.return__val)"); } return undefined; } else if (isSpreadAssignExpr(node) || isSpreadElementExpr(node)) { // handled inside ObjectLiteralExpr } else if (isStringLiteralExpr(node)) { return this.str(node.value); } else if (isTemplateExpr(node)) { return `"${node.exprs .map((expr) => { if (isStringLiteralExpr(expr)) { return expr.value; } const text = this.eval(expr, returnVar); if (text.startsWith("$")) { return `\${${text.slice(1)}}`; } else { const varName = this.var(text); return `\${${varName.slice(1)}}`; } }) .join("")}"`; } else if (isUnaryExpr(node)) { // VTL fails to evaluate unary expressions inside an object put e.g. $obj.put('x', -$v1) // a workaround is to use a temp variable. // it also doesn't handle like - signs alone (e.g. - $v1) so we have to put a 0 in front // no such problem with ! signs though if (node.op === "-") { return this.var(`0 - ${this.eval(node.expr)}`); } else { return this.var(`${node.op}${this.eval(node.expr)}`); } } else if (isVariableStmt(node)) { const varName = isInTopLevelScope(node) ? `$context.stash.${node.name}` : `$${node.name}`; if (node.expr) { return this.set(varName, node.expr); } else { return varName; } } else if (isThrowStmt(node)) { return `#throw(${this.eval(node.expr)})`; } else if (isTryStmt(node)) { } else if (isCatchClause(node)) { } else if (isContinueStmt(node)) { } else if (isDoStmt(node)) { } else if (isTypeOfExpr(node)) { } else if (isWhileStmt(node)) { } else if (isErr(node)) { throw node.error; } else if (isArgument(node)) { return this.eval(node.expr); } else { return assertNever(node); } throw new Error(`cannot evaluate Expr kind: '${node.kind}'`); } /** * Adds the VTL required to execute the body of a single map or forEach. * * @param call the map or foreach to render * @param list the list to give to the `array` parameter, should be the same one used in the vtl foreach * @param returnVariable The variable to put the final map value into. If not provided, will be generated. * Should start with a '$'. * @param index The optional `index` variable name to add if present. * Should start with a '$'. * @param array The optional `array` variable name to add if present. * Should start with a '$'. * @returns The returnVariable or generated variable name. */ private renderMapOrForEachBody( call: CallExpr, list: string, // Should start with $ returnVariable?: string, index?: string, array?: string ) { if (index) { this.add(`#set(${index} = $foreach.index)`); } if (array) { this.add(`#set(${array} = ${list})`); } const fn = assertNodeKind<FunctionExpr>( call.getArgument("callbackfn")?.expr, "FunctionExpr" ); const tmp = returnVariable ? returnVariable : this.newLocalVarName(); for (const stmt of fn.body.statements) { this.eval(stmt, tmp); } return tmp; } /** * Recursively flattens map operations until a non-map or a map with `array` parameter is found. * Evaluates the expression after the last map. * * @param before a method which executes once the * @return [firstVariable, list variable, render function] */ private flattenListMapOperations( expr: Expr, // Should start with $ returnVariable: string, before: (firstVariable: string, list: string) => void, alwaysEvaluate?: boolean ): string { if ( !alwaysEvaluate && isCallExpr(expr) && isPropAccessExpr(expr.expr) && expr.expr.name === "map" ) { const [value, index, array] = getMapForEachArgs(expr); const next = expr.expr.expr; const list = this.flattenListMapOperations( next, value, before, // If we find array, the next expression should be evaluated. // A map which relies on `array` cannot be flattened further as the array will be inaccurate. !!array ); this.renderMapOrForEachBody(expr, list, returnVariable, index, array); return list; } const list = this.eval(expr); before(returnVariable, list); // If the expression isn't a map, return the expression and return variable, render nothing return list; } } /** * Returns the [value, index, array] arguments if this CallExpr is a `forEach` or `map` call. */ const getMapForEachArgs = (call: CallExpr) => { const fn = assertNodeKind<FunctionExpr>( call.getArgument("callbackfn")?.expr, "FunctionExpr" ); return fn.parameters.map((p) => (p.name ? `$${p.name}` : p.name)); };
the_stack
import { AddonModDataSyncResult } from '@addons/mod/data/services/data-sync'; import { Injectable } from '@angular/core'; import { CoreCourseActivityPrefetchHandlerBase } from '@features/course/classes/activity-prefetch-handler'; import { CoreCourse, CoreCourseAnyModuleData } from '@features/course/services/course'; import { CoreUser } from '@features/user/services/user'; import { CoreFilepool } from '@services/filepool'; import { CoreGroup, CoreGroups } from '@services/groups'; import { CoreSites, CoreSitesReadingStrategy, CoreSitesCommonWSOptions } from '@services/sites'; import { CoreUtils } from '@services/utils/utils'; import { CoreWSExternalFile, CoreWSFile } from '@services/ws'; import { makeSingleton } from '@singletons'; import { AddonModWorkshopProvider, AddonModWorkshop, AddonModWorkshopPhase, AddonModWorkshopGradesData, AddonModWorkshopData, AddonModWorkshopGetWorkshopAccessInformationWSResponse, } from '../workshop'; import { AddonModWorkshopHelper } from '../workshop-helper'; import { AddonModWorkshopSync } from '../workshop-sync'; /** * Handler to prefetch workshops. */ @Injectable({ providedIn: 'root' }) export class AddonModWorkshopPrefetchHandlerService extends CoreCourseActivityPrefetchHandlerBase { name = 'AddonModWorkshop'; modName = 'workshop'; component = AddonModWorkshopProvider.COMPONENT; updatesNames = new RegExp('^configuration$|^.*files$|^completion|^gradeitems$|^outcomes$|^submissions$|^assessments$' + '|^assessmentgrades$|^usersubmissions$|^userassessments$|^userassessmentgrades$|^userassessmentgrades$'); /** * @inheritdoc */ async getFiles(module: CoreCourseAnyModuleData, courseId: number): Promise<CoreWSFile[]> { const info = await this.getWorkshopInfoHelper(module, courseId, { omitFail: true }); return info.files; } /** * Helper function to get all workshop info just once. * * @param module Module to get the files. * @param courseId Course ID the module belongs to. * @param options Other options. * @return Promise resolved with the info fetched. */ protected async getWorkshopInfoHelper( module: CoreCourseAnyModuleData, courseId: number, options: AddonModWorkshopGetInfoOptions = {}, ): Promise<{ workshop?: AddonModWorkshopData; groups: CoreGroup[]; files: CoreWSFile[]}> { let groups: CoreGroup[] = []; let files: CoreWSFile[] = []; let workshop: AddonModWorkshopData | undefined; let access: AddonModWorkshopGetWorkshopAccessInformationWSResponse | undefined; const modOptions = { cmId: module.id, ...options, // Include all options. }; try { const site = await CoreSites.getSite(options.siteId); const userId = site.getUserId(); const workshop = await AddonModWorkshop.getWorkshop(courseId, module.id, options); files = this.getIntroFilesFromInstance(module, workshop); files = files.concat(workshop.instructauthorsfiles || []).concat(workshop.instructreviewersfiles || []); access = await AddonModWorkshop.getWorkshopAccessInformation(workshop.id, modOptions); if (access.canviewallsubmissions) { const groupInfo = await CoreGroups.getActivityGroupInfo(module.id, false, undefined, options.siteId); if (!groupInfo.groups || groupInfo.groups.length == 0) { groupInfo.groups = [{ id: 0, name: '' }]; } groups = groupInfo.groups; } const phases = await AddonModWorkshop.getUserPlanPhases(workshop.id, modOptions); // Get submission phase info. const submissionPhase = phases[AddonModWorkshopPhase.PHASE_SUBMISSION]; const canSubmit = AddonModWorkshopHelper.canSubmit(workshop, access, submissionPhase.tasks); const canAssess = AddonModWorkshopHelper.canAssess(workshop, access); const promises: Promise<void>[] = []; if (canSubmit) { promises.push(AddonModWorkshopHelper.getUserSubmission(workshop.id, { userId, cmId: module.id, }).then((submission) => { if (submission) { files = files.concat(submission.contentfiles || []).concat(submission.attachmentfiles || []); } return; })); } if (access.canviewallsubmissions && workshop.phase >= AddonModWorkshopPhase.PHASE_SUBMISSION) { promises.push(AddonModWorkshop.getSubmissions(workshop.id, modOptions).then(async (submissions) => { await Promise.all(submissions.map(async (submission) => { files = files.concat(submission.contentfiles || []).concat(submission.attachmentfiles || []); const assessments = await AddonModWorkshop.getSubmissionAssessments(workshop!.id, submission.id, { cmId: module.id, }); assessments.forEach((assessment) => { files = files.concat(assessment.feedbackattachmentfiles) .concat(assessment.feedbackcontentfiles); }); if (workshop!.phase >= AddonModWorkshopPhase.PHASE_ASSESSMENT && canAssess) { await Promise.all(assessments.map((assessment) => AddonModWorkshopHelper.getReviewerAssessmentById(workshop!.id, assessment.id))); } })); return; })); } // Get assessment files. if (workshop.phase >= AddonModWorkshopPhase.PHASE_ASSESSMENT && canAssess) { promises.push(AddonModWorkshopHelper.getReviewerAssessments(workshop.id, modOptions).then((assessments) => { assessments.forEach((assessment) => { files = files.concat(<CoreWSExternalFile[]>assessment.feedbackattachmentfiles) .concat(assessment.feedbackcontentfiles); }); return; })); } await Promise.all(promises); return { workshop, groups, files: files.filter((file) => typeof file !== 'undefined'), }; } catch (error) { if (options.omitFail) { // Any error, return the info we have. return { workshop, groups, files: files.filter((file) => typeof file !== 'undefined'), }; } throw error; } } /** * @inheritdoc */ async invalidateContent(moduleId: number, courseId: number): Promise<void> { await AddonModWorkshop.invalidateContent(moduleId, courseId); } /** * Check if a module can be downloaded. If the function is not defined, we assume that all modules are downloadable. * * @param module Module. * @param courseId Course ID the module belongs to. * @return Whether the module can be downloaded. The promise should never be rejected. */ async isDownloadable(module: CoreCourseAnyModuleData, courseId: number): Promise<boolean> { const workshop = await AddonModWorkshop.getWorkshop(courseId, module.id, { readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE, }); const accessData = await AddonModWorkshop.getWorkshopAccessInformation(workshop.id, { cmId: module.id }); // Check if workshop is setup by phase. return accessData.canswitchphase || workshop.phase > AddonModWorkshopPhase.PHASE_SETUP; } /** * @inheritdoc */ async isEnabled(): Promise<boolean> { return AddonModWorkshop.isPluginEnabled(); } /** * @inheritdoc */ prefetch(module: CoreCourseAnyModuleData, courseId: number): Promise<void> { return this.prefetchPackage(module, courseId, this.prefetchWorkshop.bind(this, module, courseId)); } /** * Retrieves all the grades reports for all the groups and then returns only unique grades. * * @param workshopId Workshop ID. * @param groups Array of groups in the activity. * @param cmId Module ID. * @param siteId Site ID. If not defined, current site. * @return All unique entries. */ protected async getAllGradesReport( workshopId: number, groups: CoreGroup[], cmId: number, siteId: string, ): Promise<AddonModWorkshopGradesData[]> { const promises: Promise<AddonModWorkshopGradesData[]>[] = []; groups.forEach((group) => { promises.push(AddonModWorkshop.fetchAllGradeReports(workshopId, { groupId: group.id, cmId, siteId })); }); const grades = await Promise.all(promises); const uniqueGrades: Record<number, AddonModWorkshopGradesData> = {}; grades.forEach((groupGrades) => { groupGrades.forEach((grade) => { if (grade.submissionid) { uniqueGrades[grade.submissionid] = grade; } }); }); return CoreUtils.objectToArray(uniqueGrades); } /** * Prefetch a workshop. * * @param module The module object returned by WS. * @param courseId Course ID the module belongs to. * @param siteId Site ID. * @return Promise resolved when done. */ protected async prefetchWorkshop(module: CoreCourseAnyModuleData, courseId: number, siteId: string): Promise<void> { const userIds: number[] = []; const commonOptions = { readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK, siteId, }; const modOptions = { cmId: module.id, ...commonOptions, // Include all common options. }; const site = await CoreSites.getSite(siteId); const currentUserId = site.getUserId(); // Prefetch the workshop data. const info = await this.getWorkshopInfoHelper(module, courseId, commonOptions); const workshop = info.workshop!; const promises: Promise<unknown>[] = []; const assessmentIds: number[] = []; promises.push(CoreFilepool.addFilesToQueue(siteId, info.files, this.component, module.id)); promises.push(AddonModWorkshop.getWorkshopAccessInformation(workshop.id, modOptions).then(async (access) => { const phases = await AddonModWorkshop.getUserPlanPhases(workshop.id, modOptions); // Get submission phase info. const submissionPhase = phases[AddonModWorkshopPhase.PHASE_SUBMISSION]; const canSubmit = AddonModWorkshopHelper.canSubmit(workshop, access, submissionPhase.tasks); const canAssess = AddonModWorkshopHelper.canAssess(workshop, access); const promises2: Promise<unknown>[] = []; if (canSubmit) { promises2.push(AddonModWorkshop.getSubmissions(workshop.id, modOptions)); // Add userId to the profiles to prefetch. userIds.push(currentUserId); } let reportPromise: Promise<unknown> = Promise.resolve(); if (access.canviewallsubmissions && workshop.phase >= AddonModWorkshopPhase.PHASE_SUBMISSION) { // eslint-disable-next-line promise/no-nesting reportPromise = this.getAllGradesReport(workshop.id, info.groups, module.id, siteId).then((grades) => { grades.forEach((grade) => { userIds.push(grade.userid); grade.submissiongradeoverby && userIds.push(grade.submissiongradeoverby); grade.reviewedby && grade.reviewedby.forEach((assessment) => { userIds.push(assessment.userid); assessmentIds[assessment.assessmentid] = assessment.assessmentid; }); grade.reviewerof && grade.reviewerof.forEach((assessment) => { userIds.push(assessment.userid); assessmentIds[assessment.assessmentid] = assessment.assessmentid; }); }); return; }); } if (workshop.phase >= AddonModWorkshopPhase.PHASE_ASSESSMENT && canAssess) { // Wait the report promise to finish to override assessments array if needed. reportPromise = reportPromise.finally(async () => { const revAssessments = await AddonModWorkshopHelper.getReviewerAssessments(workshop.id, { userId: currentUserId, cmId: module.id, siteId, }); let files: CoreWSExternalFile[] = []; // Files in each submission. revAssessments.forEach((assessment) => { if (assessment.submission?.authorid == currentUserId) { promises.push(AddonModWorkshop.getAssessment( workshop.id, assessment.id, modOptions, )); } userIds.push(assessment.reviewerid); userIds.push(assessment.gradinggradeoverby); assessmentIds[assessment.id] = assessment.id; files = files.concat(assessment.submission?.attachmentfiles || []) .concat(assessment.submission?.contentfiles || []); }); await CoreFilepool.addFilesToQueue(siteId, files, this.component, module.id); }); } reportPromise = reportPromise.finally(() => { if (assessmentIds.length > 0) { return Promise.all(assessmentIds.map((assessmentId) => AddonModWorkshop.getAssessmentForm(workshop.id, assessmentId, modOptions))); } }); promises2.push(reportPromise); if (workshop.phase == AddonModWorkshopPhase.PHASE_CLOSED) { promises2.push(AddonModWorkshop.getGrades(workshop.id, modOptions)); if (access.canviewpublishedsubmissions) { promises2.push(AddonModWorkshop.getSubmissions(workshop.id, modOptions)); } } await Promise.all(promises2); return; })); // Add Basic Info to manage links. promises.push(CoreCourse.getModuleBasicInfoByInstance(workshop.id, 'workshop', siteId)); promises.push(CoreCourse.getModuleBasicGradeInfo(module.id, siteId)); await Promise.all(promises); // Prefetch user profiles. await CoreUser.prefetchProfiles(userIds, courseId, siteId); } /** * @inheritdoc */ async sync(module: CoreCourseAnyModuleData, courseId: number, siteId?: string): Promise<AddonModDataSyncResult> { return AddonModWorkshopSync.syncWorkshop(module.instance!, siteId); } } export const AddonModWorkshopPrefetchHandler = makeSingleton(AddonModWorkshopPrefetchHandlerService); /** * Options to pass to getWorkshopInfoHelper. */ export type AddonModWorkshopGetInfoOptions = CoreSitesCommonWSOptions & { omitFail?: boolean; // True to always return even if fails. };
the_stack
import {Collection, DropEvent, DropOperation, DroppableCollectionProps, DropPosition, DropTarget, KeyboardDelegate, Node} from '@react-types/shared'; import * as DragManager from './DragManager'; import {DroppableCollectionState} from '@react-stately/dnd'; import {getTypes} from './utils'; import {HTMLAttributes, Key, RefObject, useCallback, useEffect, useLayoutEffect, useRef} from 'react'; import {mergeProps} from '@react-aria/utils'; import {setInteractionModality} from '@react-aria/interactions'; import {useAutoScroll} from './useAutoScroll'; import {useDrop} from './useDrop'; import {useDroppableCollectionId} from './utils'; interface DroppableCollectionOptions extends DroppableCollectionProps { keyboardDelegate: KeyboardDelegate, getDropTargetFromPoint: (x: number, y: number) => DropTarget | null } interface DroppableCollectionResult { collectionProps: HTMLAttributes<HTMLElement> } interface DroppingState { collection: Collection<Node<unknown>>, focusedKey: Key, selectedKeys: Set<Key>, timeout: NodeJS.Timeout } const DROP_POSITIONS: DropPosition[] = ['before', 'on', 'after']; export function useDroppableCollection(props: DroppableCollectionOptions, state: DroppableCollectionState, ref: RefObject<HTMLElement>): DroppableCollectionResult { let localState = useRef({ props, state, nextTarget: null, dropOperation: null }).current; localState.props = props; localState.state = state; let autoScroll = useAutoScroll(ref); let {dropProps} = useDrop({ ref, onDropEnter(e) { let target = props.getDropTargetFromPoint(e.x, e.y); state.setTarget(target); }, onDropMove(e) { state.setTarget(localState.nextTarget); autoScroll.move(e.x, e.y); }, getDropOperationForPoint(types, allowedOperations, x, y) { let target = props.getDropTargetFromPoint(x, y); if (!target) { localState.dropOperation = 'cancel'; localState.nextTarget = null; return 'cancel'; } if (state.isDropTarget(target)) { localState.nextTarget = target; return localState.dropOperation; } localState.dropOperation = state.getDropOperation(target, types, allowedOperations); // If the target doesn't accept the drop, see if the root accepts it instead. if (localState.dropOperation === 'cancel') { let rootTarget: DropTarget = {type: 'root'}; let dropOperation = state.getDropOperation(rootTarget, types, allowedOperations); if (dropOperation !== 'cancel') { target = rootTarget; localState.dropOperation = dropOperation; } } localState.nextTarget = localState.dropOperation === 'cancel' ? null : target; return localState.dropOperation; }, onDropExit() { state.setTarget(null); autoScroll.stop(); }, onDropActivate(e) { if (state.target?.type === 'item' && state.target?.dropPosition === 'on' && typeof props.onDropActivate === 'function') { props.onDropActivate({ type: 'dropactivate', x: e.x, // todo y: e.y, target: state.target }); } }, onDrop(e) { if (state.target && typeof props.onDrop === 'function') { onDrop(e, state.target); } } }); let droppingState = useRef<DroppingState>(null); let onDrop = useCallback((e: DropEvent, target: DropTarget) => { let {state} = localState; // Focus the collection. state.selectionManager.setFocused(true); // Save some state of the collection/selection before the drop occurs so we can compare later. let focusedKey = state.selectionManager.focusedKey; droppingState.current = { timeout: null, focusedKey, collection: state.collection, selectedKeys: state.selectionManager.selectedKeys }; localState.props.onDrop({ type: 'drop', x: e.x, // todo y: e.y, target, items: e.items, dropOperation: e.dropOperation }); // Wait for a short time period after the onDrop is called to allow the data to be read asynchronously // and for React to re-render. If an insert occurs during this time, it will be selected/focused below. // If items are not "immediately" inserted by the onDrop handler, the application will need to handle // selecting and focusing those items themselves. droppingState.current.timeout = setTimeout(() => { // If focus didn't move already (e.g. due to an insert), and the user dropped on an item, // focus that item and show the focus ring to give the user feedback that the drop occurred. // Also show the focus ring if the focused key is not selected, e.g. in case of a reorder. let {state} = localState; if (state.selectionManager.focusedKey === focusedKey) { if (target.type === 'item' && target.dropPosition === 'on' && state.collection.getItem(target.key) != null) { state.selectionManager.setFocusedKey(target.key); state.selectionManager.setFocused(true); setInteractionModality('keyboard'); } else if (!state.selectionManager.isSelected(focusedKey)) { setInteractionModality('keyboard'); } } droppingState.current = null; }, 50); }, [localState]); // eslint-disable-next-line arrow-body-style useEffect(() => { return () => { if (droppingState.current) { clearTimeout(droppingState.current.timeout); } }; }, []); useLayoutEffect(() => { // If an insert occurs during a drop, we want to immediately select these items to give // feedback to the user that a drop occurred. Only do this if the selection didn't change // since the drop started so we don't override if the user or application did something. if ( droppingState.current && state.selectionManager.isFocused && state.collection.size > droppingState.current.collection.size && state.selectionManager.isSelectionEqual(droppingState.current.selectedKeys) ) { let newKeys = new Set<Key>(); for (let key of state.collection.getKeys()) { if (!droppingState.current.collection.getItem(key)) { newKeys.add(key); } } state.selectionManager.setSelectedKeys(newKeys); // If the focused item didn't change since the drop occurred, also focus the first // inserted item. If selection is disabled, then also show the focus ring so there // is some indication that items were added. if (state.selectionManager.focusedKey === droppingState.current.focusedKey) { let first = newKeys.keys().next().value; state.selectionManager.setFocusedKey(first); if (state.selectionManager.selectionMode === 'none') { setInteractionModality('keyboard'); } } droppingState.current = null; } }); useEffect(() => { let getNextTarget = (target: DropTarget, wrap = true): DropTarget => { if (!target) { return { type: 'root' }; } let {keyboardDelegate} = localState.props; let nextKey = target.type === 'item' ? keyboardDelegate.getKeyBelow(target.key) : keyboardDelegate.getFirstKey(); let dropPosition: DropPosition = 'before'; if (target.type === 'item') { let positionIndex = DROP_POSITIONS.indexOf(target.dropPosition); let nextDropPosition = DROP_POSITIONS[positionIndex + 1]; if (positionIndex < DROP_POSITIONS.length - 1 && !(nextDropPosition === 'after' && nextKey != null)) { return { type: 'item', key: target.key, dropPosition: nextDropPosition }; } // If the last drop position was 'after', then 'before' on the next key is equivalent. // Switch to 'on' instead. if (target.dropPosition === 'after') { dropPosition = 'on'; } } if (nextKey == null) { if (wrap) { return { type: 'root' }; } return null; } return { type: 'item', key: nextKey, dropPosition }; }; let getPreviousTarget = (target: DropTarget, wrap = true): DropTarget => { let {keyboardDelegate} = localState.props; let nextKey = target?.type === 'item' ? keyboardDelegate.getKeyAbove(target.key) : keyboardDelegate.getLastKey(); let dropPosition: DropPosition = !target || target.type === 'root' ? 'after' : 'on'; if (target?.type === 'item') { let positionIndex = DROP_POSITIONS.indexOf(target.dropPosition); let nextDropPosition = DROP_POSITIONS[positionIndex - 1]; if (positionIndex > 0 && nextDropPosition !== 'after') { return { type: 'item', key: target.key, dropPosition: nextDropPosition }; } // If the last drop position was 'before', then 'after' on the previous key is equivalent. // Switch to 'on' instead. if (target.dropPosition === 'before') { dropPosition = 'on'; } } if (nextKey == null) { if (wrap) { return { type: 'root' }; } return null; } return { type: 'item', key: nextKey, dropPosition }; }; let nextValidTarget = ( target: DropTarget, types: Set<string>, allowedDropOperations: DropOperation[], getNextTarget: (target: DropTarget, wrap: boolean) => DropTarget, wrap = true ): DropTarget => { let seenRoot = 0; let operation: DropOperation; do { let nextTarget = getNextTarget(target, wrap); if (!nextTarget) { return null; } target = nextTarget; operation = localState.state.getDropOperation(nextTarget, types, allowedDropOperations); if (target.type === 'root') { seenRoot++; } } while ( operation === 'cancel' && !localState.state.isDropTarget(target) && seenRoot < 2 ); if (operation === 'cancel') { return null; } return target; }; return DragManager.registerDropTarget({ element: ref.current, getDropOperation(types, allowedOperations) { if (localState.state.target) { return localState.state.getDropOperation(localState.state.target, types, allowedOperations); } // Check if any of the targets accept the drop. // TODO: should we have a faster way of doing this or e.g. for pagination? let target = nextValidTarget(null, types, allowedOperations, getNextTarget); return target ? 'move' : 'cancel'; }, onDropEnter(e, drag) { let types = getTypes(drag.items); let selectionManager = localState.state.selectionManager; let target: DropTarget; // When entering the droppable collection for the first time, the default drop target // is after the focused key. let key = selectionManager.focusedKey; let dropPosition: DropPosition = 'after'; // If the focused key is a cell, get the parent item instead. // For now, we assume that individual cells cannot be dropped on. let item = localState.state.collection.getItem(key); if (item?.type === 'cell') { key = item.parentKey; } // If the focused item is also selected, the default drop target is after the last selected item. // But if the focused key is the first selected item, then default to before the first selected item. // This is to make reordering lists slightly easier. If you select top down, we assume you want to // move the items down. If you select bottom up, we assume you want to move the items up. if (selectionManager.isSelected(key)) { if (selectionManager.selectedKeys.size > 1 && selectionManager.firstSelectedKey === key) { dropPosition = 'before'; } else { key = selectionManager.lastSelectedKey; } } if (key != null) { target = { type: 'item', key, dropPosition }; // If the default target is not valid, find the next one that is. if (localState.state.getDropOperation(target, types, drag.allowedDropOperations) === 'cancel') { target = nextValidTarget(target, types, drag.allowedDropOperations, getNextTarget, false) ?? nextValidTarget(target, types, drag.allowedDropOperations, getPreviousTarget, false); } } // If no focused key, then start from the root. if (!target) { target = nextValidTarget(null, types, drag.allowedDropOperations, getNextTarget); } localState.state.setTarget(target); }, onDropExit() { localState.state.setTarget(null); }, onDropTargetEnter(target) { localState.state.setTarget(target); }, onDropActivate(e) { if ( localState.state.target?.type === 'item' && localState.state.target?.dropPosition === 'on' && typeof localState.props.onDropActivate === 'function' ) { localState.props.onDropActivate({ type: 'dropactivate', x: e.x, // todo y: e.y, target: localState.state.target }); } }, onDrop(e, target) { if (localState.state.target && typeof localState.props.onDrop === 'function') { onDrop(e, target || localState.state.target); } }, onKeyDown(e, drag) { let {keyboardDelegate} = localState.props; let types = getTypes(drag.items); switch (e.key) { case 'ArrowDown': { if (keyboardDelegate.getKeyBelow) { let target = nextValidTarget(localState.state.target, types, drag.allowedDropOperations, getNextTarget); localState.state.setTarget(target); } break; } case 'ArrowUp': { if (keyboardDelegate.getKeyAbove) { let target = nextValidTarget(localState.state.target, types, drag.allowedDropOperations, getPreviousTarget); localState.state.setTarget(target); } break; } case 'Home': { if (keyboardDelegate.getFirstKey) { let target = nextValidTarget(null, types, drag.allowedDropOperations, getNextTarget); localState.state.setTarget(target); } break; } case 'End': { if (keyboardDelegate.getLastKey) { let target = nextValidTarget(null, types, drag.allowedDropOperations, getPreviousTarget); localState.state.setTarget(target); } break; } case 'PageDown': { if (keyboardDelegate.getKeyPageBelow) { let target = localState.state.target; if (!target) { target = nextValidTarget(null, types, drag.allowedDropOperations, getNextTarget); } else { // If on the root, go to the item a page below the top. Otherwise a page below the current item. let nextKey = keyboardDelegate.getKeyPageBelow( target.type === 'item' ? target.key : keyboardDelegate.getFirstKey() ); let dropPosition = target.type === 'item' ? target.dropPosition : 'after'; // If there is no next key, or we are starting on the last key, jump to the last possible position. if (nextKey == null || (target.type === 'item' && target.key === keyboardDelegate.getLastKey())) { nextKey = keyboardDelegate.getLastKey(); dropPosition = 'after'; } target = { type: 'item', key: nextKey, dropPosition }; // If the target does not accept the drop, find the next valid target. // If no next valid target, find the previous valid target. let operation = localState.state.getDropOperation(target, types, drag.allowedDropOperations); if (operation === 'cancel') { target = nextValidTarget(target, types, drag.allowedDropOperations, getNextTarget, false) ?? nextValidTarget(target, types, drag.allowedDropOperations, getPreviousTarget, false); } } localState.state.setTarget(target ?? localState.state.target); } break; } case 'PageUp': { if (!keyboardDelegate.getKeyPageAbove) { break; } let target = localState.state.target; if (!target) { target = nextValidTarget(null, types, drag.allowedDropOperations, getPreviousTarget); } else if (target.type === 'item') { // If at the top already, switch to the root. Otherwise navigate a page up. if (target.key === keyboardDelegate.getFirstKey()) { target = { type: 'root' }; } else { let nextKey = keyboardDelegate.getKeyPageAbove(target.key); let dropPosition = target.dropPosition; if (nextKey == null) { nextKey = keyboardDelegate.getFirstKey(); dropPosition = 'before'; } target = { type: 'item', key: nextKey, dropPosition }; } // If the target does not accept the drop, find the previous valid target. // If no next valid target, find the next valid target. let operation = localState.state.getDropOperation(target, types, drag.allowedDropOperations); if (operation === 'cancel') { target = nextValidTarget(target, types, drag.allowedDropOperations, getPreviousTarget, false) ?? nextValidTarget(target, types, drag.allowedDropOperations, getNextTarget, false); } } localState.state.setTarget(target ?? localState.state.target); break; } } } }); }, [localState, ref, onDrop]); let id = useDroppableCollectionId(state); return { collectionProps: mergeProps(dropProps, { id, // Remove description from collection element. If dropping on the entire collection, // there should be a drop indicator that has this description, so no need to double announce. 'aria-describedby': null }) }; }
the_stack
import * as _ from "lodash"; import * as clc from "cli-color"; import * as ora from "ora"; import { Client } from "../apiv2"; import { FirebaseError } from "../error"; import { pollOperation } from "../operation-poller"; import { promptOnce } from "../prompt"; import { Question } from "inquirer"; import * as api from "../api"; import { logger } from "../logger"; import * as utils from "../utils"; const TIMEOUT_MILLIS = 30000; const MAXIMUM_PROMPT_LIST = 100; const PROJECT_LIST_PAGE_SIZE = 1000; const CREATE_PROJECT_API_REQUEST_TIMEOUT_MILLIS = 15000; export interface CloudProjectInfo { project: string /* The resource name of the GCP project: "projects/projectId" */; displayName?: string; locationId?: string; } export interface ProjectPage<T> { projects: T[]; nextPageToken?: string; } export interface FirebaseProjectMetadata { name: string /* The fully qualified resource name of the Firebase project */; projectId: string; projectNumber: string; displayName: string; resources?: DefaultProjectResources; } export interface DefaultProjectResources { hostingSite?: string; realtimeDatabaseInstance?: string; storageBucket?: string; locationId?: string; } export enum ProjectParentResourceType { ORGANIZATION = "organization", FOLDER = "folder", } export interface ProjectParentResource { id: string; type: ProjectParentResourceType; } export const PROJECTS_CREATE_QUESTIONS: Question[] = [ { type: "input", name: "projectId", default: "", message: "Please specify a unique project id " + `(${clc.yellow("warning")}: cannot be modified afterward) [6-30 characters]:\n`, }, { type: "input", name: "displayName", default: "", message: "What would you like to call your project? (defaults to your project ID)", }, ]; const firebaseAPIClient = new Client({ urlPrefix: api.firebaseApiOrigin, auth: true, apiVersion: "v1beta1", }); export async function createFirebaseProjectAndLog( projectId: string, options: { displayName?: string; parentResource?: ProjectParentResource } ): Promise<FirebaseProjectMetadata> { const spinner = ora("Creating Google Cloud Platform project").start(); try { await createCloudProject(projectId, options); spinner.succeed(); } catch (err) { spinner.fail(); throw err; } return addFirebaseToCloudProjectAndLog(projectId); } export async function addFirebaseToCloudProjectAndLog( projectId: string ): Promise<FirebaseProjectMetadata> { let projectInfo; const spinner = ora("Adding Firebase resources to Google Cloud Platform project").start(); try { projectInfo = await addFirebaseToCloudProject(projectId); } catch (err) { spinner.fail(); throw err; } spinner.succeed(); logNewFirebaseProjectInfo(projectInfo); return projectInfo; } function logNewFirebaseProjectInfo(projectInfo: FirebaseProjectMetadata): void { logger.info(""); if (process.platform === "win32") { logger.info("=== Your Firebase project is ready! ==="); } else { logger.info("🎉🎉🎉 Your Firebase project is ready! 🎉🎉🎉"); } logger.info(""); logger.info("Project information:"); logger.info(` - Project ID: ${clc.bold(projectInfo.projectId)}`); logger.info(` - Project Name: ${clc.bold(projectInfo.displayName)}`); logger.info(""); logger.info("Firebase console is available at"); logger.info( `https://console.firebase.google.com/project/${clc.bold(projectInfo.projectId)}/overview` ); } /** * Get the user's desired project, prompting if necessary. */ export async function getOrPromptProject(options: any): Promise<FirebaseProjectMetadata> { if (options.project) { return await getFirebaseProject(options.project); } return selectProjectInteractively(); } async function selectProjectInteractively( pageSize: number = MAXIMUM_PROMPT_LIST ): Promise<FirebaseProjectMetadata> { const { projects, nextPageToken } = await getFirebaseProjectPage(pageSize); if (projects.length === 0) { throw new FirebaseError("There are no Firebase projects associated with this account."); } if (nextPageToken) { // Prompt user for project ID if we can't list all projects in 1 page logger.debug(`Found more than ${projects.length} projects, selecting via prompt`); return selectProjectByPrompting(); } return selectProjectFromList(projects); } async function selectProjectByPrompting(): Promise<FirebaseProjectMetadata> { const projectId = await promptOnce({ type: "input", message: "Please input the project ID you would like to use:", }); return await getFirebaseProject(projectId); } /** * Presents user with list of projects to choose from and gets project information for chosen project. */ async function selectProjectFromList( projects: FirebaseProjectMetadata[] = [] ): Promise<FirebaseProjectMetadata> { let choices = projects .filter((p: FirebaseProjectMetadata) => !!p) .map((p) => { return { name: p.projectId + (p.displayName ? ` (${p.displayName})` : ""), value: p.projectId, }; }); choices = _.orderBy(choices, ["name"], ["asc"]); if (choices.length >= 25) { utils.logBullet( `Don't want to scroll through all your projects? If you know your project ID, ` + `you can initialize it directly using ${clc.bold( "firebase init --project <project_id>" )}.\n` ); } const projectId: string = await promptOnce({ type: "list", name: "id", message: "Select a default Firebase project for this directory:", choices, }); const project = projects.find((p) => p.projectId === projectId); if (!project) { throw new FirebaseError("Unexpected error. Project does not exist"); } return project; } function getProjectId(cloudProject: CloudProjectInfo): string { const resourceName = cloudProject.project; // According to // https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/availableProjects/list#projectinfo, // resource name has the format of "projects/projectId" return resourceName.substring(resourceName.lastIndexOf("/") + 1); } /** * Prompt user to select an available GCP project to add Firebase resources */ export async function promptAvailableProjectId(): Promise<string> { const { projects, nextPageToken } = await getAvailableCloudProjectPage(MAXIMUM_PROMPT_LIST); if (projects.length === 0) { throw new FirebaseError( "There are no available Google Cloud projects to add Firebase services." ); } if (nextPageToken) { // Prompt for project ID if we can't list all projects in 1 page return await promptOnce({ type: "input", message: "Please input the ID of the Google Cloud Project you would like to add Firebase:", }); } else { let choices = projects .filter((p: CloudProjectInfo) => !!p) .map((p) => { const projectId = getProjectId(p); return { name: projectId + (p.displayName ? ` (${p.displayName})` : ""), value: projectId, }; }); choices = _.orderBy(choices, ["name"], ["asc"]); return await promptOnce({ type: "list", name: "id", message: "Select the Google Cloud Platform project you would like to add Firebase:", choices, }); } } /** * Send an API request to create a new Google Cloud Platform project and poll the LRO to get the * new project information. * @return a promise that resolves to the new cloud project information */ export async function createCloudProject( projectId: string, options: { displayName?: string; parentResource?: ProjectParentResource } ): Promise<any> { try { const response = await api.request("POST", "/v1/projects", { auth: true, origin: api.resourceManagerOrigin, timeout: CREATE_PROJECT_API_REQUEST_TIMEOUT_MILLIS, data: { projectId, name: options.displayName || projectId, parent: options.parentResource }, }); const projectInfo = await pollOperation<any>({ pollerName: "Project Creation Poller", apiOrigin: api.resourceManagerOrigin, apiVersion: "v1", operationResourceName: response.body.name /* LRO resource name */, }); return projectInfo; } catch (err) { if (err.status === 409) { throw new FirebaseError( `Failed to create project because there is already a project with ID ${clc.bold( projectId )}. Please try again with a unique project ID.`, { exit: 2, original: err, } ); } else { throw new FirebaseError("Failed to create project. See firebase-debug.log for more info.", { exit: 2, original: err, }); } } } /** * Send an API request to add Firebase to the Google Cloud Platform project and poll the LRO * to get the new Firebase project information. * @return a promise that resolves to the new firebase project information */ export async function addFirebaseToCloudProject( projectId: string ): Promise<FirebaseProjectMetadata> { try { const response = await api.request("POST", `/v1beta1/projects/${projectId}:addFirebase`, { auth: true, origin: api.firebaseApiOrigin, timeout: CREATE_PROJECT_API_REQUEST_TIMEOUT_MILLIS, }); const projectInfo = await pollOperation<any>({ pollerName: "Add Firebase Poller", apiOrigin: api.firebaseApiOrigin, apiVersion: "v1beta1", operationResourceName: response.body.name /* LRO resource name */, }); return projectInfo; } catch (err) { logger.debug(err.message); throw new FirebaseError( "Failed to add Firebase to Google Cloud Platform project. See firebase-debug.log for more info.", { exit: 2, original: err } ); } } async function getProjectPage<T>( apiResource: string, options: { responseKey: string; // The list is located at "apiResponse.body[responseKey]" pageSize: number; pageToken?: string; } ): Promise<ProjectPage<T>> { const queryParams: { [key: string]: string } = { pageSize: `${options.pageSize}`, }; if (options.pageToken) { queryParams.pageToken = options.pageToken; } const res = await firebaseAPIClient.request<void, { [key: string]: T[] | string | undefined }>({ method: "GET", path: apiResource, queryParams, timeout: TIMEOUT_MILLIS, skipLog: { resBody: true }, }); const projects = res.body[options.responseKey]; const token = res.body.nextPageToken; return { projects: Array.isArray(projects) ? projects : [], nextPageToken: typeof token === "string" ? token : undefined, }; } /** * Lists Firebase projects in a page using the paginated API, identified by the page token and its * size. */ export async function getFirebaseProjectPage( pageSize: number = PROJECT_LIST_PAGE_SIZE, pageToken?: string ): Promise<ProjectPage<FirebaseProjectMetadata>> { let projectPage; try { projectPage = await getProjectPage<FirebaseProjectMetadata>("/projects", { responseKey: "results", pageSize, pageToken, }); } catch (err) { logger.debug(err.message); throw new FirebaseError( "Failed to list Firebase projects. See firebase-debug.log for more info.", { exit: 2, original: err } ); } return projectPage; } /** * Lists a page of available Google Cloud Platform projects that are available to have Firebase * resources added, using the paginated API, identified by the page token and its size. */ export async function getAvailableCloudProjectPage( pageSize: number = PROJECT_LIST_PAGE_SIZE, pageToken?: string ): Promise<ProjectPage<CloudProjectInfo>> { try { return await getProjectPage<CloudProjectInfo>("/availableProjects", { responseKey: "projectInfo", pageSize, pageToken, }); } catch (err) { logger.debug(err.message); throw new FirebaseError( "Failed to list available Google Cloud Platform projects. See firebase-debug.log for more info.", { exit: 2, original: err } ); } } /** * Lists all Firebase projects associated with the currently logged-in account. Repeatedly calls the * paginated API until all pages have been read. * @return a promise that resolves to the list of all projects. */ export async function listFirebaseProjects(pageSize?: number): Promise<FirebaseProjectMetadata[]> { const projects: FirebaseProjectMetadata[] = []; let nextPageToken; do { const projectPage: ProjectPage<FirebaseProjectMetadata> = await getFirebaseProjectPage( pageSize, nextPageToken ); projects.push(...projectPage.projects); nextPageToken = projectPage.nextPageToken; } while (nextPageToken); return projects; } /** * Gets the Firebase project information identified by the specified project ID */ export async function getFirebaseProject(projectId: string): Promise<FirebaseProjectMetadata> { try { const res = await firebaseAPIClient.request<void, FirebaseProjectMetadata>({ method: "GET", path: `/projects/${projectId}`, timeout: TIMEOUT_MILLIS, }); return res.body; } catch (err) { logger.debug(err.message); throw new FirebaseError( `Failed to get Firebase project ${projectId}. ` + "Please make sure the project exists and your account has permission to access it.", { exit: 2, original: err } ); } }
the_stack
import { Component, Optional, OnInit, OnDestroy } from '@angular/core'; import { IonContent } from '@ionic/angular'; import { CoreConstants } from '@/core/constants'; import { CoreSite } from '@classes/site'; import { CoreCourseModuleMainActivityComponent } from '@features/course/classes/main-activity-component'; import { CoreCourseContentsPage } from '@features/course/pages/contents/contents'; import { CoreCourse } from '@features/course/services/course'; import { CoreH5PDisplayOptions } from '@features/h5p/classes/core'; import { CoreH5PHelper } from '@features/h5p/classes/helper'; import { CoreH5P } from '@features/h5p/services/h5p'; import { CoreXAPIOffline } from '@features/xapi/services/offline'; import { CoreXAPI } from '@features/xapi/services/xapi'; import { CoreApp } from '@services/app'; import { CoreFilepool } from '@services/filepool'; import { CoreNavigator } from '@services/navigator'; import { CoreSites } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreWSFile } from '@services/ws'; import { CoreEventObserver, CoreEvents } from '@singletons/events'; import { AddonModH5PActivity, AddonModH5PActivityAccessInfo, AddonModH5PActivityData, AddonModH5PActivityProvider, } from '../../services/h5pactivity'; import { AddonModH5PActivitySync, AddonModH5PActivitySyncProvider, AddonModH5PActivitySyncResult, } from '../../services/h5pactivity-sync'; import { CoreFileHelper } from '@services/file-helper'; import { AddonModH5PActivityModuleHandlerService } from '../../services/handlers/module'; import { CoreMainMenuPage } from '@features/mainmenu/pages/menu/menu'; import { Platform } from '@singletons'; /** * Component that displays an H5P activity entry page. */ @Component({ selector: 'addon-mod-h5pactivity-index', templateUrl: 'addon-mod-h5pactivity-index.html', }) export class AddonModH5PActivityIndexComponent extends CoreCourseModuleMainActivityComponent implements OnInit, OnDestroy { component = AddonModH5PActivityProvider.COMPONENT; moduleName = 'h5pactivity'; h5pActivity?: AddonModH5PActivityData; // The H5P activity object. accessInfo?: AddonModH5PActivityAccessInfo; // Info about the user capabilities. deployedFile?: CoreWSFile; // The H5P deployed file. stateMessage?: string; // Message about the file state. downloading = false; // Whether the H5P file is being downloaded. needsDownload = false; // Whether the file needs to be downloaded. percentage?: string; // Download/unzip percentage. showPercentage = false; // Whether to show the percentage. progressMessage?: string; // Message about download/unzip. playing = false; // Whether the package is being played. displayOptions?: CoreH5PDisplayOptions; // Display options for the package. onlinePlayerUrl?: string; // URL to play the package in online. fileUrl?: string; // The fileUrl to use to play the package. state?: string; // State of the file. siteCanDownload = false; trackComponent?: string; // Component for tracking. hasOffline = false; isOpeningPage = false; protected listeningResize = false; protected fetchContentDefaultError = 'addon.mod_h5pactivity.errorgetactivity'; protected syncEventName = AddonModH5PActivitySyncProvider.AUTO_SYNCED; protected site: CoreSite; protected observer?: CoreEventObserver; protected messageListenerFunction: (event: MessageEvent) => Promise<void>; protected resizeFunction: () => void; constructor( protected mainMenuPage: CoreMainMenuPage, protected content?: IonContent, @Optional() courseContentsPage?: CoreCourseContentsPage, ) { super('AddonModH5PActivityIndexComponent', content, courseContentsPage); this.site = CoreSites.getCurrentSite()!; this.siteCanDownload = this.site.canDownloadFiles() && !CoreH5P.isOfflineDisabledInSite(); // Listen for messages from the iframe. this.messageListenerFunction = this.onIframeMessage.bind(this); window.addEventListener('message', this.messageListenerFunction); this.resizeFunction = this.contentResized.bind(this); } /** * @inheritdoc */ async ngOnInit(): Promise<void> { super.ngOnInit(); this.loadContent(); } /** * @inheritdoc */ protected async fetchContent(refresh: boolean = false, sync: boolean = false, showErrors: boolean = false): Promise<void> { try { this.h5pActivity = await AddonModH5PActivity.getH5PActivity(this.courseId, this.module.id, { siteId: this.siteId, }); this.dataRetrieved.emit(this.h5pActivity); this.description = this.h5pActivity.intro; this.displayOptions = CoreH5PHelper.decodeDisplayOptions(this.h5pActivity.displayoptions); if (sync) { await this.syncActivity(showErrors); } await Promise.all([ this.checkHasOffline(), this.fetchAccessInfo(), this.fetchDeployedFileData(), ]); this.trackComponent = this.accessInfo?.cansubmit ? AddonModH5PActivityProvider.TRACK_COMPONENT : ''; if (this.h5pActivity.package && this.h5pActivity.package[0]) { // The online player should use the original file, not the trusted one. this.onlinePlayerUrl = CoreH5P.h5pPlayer.calculateOnlinePlayerUrl( this.site.getURL(), this.h5pActivity.package[0].fileurl, this.displayOptions, this.trackComponent, ); } if (!this.siteCanDownload || this.state == CoreConstants.DOWNLOADED) { // Cannot download the file or already downloaded, play the package directly. this.play(); } else if ((this.state == CoreConstants.NOT_DOWNLOADED || this.state == CoreConstants.OUTDATED) && CoreApp.isOnline() && this.deployedFile?.filesize && CoreFilepool.shouldDownload(this.deployedFile.filesize)) { // Package is small, download it automatically. Don't block this function for this. this.downloadAutomatically(); } } finally { this.fillContextMenu(refresh); } } /** * Fetch the access info and store it in the right variables. * * @return Promise resolved when done. */ protected async checkHasOffline(): Promise<void> { this.hasOffline = await CoreXAPIOffline.contextHasStatements(this.h5pActivity!.context, this.siteId); } /** * Fetch the access info and store it in the right variables. * * @return Promise resolved when done. */ protected async fetchAccessInfo(): Promise<void> { this.accessInfo = await AddonModH5PActivity.getAccessInformation(this.h5pActivity!.id, { cmId: this.module.id, siteId: this.siteId, }); } /** * Fetch the deployed file data if needed and store it in the right variables. * * @return Promise resolved when done. */ protected async fetchDeployedFileData(): Promise<void> { if (!this.siteCanDownload) { // Cannot download the file, no need to fetch the file data. return; } this.deployedFile = await AddonModH5PActivity.getDeployedFile(this.h5pActivity!, { displayOptions: this.displayOptions, siteId: this.siteId, }); this.fileUrl = CoreFileHelper.getFileUrl(this.deployedFile); // Listen for changes in the state. const eventName = await CoreFilepool.getFileEventNameByUrl(this.site.getId(), this.fileUrl); if (!this.observer) { this.observer = CoreEvents.on(eventName, () => { this.calculateFileState(); }); } await this.calculateFileState(); } /** * Calculate the state of the deployed file. * * @return Promise resolved when done. */ protected async calculateFileState(): Promise<void> { this.state = await CoreFilepool.getFileStateByUrl( this.site.getId(), this.fileUrl!, this.deployedFile!.timemodified, ); this.showFileState(); } /** * @inheritdoc */ protected invalidateContent(): Promise<void> { return AddonModH5PActivity.invalidateActivityData(this.courseId); } /** * Displays some data based on the state of the main file. */ protected async showFileState(): Promise<void> { if (this.state == CoreConstants.OUTDATED) { this.stateMessage = 'addon.mod_h5pactivity.filestateoutdated'; this.needsDownload = true; } else if (this.state == CoreConstants.NOT_DOWNLOADED) { this.stateMessage = 'addon.mod_h5pactivity.filestatenotdownloaded'; this.needsDownload = true; } else if (this.state == CoreConstants.DOWNLOADING) { this.stateMessage = ''; if (!this.downloading) { // It's being downloaded right now but the view isn't tracking it. "Restore" the download. await this.downloadDeployedFile(); this.play(); } } else { this.stateMessage = ''; this.needsDownload = false; } } /** * Download the file and play it. * * @param event Click event. * @return Promise resolved when done. */ async downloadAndPlay(event?: MouseEvent): Promise<void> { event?.preventDefault(); event?.stopPropagation(); if (!CoreApp.isOnline()) { CoreDomUtils.showErrorModal('core.networkerrormsg', true); return; } try { // Confirm the download if needed. await CoreDomUtils.confirmDownloadSize({ size: this.deployedFile!.filesize!, total: true }); await this.downloadDeployedFile(); if (!this.isDestroyed) { this.play(); } } catch (error) { if (CoreDomUtils.isCanceledError(error) || this.isDestroyed) { // User cancelled or view destroyed, stop. return; } CoreDomUtils.showErrorModalDefault(error, 'core.errordownloading', true); } } /** * Download the file automatically. * * @return Promise resolved when done. */ protected async downloadAutomatically(): Promise<void> { try { await this.downloadDeployedFile(); if (!this.isDestroyed) { this.play(); } } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'core.errordownloading', true); } } /** * Download athe H5P deployed file or restores an ongoing download. * * @return Promise resolved when done. */ protected async downloadDeployedFile(): Promise<void> { this.downloading = true; this.progressMessage = 'core.downloading'; try { await CoreFilepool.downloadUrl( this.site.getId(), this.fileUrl!, false, this.component, this.componentId, this.deployedFile!.timemodified, (data: DownloadProgressData) => { if (!data) { return; } this.percentage = undefined; this.showPercentage = false; if (data.message) { // Show a message. this.progressMessage = data.message; } else if (data.loaded !== undefined) { // Downloading or unzipping. const totalSize = this.progressMessage == 'core.downloading' ? this.deployedFile!.filesize : data.total; if (totalSize !== undefined) { const percentageNumber = (Number(data.loaded / totalSize) * 100); this.percentage = percentageNumber.toFixed(1); this.showPercentage = percentageNumber >= 0 && percentageNumber <= 100; } } }, ); } finally { this.progressMessage = undefined; this.percentage = undefined; this.showPercentage = false; this.downloading = false; } } /** * Play the package. */ play(): void { this.playing = true; // Mark the activity as viewed. AddonModH5PActivity.logView(this.h5pActivity!.id, this.h5pActivity!.name, this.siteId); CoreCourse.checkModuleCompletion(this.courseId, this.module.completiondata); this.setResizeListener(); } /** * Go to view user events. */ async viewMyAttempts(): Promise<void> { this.isOpeningPage = true; const userId = CoreSites.getCurrentSiteUserId(); try { await CoreNavigator.navigateToSitePath( `${AddonModH5PActivityModuleHandlerService.PAGE_NAME}/${this.courseId}/${this.module.id}/userattempts/${userId}`, ); } finally { this.isOpeningPage = false; } } /** * Treat an iframe message event. * * @param event Event. * @return Promise resolved when done. */ protected async onIframeMessage(event: MessageEvent): Promise<void> { if (!event.data || !CoreXAPI.canPostStatementsInSite(this.site) || !this.isCurrentXAPIPost(event.data)) { return; } try { const options = { offline: this.hasOffline, courseId: this.courseId, extra: this.h5pActivity!.name, siteId: this.site.getId(), }; const sent = await CoreXAPI.postStatements( this.h5pActivity!.context, event.data.component, JSON.stringify(event.data.statements), options, ); this.hasOffline = !sent; if (sent) { try { // Invalidate attempts. await AddonModH5PActivity.invalidateUserAttempts(this.h5pActivity!.id, undefined, this.siteId); } catch (error) { // Ignore errors. } } } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'Error sending tracking data.'); } } /** * Check if an event is an XAPI post statement of the current activity. * * @param data Event data. * @return Whether it's an XAPI post statement of the current activity. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any protected isCurrentXAPIPost(data: any): boolean { if (data.environment != 'moodleapp' || data.context != 'h5p' || data.action != 'xapi_post_statement' || !data.statements) { return false; } // Check the event belongs to this activity. const trackingUrl = data.statements[0] && data.statements[0].object && data.statements[0].object.id; if (!trackingUrl) { return false; } if (!this.site.containsUrl(trackingUrl)) { // The event belongs to another site, weird scenario. Maybe some JS running in background. return false; } const match = trackingUrl.match(/xapi\/activity\/(\d+)/); return match && match[1] == this.h5pActivity!.context; } /** * @inheritdoc */ protected sync(): Promise<AddonModH5PActivitySyncResult> { return AddonModH5PActivitySync.syncActivity(this.h5pActivity!.context, this.site.getId()); } /** * @inheritdoc */ protected autoSyncEventReceived(): void { this.checkHasOffline(); } /** * @inheritdoc */ async gotoBlog(): Promise<void> { this.isOpeningPage = true; try { await super.gotoBlog(); } finally { this.isOpeningPage = false; } } /** * Set the resize listener if needed. */ setResizeListener(): void { if (!this.playing || this.listeningResize) { return; } this.listeningResize = true; window.addEventListener('resize', this.contentResized.bind(this)); this.contentResized(); } /** * On content resize, change visibility of the main menu: show on portrait and hide on landscape. */ contentResized(): void { this.mainMenuPage.changeVisibility(Platform.isPortrait()); } /** * @inheritdoc */ ionViewDidEnter(): void { this.setResizeListener(); } /** * @inheritdoc */ ionViewWillLeave(): void { this.mainMenuPage.changeVisibility(true); if (this.listeningResize) { this.listeningResize = false; window.removeEventListener('resize', this.resizeFunction); } } /** * Component destroyed. */ ngOnDestroy(): void { super.ngOnDestroy(); this.observer?.off(); window.removeEventListener('message', this.messageListenerFunction); } } type DownloadProgressData = { message?: string; loaded?: number; total?: number; };
the_stack
import { UserError } from '../../../src/compiler/UserError'; import { prepareCompiler } from '../../unit/PrepareCompiler'; import { ClickHouseDbRunner } from './ClickHouseDbRunner'; import { debugLog, logSqlAndParams } from '../../unit/TestUtil'; import { ClickHouseQuery } from '../../../src/adapter/ClickHouseQuery'; describe('ClickHouse JoinGraph', () => { jest.setTimeout(200000); const dbRunner = new ClickHouseDbRunner(); afterAll(async () => { await dbRunner.tearDown(); }); const { compiler, joinGraph, cubeEvaluator } = prepareCompiler(` const perVisitorRevenueMeasure = { type: 'number', sql: new Function('visitor_revenue', 'visitor_count', 'return visitor_revenue + "/" + visitor_count') } cube(\`visitors\`, { sql: \` select * from visitors WHERE \${USER_CONTEXT.source.filter('source')} AND \${USER_CONTEXT.sourceArray.filter(sourceArray => \`source in (\${sourceArray.join(',')})\`)} \`, refreshKey: { sql: 'SELECT 1', }, joins: { visitor_checkins: { relationship: 'hasMany', sql: \`\${CUBE}.id = \${visitor_checkins}.visitor_id\` } }, measures: { visitor_count: { type: 'number', sql: \`count(*)\`, aliases: ['users count'] }, visitor_revenue: { type: 'sum', sql: 'amount', filters: [{ sql: \`\${CUBE}.source = 'some'\` }] }, per_visitor_revenue: perVisitorRevenueMeasure, revenueRunning: { type: 'runningTotal', sql: 'amount' }, revenueRolling: { type: 'sum', sql: 'amount', rollingWindow: { trailing: '2 day', offset: 'start' } }, revenueRolling3day: { type: 'sum', sql: 'amount', rollingWindow: { trailing: '3 day', offset: 'start' } }, countRolling: { type: 'count', rollingWindow: { trailing: '2 day', offset: 'start' } }, countDistinctApproxRolling: { type: 'countDistinctApprox', sql: 'id', rollingWindow: { trailing: '2 day', offset: 'start' } }, runningCount: { type: 'runningTotal', sql: '1' }, runningRevenuePerCount: { type: 'number', sql: \`round(\${revenueRunning} / \${runningCount})\` }, averageCheckins: { type: 'avg', sql: \`\${doubledCheckings}\` } }, dimensions: { id: { type: 'number', sql: 'id', primaryKey: true }, source: { type: 'string', sql: 'source' }, created_at: { type: 'time', sql: 'created_at' }, createdAtSqlUtils: { type: 'time', sql: SQL_UTILS.convertTz('created_at') }, checkins: { sql: \`\${visitor_checkins.visitor_checkins_count}\`, type: \`number\`, subQuery: true }, subQueryFail: { sql: '2', type: \`number\`, subQuery: true }, doubledCheckings: { sql: \`\${checkins} * 2\`, type: 'number' }, minVisitorCheckinDate: { sql: \`\${visitor_checkins.minDate}\`, type: 'time', subQuery: true }, minVisitorCheckinDate1: { sql: \`\${visitor_checkins.minDate1}\`, type: 'time', subQuery: true }, location: { type: \`geo\`, latitude: { sql: \`latitude\` }, longitude: { sql: \`longitude\` } } } }) cube('visitor_checkins', { sql: \` select * from visitor_checkins \`, joins: { cards: { relationship: 'hasMany', sql: \`\${CUBE}.id = \${cards}.visitor_checkin_id\` } }, measures: { visitor_checkins_count: { type: 'count' }, revenue_per_checkin: { type: 'number', sql: \`\${visitors.visitor_revenue} / \${visitor_checkins_count}\` }, google_sourced_checkins: { type: 'count', sql: 'id', filters: [{ sql: \`\${visitors}.source = 'google'\` }] }, minDate: { type: 'min', sql: 'created_at' } }, dimensions: { id: { type: 'number', sql: 'id', primaryKey: true }, visitor_id: { type: 'number', sql: 'visitor_id' }, source: { type: 'string', sql: 'source' }, created_at: { type: 'time', sql: 'created_at' }, cardsCount: { sql: \`\${cards.count}\`, type: \`number\`, subQuery: true }, }, // preAggregations: { // checkinSource: { // type: 'rollup', // measureReferences: [visitors.per_visitor_revenue], // dimensionReferences: [visitor_checkins.source], // timeDimensionReference: visitors.created_at, // granularity: 'day' // }, // visitorCountCheckinSource: { // type: 'rollup', // measureReferences: [visitors.visitor_revenue], // dimensionReferences: [visitor_checkins.source], // timeDimensionReference: visitors.created_at, // granularity: 'day' // } // } }) cube('cards', { sql: \` select * from cards \`, joins: { visitors: { relationship: 'belongsTo', sql: \`\${visitors}.id = \${cards}.visitor_id\` } }, measures: { count: { type: 'count' } }, dimensions: { id: { type: 'number', sql: 'id', primaryKey: true } } }) cube('ReferenceVisitors', { sql: \` select * from \${visitors.sql()} as t WHERE \${FILTER_PARAMS.ReferenceVisitors.createdAt.filter(\`addDays(t.created_at, 28)\`)} AND \${FILTER_PARAMS.ReferenceVisitors.createdAt.filter((from, to) => \`(addDays(t.created_at,28)) >= parseDateTimeBestEffort(\${from}) AND (addDays(t.created_at, 28)) <= parseDateTimeBestEffort(\${to})\`)} \`, measures: { count: { type: 'count' }, googleSourcedCount: { type: 'count', filters: [{ sql: \`\${CUBE}.source = 'google'\` }] }, }, dimensions: { createdAt: { type: 'time', sql: 'created_at' } } }) `); // SUCCESS but need to finish query to override ::timestamptz it('simple join', () => { const result = compiler.compile().then(() => { debugLog(joinGraph.buildJoin(['visitor_checkins', 'visitors'])); const query = new ClickHouseQuery({ joinGraph, cubeEvaluator, compiler }, { measures: [ 'visitors.visitor_revenue', 'visitors.visitor_count', 'visitor_checkins.visitor_checkins_count', 'visitors.per_visitor_revenue' ], timeDimensions: [{ dimension: 'visitors.created_at', granularity: 'day', dateRange: ['2017-01-01', '2017-01-30'] }], timezone: 'America/Los_Angeles', order: [{ id: 'visitors.created_at' }] }); logSqlAndParams(query); return dbRunner.testQuery(query.buildSqlAndParams()).then(res => { expect(res).toEqual( [ { visitors__created_at_day: '2017-01-02T00:00:00.000', visitors__visitor_revenue: '100', visitors__visitor_count: '1', visitor_checkins__visitor_checkins_count: '3', visitors__per_visitor_revenue: '100' }, { visitors__created_at_day: '2017-01-04T00:00:00.000', visitors__visitor_revenue: '200', visitors__visitor_count: '1', visitor_checkins__visitor_checkins_count: '2', visitors__per_visitor_revenue: '200' }, { visitors__created_at_day: '2017-01-05T00:00:00.000', visitors__visitor_revenue: null, visitors__visitor_count: '1', visitor_checkins__visitor_checkins_count: '1', visitors__per_visitor_revenue: null }, { visitors__created_at_day: '2017-01-06T00:00:00.000', visitors__visitor_revenue: null, visitors__visitor_count: '2', visitor_checkins__visitor_checkins_count: '0', visitors__per_visitor_revenue: null } ] ); }); }); return result; }); async function runQueryTest(q, expectedResult) { await compiler.compile(); const query = new ClickHouseQuery({ joinGraph, cubeEvaluator, compiler }, q); logSqlAndParams(query); const result = await dbRunner.testQuery(query.buildSqlAndParams()); debugLog(JSON.stringify(result)); expect(result).toEqual( expectedResult ); } it('simple join total', () => runQueryTest({ measures: [ 'visitors.visitor_revenue', 'visitors.visitor_count', 'visitor_checkins.visitor_checkins_count', 'visitors.per_visitor_revenue' ], timeDimensions: [{ dimension: 'visitors.created_at', dateRange: ['2017-01-01', '2017-01-30'] }], timezone: 'America/Los_Angeles', order: [] }, [{ visitors__visitor_revenue: '300', visitors__visitor_count: '5', visitor_checkins__visitor_checkins_count: '6', visitors__per_visitor_revenue: '60' }])); // FAILS - need to finish query to override ::timestamptz it.skip('running total', () => { const result = compiler.compile().then(() => { const query = new ClickHouseQuery({ joinGraph, cubeEvaluator, compiler }, { measures: [ 'visitors.revenueRunning' ], timeDimensions: [{ dimension: 'visitors.created_at', granularity: 'day', dateRange: ['2017-01-01', '2017-01-10'] }], order: [{ id: 'visitors.created_at' }], timezone: 'America/Los_Angeles' }); logSqlAndParams(query); // TODO ordering doesn't work for running total return dbRunner.testQuery(query.buildSqlAndParams()).then(res => { debugLog(JSON.stringify(res)); expect(res).toEqual( [{ visitors__created_at_day: '2017-01-01T00:00:00.000Z', visitors__revenue_running: null }, { visitors__created_at_day: '2017-01-02T00:00:00.000Z', visitors__revenue_running: '100' }, { visitors__created_at_day: '2017-01-03T00:00:00.000Z', visitors__revenue_running: '100' }, { visitors__created_at_day: '2017-01-04T00:00:00.000Z', visitors__revenue_running: '300' }, { visitors__created_at_day: '2017-01-05T00:00:00.000Z', visitors__revenue_running: '600' }, { visitors__created_at_day: '2017-01-06T00:00:00.000Z', visitors__revenue_running: '1500' }, { visitors__created_at_day: '2017-01-07T00:00:00.000Z', visitors__revenue_running: '1500' }, { visitors__created_at_day: '2017-01-08T00:00:00.000Z', visitors__revenue_running: '1500' }, { visitors__created_at_day: '2017-01-09T00:00:00.000Z', visitors__revenue_running: '1500' }, { visitors__created_at_day: '2017-01-10T00:00:00.000Z', visitors__revenue_running: '1500' }] ); }); }); return result; }); // FAILS - need to finish query to override ::timestamptz it.skip('rolling', () => runQueryTest({ measures: [ 'visitors.revenueRolling' ], timeDimensions: [{ dimension: 'visitors.created_at', granularity: 'day', dateRange: ['2017-01-01', '2017-01-10'] }], order: [{ id: 'visitors.created_at' }], timezone: 'America/Los_Angeles' }, [ { visitors__created_at_day: '2017-01-01T00:00:00.000Z', visitors__revenue_rolling: null }, { visitors__created_at_day: '2017-01-02T00:00:00.000Z', visitors__revenue_rolling: null }, { visitors__created_at_day: '2017-01-03T00:00:00.000Z', visitors__revenue_rolling: '100' }, { visitors__created_at_day: '2017-01-04T00:00:00.000Z', visitors__revenue_rolling: '100' }, { visitors__created_at_day: '2017-01-05T00:00:00.000Z', visitors__revenue_rolling: '200' }, { visitors__created_at_day: '2017-01-06T00:00:00.000Z', visitors__revenue_rolling: '500' }, { visitors__created_at_day: '2017-01-07T00:00:00.000Z', visitors__revenue_rolling: '1200' }, { visitors__created_at_day: '2017-01-08T00:00:00.000Z', visitors__revenue_rolling: '900' }, { visitors__created_at_day: '2017-01-09T00:00:00.000Z', visitors__revenue_rolling: null }, { visitors__created_at_day: '2017-01-10T00:00:00.000Z', visitors__revenue_rolling: null } ])); // FAILS - need to finish query to override ::timestamptz it.skip('rolling multiplied', () => runQueryTest({ measures: [ 'visitors.revenueRolling', 'visitor_checkins.visitor_checkins_count' ], timeDimensions: [{ dimension: 'visitors.created_at', granularity: 'day', dateRange: ['2017-01-01', '2017-01-10'] }], order: [{ id: 'visitors.created_at' }], timezone: 'America/Los_Angeles' }, [ { visitors__created_at_day: '2017-01-02T00:00:00.000Z', visitors__revenue_rolling: null, visitor_checkins__visitor_checkins_count: '3' }, { visitors__created_at_day: '2017-01-04T00:00:00.000Z', visitors__revenue_rolling: '100', 'visitor_checkins.visitor_checkins_count': '2' }, { visitors__created_at_day: '2017-01-05T00:00:00.000Z', visitors__revenue_rolling: '200', 'visitor_checkins.visitor_checkins_count': '1' }, { visitors__created_at_day: '2017-01-06T00:00:00.000Z', visitors__revenue_rolling: '500', 'visitor_checkins.visitor_checkins_count': '0' } ])); // FAILS - Syntax error: failed at position 107 it.skip('rolling month', () => runQueryTest({ measures: [ 'visitors.revenueRolling3day' ], timeDimensions: [{ dimension: 'visitors.created_at', granularity: 'week', dateRange: ['2017-01-09', '2017-01-10'] }], order: [{ id: 'visitors.created_at' }], timezone: 'America/Los_Angeles' }, [ { visitors__created_at_week: '2017-01-09T00:00:00.000Z', visitors__revenue_rolling3day: '900' } ])); // FAILS - Syntax error: failed at position 249 it.skip('rolling count', () => runQueryTest({ measures: [ 'visitors.countRolling' ], timeDimensions: [{ dimension: 'visitors.created_at', granularity: 'day', dateRange: ['2017-01-01', '2017-01-10'] }], order: [{ id: 'visitors.created_at' }], timezone: 'America/Los_Angeles' }, [ { visitors__created_at_day: '2017-01-01T00:00:00.000Z', visitors__count_rolling: null }, { visitors__created_at_day: '2017-01-02T00:00:00.000Z', visitors__count_rolling: null }, { visitors__created_at_day: '2017-01-03T00:00:00.000Z', visitors__count_rolling: '1' }, { visitors__created_at_day: '2017-01-04T00:00:00.000Z', visitors__count_rolling: '1' }, { visitors__created_at_day: '2017-01-05T00:00:00.000Z', visitors__count_rolling: '1' }, { visitors__created_at_day: '2017-01-06T00:00:00.000Z', visitors__count_rolling: '2' }, { visitors__created_at_day: '2017-01-07T00:00:00.000Z', visitors__count_rolling: '3' }, { visitors__created_at_day: '2017-01-08T00:00:00.000Z', visitors__count_rolling: '2' }, { visitors__created_at_day: '2017-01-09T00:00:00.000Z', visitors__count_rolling: null }, { visitors__created_at_day: '2017-01-10T00:00:00.000Z', visitors__count_rolling: null } ])); it('sql utils', () => runQueryTest({ measures: [ 'visitors.visitor_count' ], timeDimensions: [{ dimension: 'visitors.createdAtSqlUtils', granularity: 'day', dateRange: ['2017-01-01', '2017-01-10'] }], order: [{ id: 'visitors.createdAtSqlUtils' }], timezone: 'America/Los_Angeles' }, [ { visitors__created_at_sql_utils_day: '2017-01-02T00:00:00.000', visitors__visitor_count: '1' }, { visitors__created_at_sql_utils_day: '2017-01-04T00:00:00.000', visitors__visitor_count: '1' }, { visitors__created_at_sql_utils_day: '2017-01-05T00:00:00.000', visitors__visitor_count: '1' }, { visitors__created_at_sql_utils_day: '2017-01-06T00:00:00.000', visitors__visitor_count: '2' } ])); it('running total total', () => runQueryTest({ measures: [ 'visitors.revenueRunning' ], timeDimensions: [{ dimension: 'visitors.created_at', dateRange: ['2017-01-01', '2017-01-10'] }], order: [{ id: 'visitors.created_at' }], timezone: 'America/Los_Angeles' }, [ { visitors__revenue_running: '1500' } ])); // FAILS Unmatched parentheses it.skip('running total ratio', () => runQueryTest({ measures: [ 'visitors.runningRevenuePerCount' ], timeDimensions: [{ dimension: 'visitors.created_at', granularity: 'day', dateRange: ['2017-01-01', '2017-01-10'] }], order: [{ id: 'visitors.created_at' }], timezone: 'America/Los_Angeles' }, [ { visitors__created_at_day: '2017-01-01T00:00:00.000Z', visitors__running_revenue_per_count: null }, { visitors__created_at_day: '2017-01-02T00:00:00.000Z', visitors__running_revenue_per_count: '100' }, { visitors__created_at_day: '2017-01-03T00:00:00.000Z', visitors__running_revenue_per_count: '100' }, { visitors__created_at_day: '2017-01-04T00:00:00.000Z', visitors__running_revenue_per_count: '150' }, { visitors__created_at_day: '2017-01-05T00:00:00.000Z', visitors__running_revenue_per_count: '200' }, { visitors__created_at_day: '2017-01-06T00:00:00.000Z', visitors__running_revenue_per_count: '300' }, { visitors__created_at_day: '2017-01-07T00:00:00.000Z', visitors__running_revenue_per_count: '300' }, { visitors__created_at_day: '2017-01-08T00:00:00.000Z', visitors__running_revenue_per_count: '300' }, { visitors__created_at_day: '2017-01-09T00:00:00.000Z', visitors__running_revenue_per_count: '300' }, { visitors__created_at_day: '2017-01-10T00:00:00.000Z', visitors__running_revenue_per_count: '300' } ])); // FAILS ClickHouse supports multiple approximate aggregators: // uniq, uniqCombined, uniqHLL12, need to pick one to use and implement it in query it.skip('hll rolling', () => { const result = compiler.compile().then(() => { const query = new ClickHouseQuery({ joinGraph, cubeEvaluator, compiler }, { measures: [ 'visitors.countDistinctApproxRolling' ], timeDimensions: [{ dimension: 'visitors.created_at', granularity: 'day', dateRange: ['2017-01-01', '2017-01-10'] }], order: [{ id: 'visitors.created_at' }], timezone: 'America/Los_Angeles' }); logSqlAndParams(query); expect(query.buildSqlAndParams()[0]).toMatch(/HLL_COUNT\.MERGE/); expect(query.buildSqlAndParams()[0]).toMatch(/HLL_COUNT\.INIT/); }); return result; }); it('calculated join', () => { const result = compiler.compile().then(() => { const query = new ClickHouseQuery({ joinGraph, cubeEvaluator, compiler }, { measures: [ 'visitor_checkins.revenue_per_checkin' ], timeDimensions: [], timezone: 'America/Los_Angeles' }); logSqlAndParams(query); return dbRunner.testQuery(query.buildSqlAndParams()).then(res => { debugLog(JSON.stringify(res)); expect(res).toEqual( [{ visitor_checkins__revenue_per_checkin: '50' }] ); }); }); return result; }); it('filter join', () => { const result = compiler.compile().then(() => { const query = new ClickHouseQuery({ joinGraph, cubeEvaluator, compiler }, { measures: [ 'visitor_checkins.google_sourced_checkins' ], timeDimensions: [], timezone: 'America/Los_Angeles' }); logSqlAndParams(query); return dbRunner.testQuery(query.buildSqlAndParams()).then(res => { debugLog(JSON.stringify(res)); expect(res).toEqual( [{ visitor_checkins__google_sourced_checkins: '1' }] ); }); }); return result; }); it('filter join not multiplied', () => { const result = compiler.compile().then(() => { const query = new ClickHouseQuery({ joinGraph, cubeEvaluator, compiler }, { measures: [ 'visitor_checkins.google_sourced_checkins' ], timeDimensions: [], filters: [ { dimension: 'cards.id', operator: 'equals', values: [3] } // must be number ], timezone: 'America/Los_Angeles' }); logSqlAndParams(query); return dbRunner.testQuery(query.buildSqlAndParams()).then(res => { debugLog(JSON.stringify(res)); expect(res).toEqual( [{ visitor_checkins__google_sourced_checkins: '1' }] ); }); }); return result; }); it('having filter', () => compiler.compile().then(() => { const query = new ClickHouseQuery({ joinGraph, cubeEvaluator, compiler }, { measures: [ 'visitors.visitor_count' ], dimensions: [ 'visitors.source' ], timeDimensions: [], timezone: 'America/Los_Angeles', filters: [{ dimension: 'visitors.visitor_count', operator: 'gt', values: [1] // must be a number }], order: [{ id: 'visitors.source' }] }); logSqlAndParams(query); return dbRunner.testQuery(query.buildSqlAndParams()).then(res => { debugLog(JSON.stringify(res)); expect(res).toEqual( [{ visitors__source: 'some', visitors__visitor_count: '2' }, { visitors__source: null, visitors__visitor_count: '3' }] ); }); })); it('having filter without measure', () => compiler.compile().then(() => { const query = new ClickHouseQuery({ joinGraph, cubeEvaluator, compiler }, { measures: [], dimensions: [ 'visitors.source' ], timeDimensions: [], timezone: 'America/Los_Angeles', filters: [{ dimension: 'visitors.visitor_count', operator: 'gt', values: [1] // must be a number }], order: [{ id: 'visitors.source' }] }); logSqlAndParams(query); return dbRunner.testQuery(query.buildSqlAndParams()).then(res => { debugLog(JSON.stringify(res)); expect(res).toEqual( [ { visitors__source: 'some' }, { visitors__source: null }, ] ); }); })); // FAILS - doesnt support OR in JOIN it.skip('having filter without measure with join', () => compiler.compile().then(() => { const query = new ClickHouseQuery({ joinGraph, cubeEvaluator, compiler }, { measures: [], dimensions: [ 'visitors.source' ], timeDimensions: [], timezone: 'America/Los_Angeles', filters: [{ dimension: 'visitor_checkins.revenue_per_checkin', operator: 'gte', values: [60] // must be a number }], order: [{ id: 'visitors.source' }] }); logSqlAndParams(query); return dbRunner.testQuery(query.buildSqlAndParams()).then(res => { debugLog(JSON.stringify(res)); expect(res).toEqual( [{ visitors__source: 'some' }] ); }); })); it('having filter without measure single multiplied', () => compiler.compile().then(() => { const query = new ClickHouseQuery({ joinGraph, cubeEvaluator, compiler }, { measures: [], dimensions: [ 'visitors.source' ], timeDimensions: [], timezone: 'America/Los_Angeles', filters: [{ dimension: 'visitors.visitor_revenue', operator: 'gte', values: [1] // must be a number }, { dimension: 'visitor_checkins.source', operator: 'equals', values: ['google'] }], order: [{ id: 'visitors.source' }] }); logSqlAndParams(query); return dbRunner.testQuery(query.buildSqlAndParams()).then(res => { debugLog(JSON.stringify(res)); expect(res).toEqual( [{ visitors__source: 'some' }] ); }); })); it('subquery', () => { const result = compiler.compile().then(() => { const query = new ClickHouseQuery({ joinGraph, cubeEvaluator, compiler }, { measures: [ 'visitors.visitor_count' ], dimensions: [ 'visitors.checkins' ], timeDimensions: [{ dimension: 'visitors.created_at', granularity: 'day', dateRange: ['2017-01-01', '2017-01-30'] }], timezone: 'America/Los_Angeles', filters: [], order: [{ id: 'visitors.checkins' }] }); logSqlAndParams(query); return dbRunner.testQuery(query.buildSqlAndParams()).then(res => { debugLog(JSON.stringify(res)); expect(res).toEqual( [{ visitors__checkins: '0', visitors__created_at_day: '2017-01-06T00:00:00.000', visitors__visitor_count: '2' }, { visitors__checkins: '1', visitors__created_at_day: '2017-01-05T00:00:00.000', visitors__visitor_count: '1' }, { visitors__checkins: '2', visitors__created_at_day: '2017-01-04T00:00:00.000', visitors__visitor_count: '1' }, { visitors__checkins: '3', visitors__created_at_day: '2017-01-02T00:00:00.000', visitors__visitor_count: '1' }] ); }); }); return result; }); // ClickHouse does NOT support correlated subqueries // the SQL will have to be re-written to use array functions // FAILS Error: Unknown identifier: visitors.created_at_date it.skip('average subquery', () => { const result = compiler.compile().then(() => { const query = new ClickHouseQuery({ joinGraph, cubeEvaluator, compiler }, { measures: [ 'visitors.averageCheckins' ], timeDimensions: [{ dimension: 'visitors.created_at', granularity: 'day', dateRange: ['2017-01-01', '2017-01-30'] }], timezone: 'America/Los_Angeles', filters: [{ dimension: 'visitor_checkins.source', operator: 'equals', values: ['google'] }], order: [{ id: 'visitors.averageCheckins' }] }); logSqlAndParams(query); return dbRunner.testQuery(query.buildSqlAndParams()).then(res => { debugLog(JSON.stringify(res)); expect(res).toEqual( [{ visitors__created_at_day: '2017-01-02T00:00:00.000Z', visitors__average_checkins: '6__0000000000000000' }] ); }); }); return result; }); it('subquery without measure', () => runQueryTest({ dimensions: [ 'visitors.subQueryFail' ], timeDimensions: [{ dimension: 'visitors.created_at', granularity: 'day', dateRange: ['2017-01-01', '2017-01-30'] }], timezone: 'America/Los_Angeles', order: [{ id: 'visitors.created_at' }] }, [ { visitors__min_visitor_checkin_date_day: '2017-01-02T00:00:00.000Z', visitors__visitor_count: '1' }, { visitors__min_visitor_checkin_date_day: '2017-01-04T00:00:00.000Z', visitors__visitor_count: '1' }, { visitors__min_visitor_checkin_date_day: '2017-01-05T00:00:00.000Z', visitors__visitor_count: '1' } ]).then(() => { throw new Error(); }).catch((error) => { expect(error).toBeInstanceOf(UserError); })); it('min date subquery', () => runQueryTest({ measures: [ 'visitors.visitor_count' ], timeDimensions: [{ dimension: 'visitors.minVisitorCheckinDate', granularity: 'day', dateRange: ['2017-01-01', '2017-01-30'] }], timezone: 'America/Los_Angeles', order: [{ id: 'visitors.minVisitorCheckinDate' }] }, [ { visitors__min_visitor_checkin_date_day: '2017-01-02T00:00:00.000', visitors__visitor_count: '1' }, { visitors__min_visitor_checkin_date_day: '2017-01-04T00:00:00.000', visitors__visitor_count: '1' }, { visitors__min_visitor_checkin_date_day: '2017-01-05T00:00:00.000', visitors__visitor_count: '1' } ])); it('min date subquery with error', () => runQueryTest({ measures: [ 'visitors.visitor_count' ], timeDimensions: [{ dimension: 'visitors.minVisitorCheckinDate1', granularity: 'day', dateRange: ['2017-01-01', '2017-01-30'] }], timezone: 'America/Los_Angeles', order: [{ id: 'visitors.minVisitorCheckinDate1' }] }, []).catch((error) => { expect(error).toBeInstanceOf(UserError); })); it('subquery dimension with join', () => runQueryTest({ measures: [ 'visitors.visitor_revenue' ], dimensions: ['visitor_checkins.cardsCount'], timezone: 'America/Los_Angeles', order: [{ id: 'visitor_checkins.cardsCount' }] }, [ { visitor_checkins__cards_count: '0', visitors__visitor_revenue: '300' }, { visitor_checkins__cards_count: '1', visitors__visitor_revenue: '100' }, { visitor_checkins__cards_count: null, visitors__visitor_revenue: null } ])); // TODO it.skip('join rollup pre-aggregation', () => compiler.compile().then(() => { const query = new ClickHouseQuery({ joinGraph, cubeEvaluator, compiler }, { measures: [ 'visitors.per_visitor_revenue' ], dimensions: ['visitor_checkins.source'], timeDimensions: [{ dimension: 'visitors.created_at', granularity: 'day', dateRange: ['2017-01-01', '2017-01-30'] }], timezone: 'America/Los_Angeles', order: [{ id: 'visitors.created_at' }], filters: [{ dimension: 'visitors.per_visitor_revenue', operator: 'gt', values: ['50'] }, { dimension: 'visitor_checkins.source', operator: 'equals', values: ['google'] }], preAggregationsSchema: '' }); logSqlAndParams(query); const preAggregationsDescription: any = query.preAggregations?.preAggregationsDescription()[0]; debugLog(preAggregationsDescription); return dbRunner.testQueries(preAggregationsDescription.invalidateKeyQueries.concat([ [preAggregationsDescription.loadSql[0].replace('CREATE TABLE', 'CREATE TEMP TABLE'), preAggregationsDescription.loadSql[1]], query.buildSqlAndParams() ])).then(res => { debugLog(JSON.stringify(res)); expect(res).toEqual( [ { visitor_checkins__source: 'google', visitors__created_at_day: '2017-01-02T00:00:00.000Z', visitors__per_visitor_revenue: '100' } ] ); }); })); // TODO it.skip('join rollup total pre-aggregation', () => compiler.compile().then(() => { const query = new ClickHouseQuery({ joinGraph, cubeEvaluator, compiler }, { measures: [ 'visitors.visitor_revenue' ], timeDimensions: [{ dimension: 'visitors.created_at', dateRange: ['2017-01-01', '2017-01-30'] }], timezone: 'America/Los_Angeles', order: [], filters: [{ dimension: 'visitor_checkins.source', operator: 'equals', values: ['google'] }], preAggregationsSchema: '' }); logSqlAndParams(query); const preAggregationsDescription: any = query.preAggregations?.preAggregationsDescription()[0]; debugLog(preAggregationsDescription); return dbRunner.testQueries(preAggregationsDescription.invalidateKeyQueries.concat([ [ preAggregationsDescription.loadSql[0].replace('CREATE TABLE', 'CREATE TEMP TABLE'), preAggregationsDescription.loadSql[1] ], query.buildSqlAndParams() ])).then(res => { debugLog(JSON.stringify(res)); expect(res).toEqual( [ { visitors__visitor_revenue: '100' } ] ); }); })); it('security context', () => compiler.compile().then(() => { const query = new ClickHouseQuery({ joinGraph, cubeEvaluator, compiler }, { measures: [ 'visitor_checkins.revenue_per_checkin' ], timeDimensions: [], timezone: 'America/Los_Angeles', contextSymbols: { securityContext: { source: 'some' } } }); logSqlAndParams(query); return dbRunner.testQuery(query.buildSqlAndParams()).then(res => { debugLog(JSON.stringify(res)); expect(res).toEqual( [{ visitor_checkins__revenue_per_checkin: '60' }] ); }); })); it('security context array', () => compiler.compile().then(() => { const query = new ClickHouseQuery({ joinGraph, cubeEvaluator, compiler }, { measures: [ 'visitor_checkins.revenue_per_checkin' ], timeDimensions: [], timezone: 'America/Los_Angeles', contextSymbols: { securityContext: { sourceArray: ['some', 'google'] } } }); logSqlAndParams(query); return dbRunner.testQuery(query.buildSqlAndParams()).then(res => { debugLog(JSON.stringify(res)); expect(res).toEqual( [{ visitor_checkins__revenue_per_checkin: '50' }] ); }); })); it('reference cube sql', () => runQueryTest({ measures: [ 'ReferenceVisitors.count' ], timezone: 'America/Los_Angeles', order: [], timeDimensions: [{ dimension: 'ReferenceVisitors.createdAt', dateRange: ['2017-01-01', '2017-01-30'] }], }, [{ reference_visitors__count: '1' }])); it('Filtered count without primaryKey', () => runQueryTest({ measures: [ 'ReferenceVisitors.googleSourcedCount' ], timezone: 'America/Los_Angeles', order: [], timeDimensions: [{ dimension: 'ReferenceVisitors.createdAt', dateRange: ['2016-12-01', '2017-03-30'] }], }, [{ reference_visitors__google_sourced_count: '1' }])); it('builds geo dimension', () => runQueryTest({ dimensions: [ 'visitors.location' ], timezone: 'America/Los_Angeles', order: [{ id: 'visitors.location' }], }, [ // in ClickHouse float to string omits any trailing zeros after the decimal point { visitors__location: '120.12,10.6' }, { visitors__location: '120.12,40.6' }, { visitors__location: '120.12,58.1' }, { visitors__location: '120.12,58.6' }, { visitors__location: '120.12,70.6' } ])); it('applies measure_filter type filter', () => runQueryTest({ dimensions: [ 'visitors.id' ], filters: [{ dimension: 'visitors.visitor_revenue', operator: 'measure_filter' }], timezone: 'America/Los_Angeles', order: [{ id: 'visitors.id' }], // was visitors.location which is odd since its not in the select list }, [ { visitors__id: '1' }, // all numbers are transformed to strings. ClickHouse returns large number types as strings so we normalise that to all numbers as strings { visitors__id: '2' } ])); it( 'contains filter', () => runQueryTest({ measures: [], dimensions: [ 'visitors.source' ], timeDimensions: [], timezone: 'America/Los_Angeles', filters: [{ dimension: 'visitor_checkins.source', operator: 'contains', values: ['goo'] }], order: [{ id: 'visitors.source' }] }, [ { visitors__source: 'some' } ]) ); it('year granularity', () => runQueryTest({ measures: [ 'visitors.visitor_count' ], timeDimensions: [{ dimension: 'visitors.created_at', granularity: 'year', dateRange: ['2016-01-09', '2017-01-10'] }], order: [{ id: 'visitors.created_at' }], timezone: 'America/Los_Angeles' }, [ { visitors__created_at_year: '2016-01-01T00:00:00.000', visitors__visitor_count: '1' }, { visitors__created_at_year: '2017-01-01T00:00:00.000', visitors__visitor_count: '5' } ])); });
the_stack
import { Idl } from "@project-serum/anchor" import { IdlField, IdlType } from "@project-serum/anchor/dist/cjs/idl" import camelcase from "camelcase" import { sha256 } from "js-sha256" import { snakeCase } from "snake-case" /** * * Makes the type checker error if this part of code is reachable (all cases aren't handled). * */ /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ export function unreachable(_: never) { return undefined } export function fieldsInterfaceName(typeName: string) { return `${typeName}Fields` } export function valueInterfaceName(typeName: string) { return `${typeName}Value` } export function kindInterfaceName(typeName: string) { return `${typeName}Kind` } export function jsonInterfaceName(typeName: string) { return `${typeName}JSON` } export function tsTypeFromIdl( idl: Idl, ty: IdlType, definedTypesPrefix = "types.", useFieldsInterfaceForStruct = true ): string { switch (ty) { case "bool": return "boolean" case "u8": case "i8": case "u16": case "i16": case "u32": case "i32": case "f32": return "number" case "u64": case "i64": return "BN" case "f64": return "number" case "u128": case "i128": return "BN" case "bytes": return "Array<number>" case "string": return "string" case "publicKey": return "PublicKey" default: if ("vec" in ty) { return `Array<${tsTypeFromIdl( idl, ty.vec, definedTypesPrefix, useFieldsInterfaceForStruct )}>` } if ("option" in ty) { return `${tsTypeFromIdl( idl, ty.option, definedTypesPrefix, useFieldsInterfaceForStruct )} | null` } if ("coption" in ty) { return `${tsTypeFromIdl( idl, ty.coption, definedTypesPrefix, useFieldsInterfaceForStruct )} | null` } if ("defined" in ty) { const filtered = idl.types?.filter((t) => t.name === ty.defined) ?? [] if (filtered.length !== 1) { throw new Error(`Defined type not found: ${JSON.stringify(ty)}`) } switch (filtered[0].type.kind) { case "struct": { const name = useFieldsInterfaceForStruct ? fieldsInterfaceName(ty.defined) : ty.defined return `${definedTypesPrefix}${name}` } case "enum": { const name = kindInterfaceName(ty.defined) return `${definedTypesPrefix}${name}` } } } if ("array" in ty) { return `Array<${tsTypeFromIdl( idl, ty.array[0], definedTypesPrefix, useFieldsInterfaceForStruct )}>` } } unreachable(ty) throw new Error("Unreachable.") } export function layoutForType( ty: IdlType, property?: string, definedTypesPrefix = "types." ): string { const q = (property?: string) => { if (property === undefined) { return "" } return `"${property}"` } switch (ty) { case "bool": return `borsh.bool(${q(property)})` case "u8": return `borsh.u8(${q(property)})` case "i8": return `borsh.i8(${q(property)})` case "u16": return `borsh.u16(${q(property)})` case "i16": return `borsh.i16(${q(property)})` case "u32": return `borsh.u32(${q(property)})` case "f32": return `borsh.f32(${q(property)})` case "i32": return `borsh.i32(${q(property)})` case "u64": return `borsh.u64(${q(property)})` case "i64": return `borsh.i64(${q(property)})` case "f64": return `borsh.f64(${q(property)})` case "u128": return `borsh.u128(${q(property)})` case "i128": return `borsh.i128(${q(property)})` case "bytes": return `borsh.vecU8(${q(property)})` case "string": return `borsh.str(${q(property)})` case "publicKey": return `borsh.publicKey(${q(property)})` default: if ("vec" in ty) { return `borsh.vec(${layoutForType(ty.vec)}, ${q(property)})` } if ("option" in ty) { return `borsh.option(${layoutForType(ty.option)}, ${q(property)})` } if ("coption" in ty) { throw new Error("coption layout support not implemented") // TODO add support } if ("defined" in ty) { return `${definedTypesPrefix}${ty.defined}.layout(${q(property)})` } if ("array" in ty) { const propTxt = (property && `, ${q(property)}`) || "" return `borsh.array(${layoutForType(ty.array[0])}, ${ ty.array[1] }${propTxt})` } } unreachable(ty) throw new Error("Unreachable.") } export function genIxIdentifier(ixName: string) { const namespace = "global" const name = snakeCase(ixName) const preimage = `${namespace}:${name}` return sha256.digest(preimage).slice(0, 8) } export function genAccDiscriminator(accName: string) { return sha256 .digest(`account:${camelcase(accName, { pascalCase: true })}`) .slice(0, 8) } export function fieldToEncodable( idl: Idl, ty: IdlField, valPrefix = "", definedTypesPrefix = "types." ): string { switch (ty.type) { case "bool": case "u8": case "i8": case "u16": case "i16": case "u32": case "i32": case "f32": case "u64": case "i64": case "f64": case "u128": case "i128": case "string": case "publicKey": return `${valPrefix}${ty.name}` case "bytes": return `Buffer.from(${valPrefix}${ty.name})` default: if ("vec" in ty.type) { const mapBody = fieldToEncodable( idl, { name: "item", type: ty.type.vec, }, "", definedTypesPrefix ) // skip mapping when not needed if (mapBody === "item") { return `${valPrefix}${ty.name}` } return `${valPrefix}${ty.name}.map((item) => ${mapBody})` } if ("option" in ty.type) { const encodable = fieldToEncodable( idl, { name: ty.name, type: ty.type.option }, valPrefix, definedTypesPrefix ) // skip coercion when not needed if (encodable === `${valPrefix}${ty.name}`) { return encodable } return `(${valPrefix}${ty.name} && ${encodable}) || null` } if ("coption" in ty.type) { throw new Error("coption layout support not implemented") // TODO add support } if ("defined" in ty.type) { const defined = ty.type.defined const filtered = idl.types?.filter((t) => t.name === defined) ?? [] if (filtered.length !== 1) { throw new Error(`Defined type not found: ${JSON.stringify(ty)}`) } switch (filtered[0].type.kind) { case "struct": { return `${definedTypesPrefix}${ty.type.defined}.toEncodable(${valPrefix}${ty.name})` } case "enum": { return `${valPrefix}${ty.name}.toEncodable()` } } } if ("array" in ty.type) { const mapBody = fieldToEncodable( idl, { name: "item", type: ty.type.array[0], }, "", definedTypesPrefix ) // skip mapping when not needed if (mapBody === "item") { return `${valPrefix}${ty.name}` } return `${valPrefix}${ty.name}.map((item) => ${mapBody})` } unreachable(ty.type) throw new Error("Unreachable.") } } export function fieldFromDecoded( idl: Idl, ty: IdlField, valPrefix = "", definedTypesPrefix = "types." ): string { switch (ty.type) { case "bool": case "u8": case "i8": case "u16": case "i16": case "u32": case "i32": case "f32": case "u64": case "i64": case "f64": case "u128": case "i128": case "string": case "publicKey": return `${valPrefix}${ty.name}` case "bytes": return `Array.from(${valPrefix}${ty.name})` default: if ("vec" in ty.type) { const mapBody = fieldFromDecoded( idl, { name: "item", type: ty.type.vec, }, "", definedTypesPrefix ) // skip mapping when not needed if (mapBody === "item") { return `${valPrefix}${ty.name}` } return `${valPrefix}${ty.name}.map((item) => ${mapBody})` } if ("option" in ty.type) { const decoded = fieldFromDecoded( idl, { name: ty.name, type: ty.type.option }, valPrefix ) // skip coercion when not needed if (decoded === `${valPrefix}${ty.name}`) { return decoded } return `(${valPrefix}${ty.name} && ${decoded}) || null` } if ("coption" in ty.type) { throw new Error("coption layout support not implemented") // TODO add support } if ("defined" in ty.type) { const defined = ty.type.defined const filtered = idl.types?.filter((t) => t.name === defined) ?? [] if (filtered.length !== 1) { throw new Error(`Defined type not found: ${JSON.stringify(ty)}`) } switch (filtered[0].type.kind) { case "struct": case "enum": return `${definedTypesPrefix}${ty.type.defined}.fromDecoded(${valPrefix}${ty.name})` default: { unreachable(filtered[0].type) throw new Error("Unreachable.") } } } if ("array" in ty.type) { const mapBody = fieldFromDecoded( idl, { name: "item", type: ty.type.array[0], }, "", definedTypesPrefix ) // skip mapping when not needed if (mapBody === "item") { return `${valPrefix}${ty.name}` } return `${valPrefix}${ty.name}.map((item) => ${mapBody})` } unreachable(ty.type) throw new Error("Unreachable.") } } export function structFieldInitializer( idl: Idl, field: IdlField, prefix = "fields." ) { switch (field.type) { case "bool": case "u8": case "i8": case "u16": case "i16": case "u32": case "i32": case "f32": case "u64": case "i64": case "f64": case "u128": case "i128": case "bytes": case "string": case "publicKey": return `${prefix}${field.name}` default: if ("defined" in field.type) { const defined = field.type.defined const filtered = idl.types?.filter((t) => t.name === defined) ?? [] if (filtered.length !== 1) { throw new Error(`Defined type not found: ${defined}`) } switch (filtered[0].type.kind) { case "struct": return `new types.${filtered[0].name}({ ...${prefix}${field.name} })` case "enum": filtered[0].type.kind return `${prefix}${field.name}` default: unreachable(filtered[0].type) return } } if ("option" in field.type) { const initializer = structFieldInitializer( idl, { name: field.name, type: field.type.option }, prefix ) // skip coercion when not needed if (initializer === `${prefix}${field.name}`) { return initializer } else { return `(${prefix}${field.name} && ${initializer}) || null` } } if ("coption" in field.type) { const initializer = structFieldInitializer( idl, { name: field.name, type: field.type.coption }, prefix ) // skip coercion when not needed if (initializer === `${prefix}${field.name}`) { return initializer } else { return `(${prefix}${field.name} && ${initializer}) || null` } } if ("array" in field.type) { const mapBody = `${structFieldInitializer( idl, { name: "item", type: field.type.array[0], }, "" )}` // skip mapping when not needed if (mapBody === "item") { return `${prefix}${field.name}` } return `${prefix}${field.name}.map((item) => ${mapBody})` } if ("vec" in field.type) { const mapBody = `${structFieldInitializer( idl, { name: "item", type: field.type.vec, }, "" )}` // skip mapping when not needed if (mapBody === "item") { return `${prefix}${field.name}` } return `${prefix}${field.name}.map((item) => ${mapBody})` } unreachable(field.type) } } export function fieldToJSON(idl: Idl, ty: IdlField, valPrefix = ""): string { switch (ty.type) { case "bool": case "u8": case "i8": case "u16": case "i16": case "u32": case "i32": case "f32": case "f64": case "string": return `${valPrefix}${ty.name}` case "u64": case "i64": case "u128": case "i128": case "publicKey": return `${valPrefix}${ty.name}.toString()` case "bytes": return `${valPrefix}${ty.name}` default: if ("vec" in ty.type) { const mapBody = fieldToJSON(idl, { name: "item", type: ty.type.vec, }) // skip mapping when not needed if (mapBody === "item") { return `${valPrefix}${ty.name}` } return `${valPrefix}${ty.name}.map((item) => ${mapBody})` } if ("array" in ty.type) { const mapBody = fieldToJSON(idl, { name: "item", type: ty.type.array[0], }) // skip mapping when not needed if (mapBody === "item") { return `${valPrefix}${ty.name}` } return `${valPrefix}${ty.name}.map((item) => ${mapBody})` } if ("option" in ty.type) { const value = fieldToJSON( idl, { name: ty.name, type: ty.type.option }, valPrefix ) // skip coercion when not needed if (value === `${valPrefix}${ty.name}`) { return value } return `(${valPrefix}${ty.name} && ${value}) || null` } if ("coption" in ty.type) { const value = fieldToJSON( idl, { name: ty.name, type: ty.type.coption }, valPrefix ) // skip coercion when not needed if (value === `${valPrefix}${ty.name}`) { return value } return `(${valPrefix}${ty.name} && ${value}) || null` } if ("defined" in ty.type) { const defined = ty.type.defined const filtered = idl.types?.filter((t) => t.name === defined) ?? [] if (filtered.length !== 1) { throw new Error(`Defined type not found: ${JSON.stringify(ty)}`) } switch (filtered[0].type.kind) { case "struct": case "enum": return `${valPrefix}${ty.name}.toJSON()` default: { unreachable(filtered[0].type) throw new Error("Unreachable.") } } } unreachable(ty.type) throw new Error("Unreachable.") } } export function idlTypeToJSONType( ty: IdlType, definedTypesPrefix = "types." ): string { switch (ty) { case "bool": return "boolean" case "u8": case "i8": case "u16": case "i16": case "u32": case "i32": case "f32": case "f64": return "number" case "string": case "u64": case "i64": case "u128": case "i128": case "publicKey": return "string" case "bytes": return "Array<number>" default: if ("vec" in ty) { const inner = idlTypeToJSONType(ty.vec, definedTypesPrefix) return `Array<${inner}>` } if ("array" in ty) { const inner = idlTypeToJSONType(ty.array[0], definedTypesPrefix) return `Array<${inner}>` } if ("option" in ty) { const inner = idlTypeToJSONType(ty.option, definedTypesPrefix) return `${inner} | null` } if ("coption" in ty) { const inner = idlTypeToJSONType(ty.coption, definedTypesPrefix) return `${inner} | null` } if ("defined" in ty) { return `${definedTypesPrefix}${jsonInterfaceName(ty.defined)}` } unreachable(ty) throw new Error("Unreachable.") } } export function fieldFromJSON( ty: IdlField, jsonParamName = "obj", definedTypesPrefix = "types." ): string { const paramPrefix = jsonParamName ? jsonParamName + "." : "" switch (ty.type) { case "bool": case "u8": case "i8": case "u16": case "i16": case "u32": case "i32": case "f32": case "f64": case "string": case "bytes": return `${paramPrefix}${ty.name}` case "u64": case "i64": case "u128": case "i128": return `new BN(${paramPrefix}${ty.name})` case "publicKey": return `new PublicKey(${paramPrefix}${ty.name})` default: if ("vec" in ty.type) { const mapBody = fieldFromJSON( { name: "item", type: ty.type.vec, }, "", definedTypesPrefix ) // skip mapping when not needed if (mapBody === "item") { return `${paramPrefix}${ty.name}` } return `${paramPrefix}${ty.name}.map((item) => ${mapBody})` } if ("array" in ty.type) { const mapBody = fieldFromJSON( { name: "item", type: ty.type.array[0], }, "", definedTypesPrefix ) // skip mapping when not needed if (mapBody === "item") { return `${paramPrefix}${ty.name}` } return `${paramPrefix}${ty.name}.map((item) => ${mapBody})` } if ("option" in ty.type) { const inner = fieldFromJSON( { name: ty.name, type: ty.type.option }, jsonParamName, definedTypesPrefix ) // skip coercion when not needed if (inner === `${paramPrefix}${ty.name}`) { return inner } return `(${paramPrefix}${ty.name} && ${inner}) || null` } if ("coption" in ty.type) { const inner = fieldFromJSON( { name: ty.name, type: ty.type.coption }, jsonParamName, definedTypesPrefix ) // skip coercion when not needed if (inner === `${paramPrefix}${ty.name}`) { return inner } return `(${paramPrefix}${ty.name} && ${inner}) || null` } if ("defined" in ty.type) { return `${definedTypesPrefix}${ty.type.defined}.fromJSON(${paramPrefix}${ty.name})` } unreachable(ty.type) throw new Error("Unreachable.") } }
the_stack
import { Body, C, fromBodyLegacy, IncomingResponseMessage, Logger, OutgoingPublishRequest, OutgoingRequestMessage, URI } from "../core"; import { Emitter, EmitterImpl } from "./emitter"; import { PublisherOptions } from "./publisher-options"; import { PublisherPublishOptions } from "./publisher-publish-options"; import { PublisherState } from "./publisher-state"; import { PublisherUnpublishOptions } from "./publisher-unpublish-options"; import { BodyAndContentType } from "./session-description-handler"; import { UserAgent } from "./user-agent"; /** * A publisher publishes a publication (outgoing PUBLISH). * @public */ export class Publisher { private event: string; private options: PublisherOptions; private target: URI; private pubRequestBody: string | undefined; private pubRequestExpires: number; private pubRequestEtag: string | undefined; private publishRefreshTimer: number | undefined; private disposed = false; private id: string; private logger: Logger; private request: OutgoingRequestMessage; private userAgent: UserAgent; /** The publication state. */ private _state: PublisherState = PublisherState.Initial; /** Emits when the registration state changes. */ private _stateEventEmitter: EmitterImpl<PublisherState>; /** * Constructs a new instance of the `Publisher` class. * * @param userAgent - User agent. See {@link UserAgent} for details. * @param targetURI - Request URI identifying the target of the message. * @param eventType - The event type identifying the published document. * @param options - Options bucket. See {@link PublisherOptions} for details. */ public constructor(userAgent: UserAgent, targetURI: URI, eventType: string, options: PublisherOptions = {}) { // state emitter this._stateEventEmitter = new EmitterImpl<PublisherState>(); this.userAgent = userAgent; options.extraHeaders = (options.extraHeaders || []).slice(); options.contentType = options.contentType || "text/plain"; if (typeof options.expires !== "number" || options.expires % 1 !== 0) { options.expires = 3600; } else { options.expires = Number(options.expires); } if (typeof options.unpublishOnClose !== "boolean") { options.unpublishOnClose = true; } this.target = targetURI; this.event = eventType; this.options = options; this.pubRequestExpires = options.expires; this.logger = userAgent.getLogger("sip.Publisher"); const params = options.params || {}; const fromURI = params.fromUri ? params.fromUri : userAgent.userAgentCore.configuration.aor; const toURI = params.toUri ? params.toUri : targetURI; let body: Body | undefined; if (options.body && options.contentType) { const contentDisposition = "render"; const contentType = options.contentType; const content = options.body; body = { contentDisposition, contentType, content }; } const extraHeaders = (options.extraHeaders || []).slice(); // Build the request this.request = userAgent.userAgentCore.makeOutgoingRequestMessage( C.PUBLISH, targetURI, fromURI, toURI, params, extraHeaders, body ); // Identifier this.id = this.target.toString() + ":" + this.event; // Add to the user agent's publisher collection. this.userAgent._publishers[this.id] = this; } /** * Destructor. */ public dispose(): Promise<void> { if (this.disposed) { return Promise.resolve(); } this.disposed = true; this.logger.log(`Publisher ${this.id} in state ${this.state} is being disposed`); // Remove from the user agent's publisher collection delete this.userAgent._publishers[this.id]; // Send unpublish, if requested if (this.options.unpublishOnClose && this.state === PublisherState.Published) { return this.unpublish(); } if (this.publishRefreshTimer) { clearTimeout(this.publishRefreshTimer); this.publishRefreshTimer = undefined; } this.pubRequestBody = undefined; this.pubRequestExpires = 0; this.pubRequestEtag = undefined; return Promise.resolve(); } /** The publication state. */ public get state(): PublisherState { return this._state; } /** Emits when the publisher state changes. */ public get stateChange(): Emitter<PublisherState> { return this._stateEventEmitter; } /** * Publish. * @param content - Body to publish */ // eslint-disable-next-line @typescript-eslint/no-unused-vars public publish(content: string, options: PublisherPublishOptions = {}): Promise<void> { // Clean up before the run if (this.publishRefreshTimer) { clearTimeout(this.publishRefreshTimer); this.publishRefreshTimer = undefined; } // is Initial or Modify request this.options.body = content; this.pubRequestBody = this.options.body; if (this.pubRequestExpires === 0) { // This is Initial request after unpublish if (this.options.expires === undefined) { throw new Error("Expires undefined."); } this.pubRequestExpires = this.options.expires; this.pubRequestEtag = undefined; } this.sendPublishRequest(); return Promise.resolve(); } /** * Unpublish. */ // eslint-disable-next-line @typescript-eslint/no-unused-vars public unpublish(options: PublisherUnpublishOptions = {}): Promise<void> { // Clean up before the run if (this.publishRefreshTimer) { clearTimeout(this.publishRefreshTimer); this.publishRefreshTimer = undefined; } this.pubRequestBody = undefined; this.pubRequestExpires = 0; if (this.pubRequestEtag !== undefined) { this.sendPublishRequest(); } return Promise.resolve(); } /** @internal */ protected receiveResponse(response: IncomingResponseMessage): void { const statusCode: number = response.statusCode || 0; switch (true) { case /^1[0-9]{2}$/.test(statusCode.toString()): break; case /^2[0-9]{2}$/.test(statusCode.toString()): // Set SIP-Etag if (response.hasHeader("SIP-ETag")) { this.pubRequestEtag = response.getHeader("SIP-ETag"); } else { this.logger.warn("SIP-ETag header missing in a 200-class response to PUBLISH"); } // Update Expire if (response.hasHeader("Expires")) { const expires = Number(response.getHeader("Expires")); if (typeof expires === "number" && expires >= 0 && expires <= this.pubRequestExpires) { this.pubRequestExpires = expires; } else { this.logger.warn("Bad Expires header in a 200-class response to PUBLISH"); } } else { this.logger.warn("Expires header missing in a 200-class response to PUBLISH"); } if (this.pubRequestExpires !== 0) { // Schedule refresh this.publishRefreshTimer = setTimeout(() => this.refreshRequest(), this.pubRequestExpires * 900); if (this._state !== PublisherState.Published) { this.stateTransition(PublisherState.Published); } } else { this.stateTransition(PublisherState.Unpublished); } break; case /^412$/.test(statusCode.toString()): // 412 code means no matching ETag - possibly the PUBLISH expired // Resubmit as new request, if the current request is not a "remove" if (this.pubRequestEtag !== undefined && this.pubRequestExpires !== 0) { this.logger.warn("412 response to PUBLISH, recovering"); this.pubRequestEtag = undefined; if (this.options.body === undefined) { throw new Error("Body undefined."); } this.publish(this.options.body); } else { this.logger.warn("412 response to PUBLISH, recovery failed"); this.pubRequestExpires = 0; this.stateTransition(PublisherState.Unpublished); this.stateTransition(PublisherState.Terminated); } break; case /^423$/.test(statusCode.toString()): // 423 code means we need to adjust the Expires interval up if (this.pubRequestExpires !== 0 && response.hasHeader("Min-Expires")) { const minExpires = Number(response.getHeader("Min-Expires")); if (typeof minExpires === "number" || minExpires > this.pubRequestExpires) { this.logger.warn("423 code in response to PUBLISH, adjusting the Expires value and trying to recover"); this.pubRequestExpires = minExpires; if (this.options.body === undefined) { throw new Error("Body undefined."); } this.publish(this.options.body); } else { this.logger.warn("Bad 423 response Min-Expires header received for PUBLISH"); this.pubRequestExpires = 0; this.stateTransition(PublisherState.Unpublished); this.stateTransition(PublisherState.Terminated); } } else { this.logger.warn("423 response to PUBLISH, recovery failed"); this.pubRequestExpires = 0; this.stateTransition(PublisherState.Unpublished); this.stateTransition(PublisherState.Terminated); } break; default: this.pubRequestExpires = 0; this.stateTransition(PublisherState.Unpublished); this.stateTransition(PublisherState.Terminated); break; } // Do the cleanup if (this.pubRequestExpires === 0) { if (this.publishRefreshTimer) { clearTimeout(this.publishRefreshTimer); this.publishRefreshTimer = undefined; } this.pubRequestBody = undefined; this.pubRequestEtag = undefined; } } /** @internal */ protected send(): OutgoingPublishRequest { return this.userAgent.userAgentCore.publish(this.request, { onAccept: (response): void => this.receiveResponse(response.message), onProgress: (response): void => this.receiveResponse(response.message), onRedirect: (response): void => this.receiveResponse(response.message), onReject: (response): void => this.receiveResponse(response.message), onTrying: (response): void => this.receiveResponse(response.message) }); } private refreshRequest(): void { // Clean up before the run if (this.publishRefreshTimer) { clearTimeout(this.publishRefreshTimer); this.publishRefreshTimer = undefined; } // This is Refresh request this.pubRequestBody = undefined; if (this.pubRequestEtag === undefined) { throw new Error("Etag undefined"); } if (this.pubRequestExpires === 0) { throw new Error("Expires zero"); } this.sendPublishRequest(); } private sendPublishRequest(): OutgoingPublishRequest { const reqOptions = { ...this.options }; reqOptions.extraHeaders = (this.options.extraHeaders || []).slice(); reqOptions.extraHeaders.push("Event: " + this.event); reqOptions.extraHeaders.push("Expires: " + this.pubRequestExpires); if (this.pubRequestEtag !== undefined) { reqOptions.extraHeaders.push("SIP-If-Match: " + this.pubRequestEtag); } const ruri = this.target; const params = this.options.params || {}; let bodyAndContentType: BodyAndContentType | undefined; if (this.pubRequestBody !== undefined) { if (this.options.contentType === undefined) { throw new Error("Content type undefined."); } bodyAndContentType = { body: this.pubRequestBody, contentType: this.options.contentType }; } let body: Body | undefined; if (bodyAndContentType) { body = fromBodyLegacy(bodyAndContentType); } this.request = this.userAgent.userAgentCore.makeOutgoingRequestMessage( C.PUBLISH, ruri, params.fromUri ? params.fromUri : this.userAgent.userAgentCore.configuration.aor, params.toUri ? params.toUri : this.target, params, reqOptions.extraHeaders, body ); return this.send(); } /** * Transition publication state. */ private stateTransition(newState: PublisherState): void { const invalidTransition = (): void => { throw new Error(`Invalid state transition from ${this._state} to ${newState}`); }; // Validate transition switch (this._state) { case PublisherState.Initial: if ( newState !== PublisherState.Published && newState !== PublisherState.Unpublished && newState !== PublisherState.Terminated ) { invalidTransition(); } break; case PublisherState.Published: if (newState !== PublisherState.Unpublished && newState !== PublisherState.Terminated) { invalidTransition(); } break; case PublisherState.Unpublished: if (newState !== PublisherState.Published && newState !== PublisherState.Terminated) { invalidTransition(); } break; case PublisherState.Terminated: invalidTransition(); break; default: throw new Error("Unrecognized state."); } // Transition this._state = newState; this.logger.log(`Publication transitioned to state ${this._state}`); this._stateEventEmitter.emit(this._state); // Dispose if (newState === PublisherState.Terminated) { this.dispose(); } } }
the_stack
interface ICDPOperationClassification { // Domain: Accessibility // Domain: Animation 'animation.animationcanceled': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!animation.animationcanceled.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'animation.animationcreated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!animation.animationcreated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'animation.animationstarted': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!animation.animationstarted.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Audits 'audits.issueadded': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!audits.issueadded.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: BackgroundService 'backgroundservice.recordingstatechanged': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!backgroundservice.recordingstatechanged.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'backgroundservice.backgroundserviceeventreceived': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!backgroundservice.backgroundserviceeventreceived.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Browser 'browser.downloadwillbegin': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!browser.downloadwillbegin.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'browser.downloadprogress': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!browser.downloadprogress.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: CacheStorage // Domain: Cast 'cast.sinksupdated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!cast.sinksupdated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'cast.issueupdated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!cast.issueupdated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Console 'console.messageadded': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!console.messageadded.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: CSS 'css.fontsupdated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!css.fontsupdated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'css.mediaqueryresultchanged': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!css.mediaqueryresultchanged.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'css.stylesheetadded': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!css.stylesheetadded.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'css.stylesheetchanged': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!css.stylesheetchanged.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'css.stylesheetremoved': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!css.stylesheetremoved.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Database 'database.adddatabase': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!database.adddatabase.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Debugger 'debugger.breakpointresolved': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!debugger.breakpointresolved.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'debugger.paused': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!debugger.paused.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'debugger.resumed': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!debugger.resumed.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'debugger.scriptfailedtoparse': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!debugger.scriptfailedtoparse.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'debugger.scriptparsed': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!debugger.scriptparsed.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: DeviceOrientation // Domain: DOM 'dom.attributemodified': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!dom.attributemodified.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'dom.attributeremoved': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!dom.attributeremoved.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'dom.characterdatamodified': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!dom.characterdatamodified.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'dom.childnodecountupdated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!dom.childnodecountupdated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'dom.childnodeinserted': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!dom.childnodeinserted.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'dom.childnoderemoved': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!dom.childnoderemoved.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'dom.distributednodesupdated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!dom.distributednodesupdated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'dom.documentupdated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!dom.documentupdated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'dom.inlinestyleinvalidated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!dom.inlinestyleinvalidated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'dom.pseudoelementadded': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!dom.pseudoelementadded.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'dom.pseudoelementremoved': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!dom.pseudoelementremoved.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'dom.setchildnodes': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!dom.setchildnodes.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'dom.shadowrootpopped': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!dom.shadowrootpopped.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'dom.shadowrootpushed': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!dom.shadowrootpushed.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: DOMDebugger // Domain: DOMSnapshot // Domain: DOMStorage 'domstorage.domstorageitemadded': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!domstorage.domstorageitemadded.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'domstorage.domstorageitemremoved': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!domstorage.domstorageitemremoved.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'domstorage.domstorageitemupdated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!domstorage.domstorageitemupdated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'domstorage.domstorageitemscleared': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!domstorage.domstorageitemscleared.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Emulation 'emulation.virtualtimebudgetexpired': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!emulation.virtualtimebudgetexpired.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Fetch 'fetch.requestpaused': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!fetch.requestpaused.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'fetch.authrequired': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!fetch.authrequired.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: HeadlessExperimental 'headlessexperimental.needsbeginframeschanged': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!headlessexperimental.needsbeginframeschanged.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: HeapProfiler 'heapprofiler.addheapsnapshotchunk': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!heapprofiler.addheapsnapshotchunk.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'heapprofiler.heapstatsupdate': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!heapprofiler.heapstatsupdate.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'heapprofiler.lastseenobjectid': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!heapprofiler.lastseenobjectid.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'heapprofiler.reportheapsnapshotprogress': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!heapprofiler.reportheapsnapshotprogress.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'heapprofiler.resetprofiles': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!heapprofiler.resetprofiles.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: IndexedDB // Domain: Input 'input.dragintercepted': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!input.dragintercepted.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Inspector 'inspector.detached': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!inspector.detached.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'inspector.targetcrashed': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!inspector.targetcrashed.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'inspector.targetreloadedaftercrash': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!inspector.targetreloadedaftercrash.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: IO // Domain: JsDebug // Domain: LayerTree 'layertree.layerpainted': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!layertree.layerpainted.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'layertree.layertreedidchange': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!layertree.layertreedidchange.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Log 'log.entryadded': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!log.entryadded.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Media 'media.playerpropertieschanged': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!media.playerpropertieschanged.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'media.playereventsadded': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!media.playereventsadded.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'media.playermessageslogged': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!media.playermessageslogged.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'media.playererrorsraised': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!media.playererrorsraised.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'media.playerscreated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!media.playerscreated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Memory // Domain: Network 'network.datareceived': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.datareceived.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.eventsourcemessagereceived': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.eventsourcemessagereceived.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.loadingfailed': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.loadingfailed.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.loadingfinished': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.loadingfinished.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.requestintercepted': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.requestintercepted.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.requestservedfromcache': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.requestservedfromcache.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.requestwillbesent': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.requestwillbesent.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.resourcechangedpriority': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.resourcechangedpriority.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.signedexchangereceived': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.signedexchangereceived.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.responsereceived': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.responsereceived.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.websocketclosed': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.websocketclosed.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.websocketcreated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.websocketcreated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.websocketframeerror': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.websocketframeerror.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.websocketframereceived': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.websocketframereceived.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.websocketframesent': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.websocketframesent.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.websockethandshakeresponsereceived': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.websockethandshakeresponsereceived.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.websocketwillsendhandshakerequest': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.websocketwillsendhandshakerequest.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.webtransportcreated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.webtransportcreated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.webtransportconnectionestablished': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.webtransportconnectionestablished.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.webtransportclosed': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.webtransportclosed.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.requestwillbesentextrainfo': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.requestwillbesentextrainfo.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.responsereceivedextrainfo': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.responsereceivedextrainfo.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.trusttokenoperationdone': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.trusttokenoperationdone.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.subresourcewebbundlemetadatareceived': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.subresourcewebbundlemetadatareceived.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.subresourcewebbundlemetadataerror': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.subresourcewebbundlemetadataerror.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.subresourcewebbundleinnerresponseparsed': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.subresourcewebbundleinnerresponseparsed.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.subresourcewebbundleinnerresponseerror': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.subresourcewebbundleinnerresponseerror.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.reportingapireportadded': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.reportingapireportadded.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'network.reportingapireportupdated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!network.reportingapireportupdated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: NodeRuntime 'noderuntime.waitingfordisconnect': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!noderuntime.waitingfordisconnect.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: NodeTracing 'nodetracing.datacollected': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!nodetracing.datacollected.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'nodetracing.tracingcomplete': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!nodetracing.tracingcomplete.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: NodeWorker 'nodeworker.attachedtoworker': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!nodeworker.attachedtoworker.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'nodeworker.detachedfromworker': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!nodeworker.detachedfromworker.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'nodeworker.receivedmessagefromworker': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!nodeworker.receivedmessagefromworker.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Overlay 'overlay.inspectnoderequested': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!overlay.inspectnoderequested.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'overlay.nodehighlightrequested': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!overlay.nodehighlightrequested.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'overlay.screenshotrequested': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!overlay.screenshotrequested.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'overlay.inspectmodecanceled': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!overlay.inspectmodecanceled.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Page 'page.domcontenteventfired': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.domcontenteventfired.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.filechooseropened': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.filechooseropened.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.frameattached': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.frameattached.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.frameclearedschedulednavigation': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.frameclearedschedulednavigation.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.framedetached': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.framedetached.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.framenavigated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.framenavigated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.documentopened': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.documentopened.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.frameresized': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.frameresized.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.framerequestednavigation': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.framerequestednavigation.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.frameschedulednavigation': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.frameschedulednavigation.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.framestartedloading': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.framestartedloading.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.framestoppedloading': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.framestoppedloading.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.downloadwillbegin': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.downloadwillbegin.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.downloadprogress': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.downloadprogress.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.interstitialhidden': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.interstitialhidden.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.interstitialshown': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.interstitialshown.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.javascriptdialogclosed': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.javascriptdialogclosed.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.javascriptdialogopening': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.javascriptdialogopening.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.lifecycleevent': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.lifecycleevent.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.backforwardcachenotused': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.backforwardcachenotused.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.loadeventfired': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.loadeventfired.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.navigatedwithindocument': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.navigatedwithindocument.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.screencastframe': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.screencastframe.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.screencastvisibilitychanged': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.screencastvisibilitychanged.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.windowopen': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.windowopen.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'page.compilationcacheproduced': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!page.compilationcacheproduced.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Performance 'performance.metrics': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!performance.metrics.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: PerformanceTimeline 'performancetimeline.timelineeventadded': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!performancetimeline.timelineeventadded.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Profiler 'profiler.consoleprofilefinished': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!profiler.consoleprofilefinished.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'profiler.consoleprofilestarted': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!profiler.consoleprofilestarted.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'profiler.precisecoveragedeltaupdate': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!profiler.precisecoveragedeltaupdate.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Runtime 'runtime.bindingcalled': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!runtime.bindingcalled.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'runtime.consoleapicalled': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!runtime.consoleapicalled.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'runtime.exceptionrevoked': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!runtime.exceptionrevoked.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'runtime.exceptionthrown': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!runtime.exceptionthrown.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'runtime.executioncontextcreated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!runtime.executioncontextcreated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'runtime.executioncontextdestroyed': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!runtime.executioncontextdestroyed.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'runtime.executioncontextscleared': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!runtime.executioncontextscleared.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'runtime.inspectrequested': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!runtime.inspectrequested.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Schema // Domain: Security 'security.certificateerror': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!security.certificateerror.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'security.visiblesecuritystatechanged': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!security.visiblesecuritystatechanged.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'security.securitystatechanged': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!security.securitystatechanged.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: ServiceWorker 'serviceworker.workererrorreported': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!serviceworker.workererrorreported.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'serviceworker.workerregistrationupdated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!serviceworker.workerregistrationupdated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'serviceworker.workerversionupdated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!serviceworker.workerversionupdated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Storage 'storage.cachestoragecontentupdated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!storage.cachestoragecontentupdated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'storage.cachestoragelistupdated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!storage.cachestoragelistupdated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'storage.indexeddbcontentupdated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!storage.indexeddbcontentupdated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'storage.indexeddblistupdated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!storage.indexeddblistupdated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: SystemInfo // Domain: Target 'target.attachedtotarget': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!target.attachedtotarget.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'target.detachedfromtarget': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!target.detachedfromtarget.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'target.receivedmessagefromtarget': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!target.receivedmessagefromtarget.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'target.targetcreated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!target.targetcreated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'target.targetdestroyed': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!target.targetdestroyed.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'target.targetcrashed': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!target.targetcrashed.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'target.targetinfochanged': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!target.targetinfochanged.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Tethering 'tethering.accepted': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!tethering.accepted.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: Tracing 'tracing.bufferusage': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!tracing.bufferusage.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'tracing.datacollected': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!tracing.datacollected.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'tracing.tracingcomplete': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!tracing.tracingcomplete.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: WebAudio 'webaudio.contextcreated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!webaudio.contextcreated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'webaudio.contextwillbedestroyed': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!webaudio.contextwillbedestroyed.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'webaudio.contextchanged': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!webaudio.contextchanged.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'webaudio.audiolistenercreated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!webaudio.audiolistenercreated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'webaudio.audiolistenerwillbedestroyed': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!webaudio.audiolistenerwillbedestroyed.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'webaudio.audionodecreated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!webaudio.audionodecreated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'webaudio.audionodewillbedestroyed': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!webaudio.audionodewillbedestroyed.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'webaudio.audioparamcreated': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!webaudio.audioparamcreated.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'webaudio.audioparamwillbedestroyed': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!webaudio.audioparamwillbedestroyed.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'webaudio.nodesconnected': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!webaudio.nodesconnected.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'webaudio.nodesdisconnected': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!webaudio.nodesdisconnected.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'webaudio.nodeparamconnected': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!webaudio.nodeparamconnected.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; 'webaudio.nodeparamdisconnected': { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' }; '!webaudio.nodeparamdisconnected.errors': { classification: 'CallstackOrException'; purpose: 'PerformanceAndHealth' }; // Domain: WebAuthn }
the_stack
import { expect, test } from '@jest/globals'; import 'reflect-metadata'; import { Plan, SimpleModel, StringCollectionWrapper, SubModel } from './entities'; import { getClassSchema, jsonSerializer, t } from '../index'; import { resolvePropertySchema } from '../src/jit'; test('resolvePropertySchema simple', () => { expect(resolvePropertySchema(getClassSchema(SimpleModel), 'id')!.type).toBe('uuid'); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'id')!.resolveClassType).toBeUndefined(); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'id')!.isArray).toBe(false); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'id')!.isArray).toBe(false); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'plan')!.type).toBe('enum'); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'plan')!.resolveClassType).toBe(Plan); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'plan')!.isArray).toBe(false); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'plan')!.isMap).toBe(false); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'children')!.isArray).toBe(true); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'children')!.isMap).toBe(false); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'children')!.getSubType().type).toBe('class'); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'children')!.getSubType().resolveClassType).toBe(SubModel); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap')!.isArray).toBe(false); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap')!.isMap).toBe(true); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap')!.getSubType().type).toBe('class'); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap')!.getSubType().resolveClassType).toBe(SubModel); }); test('resolvePropertySchema deep', () => { expect(resolvePropertySchema(getClassSchema(SimpleModel), 'children.0.label')!.type).toBe('string'); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'children.0.label')!.resolveClassType).toBeUndefined(); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'children.0.label')!.isArray).toBe(false); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'children.0.label')!.isMap).toBe(false); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap.foo.label')!.type).toBe('string'); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap.foo.label')!.resolveClassType).toBeUndefined(); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap.foo.label')!.isArray).toBe(false); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap.foo.label')!.isMap).toBe(false); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap.foo.queue.added')).not.toBeUndefined(); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap.foo.queue.added')!.type).toBe('date'); expect(() => resolvePropertySchema(getClassSchema(SimpleModel), '')).toThrow('Invalid path in class SimpleModel'); expect(() => resolvePropertySchema(getClassSchema(SimpleModel), 'unknown.unknown')).toThrow('Invalid path unknown.unknown in class SimpleModel'); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap')).not.toBeUndefined(); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'selfChild.childrenMap')).not.toBeUndefined(); expect(() => resolvePropertySchema(getClassSchema(SimpleModel), 'yesNo.unknown')).toThrow('Invalid path yesNo.unknown in class SimpleModel'); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'types.index')).not.toBeUndefined(); expect(() => resolvePropertySchema(getClassSchema(SimpleModel), 'selfChild.unknown')).toThrow('Property SimpleModel.unknown not found'); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap.foo')).not.toBeUndefined(); expect(() => resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap.foo.unknown')).toThrow('Property SubModel.unknown not found'); expect(() => resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap.foo.queue.unknown')).toThrow('Property JobTaskQueue.unknown not found'); expect(() => resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap.foo.unknown')).toThrow('Property SubModel.unknown not found'); expect(() => resolvePropertySchema(getClassSchema(SimpleModel), 'child.unknown')).toThrow('Property SubModel.unknown not found'); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap.foo')!.type).toBe('class'); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap.foo')!.resolveClassType).toBe(SubModel); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap.foo')!.isArray).toBe(false); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenMap.foo')!.isMap).toBe(false); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenCollection.0')).not.toBeUndefined(); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenCollection.0')!.type).toBe('class'); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenCollection.0')!.resolveClassType).toBe(SubModel); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenCollection.0')!.isArray).toBe(false); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'childrenCollection.0')!.isMap).toBe(false); }); test('resolvePropertySchema decorator string', () => { expect(resolvePropertySchema(getClassSchema(SimpleModel), 'stringChildrenCollection')).toMatchObject({ type: 'class', resolveClassType: StringCollectionWrapper }); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'stringChildrenCollection')!.type).toBe('class'); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'stringChildrenCollection')!.resolveClassType).toBe(StringCollectionWrapper); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'stringChildrenCollection')!.isArray).toBe(false); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'stringChildrenCollection')!.isMap).toBe(false); }); test('resolvePropertySchema deep decorator string', () => { expect(resolvePropertySchema(getClassSchema(SimpleModel), 'stringChildrenCollection.0')!.type).toBe('string'); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'stringChildrenCollection.0')!.resolveClassType).toBeUndefined(); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'stringChildrenCollection.0')!.isArray).toBe(false); expect(resolvePropertySchema(getClassSchema(SimpleModel), 'stringChildrenCollection.0')!.isMap).toBe(false); }); test('plain-to test simple model', () => { const instance = jsonSerializer.for(SimpleModel).deserialize({ //todo, this should throw an error id: '21313', name: 'Hi' }); expect(instance.id).toBe('21313'); expect(instance.name).toBe('Hi'); }); test('partial', () => { const instance = jsonSerializer.for(SimpleModel).partialDeserialize({ name: 'Hi', children: [ { label: 'Foo' } ] }); expect(instance).not.toBeInstanceOf(SimpleModel); expect((instance as any)['id']).toBeUndefined(); expect((instance as any)['type']).toBeUndefined(); expect(instance.name).toBe('Hi'); expect(instance.children[0]).toBeInstanceOf(SubModel); expect(instance.children[0].label).toBe('Foo'); }); test('partial 3', () => { const i2 = jsonSerializer.for(SimpleModel).partialDeserialize({ 'children': [{ 'label': 3 }] }); expect(i2['children'][0]).toBeInstanceOf(SubModel); expect(i2['children'][0].label).toBe('3'); }); test('partial 6', () => { const i = jsonSerializer.for(SimpleModel).partialDeserialize({ 'types': [6, 7] }); expect(i['types']).toEqual(['6', '7']); }); test('test enum string', () => { enum MyEnum { waiting = 'waiting', downloading = 'downloading', extracting = 'extracting', verifying = 'verifying', done = 'done', } class Model { @t.enum(MyEnum) enum: MyEnum = MyEnum.waiting; } expect(jsonSerializer.for(Model).deserialize({ enum: MyEnum.waiting }).enum).toBe(MyEnum.waiting); expect(jsonSerializer.for(Model).deserialize({ enum: MyEnum.downloading }).enum).toBe(MyEnum.downloading); expect(jsonSerializer.for(Model).deserialize({ enum: 'waiting' }).enum).toBe(MyEnum.waiting); expect(jsonSerializer.for(Model).deserialize({ enum: 'extracting' }).enum).toBe(MyEnum.extracting); expect(jsonSerializer.for(Model).deserialize({ enum: 'verifying' }).enum).toBe(MyEnum.verifying); }); test('test enum labels', () => { enum MyEnum { first, second, third, } class Model { @t.enum(MyEnum) enum: MyEnum = MyEnum.third; } expect(jsonSerializer.for(Model).deserialize({ enum: MyEnum.first }).enum).toBe(MyEnum.first); expect(jsonSerializer.for(Model).deserialize({ enum: MyEnum.second }).enum).toBe(MyEnum.second); expect(jsonSerializer.for(Model).deserialize({ enum: 0 }).enum).toBe(MyEnum.first); expect(jsonSerializer.for(Model).deserialize({ enum: 1 }).enum).toBe(MyEnum.second); expect(jsonSerializer.for(Model).deserialize({ enum: 2 }).enum).toBe(MyEnum.third); expect(() => { expect(jsonSerializer.for(Model).deserialize({ enum: 'first' }).enum).toBe(MyEnum.first); }).toThrow('Invalid ENUM given in property enum: first, valid: 0,1,2'); class ModelWithLabels { @t.enum(MyEnum, true) enum: MyEnum = MyEnum.third; } expect(jsonSerializer.for(ModelWithLabels).deserialize({ enum: MyEnum.first }).enum).toBe(MyEnum.first); expect(jsonSerializer.for(ModelWithLabels).deserialize({ enum: MyEnum.second }).enum).toBe(MyEnum.second); expect(jsonSerializer.for(ModelWithLabels).deserialize({ enum: 0 }).enum).toBe(MyEnum.first); expect(jsonSerializer.for(ModelWithLabels).deserialize({ enum: 1 }).enum).toBe(MyEnum.second); expect(jsonSerializer.for(ModelWithLabels).deserialize({ enum: 2 }).enum).toBe(MyEnum.third); expect(jsonSerializer.for(ModelWithLabels).deserialize({ enum: 'first' }).enum).toBe(MyEnum.first); expect(jsonSerializer.for(ModelWithLabels).deserialize({ enum: 'second' }).enum).toBe(MyEnum.second); expect(jsonSerializer.for(ModelWithLabels).deserialize({ enum: 'third' }).enum).toBe(MyEnum.third); expect(() => { expect(jsonSerializer.for(ModelWithLabels).deserialize({ enum: 'Hi' }).enum).toBe(MyEnum.first); }).toThrow('Invalid ENUM given in property enum: Hi, valid: 0,1,2,first,second,third'); }); test('partial edge cases', () => { class Config { } class User { @t.required name!: string; @t.array(String).required tags!: string[]; @t.required config!: Config; @t.type(() => User).optional.parentReference parent?: User; } // { // const u = jsonSerializer.for(User).deserialize({ // name: 'peter', // tags: {}, // parent: {name: 'Marie'} // }); // // expect(u.name).toBe('peter'); // expect(u.tags).toEqual(undefined); // expect(u.parent).toBeUndefined(); // } // // { // const user = new User(); // user.name = null as any; // user.tags = {} as any; // user.parent = {} as any; // // const u = jsonSerializer.for(User).serialize(user); // // expect(u.name).toBe(null); // //we dont transform when coming from class. We trust TS system, if the user overwrites, its his fault. // expect(u.tags).toEqual({}); // expect(u.parent).toBeUndefined(); // } { const m = jsonSerializer.for(User).partialSerialize({ name: undefined, picture: null, tags: {} as any }); expect(m.name).toBe(null); //serialize converts undefined to null, since there's no such thing as undefined in JSON expect(m['picture']).toBe(undefined); expect(m.tags).toEqual([]); } const m = jsonSerializer.for(User).partialDeserialize({ name: undefined, picture: null, parent: new User(), tags: {} as any }); { const user = new User(); user.config = {} as any; const m = jsonSerializer.for(User).serialize(user); expect(user.config).toEqual({}); } });
the_stack
import { AllStarToken, CollectionToken, EmptyToken, GroupToken, ParameterToken, SeparatorToken, StringToken, TableStarToken, Token, createQueryState, } from './tokens'; import { Any, AnyNumber, Int4, Int8, Text, ToPostgresDataType } from './data-types'; import { AnyExpression, DefaultExpression, Expression, InternalDefaultExpression, InternalExpression, RawExpression, } from './expression'; import { AnyTable, Table } from './TableType'; import type { Column, ColumnSet } from './column'; import { DbConfig, DefaultDbConfig, GetResultType } from './config'; import { Err, GetDataType } from './types'; import { Query } from './query'; interface Tokenable { toTokens(): Token[]; } const isTokenable = (value: any): value is Tokenable => value && typeof value === 'object' && 'toTokens' in value; export class Star { private _starBrand: any; constructor(private readonly table?: AnyTable) {} toTokens() { if (this.table) { return [new TableStarToken(this.table)]; } return [new AllStarToken()]; } getName() { return `*`; } } export const now = <Config extends DbConfig = DefaultDbConfig>(): Expression< Config, Date, true, 'now' > => new InternalExpression([new StringToken(`NOW()`)], 'now') as any; export function raw< DataType, IsNotNull extends boolean = false, Name extends string = '?column?', Config extends DbConfig = DefaultDbConfig, >( strings: TemplateStringsArray, ...parameters: any[] ): Expression<Config, DataType, IsNotNull, Name> { const tokens = strings.flatMap((string, index) => { if (index === strings.length - 1) { return [new StringToken(string)]; } const parameter = parameters[index]; return [new StringToken(string), new ParameterToken(parameter)]; }); return new InternalExpression(tokens, '' as any) as any; } export const count = <Config extends DbConfig = DefaultDbConfig>( expression?: AnyExpression, ): Expression<Config, Int8, true, 'count'> => { if (!expression) { return new InternalExpression([new StringToken(`COUNT(*)`)], 'count'); } const tokens = expression.toTokens(); return new InternalExpression([new StringToken(`COUNT`), new GroupToken(tokens)], 'count'); }; export function star(): Star; export function star<T extends AnyTable>( table: T, ): T extends Table<any, any, infer Columns> ? ColumnSet<Columns> : never; export function star(table?: AnyTable) { if (table) { return new Star(table) as any; } return new Star(); } export const stringAgg = <Config extends DbConfig>( expression: Expression<Config, Text, boolean, any>, delimiter: string, ...orderBy: AnyExpression[] ): Expression<Config, Text, false, 'stringAgg'> => { return new InternalExpression( [ new StringToken(`string_agg`), new GroupToken([ new SeparatorToken(',', [ new CollectionToken(expression.toTokens(false)), new CollectionToken([ new ParameterToken(delimiter), orderBy ? new CollectionToken([ new StringToken(`ORDER BY`), new SeparatorToken( `,`, orderBy.map((expression) => new CollectionToken(expression.toTokens())), ), ]) : new EmptyToken(), ]), ]), ]), ], 'stringAgg', ); }; export const bitAnd = <Config extends DbConfig, T extends AnyNumber>( expression: Expression<Config, T, boolean, any>, ): Expression<Config, T, false, 'bitAnd'> => new InternalExpression( [new StringToken(`bit_and`), new GroupToken(expression.toTokens(false))], 'bitAnd', ) as any; export const bitOr = <Config extends DbConfig, T extends AnyNumber>( expression: Expression<Config, T, boolean, any>, ): Expression<Config, T, false, 'bitOr'> => new InternalExpression<Config, T, false, 'bitOr'>( [new StringToken(`bit_or`), new GroupToken(expression.toTokens(false))], 'bitOr', ) as any; export const boolAnd = <Config extends DbConfig>( expression: Expression<Config, boolean, boolean, any>, ): Expression<Config, number, false, 'boolAnd'> => new InternalExpression<Config, number, false, 'boolAnd'>( [new StringToken(`bool_and`), new GroupToken(expression.toTokens(false))], 'boolAnd', ); export const boolOr = <Config extends DbConfig>( expression: Expression<Config, boolean, boolean, any>, ): Expression<Config, number, false, 'boolOr'> => new InternalExpression<Config, number, false, 'boolOr'>( [new StringToken(`bool_or`), new GroupToken(expression.toTokens(false))], 'boolOr', ); export const every = <Config extends DbConfig>( expression: Expression<Config, boolean, boolean, any>, ): Expression<Config, number, false, 'every'> => new InternalExpression<Config, number, false, 'every'>( [new StringToken(`every`), new GroupToken(expression.toTokens(false))], 'every', ); export const arrayAgg = <Config extends DbConfig, DataType>( expression: Expression<Config, DataType, boolean, any>, ): Expression<Config, GetResultType<Config, DataType>[], false, 'arrayAgg'> => new InternalExpression( [new StringToken(`array_agg`), new GroupToken(expression.toTokens(false))], 'arrayAgg', ) as any; export const min = <Config extends DbConfig, DataType>( expression: Expression<Config, DataType, boolean, any>, ): Expression<Config, DataType, false, 'min'> => new InternalExpression<Config, DataType, false, 'min'>( [new StringToken(`MIN`), new GroupToken(expression.toTokens())], 'min', ) as any; export const max = <Config extends DbConfig, DataType>( expression: Expression<Config, DataType, boolean, any>, ): Expression<Config, DataType, false, 'max'> => new InternalExpression( [new StringToken(`MAX`), new GroupToken(expression.toTokens())], 'max', ) as any; export const avg = <Config extends DbConfig, T extends AnyNumber>( expression: Expression<Config, T, boolean, any>, ): Expression<Config, T, false, 'avg'> => new InternalExpression( [new StringToken(`AVG`), new GroupToken(expression.toTokens())], 'avg', ) as any; // Selecting the sum of an int4 results in a int8, but selecting the sum of any other data type // doesn't seem to change the return type at all. export const sum = <Config extends DbConfig, T>( expression: Expression<Config, T, boolean, any> | Column<Config, any, any, T, any, any, any>, ): Expression<Config, T extends Int4 ? Int8 : T, false, 'sum'> => new InternalExpression( [new StringToken(`SUM`), new GroupToken(expression.toTokens())], 'sum', ) as any; export const xmlagg = <Config extends DbConfig, DataType>( expression: Expression<Config, DataType, boolean, any>, ): Expression<Config, number, false, 'xmlagg'> => new InternalExpression<Config, number, false, 'xmlagg'>( [new StringToken(`xmlagg`), new GroupToken(expression.toTokens())], 'xmlagg', ); export const not = <Config extends DbConfig>( expression: Expression<Config, boolean, boolean, string>, ): DefaultExpression<Config, boolean> => new InternalDefaultExpression([ new StringToken(`NOT`), new GroupToken(expression.toTokens()), ]) as any; export const and = <Config extends DbConfig>( expression: Expression<Config, boolean, boolean, string>, ): DefaultExpression<Config, boolean> => new InternalDefaultExpression([ new StringToken(`AND`), new GroupToken(expression.toTokens()), ]) as any; export const or = <Config extends DbConfig>( expression: Expression<Config, boolean, boolean, string>, ): DefaultExpression<Config, boolean> => new InternalDefaultExpression([ new StringToken(`OR`), new GroupToken(expression.toTokens()), ]) as any; export const group = <Config extends DbConfig>( expression: Expression<Config, boolean, boolean, string>, ): DefaultExpression<Config, boolean> => new InternalDefaultExpression([new GroupToken(expression.toTokens())]) as any; export const any = <Config extends DbConfig, T>( array: T[], ): RawExpression<Config, T, true, '?column?'> => new InternalDefaultExpression([ new StringToken(`ANY`), new GroupToken([new ParameterToken(array)]), ]) as any; export const exists = <Config extends DbConfig>( expression: AnyExpression | Query<any>, ): DefaultExpression<Config, boolean> => new InternalDefaultExpression([new StringToken(`EXISTS`), new GroupToken(expression.toTokens())]); export const andNotExists = <Config extends DbConfig>( expression: Expression<Config, any, any, any> | Query<any>, ): DefaultExpression<Config, boolean> => new InternalDefaultExpression([ new StringToken(`AND NOT EXISTS`), new GroupToken(expression.toTokens()), ]); export const andExists = <Config extends DbConfig>( expression: Expression<Config, any, any, any> | Query<any>, ): DefaultExpression<Config, boolean> => new InternalDefaultExpression([ new StringToken(`AND EXISTS`), new GroupToken(expression.toTokens()), ]); export const notExists = <Config extends DbConfig>( expression: Expression<Config, any, any, any> | Query<any>, ): DefaultExpression<Config, boolean> => new InternalDefaultExpression([ new StringToken(`NOT EXISTS`), new GroupToken(expression.toTokens()), ]); export function nullIf<Config extends DbConfig, DataType>( value1: Expression<Config, DataType, any, any>, value2: Expression<any, DataType, any, any> | GetResultType<Config, DataType>, ): Expression<Config, DataType, false, 'nullif'> { return new InternalExpression( [ new StringToken(`nullif`), new GroupToken([ new SeparatorToken(',', [ new CollectionToken(value1.toTokens()), isTokenable(value2) ? new CollectionToken(value2.toTokens()) : new ParameterToken(value2), ]), ]), ], 'nullif', ) as any; } export function greatest<Config extends DbConfig, DataType>( first: Expression<Config, DataType, any, any>, ...rest: (Expression<any, DataType, any, any> | GetResultType<Config, DataType>)[] ): Expression<Config, DataType, false, 'greatest'> { return new InternalExpression( [ new StringToken(`greatest`), new GroupToken([ new SeparatorToken( ',', [first, ...rest].map((val) => isTokenable(val) ? new CollectionToken(val.toTokens()) : new ParameterToken(val), ), ), ]), ], 'greatest', ) as any; } export function least<Config extends DbConfig, DataType>( first: Expression<Config, DataType, any, any>, ...rest: (Expression<any, DataType, any, any> | GetResultType<Config, DataType>)[] ): Expression<Config, DataType, false, 'least'> { return new InternalExpression( [ new StringToken(`least`), new GroupToken([ new SeparatorToken( ',', [first, ...rest].map((val) => isTokenable(val) ? new CollectionToken(val.toTokens()) : new ParameterToken(val), ), ), ]), ], 'least', ) as any; } // At some point this needs to be extended, because only columns and literal types are supported. // The type system kept complaining when using Expression<..> directly and passing in columns. export function coalesce<C extends Column<any, any, any, any, any, any, any>>( expression: C, expression2: C, ): Expression< any, C extends Column<any, any, any, infer DataType, any, any, any> ? DataType : Err<'could not find column data type'>, C extends Column<any, any, any, any, infer IsNotNull, any, any> ? IsNotNull & true : false, 'coalesce' >; export function coalesce< C extends Column<any, any, any, any, any, any, any>, D extends C extends Column<infer Config, any, any, infer DataType, any, any, any> ? GetResultType<Config, DataType> | GetResultType<Config, 'Null'> : Err<'could not find column data type'>, >( expression: C, expression2: D, ): Expression< any, C extends Column<any, any, any, infer DataType, any, any, any> ? DataType : Err<'could not find column data type'>, C extends Column<infer Config, any, any, any, any, any, any> ? [D] extends [GetResultType<Config, 'Null'>] ? [GetResultType<Config, 'Null'>] extends [D] ? false : true : true : false, 'coalesce' >; export function coalesce(...expressions: any[]) { return new InternalExpression( [ new StringToken(`coalesce`), new GroupToken([ new SeparatorToken( ',', expressions.map((expression) => isTokenable(expression) ? new CollectionToken(expression.toTokens()) : new ParameterToken(expression), ), ), ]), ], 'coalesce', ) as any; } export const cast = < Config extends DbConfig, T extends Any, IsNotNull extends boolean, Name extends string, >( expression: Expression<Config, any, IsNotNull, Name>, dataType: ToPostgresDataType<T>, ): Expression<Config, T, IsNotNull, Name> => new InternalExpression( [ new StringToken(`CAST`), new GroupToken([ ...expression.toTokens(), new StringToken(`AS`), new ParameterToken(dataType), ]), ], expression.getName(), ) as any; export function toSql(query: Query<any> | { toTokens: () => Token[] }) { const queryState = createQueryState(query.toTokens()); return { text: queryState.text.join(` `), parameters: queryState.parameters, }; }
the_stack
import { Invitation, Inviter, SessionDescriptionHandler, SessionState } from "../../../src/api"; import { Logger, OutgoingRequestDelegate, SessionState as SessionDialogState, SignalingState, Timers, URI } from "../../../src/core"; import { EmitterSpy, makeEmitterSpy } from "../../support/api/emitter-spy"; import { TransportFake } from "../../support/api/transport-fake"; import { connectUserFake, makeUserFake, UserFake } from "../../support/api/user-fake"; import { soon } from "../../support/api/utils"; const SIP_ACK = [jasmine.stringMatching(/^ACK/)]; const SIP_BYE = [jasmine.stringMatching(/^BYE/)]; const SIP_CANCEL = [jasmine.stringMatching(/^CANCEL/)]; const SIP_INVITE = [jasmine.stringMatching(/^INVITE/)]; const SIP_PRACK = [jasmine.stringMatching(/^PRACK/)]; const SIP_100 = [jasmine.stringMatching(/^SIP\/2.0 100/)]; const SIP_180 = [jasmine.stringMatching(/^SIP\/2.0 180/)]; const SIP_183 = [jasmine.stringMatching(/^SIP\/2.0 183/)]; const SIP_200 = [jasmine.stringMatching(/^SIP\/2.0 200/)]; const SIP_480 = [jasmine.stringMatching(/^SIP\/2.0 480/)]; const SIP_481 = [jasmine.stringMatching(/^SIP\/2.0 481/)]; const SIP_487 = [jasmine.stringMatching(/^SIP\/2.0 487/)]; function terminate(invitation: Invitation): Promise<void> { const session = invitation; switch (session.state) { case SessionState.Initial: case SessionState.Establishing: return session.reject(); case SessionState.Established: return session.bye().then(() => { return; }); case SessionState.Terminating: case SessionState.Terminated: default: return Promise.reject(); } } /** * Session Integration Tests */ describe("API Session", () => { let alice: UserFake; let bob: UserFake; let target: URI; let inviter: Inviter; let inviterStateSpy: EmitterSpy<SessionState>; let invitation: Invitation; let invitationStateSpy: EmitterSpy<SessionState>; const inviterRequestDelegateMock = jasmine.createSpyObj<Required<OutgoingRequestDelegate>>( "OutgoingRequestDelegate", ["onAccept", "onProgress", "onRedirect", "onReject", "onTrying"] ); function bobAccept(): void { beforeEach(async () => { resetSpies(); invitation.accept(); await bob.transport.waitReceived(); // ACK }); it("her ua should send ACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_ACK); }); it("her ua should receive 200", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_200); }); it("her request delegate should onAccept", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(1); expect(spy.onProgress).toHaveBeenCalledTimes(0); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(0); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); it("her session state should transition 'established'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Established]); }); it("his session state should transition 'establishing', 'established'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Established]); }); it("her dialog should be 'confirmed' and 'stable'", () => { const session = inviter.dialog; expect(session && session.sessionState).toBe(SessionDialogState.Confirmed); expect(session && session.signalingState).toBe(SignalingState.Stable); }); it("his dialog should be 'confirmed' and 'stable'", () => { const session = invitation.dialog; expect(session && session.sessionState).toBe(SessionDialogState.Confirmed); expect(session && session.signalingState).toBe(SignalingState.Stable); }); } function bobAccept2x(): void { let threw: boolean; beforeEach(async () => { threw = false; resetSpies(); invitation.accept(); invitation.accept().catch(() => { threw = true; }); await bob.transport.waitReceived(); // ACK }); it("her ua should send ACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_ACK); }); it("her ua should receive 200", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_200); }); it("her request delegate should onAccept", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(1); expect(spy.onProgress).toHaveBeenCalledTimes(0); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(0); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); it("her session state should transition 'established'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Established]); }); it("his session state should transition 'establishing', 'established'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Established]); }); it("her dialog should be 'confirmed' and 'stable'", () => { const session = inviter.dialog; expect(session && session.sessionState).toBe(SessionDialogState.Confirmed); expect(session && session.signalingState).toBe(SignalingState.Stable); }); it("his dialog should be 'confirmed' and 'stable'", () => { const session = invitation.dialog; expect(session && session.sessionState).toBe(SessionDialogState.Confirmed); expect(session && session.signalingState).toBe(SignalingState.Stable); }); it("her second accept() threw an error", () => { expect(threw).toBe(true); }); } function bobAcceptTerminate(dropAcks: boolean): void { // The caller's UA MAY send a BYE for either confirmed or early dialogs, // and the callee's UA MAY send a BYE on confirmed dialogs, but MUST NOT // send a BYE on early dialogs. However, the callee's UA MUST NOT send a // BYE on a confirmed dialog until it has received an ACK for its 2xx // response or until the server transaction times out. // https://tools.ietf.org/html/rfc3261#section-15 beforeEach(async () => { resetSpies(); if (dropAcks) { bob.transportReceiveSpy.and.returnValue(Promise.resolve()); // drop messages } invitation.accept(); await bob.transport.waitSent(); // wait till 2xx sent terminate(invitation); // must wait for ACK or timeout before sending BYE if (dropAcks) { await alice.transport.waitSent(); // wait for first ACK sent (it will not be received) await soon(Timers.TIMER_L - 2); // transaction timeout waiting for ACK await soon(1); // a tick to let the retranmissions get processed after the clock jump await soon(1); // and then send the BYE upon transaction timeout } else { await inviterStateSpy.wait(SessionState.Terminated); } }); if (dropAcks) { it("her ua should send ACK (11x), 200", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(12); expect(spy.calls.all()[0].args).toEqual(SIP_ACK); expect(spy.calls.all()[1].args).toEqual(SIP_ACK); // ACK retransmissions that get dropped expect(spy.calls.all()[2].args).toEqual(SIP_ACK); expect(spy.calls.all()[3].args).toEqual(SIP_ACK); expect(spy.calls.all()[4].args).toEqual(SIP_ACK); expect(spy.calls.all()[5].args).toEqual(SIP_ACK); expect(spy.calls.all()[6].args).toEqual(SIP_ACK); expect(spy.calls.all()[7].args).toEqual(SIP_ACK); expect(spy.calls.all()[8].args).toEqual(SIP_ACK); expect(spy.calls.all()[9].args).toEqual(SIP_ACK); expect(spy.calls.all()[10].args).toEqual(SIP_ACK); expect(spy.calls.all()[11].args).toEqual(SIP_200); }); it("her ua should receive 200 (11x), BYE", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(12); expect(spy.calls.all()[0].args).toEqual(SIP_200); expect(spy.calls.all()[1].args).toEqual(SIP_200); // 200 retransmissions expect(spy.calls.all()[2].args).toEqual(SIP_200); expect(spy.calls.all()[3].args).toEqual(SIP_200); expect(spy.calls.all()[4].args).toEqual(SIP_200); expect(spy.calls.all()[5].args).toEqual(SIP_200); expect(spy.calls.all()[6].args).toEqual(SIP_200); expect(spy.calls.all()[7].args).toEqual(SIP_200); expect(spy.calls.all()[8].args).toEqual(SIP_200); expect(spy.calls.all()[9].args).toEqual(SIP_200); expect(spy.calls.all()[10].args).toEqual(SIP_200); expect(spy.calls.all()[11].args).toEqual(SIP_BYE); }); } else { it("her ua should send ACK, 200", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_ACK); expect(spy.calls.argsFor(1)).toEqual(SIP_200); }); it("her ua should receive 200, BYE", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_200); expect(spy.calls.argsFor(1)).toEqual(SIP_BYE); }); it("her request delegate should onAccept", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(1); expect(spy.onProgress).toHaveBeenCalledTimes(0); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(0); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); } it("her session state should transition 'established', 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual([SessionState.Established]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Terminated]); }); it("his session state should transition 'establishing', 'established', 'terminating', 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(4); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Established]); expect(spy.calls.argsFor(2)).toEqual([SessionState.Terminating]); expect(spy.calls.argsFor(3)).toEqual([SessionState.Terminated]); }); } function bobProgress(): void { beforeEach(async () => { resetSpies(); return invitation.progress(); }); it("her ua should receive 180", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_180); }); it("her request delegate onProgress", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(0); expect(spy.onProgress).toHaveBeenCalledTimes(1); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(0); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); } function bobProgress183(): void { beforeEach(async () => { resetSpies(); return invitation.progress({ statusCode: 183 }); }); it("her ua should receive 183", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_183); }); it("her request delegate onProgress", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(0); expect(spy.onProgress).toHaveBeenCalledTimes(1); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(0); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); } function bobProgress2x(): void { beforeEach(async () => { resetSpies(); invitation.progress(); return invitation.progress(); }); it("her ua should receive 180, 180", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_180); expect(spy.calls.argsFor(1)).toEqual(SIP_180); }); it("her request delegate onProgress, onProgress", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(0); expect(spy.onProgress).toHaveBeenCalledTimes(2); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(0); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); } function bobProgressReliable(): void { beforeEach(async () => { resetSpies(); invitation.progress({ rel100: true }); await bob.transport.waitSent(); // 200 for PRACK await alice.transport.waitReceived(); // 200 for PRACK }); it("her ua should receive 183", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_183); expect(spy.calls.argsFor(1)).toEqual(SIP_200); // PRACK }); it("her ua should send PRACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_PRACK); }); it("her request delegate onProgress", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(0); expect(spy.onProgress).toHaveBeenCalledTimes(1); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(0); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); } function bobProgressReliable2x(): void { beforeEach(async () => { resetSpies(); invitation.progress({ rel100: true }); invitation.progress({ rel100: true }); // This one should be ignored as we are waiting on a PRACK. await bob.transport.waitSent(); // 200 for PRACK await alice.transport.waitReceived(); // 200 for PRACK }); it("her ua should receive 183", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_183); expect(spy.calls.argsFor(1)).toEqual(SIP_200); // PRACK }); it("her ua should send PRACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_PRACK); }); it("her request delegate onProgress", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(0); expect(spy.onProgress).toHaveBeenCalledTimes(1); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(0); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); } function bobReject(): void { beforeEach(async () => { resetSpies(); invitation.reject(); await inviterStateSpy.wait(SessionState.Terminated); }); it("her ua should send ACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_ACK); }); it("her ua should receive 480", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_480); }); it("her request delegate onReject", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(0); expect(spy.onProgress).toHaveBeenCalledTimes(0); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(1); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); it("her session state should transition 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); it("his session state should transition 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); } function bobReject2x(): void { let threw: boolean; beforeEach(async () => { threw = false; resetSpies(); invitation.reject(); invitation.reject().catch(() => { threw = true; }); await inviterStateSpy.wait(SessionState.Terminated); }); it("her ua should send ACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_ACK); }); it("her ua should receive 480", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_480); }); it("her request delegate onReject", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(0); expect(spy.onProgress).toHaveBeenCalledTimes(0); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(1); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); it("her session state should transition 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); it("his session state should transition 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); it("his second reject() threw an error", () => { expect(threw).toBe(true); }); } function bobTerminate(bye = true): void { beforeEach(async () => { resetSpies(); terminate(invitation); await inviterStateSpy.wait(SessionState.Terminated); }); if (bye) { it("her ua should send 200", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_200); }); it("her ua should receive BYE", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_BYE); }); it("her session state should transition 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); it("his session state should transition 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); } else { it("her ua should send ACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_ACK); }); it("her ua should receive 480", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_480); }); it("her request delegate onReject", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(0); expect(spy.onProgress).toHaveBeenCalledTimes(0); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(1); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); it("her session state should transition 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); it("his session state should transition 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); } } function bobTerminate2x(bye = true): void { let threw: boolean; beforeEach(async () => { threw = false; resetSpies(); terminate(invitation); terminate(invitation).catch(() => { threw = true; }); await inviterStateSpy.wait(SessionState.Terminated); }); if (bye) { it("her ua should send 200", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_200); }); it("her ua should receive BYE", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_BYE); }); it("her session state should transition 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); it("his session state should transition 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); it("her second terminate() threw an error", () => { expect(threw).toBe(true); }); } else { it("her ua should send ACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_ACK); }); it("her ua should receive 480", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_480); }); it("her request delegate onReject", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(0); expect(spy.onProgress).toHaveBeenCalledTimes(0); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(1); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); it("her session state should transition 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); it("his session state should transition 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); it("her second terminate() threw an error", () => { expect(threw).toBe(true); }); } } function inviteSuite(inviteWithoutSdp: boolean): void { it("her ua should send nothing", () => { expect(alice.transportSendSpy).not.toHaveBeenCalled(); }); it("her session state should not change", () => { expect(inviter.state).toBe(SessionState.Initial); expect(inviterStateSpy).not.toHaveBeenCalled(); }); describe("Alice invite(), cancel()", () => { beforeEach(async () => { resetSpies(); inviter.invite().catch(() => { return; }); inviter.cancel(); await soon(); await soon(); // need an extra promise resolution for tests to play out await soon(); // need an extra promise resolution for tests to play out }); if (inviteWithoutSdp) { it("her ua should send INVITE, CANCEL, ACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(3); expect(spy.calls.argsFor(0)).toEqual(SIP_INVITE); expect(spy.calls.argsFor(1)).toEqual(SIP_CANCEL); expect(spy.calls.argsFor(2)).toEqual(SIP_ACK); }); it("her ua should receive 100, 180, 200, 487", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(4); expect(spy.calls.argsFor(0)).toEqual(SIP_100); expect(spy.calls.argsFor(1)).toEqual(SIP_180); expect(spy.calls.argsFor(2)).toEqual(SIP_200); expect(spy.calls.argsFor(3)).toEqual(SIP_487); }); } else { it("her ua should send nothing", () => { expect(alice.transportSendSpy).not.toHaveBeenCalled(); }); } if (inviteWithoutSdp) { it("her session state should transition 'establishing', 'terminating', 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(3); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Terminating]); expect(spy.calls.argsFor(2)).toEqual([SessionState.Terminated]); }); } else { it("her session state should transition 'terminating', 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminating]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Terminated]); }); } }); describe("Alice invite(), send fails - Transport Error", () => { beforeEach(async () => { if (!(alice.userAgent.transport instanceof TransportFake)) { throw new Error("Transport not TransportFake"); } alice.userAgent.transport.setConnected(false); resetSpies(); return inviter.invite({ requestDelegate: inviterRequestDelegateMock }); }); afterEach(() => { if (!(alice.userAgent.transport instanceof TransportFake)) { throw new Error("Transport not TransportFake"); } alice.userAgent.transport.setConnected(true); }); it("her ua should send INVITE", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual(SIP_INVITE); }); it("her request delegate onReject", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(0); expect(spy.onProgress).toHaveBeenCalledTimes(0); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(1); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); it("her request delegate onReject should receive a 503 (faked)", () => { const spy = inviterRequestDelegateMock; expect(spy.onReject.calls.argsFor(0)[0].message.statusCode).toEqual(503); }); it("her session state should transition 'establishing', 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Terminated]); }); }); describe("Alice invite(), no response - Request Timeout", () => { beforeEach(async () => { resetSpies(); bob.transportReceiveSpy.and.returnValue(Promise.resolve()); // drop messages inviter.invite({ requestDelegate: inviterRequestDelegateMock }); await alice.transport.waitSent(); await soon(Timers.TIMER_B); }); it("her ua should send INVITE", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual(SIP_INVITE); }); it("her request delegate onReject", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(0); expect(spy.onProgress).toHaveBeenCalledTimes(0); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(1); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); it("her request delegate onReject should receive a 408 (faked)", () => { const spy = inviterRequestDelegateMock; expect(spy.onReject.calls.argsFor(0)[0].message.statusCode).toEqual(408); }); it("her session state should transition 'establishing', 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Terminated]); }); }); describe("Alice invite()", () => { beforeEach(async () => { resetSpies(); return inviter.invite({ requestDelegate: inviterRequestDelegateMock }).then(() => bob.transport.waitSent()); }); it("her ua should send INVITE", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_INVITE); }); it("her ua should receive 100, 180", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_100); expect(spy.calls.argsFor(1)).toEqual(SIP_180); }); it("her request delegate onTyring, onProgress", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(0); expect(spy.onProgress).toHaveBeenCalledTimes(1); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(0); expect(spy.onTrying).toHaveBeenCalledTimes(1); }); it("her session state should transition 'establishing'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); }); describe("Alice cancel()", () => { beforeEach(async () => { resetSpies(); inviter.cancel(); await inviterStateSpy.wait(SessionState.Terminated); }); it("her ua should send CANCEL, ACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_CANCEL); expect(spy.calls.argsFor(1)).toEqual(SIP_ACK); }); it("her ua should receive 200, 487", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_200); expect(spy.calls.argsFor(1)).toEqual(SIP_487); }); it("her request delegate onReject", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(0); expect(spy.onProgress).toHaveBeenCalledTimes(0); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(1); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); it("her session state should transition 'terminating', 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminating]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Terminated]); }); it("his session state should transition 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); }); describe("Alice cancel(), Bob accept() - an async race condition (CANCEL wins)", () => { let logger: Logger; let acceptResolve: boolean; beforeEach(async () => { logger = invitation.userAgent.getLogger("sip.Invitation"); acceptResolve = false; resetSpies(); spyOn(logger, "error").and.callThrough(); inviter.cancel(); await invitation.accept().then(() => (acceptResolve = true)); }); it("his call to accept() should resolve and log an error", async () => { await soon(); expect(acceptResolve).toBe(true); expect(logger.error).toHaveBeenCalled(); }); it("her ua should send CANCEL, ACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_CANCEL); expect(spy.calls.argsFor(1)).toEqual(SIP_ACK); }); it("her ua should receive 200, 487", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_200); expect(spy.calls.argsFor(1)).toEqual(SIP_487); }); it("her session state should transition 'terminating', 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminating]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Terminated]); }); it("his session state should transition 'establishing', 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Terminated]); }); }); describe("Bob accept(), Alice cancel() - a network glare condition (200 wins)", () => { // FIXME: HACK: This test was a pain to make happen, but the case SHOULD be tested. // While accept() is called first, cancel() will get a CANCEL out before the 200 makes // it out first unless it is delayed. I didn't have a good hook to make it wait on after // the accept(), so I gave up after a while and just wrapped the cancel() in promise // resolutions until the 200 got sent before the CANCEL. On the flip side, if you wait // too long the 200 will get handled before cancel() is called. In any event, this should // be reworked so that it is deterministic instead of this fragile promise chain hack.... beforeEach(async () => { resetSpies(); invitation.accept(); if (inviteWithoutSdp) { return Promise.resolve().then(() => Promise.resolve().then(() => Promise.resolve().then(() => Promise.resolve().then(() => inviter.cancel()))) ); } else { return Promise.resolve().then(() => Promise.resolve().then(() => Promise.resolve().then(() => Promise.resolve().then(() => Promise.resolve().then(() => Promise.resolve().then(() => inviter.cancel())) ) ) ) ); } }); if (inviteWithoutSdp) { it("her ua should send CANCEL, ACK, BYE, 481", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(4); expect(spy.calls.argsFor(0)).toEqual(SIP_CANCEL); expect(spy.calls.argsFor(1)).toEqual(SIP_ACK); expect(spy.calls.argsFor(2)).toEqual(SIP_BYE); expect(spy.calls.argsFor(3)).toEqual(SIP_481); }); it("her ua should receive 200, 200, BYE, 481", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(4); expect(spy.calls.argsFor(0)).toEqual(SIP_200); expect(spy.calls.argsFor(1)).toEqual(SIP_200); expect(spy.calls.argsFor(2)).toEqual(SIP_BYE); expect(spy.calls.argsFor(3)).toEqual(SIP_481); }); } else { it("her ua should send CANCEL, ACK, BYE", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(3); expect(spy.calls.argsFor(0)).toEqual(SIP_CANCEL); expect(spy.calls.argsFor(1)).toEqual(SIP_ACK); expect(spy.calls.argsFor(2)).toEqual(SIP_BYE); }); it("her ua should receive 200, 200, 200", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(3); expect(spy.calls.argsFor(0)).toEqual(SIP_200); expect(spy.calls.argsFor(1)).toEqual(SIP_200); expect(spy.calls.argsFor(2)).toEqual(SIP_200); }); } it("her session state should transition 'terminating', 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminating]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Terminated]); }); it("his session state should transition 'establishing', 'established', 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(3); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Established]); expect(spy.calls.argsFor(2)).toEqual([SessionState.Terminated]); }); }); // These only makes sense in INVITE with SDP case. if (inviteWithoutSdp) { describe("Bob accept(), 200 SDP get fails - SDH Error", () => { let acceptReject: boolean; beforeEach(async () => { acceptReject = false; resetSpies(); { // Setup hacky thing to cause undefined body returned once // eslint-disable-next-line @typescript-eslint/no-explicit-any if (typeof (invitation as any).setupSessionDescriptionHandler !== "function") { throw new Error("setupSessionDescriptionHandler() undefined."); } // eslint-disable-next-line @typescript-eslint/no-explicit-any (invitation as any).setupSessionDescriptionHandler(); if (!invitation.sessionDescriptionHandler) { throw new Error("SDH undefined."); } const sdh = invitation.sessionDescriptionHandler as jasmine.SpyObj<SessionDescriptionHandler>; // eslint-disable-next-line @typescript-eslint/no-explicit-any (sdh as any).getDescriptionRejectOnce = true; } await invitation.accept().catch(() => (acceptReject = true)); }); it("his call to accept() should reject", async () => { await soon(); expect(acceptReject).toBe(true); }); it("her ua should send ACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual(SIP_ACK); }); it("her ua should receive 480", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual(SIP_480); }); it("her request delegate should onReject", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(0); expect(spy.onProgress).toHaveBeenCalledTimes(0); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(1); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); it("her session state should transition 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); it("his session state should transition 'establishing', 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Terminated]); }); }); } describe("Bob accept(), 200 has no SDP - Invalid 200", () => { beforeEach(async () => { resetSpies(); { // Setup hacky thing to cause undefined body returned once // eslint-disable-next-line @typescript-eslint/no-explicit-any if (typeof (invitation as any).setupSessionDescriptionHandler !== "function") { throw new Error("setupSessionDescriptionHandler() undefined."); } // eslint-disable-next-line @typescript-eslint/no-explicit-any (invitation as any).setupSessionDescriptionHandler(); if (!invitation.sessionDescriptionHandler) { throw new Error("SDH undefined."); } const sdh = invitation.sessionDescriptionHandler as jasmine.SpyObj<SessionDescriptionHandler>; // eslint-disable-next-line @typescript-eslint/no-explicit-any (sdh as any).getDescriptionUndefinedBodyOnce = true; } return invitation.accept().then(() => bob.transport.waitReceived()); }); it("her ua should send ACK, BYE, 481", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(3); expect(spy.calls.argsFor(0)).toEqual(SIP_ACK); expect(spy.calls.argsFor(1)).toEqual(SIP_BYE); expect(spy.calls.argsFor(2)).toEqual(SIP_481); }); it("her ua should receive 200, BYE, 481", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(3); expect(spy.calls.argsFor(0)).toEqual(SIP_200); expect(spy.calls.argsFor(1)).toEqual(SIP_BYE); expect(spy.calls.argsFor(2)).toEqual(SIP_481); }); it("her request delegate should onAccept", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(1); expect(spy.onProgress).toHaveBeenCalledTimes(0); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(0); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); it("her session state should transition 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); it("his session state should transition 'establishing', 'established', 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(3); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Established]); expect(spy.calls.argsFor(2)).toEqual([SessionState.Terminated]); }); it("her dialog should be 'terminated' and 'closed'", () => { const session = inviter.dialog; expect(session && session.sessionState).toBe(SessionDialogState.Terminated); expect(session && session.signalingState).toBe(SignalingState.Closed); }); it("his dialog should be 'terminated' and 'closed'", () => { const session = invitation.dialog; expect(session && session.sessionState).toBe(SessionDialogState.Terminated); expect(session && session.signalingState).toBe(SignalingState.Closed); }); }); describe("Bob accept(), 200 SDP set fails - SDH Error", () => { beforeEach(async () => { resetSpies(); { // Setup hacky thing to cause a rejection once // eslint-disable-next-line @typescript-eslint/no-explicit-any if (typeof (inviter as any).setupSessionDescriptionHandler !== "function") { throw new Error("setupSessionDescriptionHandler() undefined."); } // eslint-disable-next-line @typescript-eslint/no-explicit-any (inviter as any).setupSessionDescriptionHandler(); if (!inviter.sessionDescriptionHandler) { throw new Error("SDH undefined."); } // eslint-disable-next-line @typescript-eslint/no-explicit-any (inviter.sessionDescriptionHandler as any).setDescriptionRejectOnce = true; } return invitation.accept().then(() => bob.transport.waitReceived()); // ACK }); if (inviteWithoutSdp) { it("his ua should send 200, BYE, 481", () => { const spy = bob.transportSendSpy; expect(spy).toHaveBeenCalledTimes(3); expect(spy.calls.argsFor(0)).toEqual(SIP_200); expect(spy.calls.argsFor(1)).toEqual(SIP_BYE); expect(spy.calls.argsFor(2)).toEqual(SIP_481); }); it("his ua should receive ACK, BYE, 481", () => { const spy = bob.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(3); expect(spy.calls.argsFor(0)).toEqual(SIP_ACK); expect(spy.calls.argsFor(1)).toEqual(SIP_BYE); expect(spy.calls.argsFor(2)).toEqual(SIP_481); }); } else { it("his ua should send 200, 200", () => { const spy = bob.transportSendSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_200); expect(spy.calls.argsFor(1)).toEqual(SIP_200); }); it("his ua should receive ACK, BYE", () => { const spy = bob.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_ACK); expect(spy.calls.argsFor(1)).toEqual(SIP_BYE); }); } it("her request delegate should onAccept", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(1); expect(spy.onProgress).toHaveBeenCalledTimes(0); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(0); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); it("her session state should transition 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); it("his session state should transition 'establishing', 'established', 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(3); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Established]); expect(spy.calls.argsFor(2)).toEqual([SessionState.Terminated]); }); it("her dialog should be 'terminated' and 'closed'", () => { const session = inviter.dialog; expect(session && session.sessionState).toBe(SessionDialogState.Terminated); expect(session && session.signalingState).toBe(SignalingState.Closed); }); it("his dialog should be 'terminated' and 'closed'", () => { const session = invitation.dialog; expect(session && session.sessionState).toBe(SessionDialogState.Terminated); expect(session && session.signalingState).toBe(SignalingState.Closed); }); }); describe("Bob accept(), 200 send fails - Transport Error", () => { beforeEach(async () => { if (!(bob.userAgent.transport instanceof TransportFake)) { throw new Error("Transport not TransportFake"); } bob.userAgent.transport.setConnected(false); resetSpies(); return invitation.accept().then(() => soon(Timers.TIMER_H)); }); afterEach(() => { if (!(bob.userAgent.transport instanceof TransportFake)) { throw new Error("Transport not TransportFake"); } bob.userAgent.transport.setConnected(true); }); it("his ua should send 200, BYE", () => { const spy = bob.transportSendSpy; expect(spy).toHaveBeenCalledTimes(12); // 11 retransmissions of the 200 expect(spy.calls.argsFor(0)).toEqual(SIP_200); expect(spy.calls.argsFor(11)).toEqual(SIP_BYE); }); it("his session state should transition 'establishing', 'established', 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(3); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Established]); expect(spy.calls.argsFor(2)).toEqual([SessionState.Terminated]); }); }); // These only makes sense in INVITE without SDP case. if (inviteWithoutSdp) { describe("Bob accept(), ACK has no SDP - Invalid ACK", () => { beforeEach(async () => { resetSpies(); { // Setup hacky thing to cause undefined body returned once // eslint-disable-next-line @typescript-eslint/no-explicit-any if (typeof (inviter as any).setupSessionDescriptionHandler !== "function") { throw new Error("setupSessionDescriptionHandler() undefined."); } // eslint-disable-next-line @typescript-eslint/no-explicit-any (inviter as any).setupSessionDescriptionHandler(); if (!inviter.sessionDescriptionHandler) { throw new Error("SDH undefined."); } // eslint-disable-next-line @typescript-eslint/no-explicit-any (inviter.sessionDescriptionHandler as any).getDescriptionUndefinedBodyOnce = true; } return invitation.accept().then(() => bob.transport.waitReceived()); // ACK }); it("his ua should send 200, BYE", () => { const spy = bob.transportSendSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_200); expect(spy.calls.argsFor(1)).toEqual(SIP_BYE); }); it("his session state should transition 'establishing', 'established', 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(3); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Established]); expect(spy.calls.argsFor(2)).toEqual([SessionState.Terminated]); }); }); describe("Bob accept(), ACK SDP set fails - SDH Error", () => { beforeEach(async () => { resetSpies(); { // Setup hacky thing to cause a rejection once // eslint-disable-next-line @typescript-eslint/no-explicit-any if (typeof (invitation as any).setupSessionDescriptionHandler !== "function") { throw new Error("setupSessionDescriptionHandler() undefined."); } // eslint-disable-next-line @typescript-eslint/no-explicit-any (invitation as any).setupSessionDescriptionHandler(); if (!invitation.sessionDescriptionHandler) { throw new Error("SDH undefined."); } // eslint-disable-next-line @typescript-eslint/no-explicit-any (invitation.sessionDescriptionHandler as any).setDescriptionRejectOnce = true; } return invitation .accept() .then(() => bob.transport.waitReceived()) // ACK .then(() => bob.transport.waitReceived()); // 200 }); it("his ua should send 200, BYE", () => { const spy = bob.transportSendSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_200); expect(spy.calls.argsFor(1)).toEqual(SIP_BYE); }); it("his ua should receive ACK, 200", () => { const spy = bob.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_ACK); expect(spy.calls.argsFor(1)).toEqual(SIP_200); }); it("his session state should transition 'establishing', 'established', 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(3); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Established]); expect(spy.calls.argsFor(2)).toEqual([SessionState.Terminated]); }); }); } describe("Bob accept(), ACK send fails - Transport Error", () => { beforeEach(async () => { if (!(alice.userAgent.transport instanceof TransportFake)) { throw new Error("Transport not TransportFake"); } alice.userAgent.transport.setConnected(false); resetSpies(); return invitation .accept() .then(() => alice.transport.waitSent()) // ACK .then(() => soon(Timers.TIMER_L)); }); afterEach(() => { if (!(alice.userAgent.transport instanceof TransportFake)) { throw new Error("Transport not TransportFake"); } alice.userAgent.transport.setConnected(true); }); it("his ua should send 200, BYE", () => { const spy = bob.transportSendSpy; expect(spy).toHaveBeenCalledTimes(12); // 11 retransmissions of the 200 expect(spy.calls.argsFor(0)).toEqual(SIP_200); expect(spy.calls.argsFor(11)).toEqual(SIP_BYE); }); it("her session state should transition 'established', 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual([SessionState.Established]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Terminated]); }); it("his session state should transition 'establishing', 'established', 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(3); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Established]); expect(spy.calls.argsFor(2)).toEqual([SessionState.Terminated]); }); }); describe("Bob accept(), ACK never arrives - Request Timeout", () => { beforeEach(async () => { resetSpies(); alice.transportReceiveSpy.and.returnValue(Promise.resolve()); // drop messages return invitation.accept().then(() => soon(Timers.TIMER_L)); }); it("his ua should send 200, BYE", () => { const spy = bob.transportSendSpy; expect(spy).toHaveBeenCalledTimes(12); // 10 retransmissions of the 200 expect(spy.calls.argsFor(0)).toEqual(SIP_200); expect(spy.calls.argsFor(11)).toEqual(SIP_BYE); }); it("his session state should transition 'establishing', 'established', 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(3); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Established]); expect(spy.calls.argsFor(2)).toEqual([SessionState.Terminated]); }); }); describe("Bob reject(), ACK send fails - Transport Error", () => { beforeEach(async () => { if (!(alice.userAgent.transport instanceof TransportFake)) { throw new Error("Transport not TransportFake"); } alice.userAgent.transport.setConnected(false); resetSpies(); return invitation .reject() .then(() => alice.transport.waitSent()) // ACK .then(() => soon(Timers.TIMER_H)); }); afterEach(() => { if (!(alice.userAgent.transport instanceof TransportFake)) { throw new Error("Transport not TransportFake"); } alice.userAgent.transport.setConnected(true); }); it("his ua should send 480", () => { const spy = bob.transportSendSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual(SIP_480); }); it("her session state should transition 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); it("his session state should transition 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); }); describe("Bob nothing - no answer timeout", () => { beforeEach(async () => { resetSpies(); const noAnswerTimeout = 90000; if (alice.userAgent.configuration.noAnswerTimeout * 1000 !== noAnswerTimeout) { throw new Error("Test is assuming UA configured with 90 second no answer timeout"); } await soon(noAnswerTimeout); }); it("her ua should send ACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual(SIP_ACK); }); it("her ua should receive 180, 480", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_180); // provisional resend timer generates this at 60 sec expect(spy.calls.argsFor(1)).toEqual(SIP_480); }); it("her request delegate onProgress, onReject", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(0); expect(spy.onProgress).toHaveBeenCalledTimes(1); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(1); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); it("her session state should transition 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); }); describe("Bob accept()", () => { bobAccept(); describe("Bob terminate()", () => { bobTerminate(); }); describe("Bob terminate(), terminate()", () => { bobTerminate2x(); }); }); describe("Bob accept(), accept()", () => { if (inviteWithoutSdp) { bobAccept(); } else { bobAccept2x(); } }); describe("Bob progress(), Alice cancel(), Bob accept() - an async race condition (CANCEL wins)", () => { let logger: Logger; let progressResolve: boolean; let acceptResolve: boolean; beforeEach(async () => { progressResolve = false; acceptResolve = false; logger = invitation.userAgent.getLogger("sip.Invitation"); resetSpies(); spyOn(logger, "error").and.callThrough(); invitation.progress().then(() => (progressResolve = true)); inviter.cancel(); await invitation.accept().then(() => (acceptResolve = true)); // await invitationStateSpy.wait(SessionState.Terminated); // await soon(); }); it("his call to progress(), accept() should resolve and log an error", () => { expect(progressResolve).toBe(true); expect(acceptResolve).toBe(true); expect(logger.error).toHaveBeenCalled(); }); it("her ua should send CANCEL, ACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_CANCEL); expect(spy.calls.argsFor(1)).toEqual(SIP_ACK); }); it("her ua should receive 180, 200, 487", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(3); expect(spy.calls.argsFor(0)).toEqual(SIP_180); expect(spy.calls.argsFor(1)).toEqual(SIP_200); expect(spy.calls.argsFor(2)).toEqual(SIP_487); }); it("her session state should transition 'terminating', 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminating]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Terminated]); }); it("his session state should transition 'establishing', 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Terminated]); }); }); describe("Bob progress(reliable), Alice cancel(), Bob accept() - an async race condition (CANCEL wins)", () => { let logger: Logger; let progressResolve: boolean; let acceptResolve: boolean; beforeEach(async () => { logger = invitation.userAgent.getLogger("sip.Invitation"); progressResolve = false; acceptResolve = false; resetSpies(); spyOn(logger, "error").and.callThrough(); invitation.progress({ rel100: true }).then(() => (progressResolve = true)); inviter.cancel(); await invitation.accept().then(() => (acceptResolve = true)); }); it("his call to progress(), accept() should resolve and log an error", async () => { await soon(); expect(progressResolve).toBe(true); expect(acceptResolve).toBe(true); expect(logger.error).toHaveBeenCalled(); }); it("her ua should send CANCEL, ACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_CANCEL); expect(spy.calls.argsFor(1)).toEqual(SIP_ACK); }); it("her ua should receive 200, 487", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_200); expect(spy.calls.argsFor(1)).toEqual(SIP_487); }); it("her session state should transition 'terminating', 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminating]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Terminated]); }); it("his session state should transition 'establishing', 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Terminated]); }); }); describe("Bob progress(reliable), Bob accept(), Bob dispose() - an async race condition (dispose wins)", () => { let logger: Logger; let progressReject: boolean; let acceptReject: boolean; beforeEach(async () => { logger = invitation.userAgent.getLogger("sip.Invitation"); progressReject = false; acceptReject = false; resetSpies(); spyOn(logger, "error").and.callThrough(); invitation.progress({ rel100: true }).catch(() => (progressReject = true)); invitation.accept().catch(() => (acceptReject = true)); await invitation.dispose(); await soon(); // need an extra promise resolution for tests to play out await soon(); // need an extra promise resolution for tests to play out await soon(); // need an extra promise resolution for tests to play out }); it("his call to progress(), accept() should reject", () => { expect(progressReject).toBe(true); expect(acceptReject).toBe(true); }); it("her ua should send ACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual(SIP_ACK); }); it("her ua should receive 480", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual(SIP_480); }); it("her session state should transition 'terminated'", () => { const spy = inviterStateSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.argsFor(0)).toEqual([SessionState.Terminated]); }); it("his session state should transition 'establishing', 'terminated'", () => { const spy = invitationStateSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual([SessionState.Establishing]); expect(spy.calls.argsFor(1)).toEqual([SessionState.Terminated]); }); }); describe("Bob progress()", () => { bobProgress(); describe("Bob accept()", () => { bobAccept(); }); describe("Bob reject()", () => { bobReject(); }); describe("Bob progress()", () => { bobProgress(); describe("Bob accept()", () => { bobAccept(); }); describe("Bob reject()", () => { bobReject(); }); }); }); // Sending offer in unreliable provisional not legal, // but should still write test for that case. Punting... if (!inviteWithoutSdp) { describe("Bob progress(183)", () => { bobProgress183(); describe("Bob accept()", () => { bobAccept(); }); describe("Bob reject()", () => { bobReject(); }); describe("Bob progress()", () => { bobProgress(); describe("Bob accept()", () => { bobAccept(); }); describe("Bob reject()", () => { bobReject(); }); }); }); } describe("Bob progress(reliable)", () => { bobProgressReliable(); describe("Bob accept()", () => { bobAccept(); }); describe("Bob reject()", () => { bobReject(); }); describe("Bob progress(reliable) ", () => { bobProgressReliable(); describe("Bob accept()", () => { bobAccept(); }); describe("Bob reject()", () => { bobReject(); }); describe("Bob progress(reliable) ", () => { bobProgressReliable(); describe("Bob accept()", () => { bobAccept(); }); describe("Bob reject()", () => { bobReject(); }); }); }); describe("Bob progress()", () => { bobProgress(); describe("Bob accept()", () => { bobAccept(); }); describe("Bob reject()", () => { bobReject(); }); describe("Bob progress(reliable) ", () => { bobProgressReliable(); describe("Bob accept()", () => { bobAccept(); }); describe("Bob reject()", () => { bobReject(); }); describe("Bob progress(reliable) ", () => { bobProgressReliable(); describe("Bob accept()", () => { bobAccept(); }); describe("Bob reject()", () => { bobReject(); }); }); }); }); }); describe("Bob progress(), progress()", () => { bobProgress2x(); }); describe("Bob progress(reliable), progress(reliable)", () => { bobProgressReliable2x(); }); describe("Bob reject()", () => { bobReject(); }); describe("Bob reject(), reject()", () => { bobReject2x(); }); describe("Bob terminate()", () => { bobTerminate(false); }); describe("Bob terminate(), terminate()", () => { bobTerminate2x(false); }); describe("Bob accept(), terminate()", () => { bobAcceptTerminate(false); }); describe("Bob accept(), terminate(), no ACK - transaction timeout", () => { bobAcceptTerminate(true); }); }); } function resetSpies(): void { alice.transportReceiveSpy.calls.reset(); alice.transportSendSpy.calls.reset(); bob.transportReceiveSpy.calls.reset(); bob.transportSendSpy.calls.reset(); inviterStateSpy.calls.reset(); if (invitationStateSpy) { invitationStateSpy.calls.reset(); } inviterRequestDelegateMock.onAccept.calls.reset(); inviterRequestDelegateMock.onProgress.calls.reset(); inviterRequestDelegateMock.onRedirect.calls.reset(); inviterRequestDelegateMock.onReject.calls.reset(); inviterRequestDelegateMock.onTrying.calls.reset(); } beforeEach(async () => { jasmine.clock().install(); alice = await makeUserFake("alice", "example.com", "Alice"); bob = await makeUserFake("bob", "example.com", "Bob"); connectUserFake(alice, bob); }); afterEach(async () => { return alice.userAgent .stop() .then(() => expect(alice.isShutdown()).toBe(true)) .then(() => bob.userAgent.stop()) .then(() => expect(bob.isShutdown()).toBe(true)) .then(() => jasmine.clock().uninstall()); }); describe("Alice constructs a new INVITE targeting Bob with SDP offer", () => { beforeEach(async () => { target = bob.uri; bob.userAgent.delegate = { onInvite: (session): void => { invitation = session; invitationStateSpy = makeEmitterSpy(invitation.stateChange, bob.userAgent.getLogger("Bob")); } }; inviter = new Inviter(alice.userAgent, target); inviterStateSpy = makeEmitterSpy(inviter.stateChange, alice.userAgent.getLogger("Alice")); await soon(); }); inviteSuite(false); }); describe("Alice constructs a new INVITE targeting Bob without SDP offer", () => { beforeEach(async () => { target = bob.uri; bob.userAgent.delegate = { onInvite: (session): void => { invitation = session; invitationStateSpy = makeEmitterSpy(invitation.stateChange, bob.userAgent.getLogger("Bob")); } }; inviter = new Inviter(alice.userAgent, target, { inviteWithoutSdp: true }); inviterStateSpy = makeEmitterSpy(inviter.stateChange, alice.userAgent.getLogger("Alice")); await soon(); }); inviteSuite(true); }); describe("Early Media Disabled...", () => { beforeEach(async () => { target = bob.uri; bob.userAgent.delegate = { onInvite: (session): void => { invitation = session; invitationStateSpy = makeEmitterSpy(invitation.stateChange, bob.userAgent.getLogger("Bob")); } }; inviter = new Inviter(alice.userAgent, target, { earlyMedia: false }); inviterStateSpy = makeEmitterSpy(inviter.stateChange, alice.userAgent.getLogger("Alice")); await soon(); }); describe("Alice invite()", () => { beforeEach(() => { resetSpies(); return inviter.invite().then(() => bob.transport.waitSent()); }); it("her inviter sdh should have called get description once", () => { const sdh = inviter.sessionDescriptionHandler; if (!sdh) { fail("Inviter SDH undefined."); return; } expect(sdh.getDescription).toHaveBeenCalledTimes(1); expect(sdh.setDescription).toHaveBeenCalledTimes(0); }); describe("Bob progress(183)", () => { beforeEach(() => { resetSpies(); return invitation.progress({ statusCode: 183 }); }); it("her inviter sdh should have called get description once", () => { const sdh = inviter.sessionDescriptionHandler; if (!sdh) { fail("Inviter SDH undefined."); return; } expect(sdh.getDescription).toHaveBeenCalledTimes(1); expect(sdh.setDescription).toHaveBeenCalledTimes(0); }); describe("Bob accept()", () => { beforeEach(() => { resetSpies(); return invitation.accept().then(() => bob.transport.waitReceived()); }); it("her inviter sdh should have called get & set description once", () => { const sdh = inviter.sessionDescriptionHandler; if (!sdh) { fail("Inviter SDH undefined."); return; } expect(sdh.getDescription).toHaveBeenCalledTimes(1); expect(sdh.setDescription).toHaveBeenCalledTimes(1); }); }); describe("Bob progress(183)", () => { beforeEach(() => { resetSpies(); return invitation.progress({ statusCode: 183 }); }); it("her inviter sdh should have called get description once", () => { const sdh = inviter.sessionDescriptionHandler; if (!sdh) { fail("Inviter SDH undefined."); return; } expect(sdh.getDescription).toHaveBeenCalledTimes(1); expect(sdh.setDescription).toHaveBeenCalledTimes(0); }); describe("Bob accept()", () => { beforeEach(() => { resetSpies(); return invitation.accept().then(() => bob.transport.waitReceived()); }); it("her inviter sdh should have called get & set description once", () => { const sdh = inviter.sessionDescriptionHandler; if (!sdh) { fail("Inviter SDH undefined."); return; } expect(sdh.getDescription).toHaveBeenCalledTimes(1); expect(sdh.setDescription).toHaveBeenCalledTimes(1); }); }); }); }); }); }); describe("Early Media Enabled...", () => { beforeEach(async () => { target = bob.uri; bob.userAgent.delegate = { onInvite: (session): void => { invitation = session; invitationStateSpy = makeEmitterSpy(invitation.stateChange, bob.userAgent.getLogger("Bob")); } }; inviter = new Inviter(alice.userAgent, target, { earlyMedia: true }); inviterStateSpy = makeEmitterSpy(inviter.stateChange, alice.userAgent.getLogger("Alice")); await soon(); }); describe("Alice invite()", () => { beforeEach(() => { resetSpies(); return inviter.invite().then(() => bob.transport.waitSent()); }); it("her inviter sdh should have called get description once", () => { const sdh = inviter.sessionDescriptionHandler; if (!sdh) { fail("Inviter SDH undefined."); return; } expect(sdh.getDescription).toHaveBeenCalledTimes(1); expect(sdh.setDescription).toHaveBeenCalledTimes(0); }); describe("Bob progress(183)", () => { beforeEach(() => { resetSpies(); return invitation.progress({ statusCode: 183 }); }); it("her inviter sdh should have called get & set description once", () => { const sdh = inviter.sessionDescriptionHandler; if (!sdh) { fail("Inviter SDH undefined."); return; } expect(sdh.getDescription).toHaveBeenCalledTimes(1); expect(sdh.setDescription).toHaveBeenCalledTimes(1); }); describe("Bob accept()", () => { beforeEach(async () => { resetSpies(); invitation.accept(); await bob.transport.waitReceived(); }); it("her inviter sdh should have called get & set description once", () => { const sdh = inviter.sessionDescriptionHandler; if (!sdh) { fail("Inviter SDH undefined."); return; } expect(sdh.getDescription).toHaveBeenCalledTimes(1); expect(sdh.setDescription).toHaveBeenCalledTimes(1); }); }); describe("Bob progress(183)", () => { beforeEach(() => { resetSpies(); return invitation.progress({ statusCode: 183 }); }); it("her inviter sdh should have called get & set description once", () => { const sdh = inviter.sessionDescriptionHandler; if (!sdh) { fail("Inviter SDH undefined."); return; } expect(sdh.getDescription).toHaveBeenCalledTimes(1); expect(sdh.setDescription).toHaveBeenCalledTimes(1); }); describe("Bob accept()", () => { beforeEach(() => { resetSpies(); invitation.accept(); return bob.transport.waitReceived(); }); it("her inviter sdh should have called get & set description once", () => { const sdh = inviter.sessionDescriptionHandler; if (!sdh) { fail("Inviter SDH undefined."); return; } expect(sdh.getDescription).toHaveBeenCalledTimes(1); expect(sdh.setDescription).toHaveBeenCalledTimes(1); }); }); }); }); }); }); describe("Forking...", () => { let bob2: UserFake; let invitation2: Invitation; let invitationStateSpy2: EmitterSpy<SessionState>; function bobsAccept(answerInAck: boolean): void { const SIP_ACK_OR_BYE = [jasmine.stringMatching(/^ACK|^BYE/)]; beforeEach(async () => { resetSpies2(); invitation.accept(); invitation2.accept(); await inviterStateSpy.wait(SessionState.Established); }); if (answerInAck) { it("her ua should send ACK, BYE, ACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(4); expect(spy.calls.argsFor(0)).toEqual(SIP_ACK_OR_BYE); expect(spy.calls.argsFor(1)).toEqual(SIP_ACK_OR_BYE); // expect(spy.calls.argsFor(2)).toEqual(SIP_487); expect(spy.calls.argsFor(3)).toEqual(SIP_ACK_OR_BYE); }); } else { it("her ua should send ACK, BYE, ACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(3); expect(spy.calls.argsFor(0)).toEqual(SIP_ACK_OR_BYE); expect(spy.calls.argsFor(1)).toEqual(SIP_ACK_OR_BYE); expect(spy.calls.argsFor(2)).toEqual(SIP_ACK_OR_BYE); }); } it("her session should be 'confirmed' and 'stable'", () => { const session = inviter.dialog; expect(session && session.sessionState).toBe(SessionDialogState.Confirmed); expect(session && session.signalingState).toBe(SignalingState.Stable); }); } function bobsProgressReliable(): void { beforeEach(async () => { resetSpies2(); invitation.progress({ rel100: true }); invitation2.progress({ rel100: true }); await bob.transport.waitSent(); // 200 for PRACK await alice.transport.waitReceived(); // 200 for PRACK }); it("her ua should send PRACK, PRACK", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(2); expect(spy.calls.argsFor(0)).toEqual(SIP_PRACK); expect(spy.calls.argsFor(1)).toEqual(SIP_PRACK); }); it("her request delegate onProgress, onProgress", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(0); expect(spy.onProgress).toHaveBeenCalledTimes(2); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(0); expect(spy.onTrying).toHaveBeenCalledTimes(0); }); } function inviteSuiteFork(inviteWithoutSdp: boolean): void { it("her ua should send nothing", () => { expect(alice.transportSendSpy).not.toHaveBeenCalled(); }); describe("Alice invite() fork", () => { beforeEach(async () => { resetSpies2(); inviter.invite({ requestDelegate: inviterRequestDelegateMock }); await bob.transport.waitSent(); await soon(); // need an extra promise resolution for tests to play out }); it("her ua should send INVITE", () => { const spy = alice.transportSendSpy; expect(spy).toHaveBeenCalledTimes(1); expect(spy.calls.mostRecent().args).toEqual(SIP_INVITE); }); it("her ua should receive 100, 180", () => { const spy = alice.transportReceiveSpy; expect(spy).toHaveBeenCalledTimes(4); expect(spy.calls.argsFor(0)).toEqual(SIP_100); expect(spy.calls.argsFor(1)).toEqual(SIP_180); expect(spy.calls.argsFor(2)).toEqual(SIP_100); expect(spy.calls.argsFor(3)).toEqual(SIP_180); }); it("her request delegate onTrying, onProgress", () => { const spy = inviterRequestDelegateMock; expect(spy.onAccept).toHaveBeenCalledTimes(0); expect(spy.onProgress).toHaveBeenCalledTimes(2); expect(spy.onRedirect).toHaveBeenCalledTimes(0); expect(spy.onReject).toHaveBeenCalledTimes(0); expect(spy.onTrying).toHaveBeenCalledTimes(2); }); describe("Bob & Bob2 accept()", () => { if (inviteWithoutSdp) { bobsAccept(true); } else { bobsAccept(false); } }); describe("Bob & Bob2 progress(reliable)", () => { bobsProgressReliable(); describe("Bob & Bob2 accept()", () => { bobsAccept(false); }); }); }); } function resetSpies2(): void { resetSpies(); bob2.transportReceiveSpy.calls.reset(); bob2.transportSendSpy.calls.reset(); if (invitationStateSpy2) { invitationStateSpy2.calls.reset(); } } beforeEach(async () => { bob2 = await makeUserFake("bob", "example.com", "Bob2"); connectUserFake(alice, bob2); }); afterEach(async () => { return bob2.userAgent.stop().then(() => expect(bob2.isShutdown()).toBe(true)); }); describe("Alice constructs a new INVITE targeting 2 Bobs with SDP offer", () => { beforeEach(async () => { target = bob.uri; bob.userAgent.delegate = { onInvite: (session): void => { invitation = session; invitationStateSpy = makeEmitterSpy(invitation.stateChange, bob.userAgent.getLogger("Bob")); } }; bob2.userAgent.delegate = { onInvite: (session): void => { invitation2 = session; invitationStateSpy2 = makeEmitterSpy(invitation.stateChange, bob.userAgent.getLogger("Bob2")); } }; inviter = new Inviter(alice.userAgent, target); inviterStateSpy = makeEmitterSpy(inviter.stateChange, alice.userAgent.getLogger("Alice")); await soon(); }); inviteSuiteFork(false); }); describe("Alice constructs a new INVITE targeting 2 Bobs without SDP offer", () => { beforeEach(async () => { target = bob.uri; bob.userAgent.delegate = { onInvite: (session): void => { invitation = session; invitationStateSpy = makeEmitterSpy(invitation.stateChange, bob.userAgent.getLogger("Bob")); } }; bob2.userAgent.delegate = { onInvite: (session): void => { invitation2 = session; invitationStateSpy2 = makeEmitterSpy(invitation.stateChange, bob.userAgent.getLogger("Bob2")); } }; inviter = new Inviter(alice.userAgent, target, { inviteWithoutSdp: true }); inviterStateSpy = makeEmitterSpy(inviter.stateChange, alice.userAgent.getLogger("Alice")); await soon(); }); inviteSuiteFork(true); }); }); });
the_stack
import * as path from 'path'; import crypto from 'crypto'; import * as fse from 'fs-extra'; import * as gltf from './schema'; import { isUndefined, isNullOrUndefined } from 'util'; import { ImagePlaceholder } from '../common/image-placeholders'; import * as IMF from '../common/intermediate-format'; const MaxBufferSize = 5 << 20; const DefaultMaterial: gltf.MaterialPbrMetallicRoughness = { pbrMetallicRoughness: { baseColorFactor: [0.25, 0.25, 0.25, 1.0], metallicFactor: 0.0, roughnessFactor: 0.5 } }; export interface IWriterOptions { maxBufferSize?: number; /** Approx. size limit (in bytes) of binary buffers with mesh data (5 << 20 by default) */ ignoreMeshGeometry?: boolean; /** Don't output mesh geometry */ ignoreLineGeometry?: boolean; /** Don't output line geometry */ ignorePointGeometry?: boolean; /** Don't output point geometry */ deduplicate?: boolean; /** Find and remove mesh geometry duplicates (increases the processing time) */ skipUnusedUvs?: boolean; /** Skip unused tex coordinates. */ center?: boolean; /** Move the model to origin. */ log?: (msg: string) => void; /** Optional logging function. */ filter?: (dbid: number) => boolean; } function hasTextures(material: IMF.Material | null): boolean { return !!(material?.maps?.diffuse); } interface IWriterStats { materialsDeduplicated: number; meshesDeduplicated: number; accessorsDeduplicated: number; bufferViewsDeduplicated: number; } /** * Utility class for serializing parsed 3D content to local file system as glTF (2.0). */ export class Writer { protected options: Required<IWriterOptions>; protected baseDir: string; protected manifest: gltf.GlTf; protected bufferStream: fse.WriteStream | null; protected bufferSize: number; protected bufferViewCache = new Map<string, gltf.BufferView>(); // Cache of existing buffer views, indexed by hash of the binary data they point to protected meshHashes: string[] = []; // List of hashes of existing gltf.Mesh objects, used for deduplication protected bufferViewHashes: string[] = []; // List of hashes of existing gltf.BufferView objects, used for deduplication protected accessorHashes: string[] = []; // List of hashes of existing gltf.Accessor objects, used for deduplication protected pendingTasks: Promise<void>[] = []; protected stats: IWriterStats = { materialsDeduplicated: 0, meshesDeduplicated: 0, accessorsDeduplicated: 0, bufferViewsDeduplicated: 0 }; /** * Initializes the writer. * @param {IWriterOptions} [options={}] Additional writer options. */ constructor(options: IWriterOptions = {}) { this.options = { maxBufferSize: isNullOrUndefined(options.maxBufferSize) ? MaxBufferSize : options.maxBufferSize, ignoreMeshGeometry: !!options.ignoreMeshGeometry, ignoreLineGeometry: !!options.ignoreLineGeometry, ignorePointGeometry: !!options.ignorePointGeometry, deduplicate: !!options.deduplicate, skipUnusedUvs: !!options.skipUnusedUvs, center: !!options.center, log: (options && options.log) || function (msg: string) {}, filter: options && options.filter || ((dbid: number) => true) }; // All these properties will be properly initialized in the 'reset' call this.manifest = {} as gltf.GlTf; this.bufferStream = null; this.bufferSize = 0; this.baseDir = ''; } /** * Outputs scene into glTF. * @async * @param {IMF.IScene} imf Complete scene in intermediate, in-memory format. * @param {string} outputDir Path to output folder. */ async write(imf: IMF.IScene, outputDir: string) { this.reset(outputDir); const scene = this.createScene(imf); const scenes = this.manifest.scenes as gltf.Scene[]; scenes.push(scene); if (this.bufferStream) { const stream = this.bufferStream as fse.WriteStream; this.pendingTasks.push(new Promise((resolve, reject) => { stream.on('finish', resolve); })); this.bufferStream.close(); this.bufferStream = null; this.bufferSize = 0; } await Promise.all(this.pendingTasks); // Remove empty attributes textures or images to avoid errors in glTF validation if (this.manifest.textures && this.manifest.textures.length === 0) delete this.manifest.textures; if (this.manifest.images && this.manifest.images.length === 0) delete this.manifest.images; const gltfPath = path.join(this.baseDir, 'output.gltf'); fse.writeFileSync(gltfPath, JSON.stringify(this.manifest, null, 4)); this.options.log(`Closing gltf output: done`); this.options.log(`Stats: ${JSON.stringify(this.stats)}`); await this.postprocess(imf, gltfPath); } protected reset(outputDir: string) { this.baseDir = outputDir; this.manifest = { asset: { version: '2.0', generator: 'forge-convert-utils', copyright: '2019 (c) Autodesk' }, extensionsUsed: [ "KHR_texture_transform" ], buffers: [], bufferViews: [], accessors: [], meshes: [], materials: [], nodes: [], scenes: [], textures: [], images: [], scene: 0 }; this.bufferStream = null; this.bufferSize = 0; this.bufferViewCache.clear(); this.meshHashes = []; this.bufferViewHashes = []; this.accessorHashes = []; this.pendingTasks = []; this.stats = { materialsDeduplicated: 0, meshesDeduplicated: 0, accessorsDeduplicated: 0, bufferViewsDeduplicated: 0 }; } protected async postprocess(imf: IMF.IScene, gltfPath: string) { } protected createScene(imf: IMF.IScene): gltf.Scene { fse.ensureDirSync(this.baseDir); let scene: gltf.Scene = { nodes: [] }; const manifestNodes = this.manifest.nodes as gltf.Node[]; const manifestMaterials = this.manifest.materials as gltf.MaterialPbrMetallicRoughness[]; const rootNode: gltf.Node = { children: [] }; // Root node with transform to glTF coordinate system const xformNode: gltf.Node = { children: [] }; // Transform node with additional global transform (e.g., moving model to origin) (scene.nodes as number[]).push(manifestNodes.push(rootNode) - 1); (rootNode.children as number[]).push(manifestNodes.push(xformNode) - 1); // Setup transformation to glTF coordinate system const metadata = imf.getMetadata(); if (metadata['world up vector'] && metadata['world front vector'] && metadata['distance unit']) { const up = metadata['world up vector'].XYZ; const front = metadata['world front vector'].XYZ; const distanceUnit = metadata['distance unit'].value; if (up && front && distanceUnit) { const left = [ up[1] * front[2] - up[2] * front[1], up[2] * front[0] - up[0] * front[2], up[0] * front[1] - up[1] * front[0] ]; if (left[0] * left[0] + left[1] * left[1] + left[2] * left[2] > 0.0) { let scale = 1.0; switch (distanceUnit) { case 'centimeter': case 'cm': scale = 0.01; break; case 'millimeter': case 'mm': scale = 0.001; break; case 'foot': case 'ft': scale = 0.3048; break; case 'inch': case 'in': scale = 0.0254; break; default: // "meter" / "m" scale = 1.0; } rootNode.matrix = [ left[0] * scale, up[0] * scale, front[0] * scale, 0, left[1] * scale, up[1] * scale, front[1] * scale, 0, left[2] * scale, up[2] * scale, front[2] * scale, 0, 0, 0, 0, 1 ]; } else { console.warn('Could not compute world matrix, leaving it as identity...'); } } } // Setup translation to origin when enabled if (metadata['world bounding box'] && this.options.center) { const boundsMin = metadata['world bounding box'].minXYZ; const boundsMax = metadata['world bounding box'].maxXYZ; if (boundsMin && boundsMax) { let translation = [ -0.5 * (boundsMin[0] + boundsMax[0]), -0.5 * (boundsMin[1] + boundsMax[1]), -0.5 * (boundsMin[2] + boundsMax[2]) ]; xformNode.matrix = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, translation[0], translation[1], translation[2], 1 ]; } } const nodeIndices = (xformNode.children as number[]); this.options.log(`Writing scene nodes...`); const { filter } = this.options; for (let i = 0, len = imf.getNodeCount(); i < len; i++) { const fragment = imf.getNode(i); // Currently we only support flat lists of objects, no hierarchies if (fragment.kind !== IMF.NodeKind.Object) { continue; } if (!filter(fragment.dbid)) { continue; } const material = imf.getMaterial(fragment.material); // Only output UVs if there are any textures or if the user specifically asked not to skip unused UVs const outputUvs = hasTextures(material) || !this.options.skipUnusedUvs; const node = this.createNode(fragment, imf, outputUvs); // Only output nodes that have a mesh if (!isUndefined(node.mesh)) { nodeIndices.push(manifestNodes.push(node) - 1); } } this.options.log(`Writing materials...`); if (this.options.deduplicate) { const hashes: string[] = []; const newMaterialIndices = new Uint16Array(imf.getMaterialCount()); for (let i = 0, len = imf.getMaterialCount(); i < len; i++) { const material = imf.getMaterial(i); const hash = this.computeMaterialHash(material); const match = hashes.indexOf(hash); if (match === -1) { // If this is a first occurrence of the hash in the array, output a new material newMaterialIndices[i] = manifestMaterials.length; manifestMaterials.push(this.createMaterial(material, imf)); hashes.push(hash); } else { // Otherwise skip the material, and record an index to the first match below this.options.log(`Skipping a duplicate material (hash: ${hash})`); newMaterialIndices[i] = match; this.stats.materialsDeduplicated++; } } // Update material indices in all mesh primitives for (const mesh of (this.manifest.meshes as gltf.Mesh[])) { for (const primitive of mesh.primitives) { if (!isUndefined(primitive.material)) { primitive.material = newMaterialIndices[primitive.material]; } } } } else { for (let i = 0, len = imf.getMaterialCount(); i < len; i++) { const material = imf.getMaterial(i); const mat = this.createMaterial(material, imf); manifestMaterials.push(mat); } } this.options.log(`Writing scene: done`); return scene; } protected createNode(fragment: IMF.IObjectNode, imf: IMF.IScene, outputUvs: boolean): gltf.Node { let node: gltf.Node = { name: fragment.dbid.toString() }; if (fragment.transform) { switch (fragment.transform.kind) { case IMF.TransformKind.Matrix: node.matrix = fragment.transform.elements; break; case IMF.TransformKind.Decomposed: if (fragment.transform.scale) { const s = fragment.transform.scale; node.scale = [s.x, s.y, s.z]; } if (fragment.transform.rotation) { const r = fragment.transform.rotation; node.rotation = [r.x, r.y, r.z, r.w]; } if (fragment.transform.translation) { const t = fragment.transform.translation; node.translation = [t.x, t.y, t.z]; } break; } } const geometry = imf.getGeometry(fragment.geometry); let mesh: gltf.Mesh | undefined = undefined; switch (geometry.kind) { case IMF.GeometryKind.Mesh: mesh = this.createMeshGeometry(geometry, imf, outputUvs); break; case IMF.GeometryKind.Lines: mesh = this.createLineGeometry(geometry, imf); break; case IMF.GeometryKind.Points: mesh = this.createPointGeometry(geometry, imf); break; case IMF.GeometryKind.Empty: console.warn('Could not find mesh for fragment', fragment); break; } if (mesh && mesh.primitives.length > 0) { for (const primitive of mesh.primitives) { primitive.material = fragment.material; } node.mesh = this.addMesh(mesh); } return node; } protected addMesh(mesh: gltf.Mesh): number { const meshes = this.manifest.meshes as gltf.Mesh[]; const hash = this.computeMeshHash(mesh); const match = this.options.deduplicate ? this.meshHashes.indexOf(hash) : -1; if (match !== -1) { this.options.log(`Skipping a duplicate mesh (${hash})`); this.stats.meshesDeduplicated++; return match; } else { if (this.options.deduplicate) { this.meshHashes.push(hash); } return meshes.push(mesh) - 1; } } protected createMeshGeometry(geometry: IMF.IMeshGeometry, imf: IMF.IScene, outputUvs: boolean): gltf.Mesh { let mesh: gltf.Mesh = { primitives: [] }; if (this.options.ignoreMeshGeometry) { return mesh; } // Output index buffer const indices = geometry.getIndices(); const indexBufferView = this.createBufferView(Buffer.from(indices.buffer)); const indexBufferViewID = this.addBufferView(indexBufferView); const indexAccessor = this.createAccessor(indexBufferViewID, 5123, indexBufferView.byteLength / 2, 'SCALAR'); const indexAccessorID = this.addAccessor(indexAccessor); // Output vertex buffer const vertices = geometry.getVertices(); const positionBounds = this.computeBoundsVec3(vertices); // Compute bounds manually, just in case const positionBufferView = this.createBufferView(Buffer.from(vertices.buffer)); const positionBufferViewID = this.addBufferView(positionBufferView); const positionAccessor = this.createAccessor(positionBufferViewID, 5126, positionBufferView.byteLength / 4 / 3, 'VEC3', positionBounds.min, positionBounds.max/*[fragmesh.min.x, fragmesh.min.y, fragmesh.min.z], [fragmesh.max.x, fragmesh.max.y, fragmesh.max.z]*/); const positionAccessorID = this.addAccessor(positionAccessor); // Output normals buffer let normalAccessorID: number | undefined = undefined; const normals = geometry.getNormals(); if (normals) { const normalBufferView = this.createBufferView(Buffer.from(normals.buffer)); const normalBufferViewID = this.addBufferView(normalBufferView); const normalAccessor = this.createAccessor(normalBufferViewID, 5126, normalBufferView.byteLength / 4 / 3, 'VEC3'); normalAccessorID = this.addAccessor(normalAccessor); } // Output color buffer let colorAccessorID: number | undefined = undefined; const colors = geometry.getColors(); if (colors) { const colorBufferView = this.createBufferView(Buffer.from(colors.buffer)); const colorBufferViewID = this.addBufferView(colorBufferView); const colorAccessor = this.createAccessor(colorBufferViewID, 5126, colorBufferView.byteLength / 4 / 4, 'VEC4'); colorAccessorID = this.addAccessor(colorAccessor); } // Output UV buffers let uvAccessorID: number | undefined = undefined; if (geometry.getUvChannelCount() > 0 && outputUvs) { const uvs = geometry.getUvs(0); const uvBufferView = this.createBufferView(Buffer.from(uvs.buffer)); const uvBufferViewID = this.addBufferView(uvBufferView); const uvAccessor = this.createAccessor(uvBufferViewID, 5126, uvBufferView.byteLength / 4 / 2, 'VEC2'); uvAccessorID = this.addAccessor(uvAccessor); } mesh.primitives.push({ mode: 4, attributes: { POSITION: positionAccessorID, }, indices: indexAccessorID }); if (!isUndefined(normalAccessorID)) { mesh.primitives[0].attributes.NORMAL = normalAccessorID; } if (!isUndefined(colorAccessorID)) { mesh.primitives[0].attributes.COLOR_0 = colorAccessorID; } if (!isUndefined(uvAccessorID)) { mesh.primitives[0].attributes.TEXCOORD_0 = uvAccessorID; } return mesh; } protected createLineGeometry(geometry: IMF.ILineGeometry, imf: IMF.IScene): gltf.Mesh { let mesh: gltf.Mesh = { primitives: [] }; if (this.options.ignoreLineGeometry) { return mesh; } // Output index buffer const indices = geometry.getIndices(); const indexBufferView = this.createBufferView(Buffer.from(indices.buffer)); const indexBufferViewID = this.addBufferView(indexBufferView); const indexAccessor = this.createAccessor(indexBufferViewID, 5123, indexBufferView.byteLength / 2, 'SCALAR'); const indexAccessorID = this.addAccessor(indexAccessor); // Output vertex buffer const vertices = geometry.getVertices(); const positionBounds = this.computeBoundsVec3(vertices); const positionBufferView = this.createBufferView(Buffer.from(vertices.buffer)); const positionBufferViewID = this.addBufferView(positionBufferView); const positionAccessor = this.createAccessor(positionBufferViewID, 5126, positionBufferView.byteLength / 4 / 3, 'VEC3', positionBounds.min, positionBounds.max); const positionAccessorID = this.addAccessor(positionAccessor); // Output color buffer let colorAccessorID: number | undefined = undefined; const colors = geometry.getColors(); if (colors) { const colorBufferView = this.createBufferView(Buffer.from(colors.buffer)); const colorBufferViewID = this.addBufferView(colorBufferView); const colorAccessor = this.createAccessor(colorBufferViewID, 5126, colorBufferView.byteLength / 4 / 3, 'VEC3'); colorAccessorID = this.addAccessor(colorAccessor); } mesh.primitives.push({ mode: 1, // LINES attributes: { POSITION: positionAccessorID }, indices: indexAccessorID }); if (!isUndefined(colorAccessorID)) { mesh.primitives[0].attributes['COLOR_0'] = colorAccessorID; } return mesh; } protected createPointGeometry(geometry: IMF.IPointGeometry, imf: IMF.IScene): gltf.Mesh { let mesh: gltf.Mesh = { primitives: [] }; if (this.options.ignorePointGeometry) { return mesh; } // Output vertex buffer const vertices = geometry.getVertices(); const positionBounds = this.computeBoundsVec3(vertices); const positionBufferView = this.createBufferView(Buffer.from(vertices.buffer)); const positionBufferViewID = this.addBufferView(positionBufferView); const positionAccessor = this.createAccessor(positionBufferViewID, 5126, positionBufferView.byteLength / 4 / 3, 'VEC3', positionBounds.min, positionBounds.max); const positionAccessorID = this.addAccessor(positionAccessor); // Output color buffer let colorAccessorID: number | undefined = undefined; const colors = geometry.getColors(); if (colors) { const colorBufferView = this.createBufferView(Buffer.from(colors.buffer)); const colorBufferViewID = this.addBufferView(colorBufferView); const colorAccessor = this.createAccessor(colorBufferViewID, 5126, colorBufferView.byteLength / 4 / 3, 'VEC3'); colorAccessorID = this.addAccessor(colorAccessor); } mesh.primitives.push({ mode: 0, // POINTS attributes: { POSITION: positionAccessorID } }); if (!isUndefined(colorAccessorID)) { mesh.primitives[0].attributes['COLOR_0'] = colorAccessorID; } return mesh; } protected addBufferView(bufferView: gltf.BufferView): number { const bufferViews = this.manifest.bufferViews as gltf.BufferView[]; const hash = this.computeBufferViewHash(bufferView); const match = this.options.deduplicate ? this.bufferViewHashes.indexOf(hash) : -1; if (match !== -1) { this.options.log(`Skipping a duplicate buffer view (${hash})`); this.stats.bufferViewsDeduplicated++; return match; } else { if (this.options.deduplicate) { this.bufferViewHashes.push(hash); } return bufferViews.push(bufferView) - 1; } } protected createBufferView(data: Buffer): gltf.BufferView { const hash = this.computeBufferHash(data); const cache = this.bufferViewCache.get(hash); if (this.options.deduplicate && cache) { this.options.log(`Skipping a duplicate buffer (${hash})`); return cache; } const manifestBuffers = this.manifest.buffers as gltf.Buffer[]; // Prepare new writable stream if needed if (this.bufferStream === null || this.bufferSize > this.options.maxBufferSize) { if (this.bufferStream) { const stream = this.bufferStream as fse.WriteStream; this.pendingTasks.push(new Promise((resolve, reject) => { stream.on('finish', resolve); })); this.bufferStream.close(); this.bufferStream = null; this.bufferSize = 0; } const bufferUri = `${manifestBuffers.length}.bin`; manifestBuffers.push({ uri: bufferUri, byteLength: 0 }); const bufferPath = path.join(this.baseDir, bufferUri); this.bufferStream = fse.createWriteStream(bufferPath); } const bufferID = manifestBuffers.length - 1; const buffer = manifestBuffers[bufferID]; this.bufferStream.write(data); this.bufferSize += data.byteLength; const bufferView = { buffer: bufferID, byteOffset: buffer.byteLength, byteLength: data.byteLength }; buffer.byteLength += bufferView.byteLength; if (buffer.byteLength % 4 !== 0) { // Pad to 4-byte multiples const pad = 4 - buffer.byteLength % 4; this.bufferStream.write(new Uint8Array(pad)); this.bufferSize += pad; buffer.byteLength += pad; } if (this.options.deduplicate) { this.bufferViewCache.set(hash, bufferView); } return bufferView; } protected addAccessor(accessor: gltf.Accessor): number { const accessors = this.manifest.accessors as gltf.Accessor[]; const hash = this.computeAccessorHash(accessor); const match = this.options.deduplicate ? this.accessorHashes.indexOf(hash) : -1; if (match !== -1) { this.options.log(`Skipping a duplicate accessor (${hash})`); this.stats.accessorsDeduplicated++; return match; } else { if (this.options.deduplicate) { this.accessorHashes.push(hash); } return accessors.push(accessor) - 1; } } protected createAccessor(bufferViewID: number, componentType: number, count: number, type: string, min?: number[], max?: number[]): gltf.Accessor { const accessor: gltf.Accessor = { bufferView: bufferViewID, componentType: componentType, count: count, type: type }; if (!isUndefined(min)) { accessor.min = min.map(Math.fround); } if (!isUndefined(max)) { accessor.max = max.map(Math.fround); } return accessor; } protected createMaterial(mat: IMF.Material | null, imf: IMF.IScene): gltf.MaterialPbrMetallicRoughness { // console.log('writing material', mat) if (!mat) { return DefaultMaterial; } const diffuse = mat.diffuse; let material: gltf.MaterialPbrMetallicRoughness = { pbrMetallicRoughness: { baseColorFactor: [diffuse.x, diffuse.y, diffuse.z, 1.0], metallicFactor: mat.metallic, roughnessFactor: mat.roughness } }; if (!isUndefined(mat.opacity) && mat.opacity < 1.0 && material.pbrMetallicRoughness.baseColorFactor) { material.alphaMode = 'BLEND'; material.pbrMetallicRoughness.baseColorFactor[3] = mat.opacity; } if (mat.maps) { const manifestTextures = this.manifest.textures as gltf.Texture[]; if (mat.maps.diffuse) { const textureID = manifestTextures.length; manifestTextures.push(this.createTexture(mat.maps.diffuse, imf)); material.pbrMetallicRoughness.baseColorTexture = { index: textureID, texCoord: 0, extensions: { "KHR_texture_transform": { scale: [mat.scale?.x, mat.scale?.y] } } }; } } return material; } protected createTexture(uri: string, imf: IMF.IScene): gltf.Texture { const manifestImages = this.manifest.images as gltf.Image[]; let imageID = manifestImages.findIndex(image => image.uri === uri); if (imageID === -1) { imageID = manifestImages.length; const normalizedUri = uri.toLowerCase().split(/[\/\\]/).join(path.sep); manifestImages.push({ uri: normalizedUri }); const filePath = path.join(this.baseDir, normalizedUri); fse.ensureDirSync(path.dirname(filePath)); let imageData = imf.getImage(normalizedUri); if (!imageData) { // Default to a placeholder image based on the extension switch (normalizedUri.substr(normalizedUri.lastIndexOf('.'))) { case '.jpg': case '.jpeg': imageData = ImagePlaceholder.JPG; break; case '.png': imageData = ImagePlaceholder.PNG; break; case '.bmp': imageData = ImagePlaceholder.BMP; break; case '.gif': imageData = ImagePlaceholder.GIF; break; default: throw new Error(`Unsupported image format for ${normalizedUri}`); } } fse.writeFileSync(filePath, imageData); } return { source: imageID }; } protected computeMeshHash(mesh: gltf.Mesh): string { return mesh.primitives.map(p => { return `${p.mode || ''}/${p.material || ''}/${p.indices}/${p.attributes['POSITION'] || ''}/${p.attributes['NORMAL'] || ''}/${p.attributes['TEXCOORD_0'] || ''}/${p.attributes['COLOR_0'] || ''}`; }).join('/'); } protected computeBufferViewHash(bufferView: gltf.BufferView): string { return `${bufferView.buffer}/${bufferView.byteLength}/${bufferView.byteOffset || ''}/${bufferView.byteStride || ''}`; } protected computeAccessorHash(accessor: gltf.Accessor): string { return `${accessor.type}/${accessor.componentType}/${accessor.count}/${accessor.bufferView || 'X'}`; } protected computeBufferHash(buffer: Buffer): string { const hash = crypto.createHash('md5'); hash.update(buffer); return hash.digest('hex'); } protected computeMaterialHash(material: IMF.IPhysicalMaterial | null): string { if (!material) { return 'null'; } const hash = crypto.createHash('md5'); hash.update(JSON.stringify(material)); // TODO return hash.digest('hex'); } protected computeBoundsVec3(array: Float32Array): { min: number[], max: number[] } { const min = [array[0], array[1], array[2]]; const max = [array[0], array[1], array[2]]; for (let i = 0; i < array.length; i += 3) { min[0] = Math.min(min[0], array[i]); max[0] = Math.max(max[0], array[i]); min[1] = Math.min(min[1], array[i + 1]); max[1] = Math.max(max[1], array[i + 1]); min[2] = Math.min(min[2], array[i + 2]); max[2] = Math.max(max[2], array[i + 2]); } return { min, max }; } }
the_stack
import { Component, OnInit, OnDestroy, ViewChild, ChangeDetectorRef, ElementRef } from '@angular/core'; import { FormBuilder, FormGroup } from '@angular/forms'; import { IonContent } from '@ionic/angular'; import { CoreError } from '@classes/errors/error'; import { CanLeave } from '@guards/can-leave'; import { CoreApp } from '@services/app'; import { CoreNavigator } from '@services/navigator'; import { CoreSites, CoreSitesCommonWSOptions, CoreSitesReadingStrategy } from '@services/sites'; import { CoreSync } from '@services/sync'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreUrlUtils } from '@services/utils/url'; import { CoreUtils } from '@services/utils/utils'; import { CoreWSExternalFile } from '@services/ws'; import { ModalController, Translate } from '@singletons'; import { CoreEvents } from '@singletons/events'; import { AddonModLessonMenuModalPage } from '../../components/menu-modal/menu-modal'; import { AddonModLesson, AddonModLessonEOLPageDataEntry, AddonModLessonFinishRetakeResponse, AddonModLessonGetAccessInformationWSResponse, AddonModLessonGetPageDataWSResponse, AddonModLessonGetPagesPageWSData, AddonModLessonLaunchAttemptWSResponse, AddonModLessonLessonWSData, AddonModLessonMessageWSData, AddonModLessonPageWSData, AddonModLessonPossibleJumps, AddonModLessonProcessPageOptions, AddonModLessonProcessPageResponse, AddonModLessonProvider, } from '../../services/lesson'; import { AddonModLessonActivityLink, AddonModLessonHelper, AddonModLessonPageButton, AddonModLessonQuestion, } from '../../services/lesson-helper'; import { AddonModLessonOffline } from '../../services/lesson-offline'; import { AddonModLessonSync } from '../../services/lesson-sync'; import { CoreFormFields, CoreForms } from '@singletons/form'; /** * Page that allows attempting and reviewing a lesson. */ @Component({ selector: 'page-addon-mod-lesson-player', templateUrl: 'player.html', styleUrls: ['player.scss'], }) export class AddonModLessonPlayerPage implements OnInit, OnDestroy, CanLeave { @ViewChild(IonContent) content?: IonContent; @ViewChild('questionFormEl') formElement?: ElementRef; component = AddonModLessonProvider.COMPONENT; readonly LESSON_EOL = AddonModLessonProvider.LESSON_EOL; questionForm?: FormGroup; // The FormGroup for question pages. title?: string; // The page title. lesson?: AddonModLessonLessonWSData; // The lesson object. currentPage?: number; // Current page being viewed. review?: boolean; // Whether the user is reviewing. messages: AddonModLessonMessageWSData[] = []; // Messages to display to the user. canManage?: boolean; // Whether the user can manage the lesson. retake?: number; // Current retake number. showRetake?: boolean; // Whether the retake number needs to be displayed. lessonWidth?: string; // Width of the lesson (if slideshow mode). lessonHeight?: string; // Height of the lesson (if slideshow mode). endTime?: number; // End time of the lesson if it's timed. pageData?: AddonModLessonGetPageDataWSResponse; // Current page data. pageContent?: string; // Current page contents. pageButtons?: AddonModLessonPageButton[]; // List of buttons of the current page. question?: AddonModLessonQuestion; // Question of the current page (if it's a question page). eolData?: Record<string, AddonModLessonEOLPageDataEntry>; // Data for EOL page (if current page is EOL). processData?: AddonModLessonProcessPageResponse; // Data to display after processing a page. processDataButtons: ProcessDataButton[] = []; // Buttons to display after processing a page. loaded?: boolean; // Whether data has been loaded. displayMenu?: boolean; // Whether the lesson menu should be displayed. originalData?: CoreFormFields; // Original question data. It is used to check if data has changed. reviewPageId?: number; // Page to open if the user wants to review the attempt. courseId!: number; // The course ID the lesson belongs to. lessonPages?: AddonModLessonPageWSData[]; // Lesson pages (for the lesson menu). loadingMenu?: boolean; // Whether the lesson menu is being loaded. mediaFile?: CoreWSExternalFile; // Media file of the lesson. activityLink?: AddonModLessonActivityLink; // Next activity link data. cmId!: number; // Course module ID. protected password?: string; // Lesson password (if any). protected forceLeave = false; // If true, don't perform any check when leaving the view. protected offline?: boolean; // Whether we are in offline mode. protected accessInfo?: AddonModLessonGetAccessInformationWSResponse; // Lesson access info. protected jumps?: AddonModLessonPossibleJumps; // All possible jumps. protected firstPageLoaded?: boolean; // Whether the first page has been loaded. protected retakeToReview?: number; // Retake to review. protected menuShown = false; // Whether menu is shown. constructor( protected changeDetector: ChangeDetectorRef, protected formBuilder: FormBuilder, ) { } /** * Component being initialized. */ async ngOnInit(): Promise<void> { this.cmId = CoreNavigator.getRouteNumberParam('cmId')!; this.courseId = CoreNavigator.getRouteNumberParam('courseId')!; this.password = CoreNavigator.getRouteParam('password'); this.review = !!CoreNavigator.getRouteBooleanParam('review'); this.currentPage = CoreNavigator.getRouteNumberParam('pageId'); this.retakeToReview = CoreNavigator.getRouteNumberParam('retake'); try { // Fetch the Lesson data. const success = await this.fetchLessonData(); if (success) { // Review data loaded or new retake started, remove any retake being finished in sync. AddonModLessonSync.deleteRetakeFinishedInSync(this.lesson!.id); } } finally { this.loaded = true; } } /** * Component being destroyed. */ ngOnDestroy(): void { if (this.lesson) { // Unblock the lesson so it can be synced. CoreSync.unblockOperation(this.component, this.lesson.id); } } /** * Check if we can leave the page or not. * * @return Resolved if we can leave it, rejected if not. */ async canLeave(): Promise<boolean> { if (this.forceLeave || !this.questionForm) { return true; } if (this.question && !this.eolData && !this.processData && this.originalData) { // Question shown. Check if there is any change. if (!CoreUtils.basicLeftCompare(this.questionForm.getRawValue(), this.originalData, 3)) { await CoreDomUtils.showConfirm(Translate.instant('core.confirmcanceledit')); } } CoreForms.triggerFormCancelledEvent(this.formElement, CoreSites.getCurrentSiteId()); return true; } /** * Runs when the page is about to leave and no longer be the active page. */ ionViewWillLeave(): void { if (this.menuShown) { ModalController.dismiss(); } } /** * A button was clicked. * * @param data Button data. */ buttonClicked(data: Record<string, string>): void { this.processPage(data); } /** * Call a function and go offline if allowed and the call fails. * * @param func Function to call. * @param options Options passed to the function. * @return Promise resolved in success, rejected otherwise. */ protected async callFunction<T>(func: () => Promise<T>, options: CommonOptions): Promise<T> { try { return await func(); } catch (error) { if (this.offline || this.review || !AddonModLesson.isLessonOffline(this.lesson!)) { // Already offline or not allowed. throw error; } if (CoreUtils.isWebServiceError(error)) { // WebService returned an error, cannot perform the action. throw error; } // Go offline and retry. this.offline = true; // Get the possible jumps now. this.jumps = await AddonModLesson.getPagesPossibleJumps(this.lesson!.id, { cmId: this.cmId, readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE, }); // Call the function again with offline mode and the new jumps. options.readingStrategy = CoreSitesReadingStrategy.PREFER_CACHE; options.jumps = this.jumps; options.offline = true; return func(); } } /** * Change the page from menu or when continuing from a feedback page. * * @param pageId Page to load. * @param ignoreCurrent If true, allow loading current page. * @return Promise resolved when done. */ async changePage(pageId: number, ignoreCurrent?: boolean): Promise<void> { if (!ignoreCurrent && !this.eolData && this.currentPage == pageId) { // Page already loaded, stop. return; } this.loaded = true; this.messages = []; try { await this.loadPage(pageId); } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'Error loading page'); } finally { this.loaded = true; } } /** * Get the lesson data and load the page. * * @return Promise resolved with true if success, resolved with false otherwise. */ protected async fetchLessonData(): Promise<boolean> { try { this.lesson = await AddonModLesson.getLesson(this.courseId, this.cmId); this.title = this.lesson.name; // Temporary title. // Block the lesson so it cannot be synced. CoreSync.blockOperation(this.component, this.lesson.id); // Wait for any ongoing sync to finish. We won't sync a lesson while it's being played. await AddonModLessonSync.waitForSync(this.lesson.id); // If lesson has offline data already, use offline mode. this.offline = await AddonModLessonOffline.hasOfflineData(this.lesson.id); if (!this.offline && !CoreApp.isOnline() && AddonModLesson.isLessonOffline(this.lesson) && !this.review) { // Lesson doesn't have offline data, but it allows offline and the device is offline. Use offline mode. this.offline = true; } const options = { cmId: this.cmId, readingStrategy: this.offline ? CoreSitesReadingStrategy.PREFER_CACHE : CoreSitesReadingStrategy.ONLY_NETWORK, }; this.accessInfo = await this.callFunction<AddonModLessonGetAccessInformationWSResponse>( AddonModLesson.getAccessInformation.bind(AddonModLesson.instance, this.lesson.id, options), options, ); const promises: Promise<void>[] = []; this.canManage = this.accessInfo.canmanage; this.retake = this.accessInfo.attemptscount; this.showRetake = !this.currentPage && this.retake > 0; // Only show it in first page if it isn't the first retake. if (this.accessInfo.preventaccessreasons.length) { // If it's a password protected lesson and we have the password, allow playing it. const preventReason = AddonModLesson.getPreventAccessReason(this.accessInfo, !!this.password, this.review); if (preventReason) { // Lesson cannot be played, show message and go back. throw new CoreError(preventReason.message); } } if (this.review && this.retakeToReview != this.accessInfo.attemptscount - 1) { // Reviewing a retake that isn't the last one. Error. throw new CoreError(Translate.instant('addon.mod_lesson.errorreviewretakenotlast')); } if (this.password) { // Lesson uses password, get the whole lesson object. const options = { password: this.password, cmId: this.cmId, readingStrategy: this.offline ? CoreSitesReadingStrategy.PREFER_CACHE : CoreSitesReadingStrategy.ONLY_NETWORK, }; promises.push(this.callFunction<AddonModLessonLessonWSData>( AddonModLesson.getLessonWithPassword.bind(AddonModLesson.instance, this.lesson.id, options), options, ).then((lesson) => { this.lesson = lesson; return; })); } if (this.offline) { // Offline mode, get the list of possible jumps to allow navigation. promises.push(AddonModLesson.getPagesPossibleJumps(this.lesson.id, { cmId: this.cmId, readingStrategy: CoreSitesReadingStrategy.PREFER_CACHE, }).then((jumpList) => { this.jumps = jumpList; return; })); } await Promise.all(promises); this.mediaFile = this.lesson.mediafiles?.[0]; this.lessonWidth = this.lesson.slideshow ? CoreDomUtils.formatPixelsSize(this.lesson.mediawidth!) : ''; this.lessonHeight = this.lesson.slideshow ? CoreDomUtils.formatPixelsSize(this.lesson.mediaheight!) : ''; await this.launchRetake(this.currentPage); return true; } catch (error) { if (this.review && this.retakeToReview && CoreUtils.isWebServiceError(error)) { // The user cannot review the retake. Unmark the retake as being finished in sync. await AddonModLessonSync.deleteRetakeFinishedInSync(this.lesson!.id); } CoreDomUtils.showErrorModalDefault(error, 'core.course.errorgetmodule', true); this.forceLeave = true; CoreNavigator.back(); return false; } } /** * Finish the retake. * * @param outOfTime Whether the retake is finished because the user ran out of time. * @return Promise resolved when done. */ protected async finishRetake(outOfTime?: boolean): Promise<void> { this.messages = []; if (this.offline && CoreApp.isOnline()) { // Offline mode but the app is online. Try to sync the data. const result = await CoreUtils.ignoreErrors( AddonModLessonSync.syncLesson(this.lesson!.id, true, true), ); if (result?.warnings?.length) { // Some data was deleted. Check if the retake has changed. const info = await AddonModLesson.getAccessInformation(this.lesson!.id, { cmId: this.cmId, }); if (info.attemptscount != this.accessInfo!.attemptscount) { // The retake has changed. Leave the view and show the error. this.forceLeave = true; CoreNavigator.back(); throw new CoreError(result.warnings[0]); } // Retake hasn't changed, show the warning and finish the retake in offline. CoreDomUtils.showErrorModal(result.warnings[0]); } this.offline = false; } // Now finish the retake. const options = { password: this.password, outOfTime, review: this.review, offline: this.offline, accessInfo: this.accessInfo, }; const data = await this.callFunction<AddonModLessonFinishRetakeResponse>( AddonModLesson.finishRetake.bind(AddonModLesson.instance, this.lesson, this.courseId, options), options, ); this.title = this.lesson!.name; this.eolData = data.data; this.messages = this.messages.concat(data.messages); this.processData = undefined; CoreEvents.trigger(CoreEvents.ACTIVITY_DATA_SENT, { module: 'lesson' }); // Format activity link if present. if (this.eolData.activitylink) { this.activityLink = AddonModLessonHelper.formatActivityLink(<string> this.eolData.activitylink.value); } else { this.activityLink = undefined; } // Format review lesson if present. if (this.eolData.reviewlesson) { const params = CoreUrlUtils.extractUrlParams(<string> this.eolData.reviewlesson.value); if (!params || !params.pageid) { // No pageid in the URL, the user cannot review (probably didn't answer any question). delete this.eolData.reviewlesson; } else { this.reviewPageId = Number(params.pageid); } } } /** * Jump to a certain page after performing an action. * * @param pageId The page to load. * @return Promise resolved when done. */ protected async jumpToPage(pageId: number): Promise<void> { if (pageId === 0) { // Not a valid page, return to entry view. // This happens, for example, when the user clicks to go to previous page and there is no previous page. this.forceLeave = true; CoreNavigator.back(); return; } else if (pageId == AddonModLessonProvider.LESSON_EOL) { // End of lesson reached. return this.finishRetake(); } // Load new page. this.messages = []; return this.loadPage(pageId); } /** * Start or continue a retake. * * @param pageId The page to load. * @return Promise resolved when done. */ protected async launchRetake(pageId?: number): Promise<void> { let data: AddonModLessonLaunchAttemptWSResponse | undefined; if (this.review) { // Review mode, no need to launch the retake. } else if (!this.offline) { // Not in offline mode, launch the retake. data = await AddonModLesson.launchRetake(this.lesson!.id, this.password, pageId); } else { // Check if there is a finished offline retake. const finished = await AddonModLessonOffline.hasFinishedRetake(this.lesson!.id); if (finished) { // Always show EOL page. pageId = AddonModLessonProvider.LESSON_EOL; } } this.currentPage = pageId || this.accessInfo!.firstpageid; this.messages = data?.messages || []; if (this.lesson!.timelimit && !this.accessInfo!.canmanage) { // Get the last lesson timer. const timers = await AddonModLesson.getTimers(this.lesson!.id, { cmId: this.cmId, readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK, }); this.endTime = timers[timers.length - 1].starttime + this.lesson!.timelimit; } return this.loadPage(this.currentPage); } /** * Load the lesson menu. * * @return Promise resolved when done. */ protected async loadMenu(): Promise<void> { if (this.loadingMenu) { // Already loading. return; } try { this.loadingMenu = true; const options = { password: this.password, cmId: this.cmId, readingStrategy: this.offline ? CoreSitesReadingStrategy.PREFER_CACHE : CoreSitesReadingStrategy.ONLY_NETWORK, }; const pages = await this.callFunction<AddonModLessonGetPagesPageWSData[]>( AddonModLesson.getPages.bind(AddonModLesson.instance, this.lesson!.id, options), options, ); this.lessonPages = pages.map((entry) => entry.page); } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'Error loading menu.'); } finally { this.loadingMenu = false; } } /** * Load a certain page. * * @param pageId The page to load. * @return Promise resolved when done. */ protected async loadPage(pageId: number): Promise<void> { if (pageId == AddonModLessonProvider.LESSON_EOL) { // End of lesson reached. return this.finishRetake(); } const options = { password: this.password, review: this.review, includeContents: true, cmId: this.cmId, readingStrategy: this.offline ? CoreSitesReadingStrategy.PREFER_CACHE : CoreSitesReadingStrategy.ONLY_NETWORK, accessInfo: this.accessInfo, jumps: this.jumps, includeOfflineData: true, }; const data = await this.callFunction<AddonModLessonGetPageDataWSResponse>( AddonModLesson.getPageData.bind(AddonModLesson.instance, this.lesson, pageId, options), options, ); if (data.newpageid == AddonModLessonProvider.LESSON_EOL) { // End of lesson reached. return this.finishRetake(); } this.pageData = data; this.title = data.page!.title; this.pageContent = AddonModLessonHelper.getPageContentsFromPageData(data); this.loaded = true; this.currentPage = pageId; this.messages = this.messages.concat(data.messages); // Page loaded, hide EOL and feedback data if shown. this.eolData = this.processData = undefined; if (AddonModLesson.isQuestionPage(data.page!.type)) { // Create an empty FormGroup without controls, they will be added in getQuestionFromPageData. this.questionForm = this.formBuilder.group({}); this.pageButtons = []; this.question = AddonModLessonHelper.getQuestionFromPageData(this.questionForm, data); this.originalData = this.questionForm.getRawValue(); // Use getRawValue to include disabled values. } else { this.pageButtons = AddonModLessonHelper.getPageButtonsFromHtml(data.pagecontent || ''); this.question = undefined; this.originalData = undefined; } // Don't display the navigation menu in review mode, using them displays errors. if (data.displaymenu && !this.displayMenu && !this.review) { // Load the menu. this.loadMenu(); } this.displayMenu = !this.review && !!data.displaymenu; if (!this.firstPageLoaded) { this.firstPageLoaded = true; } else { this.showRetake = false; } } /** * Process a page, sending some data. * * @param data The data to send. * @param formSubmitted Whether a form was submitted. * @return Promise resolved when done. */ protected async processPage(data: CoreFormFields, formSubmitted?: boolean): Promise<void> { this.loaded = false; const options: AddonModLessonProcessPageOptions = { password: this.password, review: this.review, offline: this.offline, accessInfo: this.accessInfo, jumps: this.jumps, }; try { const result = await this.callFunction<AddonModLessonProcessPageResponse>( AddonModLesson.processPage.bind( AddonModLesson.instance, this.lesson, this.courseId, this.pageData, data, options, ), options, ); if (formSubmitted) { CoreForms.triggerFormSubmittedEvent( this.formElement, result.sent, CoreSites.getCurrentSiteId(), ); } if (!this.offline && !this.review && AddonModLesson.isLessonOffline(this.lesson!)) { // Lesson allows offline and the user changed some data in server. Update cached data. const retake = this.accessInfo!.attemptscount; const options = { cmId: this.cmId, readingStrategy: CoreSitesReadingStrategy.ONLY_NETWORK, }; // Update in background the list of content pages viewed or question attempts. if (AddonModLesson.isQuestionPage(this.pageData?.page?.type || -1)) { AddonModLesson.getQuestionsAttemptsOnline(this.lesson!.id, retake, options); } else { AddonModLesson.getContentPagesViewedOnline(this.lesson!.id, retake, options); } } if (result.nodefaultresponse || result.inmediatejump) { // Don't display feedback or force a redirect to a new page. Load the new page. return await this.jumpToPage(result.newpageid); } // Not inmediate jump, show the feedback. result.feedback = AddonModLessonHelper.removeQuestionFromFeedback(result.feedback); this.messages = result.messages; this.processData = result; this.processDataButtons = []; if (this.lesson!.review && !result.correctanswer && !result.noanswer && !result.isessayquestion && !result.maxattemptsreached && !result.reviewmode) { // User can try again, show button to do so. this.processDataButtons.push({ label: 'addon.mod_lesson.reviewquestionback', pageId: this.currentPage!, }); } // Button to continue. if (this.lesson!.review && !result.correctanswer && !result.noanswer && !result.isessayquestion && !result.maxattemptsreached) { /* If both the "Yes, I'd like to try again" and "No, I just want to go on to the next question" point to the same page then don't show the "No, I just want to go on to the next question" button. It's confusing. */ if (this.pageData!.page!.id != result.newpageid) { // Button to continue the lesson (the page to go is configured by the teacher). this.processDataButtons.push({ label: 'addon.mod_lesson.reviewquestioncontinue', pageId: result.newpageid, }); } } else { this.processDataButtons.push({ label: 'addon.mod_lesson.continue', pageId: result.newpageid, }); } } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'Error processing page'); } finally { this.loaded = true; } } /** * Review the lesson. * * @param pageId Page to load. */ async reviewLesson(pageId: number): Promise<void> { this.loaded = false; this.review = true; this.offline = false; // Don't allow offline mode in review. try { await this.loadPage(pageId); } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'Error loading page'); } finally { this.loaded = true; } } /** * Submit a question. * * @param e Event. */ submitQuestion(e: Event): void { e.preventDefault(); e.stopPropagation(); this.loaded = false; // Use getRawValue to include disabled values. const data = AddonModLessonHelper.prepareQuestionData(this.question!, this.questionForm!.getRawValue()); this.processPage(data, true).finally(() => { this.loaded = true; }); } /** * Time up. */ async timeUp(): Promise<void> { // Time up called, hide the timer. this.endTime = undefined; this.loaded = false; try { await this.finishRetake(true); } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'Error finishing attempt'); } finally { this.loaded = true; } } /** * Show the navigation modal. * * @return Promise resolved when done. */ async showMenu(): Promise<void> { this.menuShown = true; await CoreDomUtils.openSideModal({ component: AddonModLessonMenuModalPage, componentProps: { pageInstance: this, }, }); this.menuShown = false; } } /** * Common options for functions called using callFunction. */ type CommonOptions = CoreSitesCommonWSOptions & { jumps?: AddonModLessonPossibleJumps; offline?: boolean; }; /** * Button displayed after processing a page. */ type ProcessDataButton = { label: string; pageId: number; };
the_stack