text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { getAbandonSeedAddress } from "@ledgerhq/cryptoassets"; import { log } from "@ledgerhq/logs"; import { from } from "rxjs"; import secp256k1 from "secp256k1"; import invariant from "invariant"; import { TransportStatusError, WrongDeviceForAccount } from "@ledgerhq/errors"; import { delay } from "../../promise"; import Exchange from "../hw-app-exchange/Exchange"; import { mockInitSwap } from "./mock"; import perFamily from "../../generated/exchange"; import { getAccountCurrency, getMainAccount, getAccountUnit, } from "../../account"; import network from "../../network"; import { getAccountBridge } from "../../bridge"; import { BigNumber } from "bignumber.js"; import { SwapGenericAPIError, TransactionRefusedOnDevice } from "../../errors"; import type { SwapRequestEvent, InitSwapInput } from "./types"; import { Observable } from "rxjs"; import { withDevice } from "../../hw/deviceAccess"; import { getProviderNameAndSignature, getSwapAPIBaseURL } from "./"; import { getCurrencyExchangeConfig } from "../"; import { getEnv } from "../../env"; import { TRANSACTION_RATES, TRANSACTION_TYPES, } from "../hw-app-exchange/Exchange"; const withDevicePromise = (deviceId, fn) => withDevice(deviceId)((transport) => from(fn(transport))).toPromise(); // init a swap with the Exchange app // throw if TransactionStatus have errors // you get at the end a final Transaction to be done (it's not yet signed, nor broadcasted!) and a swapId const initSwap = (input: InitSwapInput): Observable<SwapRequestEvent> => { let { transaction } = input; const { exchange, exchangeRate, deviceId, userId } = input; if (getEnv("MOCK")) return mockInitSwap(exchange, exchangeRate, transaction); return new Observable((o) => { let unsubscribed = false; const confirmSwap = async () => { let swapId; let ignoreTransportError; log("swap", `attempt to connect to ${deviceId}`); await withDevicePromise(deviceId, async (transport) => { const ratesFlag = exchangeRate.tradeMethod === "fixed" ? TRANSACTION_RATES.FIXED : TRANSACTION_RATES.FLOATING; const swap = new Exchange(transport, TRANSACTION_TYPES.SWAP, ratesFlag); // NB this id is crucial to prevent replay attacks, if it changes // we need to start the flow again. const deviceTransactionId = await swap.startNewTransaction(); if (unsubscribed) return; const { provider, rateId, payoutNetworkFees } = exchangeRate; const { fromParentAccount, fromAccount, toParentAccount, toAccount } = exchange; const { amount } = transaction; const refundCurrency = getAccountCurrency(fromAccount); const unitFrom = getAccountUnit(exchange.fromAccount); const unitTo = getAccountUnit(exchange.toAccount); const payoutCurrency = getAccountCurrency(toAccount); const refundAccount = getMainAccount(fromAccount, fromParentAccount); const payoutAccount = getMainAccount(toAccount, toParentAccount); const apiAmount = new BigNumber(amount).div( new BigNumber(10).pow(unitFrom.magnitude) ); // Request a swap, this locks the rates for fixed trade method only. // NB Added the try/catch because of the API stability issues. let res; try { res = await network({ method: "POST", url: `${getSwapAPIBaseURL()}/swap`, headers: { EquipmentId: getEnv("USER_ID"), ...(userId ? { userId } : {}), }, data: { provider, amountFrom: apiAmount, from: refundCurrency.id, to: payoutCurrency.id, address: payoutAccount.freshAddress, refundAddress: refundAccount.freshAddress, deviceTransactionId, ...(rateId ? { rateId, } : {}), // NB float rates dont need rate ids. }, }); if (unsubscribed || !res || !res.data) return; } catch (e) { o.next({ type: "init-swap-error", error: new SwapGenericAPIError(), }); o.complete(); return; } const swapResult = res.data; swapId = swapResult.swapId; const providerNameAndSignature = getProviderNameAndSignature( swapResult.provider ); const accountBridge = getAccountBridge(refundAccount); transaction = accountBridge.updateTransaction(transaction, { recipient: swapResult.payinAddress, }); if (refundCurrency.id === "ripple") { transaction = accountBridge.updateTransaction(transaction, { tag: new BigNumber(swapResult.payinExtraId).toNumber(), }); invariant( transaction.tag, "Refusing to swap xrp without a destination tag" ); } else if (refundCurrency.id === "stellar") { transaction = accountBridge.updateTransaction(transaction, { memoValue: swapResult.payinExtraId, memoType: "MEMO_TEXT", }); invariant( transaction.memoValue, "Refusing to swap xlm without a destination memo" ); } // Triplecheck we're not working with an abandonseed recipient anymore invariant( transaction.recipient !== getAbandonSeedAddress( refundCurrency.type === "TokenCurrency" ? refundCurrency.parentCurrency.id : refundCurrency.id ), "Recipient address should never be the abandonseed address" ); transaction = await accountBridge.prepareTransaction( refundAccount, transaction ); if (unsubscribed) return; const { errors, estimatedFees } = await accountBridge.getTransactionStatus(refundAccount, transaction); if (unsubscribed) return; const errorsKeys = Object.keys(errors); if (errorsKeys.length > 0) { throw errors[errorsKeys[0]]; // throw the first error } // Prepare swap app to receive the tx to forward. await swap.setPartnerKey(providerNameAndSignature.nameAndPubkey); if (unsubscribed) return; await swap.checkPartner(providerNameAndSignature.signature); if (unsubscribed) return; await swap.processTransaction( Buffer.from(swapResult.binaryPayload, "hex"), estimatedFees ); if (unsubscribed) return; const goodSign = <Buffer>( secp256k1.signatureExport(Buffer.from(swapResult.signature, "hex")) ); await swap.checkTransactionSignature(goodSign); if (unsubscribed) return; const mainPayoutCurrency = getAccountCurrency(payoutAccount); invariant( mainPayoutCurrency.type === "CryptoCurrency", "This should be a cryptocurrency" ); // FIXME: invariant not triggering typescriptp type guard if (mainPayoutCurrency.type !== "CryptoCurrency") { throw new Error("This should be a cryptocurrency"); } const payoutAddressParameters = await perFamily[ mainPayoutCurrency.family ].getSerializedAddressParameters( payoutAccount.freshAddressPath, payoutAccount.derivationMode, mainPayoutCurrency.id ); if (unsubscribed) return; const { config: payoutAddressConfig, signature: payoutAddressConfigSignature, } = getCurrencyExchangeConfig(payoutCurrency); try { await swap.checkPayoutAddress( payoutAddressConfig, payoutAddressConfigSignature, payoutAddressParameters.addressParameters ); } catch (e) { // @ts-expect-error TransportStatusError to be typed on ledgerjs if (e instanceof TransportStatusError && e.statusCode === 0x6a83) { throw new WrongDeviceForAccount(undefined, { accountName: payoutAccount.name, }); } throw e; } if (unsubscribed) return; const mainRefundCurrency = getAccountCurrency(refundAccount); invariant( mainRefundCurrency.type === "CryptoCurrency", "This should be a cryptocurrency" ); // FIXME: invariant not triggering typescriptp type guard if (mainRefundCurrency.type !== "CryptoCurrency") { throw new Error("This should be a cryptocurrency"); } const refundAddressParameters = await perFamily[ mainRefundCurrency.family ].getSerializedAddressParameters( refundAccount.freshAddressPath, refundAccount.derivationMode, mainRefundCurrency.id ); if (unsubscribed) return; const { config: refundAddressConfig, signature: refundAddressConfigSignature, } = getCurrencyExchangeConfig(refundCurrency); if (unsubscribed) return; // NB Floating rates may change the original amountTo so we can pass an override // to properly render the amount on the device confirmation steps. Although changelly // made the calculation inside the binary payload, we still have to deal with it here // to not break their other clients. let amountExpectedTo; if (swapResult?.amountExpectedTo) { amountExpectedTo = new BigNumber(swapResult.amountExpectedTo) .times(new BigNumber(10).pow(unitTo.magnitude)) .minus(new BigNumber(payoutNetworkFees || 0)) .toString(); } o.next({ type: "init-swap-requested", amountExpectedTo, estimatedFees, }); try { await swap.checkRefundAddress( refundAddressConfig, refundAddressConfigSignature, refundAddressParameters.addressParameters ); } catch (e) { // @ts-expect-error TransportStatusError to be typed on ledgerjs if (e instanceof TransportStatusError && e.statusCode === 0x6a83) { throw new WrongDeviceForAccount(undefined, { accountName: refundAccount.name, }); } throw e; } if (unsubscribed) return; ignoreTransportError = true; await swap.signCoinTransaction(); }).catch((e) => { if (ignoreTransportError) return; // @ts-expect-error TransportStatusError to be typed on ledgerjs if (e instanceof TransportStatusError && e.statusCode === 0x6a84) { throw new TransactionRefusedOnDevice(); } throw e; }); if (!swapId) return; log("swap", "awaiting device disconnection"); await delay(3000); if (unsubscribed) return; o.next({ type: "init-swap-result", initSwapResult: { transaction, swapId, }, }); }; confirmSwap().then( () => { o.complete(); unsubscribed = true; }, (e) => { o.next({ type: "init-swap-error", error: e, }); o.complete(); unsubscribed = true; } ); return () => { unsubscribed = true; }; }); }; export default initSwap;
the_stack
import {useEffect, useState} from "react"; import {CameraOutlined, EyeOutlined, SaveOutlined, SendOutlined} from '@ant-design/icons'; import {Button, Input, Modal, Radio} from "antd"; import Form from "antd/es/form"; import Row from "antd/es/grid/row"; import Col from "antd/es/grid/col"; import Divider from "antd/es/divider"; import Title from "antd/es/typography/Title"; import Card from "antd/es/card"; import Dragger from "antd/es/upload/Dragger"; import Switch from "antd/es/switch"; import TextArea from "antd/es/input/TextArea"; import {message} from "antd/es"; import Image from "antd/es/image"; import jquery from 'jquery'; import MyEditorMdWrapper, {ChangedContent} from "./editor/my-editormd-wrapper"; import './article-edit.less' import Constants, {getRes} from "../../utils/constants"; import screenfull from "screenfull"; import ArticleEditTag from "./article-edit-tag"; import axios from "axios"; import {UploadChangeParam} from "antd/es/upload"; const md5 = require('md5'); export type ArticleEntry = ChangedContent & { keywords?: string, rubbish?: boolean, alias?: string, logId?: number, digest?: string, thumbnail?: string, version: number, } type ArticleEditState = { types: [], typeOptions: any[], tags: any[], globalLoading: boolean, article: ArticleEntry, fullScreen: boolean, editorInitSuccess: boolean, } type ActicleSavingState = { rubbishSaving: boolean, savedVersion: number, previewIng: boolean, releaseSaving: boolean, } const ArticleEdit = () => { const [state, setState] = useState<ArticleEditState>({ typeOptions: [], article: { version: 0, }, editorInitSuccess: false, fullScreen: false, globalLoading: true, tags: [], types: [] }) const [savingState, setSavingState] = useState<ActicleSavingState>({ previewIng: false, releaseSaving: false, rubbishSaving: false, savedVersion: 0, }) const rubbish = async (preview: boolean) => { await onSubmit(state.article, true, false, preview); } useEffect(() => { axios.get("/api/admin/article/global").then(({data}) => { const options: any[] = []; data.data.types.forEach((x: any) => { options.push(<Radio style={{display: "block"}} key={x.id} value={x.id}>{x.typeName}</Radio>); }) const nDate = data; const query = new URLSearchParams(window.location.search); const id = query.get("id"); if (id !== null && id !== '') { axios.get("/api/admin/article/detail?id=" + id).then(({data}) => { if (data.error) { message.error(data.message); return; } setState({ ...state, globalLoading: false, article: data.data, typeOptions: options, types: nDate.data.types, tags: nDate.data.tags, }) }) } else { setState({ ...state, typeOptions: options, types: nDate.data.types, tags: nDate.data.tags, globalLoading: false }); } }); }, []) const getCurrentSignVersion = (allValues: ArticleEntry | undefined) => { const signObj = JSON.parse(JSON.stringify(allValues)); //version会改变随着保存,所以不参与变更检查 delete signObj.version; return md5(JSON.stringify(signObj)); } const onSubmit = async (allValues: ArticleEntry, release: boolean, preview: boolean, autoSave: boolean) => { allValues.rubbish = !release; allValues.keywords = jquery("#keywords").val() as unknown as string; let uri; const create = allValues!.logId === undefined; if (create) { uri = '/api/admin/article/create'; } else { uri = '/api/admin/article/update'; } const currentVersion = getCurrentSignVersion(allValues); //自动保存模式下,没有变化 if (autoSave && currentVersion === savingState.savedVersion) { return; } if (release) { setSavingState({ ...savingState, releaseSaving: true }) } else { setSavingState({ ...savingState, rubbishSaving: true, previewIng: preview, }) } exitTips(getRes()['articleEditExitWithOutSaveSuccess']); if (allValues.version < state.article.version) { return; } await axios.post(uri, allValues).then(({data}) => { if (data.error) { Modal.error({ title: '保存失败', content: data.message, okText: '确认' }); return; } exitNotTips(); if (release) { message.info(getRes()['releaseSuccess']); } else { if (!autoSave) { message.info(getRes()['saveSuccess']); } if (preview) { window.open(document.baseURI + "post/" + allValues!.logId, '_blank'); } } const respData = data.data; //当前文本已经存在了,就不用服务器端的覆盖了 if (allValues!.alias && allValues!.alias !== '') { delete respData.alias; } if (allValues!.digest && allValues!.digest !== '') { delete respData.digest; } setState({ ...state, article: {...state, ...respData} }) setSavingState({ ...savingState, savedVersion: currentVersion }) if (create) { const url = new URL(window.location.href); url.searchParams.set('id', data.data.logId); window.history.replaceState(null, "", url.toString()); } }).catch((e) => { let msg; if (e.error) { msg = e.message; } else { msg = e.toString(); } Modal.error({ title: "保存失败", content: msg, okText: '确认' }); }).finally(() => { if (release) { setSavingState({ ...savingState, releaseSaving: false }) } else { setSavingState({ ...savingState, rubbishSaving: false, previewIng: preview, }) } }); } const getArticleRoute = () => { if (state === undefined || getRes() === undefined || getRes()['articleRoute'] === undefined) { return ""; } return getRes()['articleRoute']; } const gup = (name: string, url: string) => { // eslint-disable-next-line const results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(url); if (!results) { return undefined; } return results[1] || undefined; } const setThumbnailHeight = (url: string) => { let h = Number.parseInt(gup("h", url) + ""); if (h) { const originW = Number.parseInt(jquery("#thumbnail").width() + ""); const w = Number.parseInt(gup("w", url) + ""); jquery("#thumbnail").width(w / originW * h); } } const onUploadChange = async (info: UploadChangeParam) => { const {status} = info.file; if (status === 'done') { //message.success(`${info.file.name} file uploaded successfully.`); setThumbnailHeight(info.file.response.data.url); await autoSaveToRubbish({thumbnail: info.file.response.data.url}, 0) } else if (status === 'error') { message.error(`${info.file.name} file upload failed.`); } }; const onfullscreen = (editor: any) => { if (screenfull.isEnabled) { screenfull.request().then(() => { setState({ ...state, fullScreen: true, }); }); screenfull.on('change', () => { //@ts-ignore if (!screenfull.isFullscreen) { editor.fullscreenExit(); } }); } else { setState({ ...state, fullScreen: true, }); } } const onfullscreenExit = () => { setState({ ...state, fullScreen: false, }); //@ts-ignore screenfull.exit(); } const exitTips = (tips: string) => { window.onbeforeunload = function () { return tips; }; } const exitNotTips = () => { window.onbeforeunload = null; } const save = async (article: ArticleEntry) => { //如果正在保存,尝试1s后再检查下 if (savingState.rubbishSaving || savingState.releaseSaving) { setTimeout(() => { save(article) }, 1000); return; } await onSubmit(article, false, false, true); }; const autoSaveToRubbish = (changedValues: any, delayMs: number) => { //editor loading /*if (!state.editorInitSuccess) { return; }*/ setTimeout(async () => { await save({...state.article, ...changedValues}) }, delayMs); } if (state.globalLoading) { return <></> } return ( <> <Title className='page-header' level={3}>{getRes()['admin.log.edit'] + (state.article!.rubbish ? '-当前为草稿' : '')}</Title> <Divider/> <Form onValuesChange={(_k, v) => autoSaveToRubbish(v, 0)} initialValues={state.article} onFinish={() => onSubmit(state.article, true, false, false)}> <Form.Item name='logId' style={{display: "none"}}> <Input hidden={true}/> </Form.Item> <Form.Item name='thumbnail' style={{display: "none"}}> <Input hidden={true}/> </Form.Item> <Form.Item name='rubbish' style={{display: "none"}}> <Input hidden={true}/> </Form.Item> <Form.Item name='markdown' style={{display: "none"}}> <Input hidden={true}/> </Form.Item> <Form.Item name='content' style={{display: "none"}}> <Input hidden={true}/> </Form.Item> <Row gutter={[8, 8]} style={{paddingBottom: "5px"}}> <Col md={14} xxl={18} sm={6} span={0}/> <Col xxl={2} md={4} sm={6} className={state.fullScreen ? 'saveToRubbish-btn-full-screen' : ''}> <Button type={state.fullScreen ? 'default' : "ghost"} block={true} loading={savingState.rubbishSaving} onClick={() => rubbish(false)}> <SaveOutlined hidden={savingState.rubbishSaving}/> {savingState.rubbishSaving ? getRes().saving : getRes().saveAsDraft} </Button> </Col> <Col xxl={2} md={3} sm={6}> <Button type="ghost" loading={savingState.rubbishSaving && savingState.previewIng} block={true} onClick={() => rubbish(true)}> <EyeOutlined/> {getRes().preview} </Button> </Col> <Col xxl={2} md={3} sm={6} className={state.fullScreen ? 'save-btn-full-screen' : ''}> <Button id='save' type='primary' loading={savingState.releaseSaving} block={true} htmlType='submit'> <SendOutlined/> {getRes().release}</Button> </Col> </Row> <Row gutter={8}> <Col md={8} xs={24}> <Form.Item style={{marginBottom: 8}} name="title" rules={[{required: true, message: getRes().inputArticleTitle}]}> <Input placeholder={getRes().inputArticleTitle}/> </Form.Item> </Col> <Col md={5} xs={24}> <Form.Item style={{marginBottom: 8}} name="alias"> <Input addonBefore={getArticleRoute() + "/"} placeholder={getRes().inputArticleAlias}/> </Form.Item> </Col> <Col md={5} xs={0}> </Col> </Row> <Row gutter={[8, 8]}> <Col md={18} xs={24} style={{zIndex: 10}}> {!state.globalLoading && <MyEditorMdWrapper onfullscreen={onfullscreen} onfullscreenExit={onfullscreenExit} markdown={state.article!.markdown} loadSuccess={() => { setState({...state, editorInitSuccess: true}) } } autoSaveToRubbish={autoSaveToRubbish}/> } </Col> <Col md={6} xs={24}> <Row gutter={[8, 8]}> <Col span={24}> <Card size="small" style={{textAlign: 'center'}}> <Dragger accept={"image/*"} action={"/api/admin/upload/thumbnail?dir=thumbnail"} name='imgFile' onChange={(e) => onUploadChange(e)}> {(state.article!.thumbnail === undefined || state.article!.thumbnail === null || state.article!.thumbnail === '') && ( <> <p className="ant-upload-drag-icon" style={{height: '88px'}}> <CameraOutlined style={{fontSize: "28px", paddingTop: '40px'}}/> </p> <p className="ant-upload-text">拖拽或点击,上传文章封面</p> </> )} {state.article!.thumbnail !== '' && ( <Image fallback={Constants.getFillBackImg()} preview={false} id='thumbnail' src={state.article!.thumbnail}/> )} </Dragger> </Card> </Col> <Col span={24}> <Card size="small" title={getRes()['admin.setting']}> <Row> <Col xs={24} md={12}> <Form.Item style={{marginBottom: 0}} valuePropName="checked" name='canComment' label={getRes()['commentAble']}> <Switch size="small"/> </Form.Item> </Col> <Col xs={24} md={12}> <Form.Item style={{marginBottom: 0}} valuePropName="checked" name='privacy' label={getRes()['private']}> <Switch size="small"/> </Form.Item> </Col> </Row> </Card> </Col> <Col span={24}> <Card size="small" title={getRes()['admin.type.manage']}> <Form.Item label='' style={{marginBottom: 0}} name='typeId' rules={[{ required: true, message: "请选择" + getRes()['admin.type.manage'] }]}> <Radio.Group style={{width: "100%"}}> {state.typeOptions} </Radio.Group> </Form.Item> </Card> </Col> <Col span={24}> <Card size="small" title={getRes().tag}> <ArticleEditTag keywords={state.article!.keywords} allTags={state.tags.map(x => x.text)}/> </Card> </Col> <Col span={24}> <Card size="small" title={getRes().digest}> <Form.Item style={{marginBottom: 0}} name='digest'> <TextArea placeholder={getRes().digestTips} rows={3}/> </Form.Item> </Card> </Col> </Row> </Col> </Row> </Form> </> ) } export default ArticleEdit;
the_stack
import type { AttachJsonRpcTransport, AttachMessageTransport, AttachProtocolTransport, AttachSession, Cancellation, DebugCallback, DetachSession, ErrorResponse, Notification, OnClose, OnError, OnEvent, OnMessage, OnNotification, ProtocolError, ProtocolTransport, RaceCancellation, Request, Response, ResponseError, SendMessage, SendMethod, SendRequest, SuccessResponse, Task, } from "@tracerbench/protocol-transport"; import type { Protocol } from "devtools-protocol"; import type { ProtocolMapping } from "devtools-protocol/types/protocol-mapping"; export type { AttachJsonRpcTransport, AttachMessageTransport, AttachProtocolTransport, AttachSession, Cancellation, DebugCallback, DetachSession, ErrorResponse, Notification, OnClose, OnError, OnEvent, OnMessage, OnNotification, Protocol, ProtocolMapping, ProtocolError, ProtocolTransport, RaceCancellation, Request, Response, ResponseError, SendMessage, SendMethod, SendRequest, SuccessResponse, Task, }; export type ProtocolConnection = SessionConnection | RootConnection; export interface SessionConnection extends ProtocolConnectionBase { readonly sessionId: SessionID; readonly targetId: TargetID; readonly targetInfo: TargetInfo; } export interface RootConnection extends ProtocolConnectionBase { readonly sessionId?: undefined; readonly targetId?: undefined; readonly targetInfo?: undefined; } export interface ProtocolConnectionBase { /** * Whether the connection is still attached. */ readonly isDetached: boolean; /** * Use to race an async task against the connection detaching. */ readonly raceDetached: RaceCancellation; /** * Get a connection for a currently attached session. * * If the session is not attached this will throw. * * Should be used with Target.attachToTarget or Target.createTarget * * @param sessionId the session id or a obj with a sessionId or a targetId */ connection( sessionId: SessionIdentifier, throwIfNotAttached?: true, ): SessionConnection; /** * Get a connection for a currently attached session. * * If throwIfNotAttached is undefined or true, it will throw if session is not attached, * otherwise it returns undefined. * * @param sessionId the session id or a obj with a sessionId or a targetId * @param throwIfNotAttached whether to throw if session is not attached, defaults to true. */ connection( sessionId: SessionIdentifier, throwIfNotAttached: boolean | undefined, ): SessionConnection | undefined; /** * Attaches to a target and returns the SessionConnection, if the target is already attached, * it returns the existing SessionConnection. * * This is a convenience for ensuring that flattened sessions are used it is the same as * ```js * conn.connection(await conn.send("Target.attachToTarget", { targetId, flatten: true })); * ``` * * You can either use with Target.createTarget or the Target.setDiscoverTargets method and * Target.targetCreated events. * * https://chromedevtools.github.io/devtools-protocol/tot/Target#method-attachToTarget */ attachToTarget( targetId: TargetID | { targetId: TargetID }, raceCancellation?: RaceCancellation, ): Promise<SessionConnection>; /** * This will cause Target.attachedToTarget events to fire for related targets. * * This is a convenience for ensuring that flattened sessions are used it is the same as * * ```js * await conn.send("Target.setAutoAttach", { autoAttach, waitForDebuggerOnStart, flatten: true }); * ``` * https://chromedevtools.github.io/devtools-protocol/tot/Target#method-setAutoAttach * * You suscribe to the Target.attachedToTarget event and use the connection method to get * the connection for the attached session. If it isn't a target you are interested in * you must detach from it or it will stay alive until you set auto attach to false. This * can be an issue with testing service workers. * * ```js * conn.on("Target.attachedToTarget", event => { * const session = conn.connection(event); * }) * ``` * * @param autoAttach auto attach flag * @param waitForDebuggerOnStart whether the debugger should wait target to be attached. */ setAutoAttach( autoAttach: boolean, waitForDebuggerOnStart?: boolean, raceCancellation?: RaceCancellation, ): Promise<void>; /** * Cancellable send of a request and wait for response. This * already races against closing the connection but you can * pass in another raceCancellation concern like a timeout. * * See documentation of DevTools API for documentation of methods * https://chromedevtools.github.io/devtools-protocol/tot * * The request and reponse types are provide by the devtools-protocol * peer dependency. * * @param method the DevTools API method * @param request required request parameters * @param raceCancellation * @returns a promise of the method's result. */ send<M extends MappedRequestMethod>( method: M, request: RequestMapping[M], raceCancellation?: RaceCancellation, ): Promise<ResponseMapping[M]>; /** * Cancellable send of a request and wait for response. This * already races against closing the connection but you can * pass in another raceCancellation concern like a timeout. * * See documentation of DevTools API for documentation of methods * https://chromedevtools.github.io/devtools-protocol/tot * * The request and reponse types are provide by the devtools-protocol * peer dependency. * * @param method the DevTools API method * @param request optional request parameters * @param raceCancellation * @returns a promise of the method's result. */ send<M extends MaybeMappedRequestMethod>( method: M, request?: RequestMapping[M], raceCancellation?: RaceCancellation, ): Promise<ResponseMapping[M]>; /** * Cancellable send of a request and wait for response. This * already races against session detached/transport close * but you can pass in another raceCancellation concern * like a timeout. * * See documentation of DevTools API for documentation of methods * https://chromedevtools.github.io/devtools-protocol/tot * * The request and reponse types are provide by the devtools-protocol * peer dependency. * * @param method the DevTools API method * @param request this request takes no params or empty pojo * @param raceCancellation * @returns a promise of the method's result. */ send<M extends VoidRequestMappedResponseMethod>( method: M, request?: object, raceCancellation?: RaceCancellation, ): Promise<ResponseMapping[M]>; /** * Cancellable send of a request and wait for response. This * already races against session detached/transport close * but you can pass in another raceCancellation concern * like a timeout. * * See documentation of DevTools API for documentation of methods * https://chromedevtools.github.io/devtools-protocol/tot * * The request and reponse types are provide by the devtools-protocol * peer dependency. * * @param method the DevTools API method * @param request this request takes no params or empty pojo * @param raceCancellation * @returns a promise of the method completion. */ send( method: VoidRequestVoidResponseMethod, request?: undefined, raceCancellation?: RaceCancellation, ): Promise<void>; /** * Subscribe to an event. * @param event name of event * @param listener callback with event object */ on<E extends MappedEvent>( event: E, listener: (event: EventMapping[E]) => void, ): void; /** * Subscribe to an event. * @param event name of event * @param listener void callback */ on(event: VoidEvent, listener: () => void): void; off<E extends MappedEvent>( event: E, listener: (event: EventMapping[E]) => void, ): void; off(event: VoidEvent, listener: () => void): void; once<E extends MappedEvent>( event: E, listener: (event: EventMapping[E]) => void, ): void; once(event: VoidEvent, listener: () => void): void; removeListener<E extends MappedEvent>( event: E, listener: (event: EventMapping[E]) => void, ): void; removeListener(event: VoidEvent, listener: () => void): void; removeAllListeners(event?: Event): void; /** * Cancellable promise of an event with an optional predicate function * to check whether the event is the one you are waiting for. * * See documentation of DevTools API for documentation of events * https://chromedevtools.github.io/devtools-protocol/tot * * Event types are provided by the devtools-protocol peer dependency. * * @param event the name of the event * @param predicate optional callback to test event object whether to resolve the until * @param raceCancellation additional cancellation concern, until already races against session detached/transport close. */ until<E extends MappedEvent>( event: E, predicate?: EventPredicate<EventMapping[E]>, raceCancellation?: RaceCancellation, ): Promise<EventMapping[E]>; /** * Cancellable promise of an event. * * See documentation of DevTools API for documentation of events * https://chromedevtools.github.io/devtools-protocol/tot * * @param event the name of the event * @param predicate this event doesn't have an object so this will be undefined * @param raceCancellation additional cancellation concern, until already races against detachment. */ until( event: VoidEvent, predicate?: () => boolean, raceCancellation?: RaceCancellation, ): Promise<void>; } export type EventListener = (...args: any[]) => void; export interface EventEmitter { on(event: string, listener: EventListener): void; once(event: string, listener: EventListener): void; removeListener(event: string, listener: EventListener): void; removeAllListeners(event?: string): void; emit(event: string, ...args: any[]): void; } export type EventPredicate<Event> = (event: Event) => boolean; export type NewEventEmitter = () => EventEmitter; export type TargetID = Protocol.Target.TargetID; export type TargetInfo = Protocol.Target.TargetInfo; export type SessionID = Protocol.Target.SessionID; export type Method = keyof ProtocolMapping.Commands; export type Event = keyof ProtocolMapping.Events | "error" | "detached"; export type EventMapping = { [E in keyof ProtocolMapping.Events]: ProtocolMapping.Events[E] extends [ (infer T)?, ] ? T : never; } & { error: Error; }; export type RequestMapping = { [M in Method]: ProtocolMapping.Commands[M]["paramsType"] extends [(infer T)?] ? T : never; }; export type ResponseMapping = { [M in Method]: ProtocolMapping.Commands[M]["returnType"]; }; export type VoidRequestMethod = { [M in Method]: ProtocolMapping.Commands[M]["paramsType"] extends [] ? M : never; }[Method]; export type MappedRequestMethod = { [M in Method]: ProtocolMapping.Commands[M]["paramsType"] extends [infer T] ? M : never; }[Method]; export type MaybeMappedRequestMethod = Exclude< Method, VoidRequestMethod | MappedRequestMethod >; export type VoidResponseMethod = { [M in Method]: ProtocolMapping.Commands[M]["returnType"] extends void ? M : never; }[Method]; export type MappedResponseMethod = Exclude<Method, VoidResponseMethod>; export type VoidRequestVoidResponseMethod = Extract< MaybeMappedRequestMethod | VoidRequestMethod, VoidResponseMethod >; export type VoidRequestMappedResponseMethod = Exclude< MaybeMappedRequestMethod | VoidRequestMethod, VoidRequestVoidResponseMethod >; export type VoidEvent = | { [E in keyof ProtocolMapping.Events]: ProtocolMapping.Events[E] extends [] ? E : never; }[keyof ProtocolMapping.Events] | "detached"; export type MappedEvent = Exclude<Event, VoidEvent> | "error"; export type SessionIdentifier = | SessionID | { targetId: TargetID; } | { sessionId: SessionID; };
the_stack
import { isIsomorphicApp } from './iso-component'; import { resolveAssetsPath, getStaticBucketName } from '../libs/iso-libs'; import * as deepmerge from 'deepmerge'; import { IConfigParseResult } from '../libs/config-parse-result'; import {IPlugin, forwardChildIamRoleStatements} from '../libs/plugin'; import { PARSER_MODES } from '../libs/parser'; /** * Parameters that apply to the whole Plugin, passed by other plugins */ export interface IIsoPlugin { /** * one of the [[PARSER_MODES]] */ parserMode: string, /** * path to a directory where we put the final bundles */ buildPath: string, /** * path to the main config file */ configFilePath: string } /** * A Plugin to detect Isomorphic-App-Components * @param props */ export const IsoPlugin = (props: IIsoPlugin): IPlugin => { //console.log("configFilePath: " , props.configFilePath); const result: IPlugin = { // identify Isomorphic-App-Components applies: (component): boolean => { return isIsomorphicApp(component); }, // convert the component into configuration parts process: ( component: any, childConfigs: Array<IConfigParseResult>, infrastructureMode: string | undefined ): IConfigParseResult => { const path = require('path'); // we use the hardcoded name `server` as name const serverName = "server"; const serverBuildPath = path.join(require("../../../infrastructure-scripts/dist/infra-comp-utils/system-libs").currentAbsolutePath(), props.buildPath); // the isomorphic app has a server application const serverWebPack = require("../../../infrastructure-scripts/dist/infra-comp-utils/webpack-libs").complementWebpackConfig( require("../../../infrastructure-scripts/dist/infra-comp-utils/webpack-libs").createServerWebpackConfig( "./"+path.join("node_modules", "infrastructure-components", "dist" , "assets", "server.js"), //entryPath: string, serverBuildPath, //use the buildpath from the parent plugin serverName, // name of the server { __CONFIG_FILE_PATH__: require("../../../infrastructure-scripts/dist/infra-comp-utils/system-libs").pathToConfigFile(props.configFilePath), // replace the IsoConfig-Placeholder with the real path to the main-config-bundle // required of data-layer, makes the context match! "infrastructure-components": path.join( require("../../../infrastructure-scripts/dist/infra-comp-utils/system-libs").currentAbsolutePath(), "node_modules", "infrastructure-components", "dist", "index.js"), // required of the routed-app "react-router-dom": path.join( require("../../../infrastructure-scripts/dist/infra-comp-utils/system-libs").currentAbsolutePath(), "node_modules", "react-router-dom"), // required of the data-layer / apollo "react-apollo": path.join( require("../../../infrastructure-scripts/dist/infra-comp-utils/system-libs").currentAbsolutePath(), "node_modules", "react-apollo"), }, { __ISOMORPHIC_ID__: `"${component.instanceId}"`, __ASSETS_PATH__: `"${component.assetsPath}"`, __DATALAYER_ID__: `"${component.dataLayerId}"`, __ISOFFLINE__: props.parserMode === PARSER_MODES.MODE_START, __RESOLVED_ASSETS_PATH__: `"${resolveAssetsPath( component.buildPath, serverName, component.assetsPath ) }"` // TODO add replacements of datalayers here! } ), props.parserMode === PARSER_MODES.MODE_DEPLOY //isProd ); const domain = childConfigs.map(config => config.domain).reduce((result, domain) => result !== undefined ? result : domain, undefined); const certArn = childConfigs.map(config => config.certArn).reduce((result, certArn) => result !== undefined ? result : certArn, undefined); const environments = childConfigs.reduce((result, config) => (result !== undefined ? result : []).concat(config.environments !== undefined ? config.environments : []), []); // provide all client configs in a flat list const webpackConfigs: any = childConfigs.reduce((result, config) => result.concat( config.webpackConfigs.map(wp => wp({ // when we deploy an Isomorphic App without a domain, we need to add the stagename! stagePath: props.parserMode === PARSER_MODES.MODE_DEPLOY && domain == undefined && environments !== undefined && environments.length > 0 ? environments[0].name : undefined })) ), []); const copyAssetsPostBuild = () => { //console.log("check for >>copyAssetsPostBuild<<"); if (props.parserMode !== PARSER_MODES.MODE_DOMAIN && props.parserMode !== PARSER_MODES.MODE_DEPLOY) { // always copy the assets, unless we setup the domain console.log("copyAssetsPostBuild: now copy the assets!"); webpackConfigs.map(config => require("../../../infrastructure-scripts/dist/infra-comp-utils/system-libs").copyAssets( config.output.path, path.join(serverBuildPath, serverName, component.assetsPath))); } else { // delete the assets folder for we don't want to include all these bundled files in the deployment-package const rimraf = require("rimraf"); rimraf.sync(path.join(serverBuildPath, serverName, component.assetsPath)); } }; /* const postDeploy = async () => { console.log("check for >>postDeploy<<"); if (props.parserMode === PARSER_MODES.MODE_DEPLOY) { var endpointUrl = undefined; var eps: any = {}; await require("../../../infrastructure-scripts/dist/infra-comp-utils/sls-libs").runSlsCmd("echo $(sls info)", data => { //console.log("data: " , data); eps = data.split(" ").reduce(({inSection, endpoints}, val, idx) => { //console.log("eval: " , val); if (inSection && val.indexOf("https://") > -1) { return { inSection: true, endpoints: endpoints.concat( val.indexOf("{proxy+}") == -1 ? [val] : [] )} } if (val.startsWith("endpoints:")) { return { inSection: true, endpoints: endpoints } } if (val.startsWith("functions:")) { return { inSection: false, endpoints: endpoints } } return { inSection: inSection, endpoints: endpoints } }, {inSection: false, endpoints: []}); //console.log("endpoints" , eps) }, false); const data = Object.assign({ proj: component.stackName, envi: component.name, domain: domain }, eps.endpoints.length > 0 ? { endp: eps.endpoints[0]} : {}); await require('../libs/scripts-libs').fetchData("deploy", data); if (eps.endpoints.length > 0) { console.log("Your React-App is now available at: ", eps.endpoints[0]) } } }*/ /* async function uploadAssetsPostBuild () { //console.log("check for >>copyAssetsPostBuild<<"); if (props.parserMode === PARSER_MODES.MODE_DEPLOY) { // always copy the assets, unless we setup the domain console.log("uploadAssetsPostBuild: now copy the assets!"); const staticBucketName = getStaticBucketName(component.stackName, component.assetsPath, stage); // copy the client apps to the assets-folder console.log("start S3 Sync"); await Promise.all( // only copy webapps webpackConfigs.filter(wpConfig => wpConfig.target === "web").map(async wpConfig => { await s3sync(component.region, staticBucketName, path.join(component.buildPath, wpConfig.name)) }) ); //webpackConfigs.map(config => require("../../../infrastructure-scripts/dist/infra-comp-utils/system-libs").copyAssets( config.output.path, path.join(serverBuildPath, serverName, component.assetsPath))); } };*/ async function initDomain () { //console.log("check for >>initDomain<<"); if (props.parserMode === PARSER_MODES.MODE_DOMAIN) { console.log("initDomain!") await require("../../../infrastructure-scripts/dist/infra-comp-utils/sls-libs").initDomain(component.stackName); } } const domainConfig = domain !== undefined ? { plugins: ["serverless-domain-manager"], custom: { customDomain: { domainName: domain, basePath: "''", stage: "${self:provider.stage, env:STAGE, 'dev'}", createRoute53Record: true } } } : {}; const envS3Config = { provider: { environment: { BUCKET_ID: "${self:provider.staticBucket}", } } }; const additionalStatements: Array<any> = forwardChildIamRoleStatements(childConfigs).concat( component.iamRoleStatements ? component.iamRoleStatements : [] ); //console.log("additionalStatements: ", additionalStatements); const iamRoleAssignment = { functions: {} }; iamRoleAssignment.functions[serverName] = { role: "IsomorphicAppLambdaRole" }; const iamPermissions = { resources: { Resources: { IsomorphicAppLambdaRole: { Type: "AWS::IAM::Role", Properties: { RoleName: "${self:service}-${self:provider.stage, env:STAGE, 'dev'}-IsomorphicAppLambdaRole", AssumeRolePolicyDocument: { Version: '"2012-10-17"', Statement: [ { Effect: "Allow", Principal: { Service: ["lambda.amazonaws.com"] }, Action: "sts:AssumeRole" } ] }, Policies: [ { PolicyName: "${self:service}-${self:provider.stage, env:STAGE, 'dev'}-IsomorphicAppLambdaPolicy", PolicyDocument: { Version: '"2012-10-17"', Statement: [ { Effect: "Allow", Action: [ '"logs:*"', '"cloudwatch:*"' ], Resource: '"*"' }, { Effect: "Allow", Action: [ "s3:Get*", "s3:List*", "s3:Put*", "s3:Delete*", ], Resource: { "Fn::Join": '["", ["arn:aws:s3:::", {"Ref": "StaticBucket" }, "/*"]]' } }, ].concat(additionalStatements) } } ] } }, /*ProxyMethod: { Properties: { Integration: { Uri: "https://${self:provider.staticBucket}.s3-${self:provider.region}.amazonaws.com/{proxy}" } } //"https://${self:provider.staticBucket}/{proxy}" },*/ }, } } return { stackType: "ISO", slsConfigs: deepmerge.all([ require("../../../infrastructure-scripts/dist/infra-comp-utils/sls-libs").toSlsConfig( component.stackName, serverName, component.buildPath, component.assetsPath, component.region), // # allows running the stack locally on the dev-machine { plugins: ["serverless-offline", "serverless-pseudo-parameters"], custom: { "serverless-offline": { host: "0.0.0.0", port: "${self:provider.port, env:PORT, '3000'}" } } }, // add the domain config domainConfig, ...childConfigs.map(config => config.slsConfigs), // add the IAM-Role-Statements iamPermissions, // assign the role // assign the role iamRoleAssignment, // set the bucket as an env envS3Config ]), // add the server config webpackConfigs: webpackConfigs.concat([serverWebPack]), postBuilds: childConfigs.reduce((result, config) => result.concat(config.postBuilds), [copyAssetsPostBuild, initDomain /*, postDeploy*/]), iamRoleStatements: [], environments: environments, stackName: component.stackName, assetsPath: component.assetsPath, buildPath: component.buildPath, region: component.region, domain: domain, certArn: certArn, supportOfflineStart: true, supportCreateDomain: true } } } return result; };
the_stack
import * as assert from 'assert' import * as Automerge from 'automerge' import { Backend, Frontend, Counter, Doc } from 'automerge' const UUID_PATTERN = /^[0-9a-f]{32}$/ interface BirdList { birds: Automerge.List<string> } interface NumberBox { number: number } describe('TypeScript support', () => { describe('Automerge.init()', () => { it('should allow a document to be `any`', () => { let s1 = Automerge.init<any>() s1 = Automerge.change(s1, doc => (doc.key = 'value')) assert.strictEqual(s1.key, 'value') assert.strictEqual(s1.nonexistent, undefined) assert.deepStrictEqual(s1, { key: 'value' }) }) it('should allow a document type to be specified as a parameter to `init`', () => { let s1 = Automerge.init<BirdList>() // Note: Technically, `s1` is not really a `BirdList` yet but just an empty object. assert.equal(s1.hasOwnProperty('birds'), false) // Since we're pulling the wool over TypeScript's eyes, it can't give us compile-time protection // from something like this: // assert.equal(s1.birds.length, 0) // Runtime error: Cannot read property 'length' of undefined // Nevertheless this way seems more ergonomical (than having `init` return a type of `{}` or // `Partial<T>`, for example) because it allows us to have a single type for the object // throughout its life, rather than having to recast it once its required fields have // been populated. s1 = Automerge.change(s1, doc => (doc.birds = ['goldfinch'])) assert.deepStrictEqual(s1.birds, ['goldfinch']) }) it('should allow a document type to be specified on the result of `init`', () => { // This is equivalent to passing the type parameter to `init`; note that the result is a // `Doc`, which is frozen let s1: Doc<BirdList> = Automerge.init() let s2 = Automerge.change(s1, doc => (doc.birds = ['goldfinch'])) assert.deepStrictEqual(s2.birds, ['goldfinch']) }) it('should allow a document to be initialized with `from`', () => { const s1 = Automerge.from<BirdList>({ birds: [] }) assert.strictEqual(s1.birds.length, 0) const s2 = Automerge.change(s1, doc => doc.birds.push('magpie')) assert.strictEqual(s2.birds[0], 'magpie') }) it('should allow passing options when initializing with `from`', () => { const actorId = '1234' const s1 = Automerge.from<BirdList>({ birds: [] }, actorId) assert.strictEqual(Automerge.getActorId(s1), '1234') const s2 = Automerge.from<BirdList>({ birds: [] }, { actorId }) assert.strictEqual(Automerge.getActorId(s2), '1234') }) it('should allow the actorId to be configured', () => { let s1 = Automerge.init<BirdList>('111111') assert.strictEqual(Automerge.getActorId(s1), '111111') let s2 = Automerge.init<BirdList>() assert.strictEqual(UUID_PATTERN.test(Automerge.getActorId(s2)), true) }) it('should allow the freeze option to be passed in', () => { let s1 = Automerge.init<BirdList>({ freeze: true }) let s2 = Automerge.change(s1, doc => (doc.birds = [])) assert.strictEqual(Object.isFrozen(s2), true) assert.strictEqual(Object.isFrozen(s2.birds), true) }) it('should allow a frontend to be `any`', () => { const s0 = Frontend.init<any>() const [s1, req1] = Frontend.change(s0, doc => (doc.key = 'value')) assert.strictEqual(s1.key, 'value') assert.strictEqual(s1.nonexistent, undefined) assert.strictEqual(UUID_PATTERN.test(Frontend.getActorId(s1)), true) }) it('should allow a frontend type to be specified', () => { const s0 = Frontend.init<BirdList>() const [s1, req1] = Frontend.change(s0, doc => (doc.birds = ['goldfinch'])) assert.strictEqual(s1.birds[0], 'goldfinch') assert.deepStrictEqual(s1, { birds: ['goldfinch'] }) }) it('should allow a frontend actorId to be configured', () => { const s0 = Frontend.init<NumberBox>('111111') assert.strictEqual(Frontend.getActorId(s0), '111111') }) it('should allow frontend actorId assignment to be deferred', () => { const s0 = Frontend.init<NumberBox>({ deferActorId: true }) assert.strictEqual(Frontend.getActorId(s0), undefined) const s1 = Frontend.setActorId(s0, 'abcdef1234') const [s2, req] = Frontend.change(s1, doc => (doc.number = 15)) assert.deepStrictEqual(s2, { number: 15 }) }) it('should allow a frontend to be initialized with `from`', () => { const [s1, req1] = Frontend.from<BirdList>({ birds: [] }) assert.strictEqual(s1.birds.length, 0) const [s2, req2] = Frontend.change(s1, doc => doc.birds.push('magpie')) assert.strictEqual(s2.birds[0], 'magpie') }) it('should allow options to be passed to Frontend.from()', () => { const [s1, req1] = Frontend.from<BirdList>({ birds: []}, { actorId: '1234' }) assert.strictEqual(Frontend.getActorId(s1), '1234') assert.deepStrictEqual(s1, { birds: [] }) const [s2, req2] = Frontend.from<BirdList>({ birds: []}, '1234') assert.strictEqual(Frontend.getActorId(s2), '1234') }) it('should allow the length of the array to be increased', () => { let s1: Doc<BirdList> = Automerge.from({ birds: []}) let s2 = Automerge.change(s1, doc => doc.birds.length = 1) assert.deepStrictEqual(s2.birds, [null]) }) it('should allow the length of the array to be decreased', () => { let s1: Doc<BirdList> = Automerge.from({ birds: ['1234']}) let s2 = Automerge.change(s1, doc => doc.birds.length = 0) assert.deepStrictEqual(s2.birds, []) }) it('should throw error if length is invalid', () => { let s1: Doc<BirdList> = Automerge.from({ birds: ['1234']}) assert.throws(() => Automerge.change(s1, doc => { doc.birds.length = undefined }), "array length") assert.throws(() => Automerge.change(s1, doc => { doc.birds.length = NaN }), "array length") }) }) describe('saving and loading', () => { it('should allow an `any` type document to be loaded', () => { let s1 = Automerge.init<any>() s1 = Automerge.change(s1, doc => (doc.key = 'value')) let s2: any = Automerge.load(Automerge.save(s1)) assert.strictEqual(s2.key, 'value') assert.deepStrictEqual(s2, { key: 'value' }) }) it('should allow a document of declared type to be loaded', () => { let s1 = Automerge.init<BirdList>() s1 = Automerge.change(s1, doc => (doc.birds = ['goldfinch'])) let s2 = Automerge.load<BirdList>(Automerge.save(s1)) assert.strictEqual(s2.birds[0], 'goldfinch') assert.deepStrictEqual(s2, { birds: ['goldfinch'] }) assert.strictEqual(UUID_PATTERN.test(Automerge.getActorId(s2)), true) }) it('should allow the actorId to be configured', () => { let s1 = Automerge.init<BirdList>() s1 = Automerge.change(s1, doc => (doc.birds = ['goldfinch'])) let s2 = Automerge.load<BirdList>(Automerge.save(s1), '111111') assert.strictEqual(Automerge.getActorId(s2), '111111') }) it('should allow the freeze option to be passed in', () => { let s1 = Automerge.init<BirdList>() s1 = Automerge.change(s1, doc => (doc.birds = ['goldfinch'])) let s2 = Automerge.load<BirdList>(Automerge.save(s1), { freeze: true }) assert.strictEqual(Object.isFrozen(s2), true) assert.strictEqual(Object.isFrozen(s2.birds), true) }) }) describe('making changes', () => { it('should accept an optional message', () => { let s1 = Automerge.init<BirdList>() s1 = Automerge.change(s1, 'hello', doc => (doc.birds = [])) assert.strictEqual(Automerge.getHistory(s1)[0].change.message, 'hello') }) it('should support list modifications', () => { let s1: Doc<BirdList> = Automerge.init<BirdList>() s1 = Automerge.change(s1, doc => (doc.birds = ['goldfinch'])) s1 = Automerge.change(s1, doc => { doc.birds.insertAt(1, 'greenfinch', 'bullfinch', 'chaffinch') doc.birds.deleteAt(0) doc.birds.deleteAt(0, 2) }) assert.deepStrictEqual(s1, { birds: ['chaffinch'] }) }) it('should allow empty changes', () => { let s1 = Automerge.init() s1 = Automerge.emptyChange(s1, 'my message') assert.strictEqual(Automerge.getHistory(s1)[0].change.message, 'my message') }) it('should allow inspection of conflicts', () => { let s1 = Automerge.init<NumberBox>('111111') s1 = Automerge.change(s1, doc => (doc.number = 3)) let s2 = Automerge.init<NumberBox>('222222') s2 = Automerge.change(s2, doc => (doc.number = 42)) let s3 = Automerge.merge(s1, s2) assert.strictEqual(s3.number, 42) assert.deepStrictEqual( Automerge.getConflicts(s3, 'number'), { '1@111111': 3, '1@222222': 42 }) }) it('should allow changes in the frontend', () => { const s0 = Frontend.init<BirdList>() const [s1, change1] = Frontend.change(s0, doc => (doc.birds = ['goldfinch'])) const [s2, change2] = Frontend.change(s1, doc => doc.birds.push('chaffinch')) assert.strictEqual(s2.birds[1], 'chaffinch') assert.deepStrictEqual(s2, { birds: ['goldfinch', 'chaffinch'] }) assert.strictEqual(change2.actor, Frontend.getActorId(s0)) assert.strictEqual(change2.seq, 2) assert.strictEqual(change2.time > 0, true) assert.strictEqual(change2.message, '') }) it('should accept a message in the frontend', () => { const s0 = Frontend.init<NumberBox>() const [s1, req1] = Frontend.change(s0, 'test message', doc => (doc.number = 1)) assert.strictEqual(req1.message, 'test message') assert.strictEqual(req1.actor, Frontend.getActorId(s0)) assert.strictEqual(req1.ops.length, 1) }) it('should allow empty changes in the frontend', () => { const s0 = Frontend.init<NumberBox>() const [s1, req1] = Frontend.emptyChange(s0, 'nothing happened') assert.strictEqual(req1.message, 'nothing happened') assert.strictEqual(req1.actor, Frontend.getActorId(s0)) assert.strictEqual(req1.ops.length, 0) }) it('should work with split frontend and backend', () => { const s0 = Frontend.init<NumberBox>(), b0 = Backend.init() const [s1, change1] = Frontend.change(s0, doc => (doc.number = 1)) const [b1, patch1] = Backend.applyLocalChange(b0, change1) const s2 = Frontend.applyPatch(s1, patch1) assert.strictEqual(s2.number, 1) assert.strictEqual(patch1.actor, Automerge.getActorId(s0)) assert.strictEqual(patch1.seq, 1) assert.strictEqual(patch1.diffs.objectId, '_root') assert.strictEqual(patch1.diffs.type, 'map') assert.deepStrictEqual(Object.keys(patch1.diffs.props), ['number']) const value = patch1.diffs.props.number[`1@${Automerge.getActorId(s0)}`] assert.strictEqual((value as Automerge.ValueDiff).value, 1) }) }) describe('getting and applying changes', () => { it('should return an array of change objects', () => { let s1 = Automerge.init<BirdList>() s1 = Automerge.change(s1, doc => (doc.birds = ['goldfinch'])) let s2 = Automerge.change(s1, 'add chaffinch', doc => doc.birds.push('chaffinch')) const changes = Automerge.getChanges(s1, s2) assert.strictEqual(changes.length, 1) const change = Automerge.decodeChange(changes[0]) assert.strictEqual(change.message, 'add chaffinch') assert.strictEqual(change.actor, Automerge.getActorId(s2)) assert.strictEqual(change.seq, 2) }) it('should include operations in changes', () => { let s1 = Automerge.init<NumberBox>() s1 = Automerge.change(s1, doc => (doc.number = 3)) const changes = Automerge.getAllChanges(s1) assert.strictEqual(changes.length, 1) const change = Automerge.decodeChange(changes[0]) assert.strictEqual(change.ops.length, 1) assert.strictEqual(change.ops[0].action, 'set') assert.strictEqual(change.ops[0].obj, '_root') assert.strictEqual(change.ops[0].key, 'number') assert.strictEqual(change.ops[0].value, 3) }) it('should allow changes to be re-applied', () => { let s1 = Automerge.init<BirdList>() s1 = Automerge.change(s1, doc => (doc.birds = [])) let s2 = Automerge.change(s1, doc => doc.birds.push('goldfinch')) const changes = Automerge.getAllChanges(s2) let [s3, patch] = Automerge.applyChanges(Automerge.init<BirdList>(), changes) assert.deepStrictEqual(s3.birds, ['goldfinch']) }) it('should allow concurrent changes to be merged', () => { let s1 = Automerge.init<BirdList>() s1 = Automerge.change(s1, doc => (doc.birds = ['goldfinch'])) let s2 = Automerge.merge(Automerge.init<BirdList>(), s1) s1 = Automerge.change(s1, doc => doc.birds.unshift('greenfinch')) s2 = Automerge.change(s2, doc => doc.birds.push('chaffinch')) let s3 = Automerge.merge(s1, s2) assert.deepStrictEqual(s3.birds, ['greenfinch', 'goldfinch', 'chaffinch']) }) }) describe('history inspection', () => { it('should inspect document history', () => { const s0 = Automerge.init<NumberBox>() const s1 = Automerge.change(s0, 'one', doc => (doc.number = 1)) const s2 = Automerge.change(s1, 'two', doc => (doc.number = 2)) const history = Automerge.getHistory(s2) assert.strictEqual(history.length, 2) assert.strictEqual(history[0].change.message, 'one') assert.strictEqual(history[1].change.message, 'two') assert.strictEqual(history[0].snapshot.number, 1) assert.strictEqual(history[1].snapshot.number, 2) }) }) describe('state inspection', () => { it('should support looking up objects by ID', () => { const s0 = Automerge.init<BirdList>() const s1 = Automerge.change(s0, doc => (doc.birds = ['goldfinch'])) const obj = Automerge.getObjectId(s1.birds) assert.strictEqual(Automerge.getObjectById(s1, obj).length, 1) assert.strictEqual(Automerge.getObjectById(s1, obj), s1.birds) }) it('should allow looking up list element IDs', () => { const s0 = Automerge.init<BirdList>() const s1 = Automerge.change(s0, doc => (doc.birds = ['goldfinch'])) const elemIds = Automerge.Frontend.getElementIds(s1.birds) assert.deepStrictEqual(elemIds, [`2@${Automerge.getActorId(s1)}`]) }) }) describe('Automerge.Text', () => { interface TextDoc { text: Automerge.Text } let doc: Doc<TextDoc> beforeEach(() => { doc = Automerge.change(Automerge.init<TextDoc>(), doc => (doc.text = new Automerge.Text())) }) describe('insertAt', () => { it('should support inserting a single element', () => { doc = Automerge.change(doc, doc => doc.text.insertAt(0, 'abc')) assert.strictEqual(JSON.stringify(doc.text), '"abc"') }) it('should support inserting multiple elements', () => { doc = Automerge.change(doc, doc => doc.text.insertAt(0, 'a', 'b', 'c')) assert.strictEqual(JSON.stringify(doc.text), '"abc"') }) }) describe('deleteAt', () => { beforeEach(() => { doc = Automerge.change(doc, doc => doc.text.insertAt(0, 'a', 'b', 'c', 'd', 'e', 'f', 'g')) }) it('should support deleting a single element without specifying `numDelete`', () => { doc = Automerge.change(doc, doc => doc.text.deleteAt(2)) assert.strictEqual(JSON.stringify(doc.text), '"abdefg"') }) it('should support deleting multiple elements', () => { doc = Automerge.change(doc, doc => doc.text.deleteAt(3, 2)) assert.strictEqual(JSON.stringify(doc.text), '"abcfg"') }) }) describe('get', () => { it('should get the element at the given index', () => { doc = Automerge.change(doc, doc => doc.text.insertAt(0, 'a', 'b', 'cdefg', 'hi', 'jkl')) assert.strictEqual(doc.text.get(0), 'a') assert.strictEqual(doc.text.get(2), 'cdefg') }) }) describe('delegated read-only operations from `Array`', () => { const a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] beforeEach(() => { doc = Automerge.change(doc, doc => doc.text.insertAt(0, ...a)) }) it('supports `indexOf`', () => assert.strictEqual(doc.text.indexOf('c'), 2)) it('supports `length`', () => assert.strictEqual(doc.text.length, 9)) it('supports `concat`', () => assert.strictEqual(doc.text.concat(['j']).length, 10)) it('supports `includes`', () => assert.strictEqual(doc.text.includes('q'), false)) }) describe('getElementIds', () => { it('should return the element ID of each character', () => { doc = Automerge.change(doc, doc => doc.text.insertAt(0, 'a', 'b')) const elemIds = Automerge.Frontend.getElementIds(doc.text) assert.deepStrictEqual(elemIds, [`2@${Automerge.getActorId(doc)}`, `3@${Automerge.getActorId(doc)}`]) }) }) }) describe('Automerge.Table', () => { interface Book { authors: string | string[] title: string isbn?: string } interface BookDb { books: Automerge.Table<Book> } // Example data const DDIA: Book = { authors: ['Kleppmann, Martin'], title: 'Designing Data-Intensive Applications', isbn: '1449373321', } const RSDP: Book = { authors: ['Cachin, Christian', 'Guerraoui, Rachid', 'Rodrigues, Luís'], title: 'Introduction to Reliable and Secure Distributed Programming', isbn: '3-642-15259-7', } let s1: Doc<BookDb> let id: Automerge.UUID let ddiaWithId: Book & Automerge.TableRow beforeEach(() => { s1 = Automerge.change(Automerge.init<BookDb>(), doc => { doc.books = new Automerge.Table() id = doc.books.add(DDIA) }) ddiaWithId = Object.assign({id}, DDIA) }) it('supports `byId`', () => assert.deepStrictEqual(s1.books.byId(id), ddiaWithId)) it('supports `count`', () => assert.strictEqual(s1.books.count, 1)) it('supports `ids`', () => assert.deepStrictEqual(s1.books.ids, [id])) it('supports iteration', () => assert.deepStrictEqual([...s1.books], [ddiaWithId])) it('allows adding row properties', () => { // Note that if we add columns and want to actually use them, we need to recast the table to a // new type e.g. without the `ts-ignore` flag, this would throw a type error: // @ts-ignore - Property 'publisher' does not exist on type book const p2 = s1.books.byId(id).publisher // So we need to create new types interface BookDeluxe extends Book { // ... existing properties, plus: publisher?: string } interface BookDeluxeDb { books: Automerge.Table<BookDeluxe> } const s2 = s1 as Doc<BookDeluxeDb> // Cast existing table to new type const s3 = Automerge.change( s2, doc => (doc.books.byId(id).publisher = "O'Reilly") ) // Now we're off to the races const p3 = s3.books.byId(id).publisher assert.strictEqual(p3, "O'Reilly") }) it('supports `remove`', () => { const s2 = Automerge.change(s1, doc => doc.books.remove(id)) assert.strictEqual(s2.books.count, 0) }) describe('supports `add`', () => { it('accepts value passed as object', () => { let bookId: string const s2 = Automerge.change(s1, doc => (bookId = doc.books.add(RSDP))) assert.deepStrictEqual(s2.books.byId(bookId), Object.assign({id: bookId}, RSDP)) assert.strictEqual(s2.books.byId(bookId).id, bookId) }) }) describe('standard array operations on rows', () => { it('returns a list of rows', () => assert.deepEqual(s1.books.rows, [ddiaWithId])) it('supports `filter`', () => assert.deepStrictEqual(s1.books.filter(book => book.authors.length === 1), [ddiaWithId])) it('supports `find`', () => { assert.deepStrictEqual(s1.books.find(book => book.isbn === '1449373321'), ddiaWithId)}) it('supports `map`', () => assert.deepStrictEqual(s1.books.map<string>(book => book.title), [DDIA.title])) }) }) describe('Automerge.Counter', () => { interface CounterMap { [name: string]: Counter } interface CounterList { counts: Counter[] } interface BirdCounterMap { birds: CounterMap } it('should handle counters inside maps', () => { const doc1 = Automerge.change(Automerge.init<CounterMap>(), doc => { doc.wrens = new Counter() }) assert.equal(doc1.wrens, 0) const doc2 = Automerge.change(doc1, doc => { doc.wrens.increment() }) assert.equal(doc2.wrens, 1) }) it('should handle counters inside lists', () => { const doc1 = Automerge.change(Automerge.init<CounterList>(), doc => { doc.counts = [new Counter(1)] }) assert.equal(doc1.counts[0], 1) const doc2 = Automerge.change(doc1, doc => { doc.counts[0].increment(2) }) assert.equal(doc2.counts[0].value, 3) }) describe('counter as numeric primitive', () => { let doc1: CounterMap beforeEach(() => { doc1 = Automerge.change(Automerge.init<CounterMap>(), doc => { doc.birds = new Counter(3) }) }) it('is equal (==) but not strictly equal (===) to its numeric value', () => { assert.equal(doc1.birds, 3) assert.notStrictEqual(doc1.birds, 3) }) it('has to be explicitly cast to be used as a number', () => { let birdCount: number // This is valid javascript, but without the `ts-ignore` flag, it fails to compile: // @ts-ignore birdCount = doc1.birds // Type 'Counter' is not assignable to type 'number'.ts(2322) // This is because TypeScript doesn't know about the `.valueOf()` trick. // https://github.com/Microsoft/TypeScript/issues/2361 // If we want to treat a counter value as a number, we have to explicitly cast it to keep // TypeScript happy. // We can cast by putting a `+` in front of it: birdCount = +doc1.birds assert.equal(birdCount < 4, true) assert.equal(birdCount >= 0, true) // Or we can be explicit (have to cast as unknown, then number): birdCount = (doc1.birds as unknown) as number assert.equal(birdCount <= 2, false) assert.equal(birdCount + 10, 13) }) it('is converted to a string using its numeric value', () => { assert.equal(doc1.birds.toString(), '3') assert.equal(`I saw ${doc1.birds} birds`, 'I saw 3 birds') assert.equal(['I saw', doc1.birds, 'birds'].join(' '), 'I saw 3 birds') }) }) }) describe('Automerge.Observable', () => { interface TextDoc { text: Automerge.Text } it('should call a patchCallback when a document changes', () => { let callbackCalled = false, actor = '' let doc = Automerge.init<TextDoc>({patchCallback: (patch, before, after, local, changes) => { callbackCalled = true assert.deepStrictEqual(patch.diffs.props.text[`1@${actor}`], { objectId: `1@${actor}`, type: 'text', edits: [ {action: 'insert', index: 0, elemId: `2@${actor}`, opId: `2@${actor}`, value: {type: 'value', value: 'a'}} ] }) assert.deepStrictEqual(before, {}) assert.strictEqual(after.text.toString(), 'a') assert.strictEqual(local, true) assert.strictEqual(changes.length, 1) assert.ok(changes[0] instanceof Uint8Array) }}) actor = Automerge.getActorId(doc) doc = Automerge.change(doc, doc => doc.text = new Automerge.Text('a')) assert.strictEqual(callbackCalled, true) }) it('should call an observer when a document changes', () => { let observable = new Automerge.Observable(), callbackCalled = false let doc = Automerge.from({text: new Automerge.Text()}, {observable}) let actor = Automerge.getActorId(doc) observable.observe(doc.text, (diff, before, after, local, changes) => { callbackCalled = true if (diff.type == 'text') { assert.deepStrictEqual(diff.edits, [ {action: 'insert', index: 0, elemId: `2@${actor}`, opId: `2@${actor}`, value: {type: 'value', value: 'a'}} ]) } assert.strictEqual(before.toString(), '') assert.strictEqual(after.toString(), 'a') assert.strictEqual(local, true) assert.strictEqual(changes.length, 1) assert.ok(changes[0] instanceof Uint8Array) }) doc = Automerge.change(doc, doc => doc.text.insertAt(0, 'a')) assert.strictEqual(callbackCalled, true) }) }) })
the_stack
import { RouteRecognizer, RouteHandler, ConfigurableRoute, State, RecognizedRoute } from 'aurelia-route-recognizer'; import { Container } from 'aurelia-dependency-injection'; import { History, NavigationOptions } from 'aurelia-history'; import { NavigationInstruction, NavigationInstructionInit } from './navigation-instruction'; import { NavModel } from './nav-model'; import { RouterConfiguration } from './router-configuration'; import { _ensureArrayWithSingleRoutePerConfig, _normalizeAbsolutePath, _createRootedPath, _resolveUrl } from './util'; import { RouteConfig, RouteConfigSpecifier, ViewPortInstruction } from './interfaces'; import { PipelineProvider } from './pipeline-provider'; /**@internal */ declare module 'aurelia-history' { interface History { // This is wrong, as it's an implementation detail from aurelia-history-browser // but we are poking it in here so probably will need to make it official in `aurelia-history` /** * A private flag of Aurelia History implementation to indicate if push state should be used */ _hasPushState: boolean; previousLocation: string; } } /**@internal */ declare module 'aurelia-route-recognizer' { interface State { types: { dynamics: DynamicSegment; stars: StarSegment; }; } interface RouteHandler { navigationStrategy?: (instruction: NavigationInstruction) => any; } interface RecognizedRoute { config?: RouteConfig; queryParams?: Record<string, any>; } } type RouterConfigurationResolution = RouterConfiguration | ((cfg: RouterConfiguration) => void | RouterConfiguration | Promise<RouterConfiguration>); /** * The primary class responsible for handling routing and navigation. */ export class Router { /** * Container associated with this router. Also used to create child container for creating child router. */ container: Container; /** * History instance of Aurelia abstract class for wrapping platform history global object */ history: History; /** * A registry of registered viewport. Will be used to handle process navigation instruction route loading * and dom swapping */ viewPorts: Record<string, any>; /** * List of route configs registered with this router */ routes: RouteConfig[]; /** * The [[Router]]'s current base URL, typically based on the [[Router.currentInstruction]]. */ baseUrl: string; /** * If defined, used in generation of document title for [[Router]]'s routes. */ title: string | undefined; /** * The separator used in the document title between [[Router]]'s routes. */ titleSeparator: string | undefined; /** * True if the [[Router]] has been configured. */ isConfigured: boolean; /** * True if the [[Router]] is currently processing a navigation. */ isNavigating: boolean; /** * True if the [[Router]] is navigating due to explicit call to navigate function(s). */ isExplicitNavigation: boolean; /** * True if the [[Router]] is navigating due to explicit call to navigateBack function. */ isExplicitNavigationBack: boolean; /** * True if the [[Router]] is navigating into the app for the first time in the browser session. */ isNavigatingFirst: boolean; /** * True if the [[Router]] is navigating to a page instance not in the browser session history. */ isNavigatingNew: boolean; /** * True if the [[Router]] is navigating forward in the browser session history. */ isNavigatingForward: boolean; /** * True if the [[Router]] is navigating back in the browser session history. */ isNavigatingBack: boolean; /** * True if the [[Router]] is navigating due to a browser refresh. */ isNavigatingRefresh: boolean; /** * True if the previous instruction successfully completed the CanDeactivatePreviousStep in the current navigation. */ couldDeactivate: boolean; /** * The currently active navigation tracker. */ currentNavigationTracker: number; /** * The navigation models for routes that specified [[RouteConfig.nav]]. */ navigation: NavModel[]; /** * The currently active navigation instruction. */ currentInstruction: NavigationInstruction; /** * The parent router, or null if this instance is not a child router. */ parent: Router = null; options: any = {}; /** * The defaults used when a viewport lacks specified content */ viewPortDefaults: Record<string, any> = {}; /**@internal */ catchAllHandler: (instruction: NavigationInstruction) => NavigationInstruction | Promise<NavigationInstruction>; /**@internal */ fallbackRoute: string; /**@internal */ pipelineProvider: PipelineProvider; /**@internal */ _fallbackOrder: number; /**@internal */ _recognizer: RouteRecognizer; /**@internal */ _childRecognizer: RouteRecognizer; /**@internal */ _configuredPromise: Promise<any>; /**@internal */ _resolveConfiguredPromise: (value?: any) => void; /** * Extension point to transform the document title before it is built and displayed. * By default, child routers delegate to the parent router, and the app router * returns the title unchanged. */ transformTitle: (title: string) => string = (title: string) => { if (this.parent) { return this.parent.transformTitle(title); } return title; } /** * @param container The [[Container]] to use when child routers. * @param history The [[History]] implementation to delegate navigation requests to. */ constructor(container: Container, history: History) { this.container = container; this.history = history; this.reset(); } /** * Fully resets the router's internal state. Primarily used internally by the framework when multiple calls to setRoot are made. * Use with caution (actually, avoid using this). Do not use this to simply change your navigation model. */ reset() { this.viewPorts = {}; this.routes = []; this.baseUrl = ''; this.isConfigured = false; this.isNavigating = false; this.isExplicitNavigation = false; this.isExplicitNavigationBack = false; this.isNavigatingFirst = false; this.isNavigatingNew = false; this.isNavigatingRefresh = false; this.isNavigatingForward = false; this.isNavigatingBack = false; this.couldDeactivate = false; this.navigation = []; this.currentInstruction = null; this.viewPortDefaults = {}; this._fallbackOrder = 100; this._recognizer = new RouteRecognizer(); this._childRecognizer = new RouteRecognizer(); this._configuredPromise = new Promise(resolve => { this._resolveConfiguredPromise = resolve; }); } /** * Gets a value indicating whether or not this [[Router]] is the root in the router tree. I.e., it has no parent. */ get isRoot(): boolean { return !this.parent; } /** * Registers a viewPort to be used as a rendering target for activated routes. * * @param viewPort The viewPort. * @param name The name of the viewPort. 'default' if unspecified. */ registerViewPort(viewPort: /*ViewPort*/any, name?: string): void { name = name || 'default'; this.viewPorts[name] = viewPort; } /** * Returns a Promise that resolves when the router is configured. */ ensureConfigured(): Promise<void> { return this._configuredPromise; } /** * Configures the router. * * @param callbackOrConfig The [[RouterConfiguration]] or a callback that takes a [[RouterConfiguration]]. */ configure(callbackOrConfig: RouterConfiguration | ((config: RouterConfiguration) => RouterConfiguration)): Promise<void> { this.isConfigured = true; let result: RouterConfigurationResolution = callbackOrConfig as RouterConfiguration; let config: RouterConfiguration; if (typeof callbackOrConfig === 'function') { config = new RouterConfiguration(); result = callbackOrConfig(config); } return Promise .resolve(result) .then((c) => { if (c && (c as RouterConfiguration).exportToRouter) { config = c; } config.exportToRouter(this); this.isConfigured = true; this._resolveConfiguredPromise(); }); } /** * Navigates to a new location. * * @param fragment The URL fragment to use as the navigation destination. * @param options The navigation options. */ navigate(fragment: string, options?: NavigationOptions): boolean { if (!this.isConfigured && this.parent) { return this.parent.navigate(fragment, options); } this.isExplicitNavigation = true; return this.history.navigate(_resolveUrl(fragment, this.baseUrl, this.history._hasPushState), options); } /** * Navigates to a new location corresponding to the route and params specified. Equivallent to [[Router.generate]] followed * by [[Router.navigate]]. * * @param route The name of the route to use when generating the navigation location. * @param params The route parameters to be used when populating the route pattern. * @param options The navigation options. */ navigateToRoute(route: string, params?: any, options?: NavigationOptions): boolean { let path = this.generate(route, params); return this.navigate(path, options); } /** * Navigates back to the most recent location in history. */ navigateBack(): void { this.isExplicitNavigationBack = true; this.history.navigateBack(); } /** * Creates a child router of the current router. * * @param container The [[Container]] to provide to the child router. Uses the current [[Router]]'s [[Container]] if unspecified. * @returns {Router} The new child Router. */ createChild(container?: Container): Router { let childRouter = new Router(container || this.container.createChild(), this.history); childRouter.parent = this; return childRouter; } /** * Generates a URL fragment matching the specified route pattern. * * @param name The name of the route whose pattern should be used to generate the fragment. * @param params The route params to be used to populate the route pattern. * @param options If options.absolute = true, then absolute url will be generated; otherwise, it will be relative url. * @returns {string} A string containing the generated URL fragment. */ generate(nameOrRoute: string | RouteConfig, params: any = {}, options: any = {}): string { // A child recognizer generates routes for potential child routes. Any potential child route is added // to the childRoute property of params for the childRouter to recognize. When generating routes, we // use the childRecognizer when childRoute params are available to generate a child router enabled route. let recognizer = 'childRoute' in params ? this._childRecognizer : this._recognizer; let hasRoute = recognizer.hasRoute(nameOrRoute as string | RouteHandler); if (!hasRoute) { if (this.parent) { return this.parent.generate(nameOrRoute, params, options); } throw new Error(`A route with name '${nameOrRoute}' could not be found. Check that \`name: '${nameOrRoute}'\` was specified in the route's config.`); } let path = recognizer.generate(nameOrRoute as string | RouteHandler, params); let rootedPath = _createRootedPath(path, this.baseUrl, this.history._hasPushState, options.absolute); return options.absolute ? `${this.history.getAbsoluteRoot()}${rootedPath}` : rootedPath; } /** * Creates a [[NavModel]] for the specified route config. * * @param config The route config. */ createNavModel(config: RouteConfig): NavModel { let navModel = new NavModel( this, 'href' in config ? config.href // potential error when config.route is a string[] ? : config.route as string); navModel.title = config.title; navModel.order = config.nav; navModel.href = config.href; navModel.settings = config.settings; navModel.config = config; return navModel; } /** * Registers a new route with the router. * * @param config The [[RouteConfig]]. * @param navModel The [[NavModel]] to use for the route. May be omitted for single-pattern routes. */ addRoute(config: RouteConfig, navModel?: NavModel): void { if (Array.isArray(config.route)) { let routeConfigs = _ensureArrayWithSingleRoutePerConfig(config); // the following is wrong. todo: fix this after TS refactoring release routeConfigs.forEach(this.addRoute.bind(this)); return; } validateRouteConfig(config); if (!('viewPorts' in config) && !config.navigationStrategy) { config.viewPorts = { 'default': { moduleId: config.moduleId, view: config.view } }; } if (!navModel) { navModel = this.createNavModel(config); } this.routes.push(config); let path = config.route; if (path.charAt(0) === '/') { path = path.substr(1); } let caseSensitive = config.caseSensitive === true; let state: State = this._recognizer.add({ path: path, handler: config as RouteHandler, caseSensitive: caseSensitive } as ConfigurableRoute); if (path) { let settings = config.settings; delete config.settings; let withChild = JSON.parse(JSON.stringify(config)); config.settings = settings; withChild.route = `${path}/*childRoute`; withChild.hasChildRouter = true; this._childRecognizer.add({ path: withChild.route, handler: withChild, caseSensitive: caseSensitive }); withChild.navModel = navModel; withChild.settings = config.settings; withChild.navigationStrategy = config.navigationStrategy; } config.navModel = navModel; let navigation = this.navigation; if ((navModel.order || navModel.order === 0) && navigation.indexOf(navModel) === -1) { if ((!navModel.href && navModel.href !== '') && (state.types.dynamics || state.types.stars)) { throw new Error('Invalid route config for "' + config.route + '" : dynamic routes must specify an "href:" to be included in the navigation model.'); } if (typeof navModel.order !== 'number') { navModel.order = ++this._fallbackOrder; } navigation.push(navModel); // this is a potential error / inconsistency between browsers // // MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort // If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, // but sorted with respect to all different elements. // Note: the ECMAscript standard does not guarantee this behaviour, // and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this. navigation.sort((a, b) => <any>a.order - <any>b.order); } } /** * Gets a value indicating whether or not this [[Router]] or one of its ancestors has a route registered with the specified name. * * @param name The name of the route to check. */ hasRoute(name: string): boolean { return !!(this._recognizer.hasRoute(name) || this.parent && this.parent.hasRoute(name)); } /** * Gets a value indicating whether or not this [[Router]] has a route registered with the specified name. * * @param name The name of the route to check. */ hasOwnRoute(name: string): boolean { return this._recognizer.hasRoute(name); } /** * Register a handler to use when the incoming URL fragment doesn't match any registered routes. * * @param config The moduleId, or a function that selects the moduleId, or a [[RouteConfig]]. */ handleUnknownRoutes(config?: RouteConfigSpecifier): void { if (!config) { throw new Error('Invalid unknown route handler'); } this.catchAllHandler = instruction => { return this ._createRouteConfig(config, instruction) .then(c => { instruction.config = c; return instruction; }); }; } /** * Updates the document title using the current navigation instruction. */ updateTitle(): void { let parentRouter = this.parent; if (parentRouter) { return parentRouter.updateTitle(); } let currentInstruction = this.currentInstruction; if (currentInstruction) { currentInstruction._updateTitle(); } return undefined; } /** * Updates the navigation routes with hrefs relative to the current location. * Note: This method will likely move to a plugin in a future release. */ refreshNavigation(): void { let nav = this.navigation; for (let i = 0, length = nav.length; i < length; i++) { let current = nav[i]; if (!current.config.href) { current.href = _createRootedPath(current.relativeHref, this.baseUrl, this.history._hasPushState); } else { current.href = _normalizeAbsolutePath(current.config.href, this.history._hasPushState); } } } /** * Sets the default configuration for the view ports. This specifies how to * populate a view port for which no module is specified. The default is * an empty view/view-model pair. */ useViewPortDefaults($viewPortDefaults: Record<string, any>): void { // a workaround to have strong typings while not requiring to expose interface ViewPortInstruction let viewPortDefaults: Record<string, ViewPortInstruction> = $viewPortDefaults; for (let viewPortName in viewPortDefaults) { let viewPortConfig = viewPortDefaults[viewPortName]; this.viewPortDefaults[viewPortName] = { moduleId: viewPortConfig.moduleId }; } } /**@internal */ _refreshBaseUrl(): void { let parentRouter = this.parent; if (parentRouter) { this.baseUrl = generateBaseUrl(parentRouter, parentRouter.currentInstruction); } } /**@internal */ _createNavigationInstruction(url: string = '', parentInstruction: NavigationInstruction = null): Promise<NavigationInstruction> { let fragment = url; let queryString = ''; let queryIndex = url.indexOf('?'); if (queryIndex !== -1) { fragment = url.substr(0, queryIndex); queryString = url.substr(queryIndex + 1); } let urlRecognizationResults = this._recognizer.recognize(url) as IRouteRecognizationResults; if (!urlRecognizationResults || !urlRecognizationResults.length) { urlRecognizationResults = this._childRecognizer.recognize(url) as IRouteRecognizationResults; } let instructionInit: NavigationInstructionInit = { fragment, queryString, config: null, parentInstruction, previousInstruction: this.currentInstruction, router: this, options: { compareQueryParams: this.options.compareQueryParams } }; let result: Promise<NavigationInstruction>; if (urlRecognizationResults && urlRecognizationResults.length) { let first = urlRecognizationResults[0]; let instruction = new NavigationInstruction(Object.assign({}, instructionInit, { params: first.params, queryParams: first.queryParams || urlRecognizationResults.queryParams, config: first.config || first.handler })); if (typeof first.handler === 'function') { result = evaluateNavigationStrategy(instruction, first.handler, first); } else if (first.handler && typeof first.handler.navigationStrategy === 'function') { result = evaluateNavigationStrategy(instruction, first.handler.navigationStrategy, first.handler); } else { result = Promise.resolve(instruction); } } else if (this.catchAllHandler) { let instruction = new NavigationInstruction(Object.assign({}, instructionInit, { params: { path: fragment }, queryParams: urlRecognizationResults ? urlRecognizationResults.queryParams : {}, config: null // config will be created by the catchAllHandler })); result = evaluateNavigationStrategy(instruction, this.catchAllHandler); } else if (this.parent) { let router = this._parentCatchAllHandler(this.parent); if (router) { let newParentInstruction = this._findParentInstructionFromRouter(router, parentInstruction); let instruction = new NavigationInstruction(Object.assign({}, instructionInit, { params: { path: fragment }, queryParams: urlRecognizationResults ? urlRecognizationResults.queryParams : {}, router: router, parentInstruction: newParentInstruction, parentCatchHandler: true, config: null // config will be created by the chained parent catchAllHandler })); result = evaluateNavigationStrategy(instruction, router.catchAllHandler); } } if (result && parentInstruction) { this.baseUrl = generateBaseUrl(this.parent, parentInstruction); } return result || Promise.reject(new Error(`Route not found: ${url}`)); } /**@internal */ _findParentInstructionFromRouter(router: Router, instruction: NavigationInstruction): NavigationInstruction { if (instruction.router === router) { instruction.fragment = router.baseUrl; // need to change the fragment in case of a redirect instead of moduleId return instruction; } else if (instruction.parentInstruction) { return this._findParentInstructionFromRouter(router, instruction.parentInstruction); } return undefined; } /**@internal */ _parentCatchAllHandler(router: Router): Router | false { if (router.catchAllHandler) { return router; } else if (router.parent) { return this._parentCatchAllHandler(router.parent); } return false; } /** * @internal */ _createRouteConfig(config: RouteConfigSpecifier, instruction: NavigationInstruction): Promise<RouteConfig> { return Promise .resolve(config) .then((c: any) => { if (typeof c === 'string') { return { moduleId: c } as RouteConfig; } else if (typeof c === 'function') { return c(instruction); } return c; }) // typing here could be either RouteConfig or RedirectConfig // but temporarily treat both as RouteConfig // todo: improve typings precision .then((c: string | RouteConfig) => typeof c === 'string' ? { moduleId: c } as RouteConfig : c) .then((c: RouteConfig) => { c.route = instruction.params.path; validateRouteConfig(c); if (!c.navModel) { c.navModel = this.createNavModel(c); } return c; }); } } /* @internal exported for unit testing */ export const generateBaseUrl = (router: Router, instruction: NavigationInstruction): string => { return `${router.baseUrl || ''}${instruction.getBaseUrl() || ''}`; }; /* @internal exported for unit testing */ export const validateRouteConfig = (config: RouteConfig): void => { if (typeof config !== 'object') { throw new Error('Invalid Route Config'); } if (typeof config.route !== 'string') { let name = config.name || '(no name)'; throw new Error('Invalid Route Config for "' + name + '": You must specify a "route:" pattern.'); } if (!('redirect' in config || config.moduleId || config.navigationStrategy || config.viewPorts)) { throw new Error('Invalid Route Config for "' + config.route + '": You must specify a "moduleId:", "redirect:", "navigationStrategy:", or "viewPorts:".'); } }; /* @internal exported for unit testing */ export const evaluateNavigationStrategy = ( instruction: NavigationInstruction, evaluator: Function, context?: any ): Promise<NavigationInstruction> => { return Promise .resolve(evaluator.call(context, instruction)) .then(() => { if (!('viewPorts' in instruction.config)) { instruction.config.viewPorts = { 'default': { moduleId: instruction.config.moduleId } }; } return instruction; }); }; interface IRouteRecognizationResults extends Array<RecognizedRoute> { queryParams: Record<string, any>; }
the_stack
import { chimeeLog } from 'chimee-helper-log'; import { style } from 'dom-helpers'; import { addClass } from 'dom-helpers/class'; import { off as removeEvent, on as addEvent } from 'dom-helpers/events'; import { querySelectorAll } from 'dom-helpers/query'; import { esFullscreen } from 'es-fullscreen'; import { isArray, isFunction, isPlainObject, isString } from 'lodash'; import { autobind, waituntil } from 'toxic-decorators'; import { isElement, isEvent, isHTMLString, isPosterityNode } from 'toxic-predicate-functions'; import { hypenate } from 'toxic-utils'; import { RealChimeeDomElement } from '../const/dom'; import Dispatcher from '../dispatcher/index'; import { UserConfig } from '../typings/base'; export interface IFriendlyDom { autoFocusToVideo(element: Element, remove?: boolean): void; } /** * <pre> * Dom work for Dispatcher. * It take charge of dom management of Dispatcher. * </pre> */ export default class Dom { get mouseInVideo(): boolean { return this.mouseInVideoValue; } set mouseInVideo(val: boolean) { this.mouseInVideoValue = !!val; } get videoExtendedNodes(): Element[] { return this.videoExtendedNodesArray; } public container: Element; public destroyed: boolean; public dispatcher: Dispatcher; public fullscreenElement: Element | 'wrapper' | 'container' | 'video' | void; public isFullscreen: boolean | string; /** * to mark is the mouse in the video area */ public mouseInVideoValue: boolean; /** * the html to restore when we are destroyed */ public originHTML: string; /** * all plugin's dom element set */ public plugins: {[x: string]: Element}; public videoElement: HTMLVideoElement; /** * collection of video extension nodes * some nodes can be regarded as part of video (such as penetrate element) * so we store them here */ public videoExtendedNodesArray: Element[]; public videoRequireGuardedAttributes: string[]; public wrapper: Element; constructor(config: UserConfig, dispatcher: Dispatcher) { const { wrapper } = config; this.dispatcher = dispatcher; this.mouseInVideoValue = false; this.destroyed = false; this.isFullscreen = false; this.originHTML = ''; this.plugins = {}; this.videoExtendedNodesArray = ([] as Element[]); if (isString(wrapper)) { const $wrapper = querySelectorAll(document.body, wrapper); // TODO: we have to decalre length for wrapper if ($wrapper.length === 0) { throw new TypeError('Can not get dom node accroding wrapper. Please check your wrapper'); } /** * the referrence of the dom wrapper of whole Chimee */ this.wrapper = $wrapper[0]; } else if (isElement(wrapper)) { this.wrapper = wrapper; } else { throw new TypeError(`Wrapper can only be string or HTMLElement, but not ${typeof wrapper}`); } this.originHTML = this.wrapper.innerHTML; // if we find video element inside wrapper // we use it // or we create a video element by ourself. let videoElement: HTMLVideoElement | void = (querySelectorAll(this.wrapper, 'video')[0] as HTMLVideoElement | void); if (!videoElement) { videoElement = document.createElement('video'); } /** * referrence of video's dom element */ this.installVideo(videoElement); this.fullscreenMonitor(); esFullscreen.on('fullscreenchange', this.fullscreenMonitor); // As some video attributes will missed when we switch kernel // we set a guarder for it // and we must make sure style be guarded const videoRequiredGuardedAttributes = isArray(config.videoRequiredGuardedAttributes) ? config.videoRequiredGuardedAttributes : []; if (videoRequiredGuardedAttributes.indexOf('style') < 0) { videoRequiredGuardedAttributes.unshift('style'); } this.videoRequireGuardedAttributes = videoRequiredGuardedAttributes; } /** * function called when we distory */ public destroy() { this.removeVideo(); esFullscreen.off('fullscreenchange', this.fullscreenMonitor); this.wrapper.innerHTML = this.originHTML; delete this.wrapper; delete this.plugins; this.destroyed = true; } public exitFullscreen(): boolean { return esFullscreen.exit(); } public focus() { this.videoElement.focus(); } public fullscreen(request: boolean = true, target: RealChimeeDomElement = 'container'): boolean { return request ? this.requestFullscreen(target) : this.exitFullscreen(); } public getAttr(target: RealChimeeDomElement, attr: string): string { return this[target].getAttribute(attr); } public getStyle(target: RealChimeeDomElement, attr: string): string { if (!isString(attr)) { throw new TypeError(`to handle dom's attribute or style, your attr parameter must be string, but not ${attr} in ${typeof attr}`); } if (!isString(target)) { throw new TypeError(`to handle dom's attribute or style, your target parameter must be string, , but not ${target} in ${typeof target}`); } if (!isElement(this[target])) { throw new TypeError(`Your target "${target}" is not a legal HTMLElement`); } return style(this[target], attr); } /** * each plugin has its own dom node, this function will create one or them. * we support multiple kind of el * 1. Element, we will append this dom node on wrapper straight * 2. HTMLString, we will create dom based on this HTMLString and append it on wrapper * 3. string, we will transfer this string into hypen string, then we create a custom elment called by this and bind it on wrapper * 4. nothing, we will create a div and bind it on the wrapper */ public insertPlugin(id: string, el?: string | HTMLElement | { className?: string | string[], inner?: boolean, penetrate?: boolean } | void, option: { className?: string | string[], inner?: boolean, penetrate?: boolean } = {}) { if (!isString(id)) { throw new TypeError('insertPlugin id parameter must be string'); } if (isElement(this.plugins[id])) { /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { chimeeLog.warn('Dispatcher.dom', `Plugin ${id} have already had a dom node. Now it will be replaced`); } this.removePlugin(id); } if (isString(el)) { if (isHTMLString(el)) { const outer = document.createElement('div'); outer.innerHTML = el; el = outer.children[0]; } else { el = document.createElement(hypenate(el)); } } else if (el && isPlainObject(el)) { option = el; } const { inner, penetrate, className } = option; const node = (el && isElement(el)) ? el : document.createElement('div'); const classNames = isString(className) ? className.split(/\s+/) : isArray(className) ? className : []; classNames.forEach((name) => { addClass(node, name); }); this.plugins[id] = node; const outerElement = inner ? this.container : this.wrapper; const originElement = inner ? this.videoElement : this.container; // auto forward the event if this plugin can be penetrate if (penetrate) { this.dispatcher.binder.bindEventOnPenetrateNode(node); this.videoExtendedNodesArray.push(node); } if (outerElement.lastChild === originElement) { outerElement.appendChild(node); return node; } outerElement.insertBefore(node, originElement.nextSibling); return node; } public installVideo(videoElement: HTMLVideoElement): HTMLVideoElement { this.videoExtendedNodesArray.push(videoElement); videoElement.setAttribute('tabindex', '-1'); this.autoFocusToVideo(videoElement); if (!isElement(this.container)) { // create container if (videoElement.parentElement && isElement(videoElement.parentElement) && videoElement.parentElement !== this.wrapper ) { this.container = videoElement.parentElement; } else { this.container = document.createElement('container'); this.container.appendChild(videoElement); } } else { const container = this.container; if (container.childNodes.length === 0) { container.appendChild(videoElement); } else { container.insertBefore(videoElement, container.childNodes[0]); } } // check container.position if (this.container.parentElement !== this.wrapper) { this.wrapper.appendChild(this.container); } this.videoElement = videoElement; return videoElement; } public isNodeInsideVideo(node: Element): boolean { return this.videoExtendedNodesArray.indexOf(node) > -1 || this.videoExtendedNodesArray.reduce((flag, video) => { if (flag) { return flag; } return isPosterityNode(video, node); }, false); } public migrateVideoRequiredGuardedAttributes(video: HTMLVideoElement) { const guardedAttributesAndValue = this.videoRequireGuardedAttributes.map((attr) => ([ attr, this.videoElement.getAttribute(attr) ])); guardedAttributesAndValue.forEach(([ attr, value ]) => { video.setAttribute(attr, value); }); } /** * remove plugin's dom */ public removePlugin(id: string) { if (!isString(id)) { return; } const dom = this.plugins[id]; if (isElement(dom)) { if (dom.parentNode) { dom.parentNode.removeChild(dom); } this.autoFocusToVideo(dom, true); } // @ts-ignore: Property 'penetrate' does not exist on type 'PluginConfig | IChimeePluginConstructor | { penetrate?: false; }'. const { penetrate = false } = this.dispatcher.getPluginConfig(id) || {}; if (penetrate) { this.dispatcher.binder.bindEventOnPenetrateNode(dom, true); } delete this.plugins[id]; } public removeVideo(): HTMLVideoElement { const videoElement = this.videoElement; this.autoFocusToVideo(this.videoElement, false); // when we destroy the chimee // binder is destroyed before dom // so we need to make a check here if (this.dispatcher.binder) { this.dispatcher.binder.bindEventOnVideo(videoElement, true); } if (this.videoElement.parentNode) { this.videoElement.parentNode.removeChild(this.videoElement); } delete this.videoElement; return videoElement; } public requestFullscreen(target: RealChimeeDomElement) { // @ts-ignore: user may pass video when they are using JavaScript if (target === 'video') { target = 'videoElement'; } return esFullscreen.open((this[target] as HTMLElement)); } /** * set attribute on our dom * @param {string} attr attribute's name * @param {anything} val attribute's value * @param {string} target the HTMLElemnt string name, only support video/wrapper/container now */ @waituntil('dispatcher.videoConfigReady') public setAttr(target: RealChimeeDomElement, attr: string, val: string | void | number | boolean): void { if (typeof val === 'undefined') { this[target].removeAttribute(attr); return; } this[target].setAttribute(attr, val as any); } /** * Set zIndex for a plugins list */ public setPluginsZIndex(plugins: string[]): void { plugins.forEach((key: string, index) => style(key.match(/^(videoElement|container)$/) ? this[(key as RealChimeeDomElement)] : this.plugins[key], 'z-index', ++index)); } public setStyle(target: RealChimeeDomElement, attr: string, val: any): void { if (!isString(attr)) { throw new TypeError(`to handle dom's attribute or style, your attr parameter must be string, but not ${attr} in ${typeof attr}`); } if (!isString(target)) { throw new TypeError(`to handle dom's attribute or style, your target parameter must be string, , but not ${target} in ${typeof target}`); } if (!isElement(this[target])) { throw new TypeError(`Your target "${target}" is not a legal HTMLElement`); } style(this[target], attr, val); } protected autoFocusToVideo(element: Element, remove: boolean = false): void { /* istanbule ignore next */ if (!isElement(element)) { return; } (remove ? removeEvent : addEvent)(element, 'mouseup', this.focusToVideo); (remove ? removeEvent : addEvent)(element, 'touchend', this.focusToVideo); } @(autobind as MethodDecorator) private focusToVideo() { const x = window.scrollX; const y = window.scrollY; if (isFunction(this.videoElement.focus)) { this.videoElement.focus(); } window.scrollTo(x, y); } @(autobind as MethodDecorator) private fullscreenMonitor(evt?: Event) { const element = esFullscreen.fullscreenElement; const original = this.isFullscreen; if (!element || (!isPosterityNode(this.wrapper, element) && element !== this.wrapper)) { this.isFullscreen = false; this.fullscreenElement = undefined; } else { this.isFullscreen = true; this.fullscreenElement = this.wrapper === element ? 'wrapper' : this.container === element ? 'container' : this.videoElement === element ? 'video' : element; } if (isEvent(evt) && original !== this.isFullscreen) { this.dispatcher.binder.triggerSync({ id: 'dispatcher', name: 'fullscreenchange', target: 'esFullscreen', }, evt); } } }
the_stack
import { DefinitionType } from '@yozora/ast' import type { INodePoint } from '@yozora/character' import { AsciiCodePoint, calcStringFromNodePoints } from '@yozora/character' import type { IMatchBlockHookCreator, IPhrasingContentLine, IResultOfEatContinuationText, IResultOfEatOpener, IResultOfOnClose, } from '@yozora/core-tokenizer' import { calcEndPoint, calcStartPoint, eatOptionalWhitespaces, resolveLabelToIdentifier, } from '@yozora/core-tokenizer' import type { IThis, IToken, T } from './types' import { eatAndCollectLinkDestination } from './util/link-destination' import { eatAndCollectLinkLabel } from './util/link-label' import { eatAndCollectLinkTitle } from './util/link-title' /** * A link reference definition consists of a link label, indented up to three * spaces, followed by a colon (:), optional whitespace (including up to one * line ending), a link destination, optional whitespace (including up to one * line ending), and an optional link title, which if it is present must be * separated from the link destination by whitespace. No further non-whitespace * characters may occur on the line. * * A link reference definition does not correspond to a structural element of * a document. Instead, it defines a label which can be used in reference * links and reference-style images elsewhere in the document. Link reference * definitions can come either before or after the links that use them. * * @see https://github.github.com/gfm/#link-reference-definition */ export const match: IMatchBlockHookCreator<T, IToken, IThis> = function (api) { return { isContainingBlock: false, eatOpener, eatContinuationText, onClose, } function eatOpener(line: Readonly<IPhrasingContentLine>): IResultOfEatOpener<T, IToken> { /** * Four spaces are too much * @see https://github.github.com/gfm/#example-180 */ if (line.countOfPrecedeSpaces >= 4) return null const { nodePoints, startIndex, endIndex, firstNonWhitespaceIndex } = line if (firstNonWhitespaceIndex >= endIndex) return null // Try to match link label let i = firstNonWhitespaceIndex const { nextIndex: labelEndIndex, state: labelState } = eatAndCollectLinkLabel( nodePoints, i, endIndex, null, ) if (labelEndIndex < 0) return null const lineNo = nodePoints[startIndex].line // Optimization: lazy calculation const createInitState = (): IToken => { const token: IToken = { nodeType: DefinitionType, position: { start: calcStartPoint(nodePoints, startIndex), end: calcEndPoint(nodePoints, endIndex - 1), }, label: labelState, destination: null, title: null, lineNoOfLabel: lineNo, lineNoOfDestination: -1, lineNoOfTitle: -1, lines: [line], } return token } if (!labelState.saturated) { const token = createInitState() return { token, nextIndex: endIndex } } // Saturated but no following colon exists. if ( labelEndIndex < 0 || labelEndIndex + 1 >= endIndex || nodePoints[labelEndIndex].codePoint !== AsciiCodePoint.COLON ) return null /** * At most one line break can be used between link destination and link label * @see https://github.github.com/gfm/#example-162 * @see https://github.github.com/gfm/#example-164 * @see https://github.github.com/gfm/#link-reference-definition */ i = eatOptionalWhitespaces(nodePoints, labelEndIndex + 1, endIndex) if (i >= endIndex) { const token = createInitState() return { token, nextIndex: endIndex } } // Try to match link destination const { nextIndex: destinationEndIndex, state: destinationState } = eatAndCollectLinkDestination(nodePoints, i, endIndex, null) /** * The link destination may not be omitted * @see https://github.github.com/gfm/#example-168 */ if (destinationEndIndex < 0) return null // Link destination not saturated if (!destinationState.saturated && destinationEndIndex !== endIndex) return null /** * At most one line break can be used between link title and link destination * @see https://github.github.com/gfm/#example-162 * @see https://github.github.com/gfm/#example-164 * @see https://github.github.com/gfm/#link-reference-definition */ i = eatOptionalWhitespaces(nodePoints, destinationEndIndex, endIndex) if (i >= endIndex) { const token = createInitState() token.destination = destinationState token.lineNoOfDestination = lineNo return { token, nextIndex: endIndex } } /** * The title must be separated from the link destination by whitespace. * @see https://github.github.com/gfm/#example-170 */ if (i === destinationEndIndex) return null // Try to match link-title const { nextIndex: titleEndIndex, state: titleState } = eatAndCollectLinkTitle( nodePoints, i, endIndex, null, ) /** * non-whitespace characters after title is not allowed * @see https://github.github.com/gfm/#example-178 */ if (titleEndIndex >= 0) i = titleEndIndex if (i < endIndex) { const k = eatOptionalWhitespaces(nodePoints, i, endIndex) if (k < endIndex) return null } const token = createInitState() token.destination = destinationState token.title = titleState token.lineNoOfDestination = lineNo token.lineNoOfTitle = lineNo return { token, nextIndex: endIndex } } function eatContinuationText( line: Readonly<IPhrasingContentLine>, token: IToken, ): IResultOfEatContinuationText { // All parts of Definition have been matched if (token.title != null && token.title.saturated) return { status: 'notMatched' } const { nodePoints, startIndex, firstNonWhitespaceIndex, endIndex } = line const lineNo = nodePoints[startIndex].line let i = firstNonWhitespaceIndex if (!token.label.saturated) { const { nextIndex: labelEndIndex, state: labelState } = eatAndCollectLinkLabel( nodePoints, i, endIndex, token.label, ) if (labelEndIndex < 0) { return { status: 'failedAndRollback', lines: token.lines } } if (!labelState.saturated) { token.lines.push(line) return { status: 'opening', nextIndex: endIndex } } // Saturated but no following colon exists. if ( labelEndIndex + 1 >= endIndex || nodePoints[labelEndIndex].codePoint !== AsciiCodePoint.COLON ) { return { status: 'failedAndRollback', lines: token.lines } } i = labelEndIndex + 1 } if (token.destination == null) { i = eatOptionalWhitespaces(nodePoints, i, endIndex) if (i >= endIndex) { return { status: 'failedAndRollback', lines: token.lines } } // Try to match link destination const { nextIndex: destinationEndIndex, state: destinationState } = eatAndCollectLinkDestination(nodePoints, i, endIndex, null) /** * At most one line break can be used between link destination and link label, * therefore, this line must match a complete link destination */ if (destinationEndIndex < 0 || !destinationState.saturated) { return { status: 'failedAndRollback', lines: token.lines } } /** * At most one line break can be used between link title and link destination * @see https://github.github.com/gfm/#example-162 * @see https://github.github.com/gfm/#example-164 * @see https://github.github.com/gfm/#link-reference-definition */ i = eatOptionalWhitespaces(nodePoints, destinationEndIndex, endIndex) if (i >= endIndex) { // eslint-disable-next-line no-param-reassign token.destination = destinationState token.lines.push(line) return { status: 'opening', nextIndex: endIndex } } // eslint-disable-next-line no-param-reassign token.lineNoOfDestination = lineNo // eslint-disable-next-line no-param-reassign token.lineNoOfTitle = lineNo } if (token.lineNoOfTitle < 0) { // eslint-disable-next-line no-param-reassign token.lineNoOfTitle = lineNo } const { nextIndex: titleEndIndex, state: titleState } = eatAndCollectLinkTitle( nodePoints, i, endIndex, token.title, ) // eslint-disable-next-line no-param-reassign token.title = titleState if ( titleEndIndex < 0 || titleState.nodePoints.length <= 0 || (titleState.saturated && eatOptionalWhitespaces(nodePoints, titleEndIndex, endIndex) < endIndex) ) { // check if there exists a valid title if (token.lineNoOfDestination === token.lineNoOfTitle) { return { status: 'failedAndRollback', lines: token.lines } } const lastLine = token.lines[token.lines.length - 1] // eslint-disable-next-line no-param-reassign token.title = null // eslint-disable-next-line no-param-reassign token.position.end = calcEndPoint(lastLine.nodePoints, lastLine.endIndex - 1) return { status: 'closingAndRollback', lines: token.lines.slice(token.lineNoOfTitle - 1), } } token.lines.push(line) const saturated: boolean = token.title?.saturated return { status: saturated ? 'closing' : 'opening', nextIndex: endIndex } } function onClose(token: IToken): IResultOfOnClose { let result: IResultOfOnClose // Not all parts of Definition have been matched. if (token.title == null || !token.title.saturated) { // No valid label matched. if (!token.label.saturated) { return { status: 'failedAndRollback', lines: token.lines } } // No valid destination matched. if (token.destination == null || !token.destination.saturated) { return { status: 'failedAndRollback', lines: token.lines } } // No valid title matched. if (token.title != null && !token.title.saturated) { if (token.lineNoOfDestination === token.lineNoOfTitle) { return { status: 'failedAndRollback', lines: token.lines } } const lines = token.lines.splice(token.lineNoOfTitle - 1) const lastLine = token.lines[token.lines.length - 1] // eslint-disable-next-line no-param-reassign token.title = null // eslint-disable-next-line no-param-reassign token.position.end = calcEndPoint(lastLine.nodePoints, lastLine.endIndex - 1) result = { status: 'closingAndRollback', lines } } } /** * Labels are trimmed and case-insensitive * @see https://github.github.com/gfm/#example-174 * @see https://github.github.com/gfm/#example-175 */ const labelPoints: INodePoint[] = token.label.nodePoints const label = calcStringFromNodePoints(labelPoints, 1, labelPoints.length - 1) const identifier = resolveLabelToIdentifier(label) // Register definition identifier. api.registerDefinitionIdentifier(identifier) // Cache label and identifier for performance. // eslint-disable-next-line no-param-reassign token._label = label // eslint-disable-next-line no-param-reassign token._identifier = identifier return result } }
the_stack
module LightSpeed { export class Player extends BABYLON.LeaderBoard.Character { shipLevel: number; levelMax: number; levelPoints: number; highScore: number; constructor() { super(); } } export class PlayerShip { shipLevel: number = 0; currentLevelStats: any = levelingDefs[this.shipLevel]; lightSpeedGauge: number = 0; levelPoints: number = 0; gamePoints: number = 0; canMove: boolean = true; lightSpeedGaugeCapacity: number = 100; health: number = this.currentLevelStats.health; maxHealth: number = this.currentLevelStats.health; speed: number = this.currentLevelStats.speed; bulletSpeed: number = 2; bulletDamage: number = this.currentLevelStats.damage; bulletsshot: number = 0; currentDirection: string = "left"; bullets = []; movex: any; movez: any; movey: any; explosionSystem: BABYLON.ParticleSystem; jetSystem: BABYLON.ParticleSystem; laser: LightSpeed.Laser; boundingBox: any; cameraFollower: any; // event public lightSpeedGaugeChanged: (val: string) => void; public pointsChanged: (levelPoints: number, gamePoints:number) => void; public healthGaugeChanged: (val: string) => void; public shipLevelChanged: (lvl: number, speed: number, health: number, bulletDamage: number) => void; public resetOccured: () => void; public lightSpeedReadyOccured: () => void; public explodeOccured: () => void; public jumpToLightSpeedEnd: () => void; constructor(public scene: BABYLON.Scene, public camera: BABYLON.ArcRotateCamera, public graphic: BABYLON.AbstractMesh, public particleTexture: BABYLON.Texture) { this.boundingBox = BABYLON.Mesh.CreateBox("Player", 13.0, scene); this.cameraFollower = BABYLON.Mesh.CreateBox("cameraFollower", 1.0, scene); var material = new BABYLON.StandardMaterial("texture1", scene); material.wireframe = true; this.boundingBox.material = material; this.boundingBox.isVisible = false; this.cameraFollower.isVisible = false; this.laser = new LightSpeed.Laser(); this.jetSystem = new BABYLON.ParticleSystem("jetstream", 25, scene); this.jetSystem.particleTexture = this.particleTexture; this.jetSystem.emitter = this.graphic; this.jetSystem.minEmitBox = new BABYLON.Vector3(-100, 100, 700); this.jetSystem.maxEmitBox = new BABYLON.Vector3(100, 100, 800); this.jetSystem.color1 = new BABYLON.Color4(0.4, 0.8, 1.0, 1.0); this.jetSystem.color2 = new BABYLON.Color4(0.2, 0.5, 1.0, 1.0); this.jetSystem.colorDead = new BABYLON.Color4(0, 0, 0.2, 0.0); this.jetSystem.minSize = 10.0; this.jetSystem.maxSize = 15.5; this.jetSystem.minLifeTime = 0.01; this.jetSystem.maxLifeTime = .20; this.jetSystem.emitRate = 150; this.jetSystem.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE; this.jetSystem.direction1 = new BABYLON.Vector3(-6, 8, 3); this.jetSystem.direction2 = new BABYLON.Vector3(6, 8, -3); this.jetSystem.targetStopDuration = 0; this.jetSystem.minEmitPower = 1; this.jetSystem.maxEmitPower = 3; this.jetSystem.updateSpeed = 0.005; this.jetSystem.disposeOnStop = false; this.jetSystem.start(); } public lightSpeedGaugeChange(val: string) { if (this.lightSpeedGaugeChanged != null) this.lightSpeedGaugeChanged(val); } public healthGaugeChange(percent: string) { if (this.healthGaugeChanged != null) this.healthGaugeChanged(percent); } public shipLevelChange(lvl: number, speed: number, health: number, bulletDamage: number) { if (this.shipLevelChanged != null) this.shipLevelChanged(lvl, speed, health, bulletDamage); } public levelUp() { GameSound.play("levelup"); this.shipLevel += 1; this.currentLevelStats = levelingDefs[this.shipLevel]; this.speed = this.currentLevelStats.speed; this.health = this.currentLevelStats.health; this.maxHealth = this.currentLevelStats.health; this.bulletDamage = this.currentLevelStats.damage; this.shipLevelChange(this.shipLevel, this.speed, this.health, this.bulletDamage); this.healthGaugeChange(((this.health / this.maxHealth) * 100) + "%"); } public reset() { this.lightSpeedGauge = 0; this.lightSpeedGaugeChange("0px"); this.healthGaugeChange(((this.health / this.maxHealth) * 100) + "%"); this.health = this.maxHealth; this.levelPoints = 0; if (this.resetOccured != null) { this.resetOccured(); } this.boundingBox.position = new BABYLON.Vector3(0, 0, 0); this.graphic.position = new BABYLON.Vector3(0, 0, 0); this.graphic.rotation.x = 0; this.graphic.rotation.y = 0; this.currentDirection = "left"; this.movex = 0, this.movez = 0, this.movey = 0; this.canMove = true; this.graphic.setEnabled(true); } public explode() { this.canMove = false; if (this.graphic.isEnabled() == true) { GameSound.play("playerexplode"); var totalB = this.bullets.length; while (totalB--) { this.bullets[totalB].graphic.dispose(); } this.bullets = []; this.graphic.isVisible = false; this.graphic.setEnabled(false); this.explosionSystem = new BABYLON.ParticleSystem("particlesexplode", 2000, this.scene); this.explosionSystem.particleTexture = this.particleTexture; this.explosionSystem.emitter = this.boundingBox; this.explosionSystem.minEmitBox = new BABYLON.Vector3(0, 0, 0); this.explosionSystem.maxEmitBox = new BABYLON.Vector3(0, 0, 0); this.explosionSystem.color1 = new BABYLON.Color4(0.4, 0.8, 1.0, 1.0); this.explosionSystem.color2 = new BABYLON.Color4(0.2, 0.5, 1.0, 1.0); this.explosionSystem.colorDead = new BABYLON.Color4(0, 0, 0.2, 0.0); this.explosionSystem.minSize = 6.0; this.explosionSystem.maxSize = 7.5; this.explosionSystem.minLifeTime = 0.15; this.explosionSystem.maxLifeTime = 1.15; this.explosionSystem.emitRate = 50000; this.explosionSystem.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE; this.explosionSystem.gravity = new BABYLON.Vector3(0, -9.81, 0); this.explosionSystem.direction1 = new BABYLON.Vector3(-8, 8, 8); this.explosionSystem.direction2 = new BABYLON.Vector3(8, 8, -8); this.explosionSystem.minAngularSpeed = 0; this.explosionSystem.maxAngularSpeed = Math.PI; this.explosionSystem.targetStopDuration = .1; this.explosionSystem.minEmitPower = 1; this.explosionSystem.maxEmitPower = 100; this.explosionSystem.updateSpeed = 0.005; this.explosionSystem.disposeOnStop = false; this.explosionSystem.start(); if (this.explodeOccured != null) { this.explodeOccured(); } ////show you died and request reset/start over } } public getDamage(intDamage: number) { if (this.canMove == true) { GameSound.play("playerhit"); this.health -= intDamage; this.healthGaugeChange(((this.health / this.maxHealth) * 100) + "%"); } if (this.health <= 0) { this.healthGaugeChange("0%"); this.explode(); } } public jumpToLightSpeed() { if (this.lightSpeedGauge >= this.lightSpeedGaugeCapacity && this.health > 0 && this.canMove == true) { //GameSound.play("LSgo"); this.canMove = false; var totalB = this.bullets.length; while (totalB--) { this.bullets[totalB].graphic.dispose(); } this.bullets = []; this.movex = 0; this.movez = 0; this.graphic.position.y += -100; this.boundingBox.position.y += -100 this.camera.target = this.boundingBox.position; var cameraMovein = new BABYLON.Animation("cameraMove", "radius", 80, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE); var cameraKeys = []; cameraKeys.push({ frame: 0, value: this.camera.radius }); cameraKeys.push({ frame: 50, value: 50 }); cameraKeys.push({ frame: 100, value: 25 }); cameraMovein.setKeys(cameraKeys); this.camera.animations.push(cameraMovein); //GameSound.play("LSstart"); this.graphic.rotation.x = Math.PI + (Math.PI / 2); this.graphic.rotation.y = (Math.PI / 2); this.scene.beginAnimation(this.camera, 0, 100, false, 1, () => { var shiplightspeedMove = new BABYLON.Animation("shiplightspeedMove", "position.y", 40, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE); var shipkeys = []; shipkeys.push({frame: 0, value: this.graphic.position.y}); shipkeys.push({frame: 25,value: this.graphic.position.y - 1000}); shipkeys.push({ frame: 100, value: this.graphic.position.y - 13000 }); shiplightspeedMove.setKeys(shipkeys); this.graphic.animations.push(shiplightspeedMove); this.scene.beginAnimation(this.graphic, 0, 100, false, 1, () => { gameLevel += 1; // Say to global that we can reset the scene if (this.jumpToLightSpeedEnd != null) { this.jumpToLightSpeedEnd(); } }); }); } } public addResources(resAmount: number) { var amount = resAmount; this.levelPoints += resAmount; this.gamePoints += resAmount if (this.pointsChanged != null) this.pointsChanged(this.levelPoints, this.gamePoints); if (this.lightSpeedGauge < this.lightSpeedGaugeCapacity) { // just check if amount > the rest of the bar amount = (this.lightSpeedGauge + amount > this.lightSpeedGaugeCapacity) ? (this.lightSpeedGaugeCapacity - this.lightSpeedGauge) : amount; this.lightSpeedGauge += amount; // Change light speed gauge in percent var newL = (this.lightSpeedGauge / this.lightSpeedGaugeCapacity) * 100; this.lightSpeedGaugeChange(newL.toString() + "%"); if (this.lightSpeedGauge >= this.lightSpeedGaugeCapacity) { if (this.lightSpeedReadyOccured != null) { this.lightSpeedReadyOccured(); } } } } public update(up: boolean, down: boolean, left: boolean, right: boolean, adjmovement: number, height: number, width: number, playingBoardSize: number) { if (this.canMove == false) { return; } if (this.health <= 0) { this.explode(); return; } var nextlvlneed = levelingDefs[this.shipLevel + 1].need; if (this.levelPoints >= nextlvlneed) { this.levelUp(); } ////////////player movement if (up && right) { this.graphic.rotation.y = Math.PI * .75; //up-and-right this.currentDirection = "upright"; } else if (up && left) { this.graphic.rotation.y = Math.PI / 4; //up-and-left this.currentDirection = "upleft"; } else if (down && right) { this.graphic.rotation.y = Math.PI * 1.25; //down-and-right this.currentDirection = "downright"; } else if (down && left) { this.graphic.rotation.y = Math.PI * 1.75; //down and left this.currentDirection = "downleft"; } else if (up) { this.graphic.rotation.y = Math.PI / 2; this.currentDirection = "up"; } else if (down) { this.graphic.rotation.y = Math.PI * 1.5; this.currentDirection = "down"; } else if (left) { this.graphic.rotation.y = 0; this.currentDirection = "left"; } else if (right) { this.graphic.rotation.y = Math.PI; this.currentDirection = "right"; } this.movez = Math.cos(Math.PI + this.graphic.rotation.y) * (this.speed * adjmovement);//this.speed*adjmovement; // need stat on player object this.movex = Math.sin(Math.PI + this.graphic.rotation.y) * (this.speed * adjmovement);//0; ///////////////////////// //////////Bound player inside sky box need width height of window for bounding if ((this.graphic.position.x + this.movex > height || this.graphic.position.x + this.movex < -height) || (this.graphic.position.z + this.movez > width || this.graphic.position.z + this.movez < -width)) { this.movez = 0; this.movex = 0; } if (this.graphic.position.x + this.movex < playingBoardSize && this.graphic.position.x + this.movex > -playingBoardSize) { ///500 this.cameraFollower.position.x = this.graphic.position.x + this.movex; } if (this.graphic.position.z + this.movez < playingBoardSize && this.graphic.position.z + this.movez > -playingBoardSize) { //500 this.cameraFollower.position.z = this.graphic.position.z + this.movez; } this.graphic.position.z += this.movez; this.graphic.position.x += this.movex; this.boundingBox.position.x = this.graphic.position.x; this.boundingBox.position.z = this.graphic.position.z; ////////////////////// ///////////////////////////////// this.laser.behavior(time, this, bulletobj2); //////player bullet movement/////// var totalB = this.bullets.length; while (totalB--) { this.bullets[totalB].graphic.position.x += Math.sin(Math.PI + this.bullets[totalB].direction) * ((this.speed * adjmovement) + (this.bulletSpeed * adjmovement)); this.bullets[totalB].graphic.position.z += Math.cos(Math.PI + this.bullets[totalB].direction) * ((this.speed * adjmovement) + (this.bulletSpeed * adjmovement)); /////////bullet disposal/////////// if (this.bullets[totalB].graphic.position.z > width + 50 || this.bullets[totalB].graphic.position.z < -width - 50 || this.bullets[totalB].graphic.position.x > height + 50 || this.bullets[totalB].graphic.position.x < -height - 50) { this.bullets[totalB].graphic.dispose(); this.bullets.splice(totalB, 1); } } } } }
the_stack
'use strict'; import { KongPlugin, KongApi, KongApiConfig } from "./kong-interfaces"; // ==================== // WICKED TYPES // ==================== /** * Options defining how wicked awaits an URL. */ export interface WickedAwaitOptions { /** The expected status code */ statusCode?: number, /** Maximum number of retries until wicked gives up */ maxTries?: number, /** Delay between retries (ms) */ retryDelay?: number } /** * Initialization options for the wicked SDK. */ export interface WickedInitOptions extends WickedAwaitOptions { /** A user agent name; do not use the `wicked` prefix, otherwise a strict version check is enforced. */ userAgentName: string, /** The version of your user agent, must be a valid SemVer (see http://semver.org). */ userAgentVersion: string, /** Defaults to `false`; if `false`, the wicked SDK will poll the `/confighash` end point of the wicked API to check for updated static configuration; if such is detected, the SDK will force quit the component to make the assumed orchestrator restart it. */ doNotPollConfigHash?: boolean, /** Retries before failing: The number of retries the SDK does before failing when accessing the wicked API. Defaults to 10. */ apiMaxTries?: number, /** Retry interval in ms; if an API call is failing, the SDK will retry after a certain amount of time again. Defaults to 500ms. */ apiRetryDelay?: number } export interface WickedGlobals { /** The wicked static config version (written by the Kickstarter, don't change this) */ version: number, title: string, footer: string, /** This contains the NODE_ENV of the API container */ environment: string, /** Selected password strategy identifier; use wicked SDK to get a list of supported strategies */ passwordStrategy: string, company: string, /** Group validated users are automatically assigned to */ validatedUsergGroup?: string, /** Used to validate that the secret config key is correct */ configKeyCheck: string, api?: WickedGlobalsApi network: WickedGlobalsNetwork, db: WickedGlobalsDb, sessionStore: WickedSessionStoreConfig, kongAdapter?: WickedKongAdapterConfig, portal: WickedPortalConfig, storage: WickedStorageConfig, initialUsers: WickedGlobalsInitialUser[], recaptcha: WickedRecaptchaConfig mailer: WickedMailerConfig chatbot: WickedChatbotConfig, layouts?: WickedLayoutConfig views?: WickedViewsConfig, } export interface WickedPasswordStrategy { /** Identifier of the strategy */ strategy: string, /** Description of the strategy */ description: string, /** Regex string of the password strategy, for use with `new RegExp()` */ regex: string } export interface WickedStorageConfig { type: WickedStorageType pgHost?: string pgPort?: number, pgUser?: string, pgPassword?: string } export enum WickedStorageType { JSON = 'json', Postgres = 'postgres' } export interface WickedPortalConfig { /** * Array of allowed auth methods for the portal login; in the form * `<auth server name>:<auth method name>`. * * Example: `["default:local", "default:google"]` */ authMethods: string[] } export interface WickedKongAdapterConfig { useKongAdapter: boolean, /** List of Kong plugins which the Kong Adapter doesn't touch when configuring Kong */ ignoreList: string[] } export interface WickedSessionStoreConfig { type: WickedSessionStoreType host?: string, port?: number, password?: string } export enum WickedSessionStoreType { Redis = 'redis', File = 'file' } export interface WickedViewsConfig { apis: { showApiIcon: boolean, titleTagline: string }, applications: { titleTagline: string }, application: { titleTagline: string } } export interface WickedLayoutConfig { defautRootUrl: string, defautRootUrlTarget: string, defautRootUrlText: null, menu: { homeLinkText: string, apisLinkVisibleToGuest: boolean, applicationsLinkVisibleToGuest: boolean, contactLinkVisibleToGuest: boolean, contentLinkVisibleToGuest: boolean, classForLoginSignupPosition: string, showSignupLink: boolean, loginLinkText: string }, footer: { showBuiltBy: boolean, showBuilds: boolean }, swaggerUi: { menu: { homeLinkText: string, showContactLink: boolean, showContentLink: boolean } } } export interface WickedChatbotConfig { username: string, icon_url: string, hookUrls: string[], events: WickedChatbotEventsConfig } export interface WickedChatbotEventsConfig { userSignedUp: boolean, userValidatedEmail: boolean, applicationAdded: boolean, applicationDeleted: boolean, subscriptionAdded: boolean, subscriptionDeleted: boolean, approvalRequired: boolean, lostPasswordRequest: boolean, verifyEmailRequest: boolean } export interface WickedMailerConfig { senderEmail: string, senderName: string, smtpHost: string, smtpPort?: number, username?: string, password?: string, adminEmail: string, adminName: string } export interface WickedRecaptchaConfig { useRecaptcha: boolean, websiteKey: string, secretKey: string } export interface WickedGlobalsApi { headerName: string, /** Required user group for subscribing to the portal-api internal API */ apiUserGroup?: string, /** Required user group for subscribing to the echo internal API */ echoUserGroup?: string } export interface WickedGlobalsNetwork { schema: string, portalHost: string, apiHost: string, apiUrl: string, portalUrl: string, kongAdapterUrl: string, kongAdminUrl: string, kongProxyUrl?: string, mailerUrl: string, chatbotUrl: string } export interface WickedGlobalsDb { staticConfig: string, dynamicConfig?: string } export interface WickedGlobalsInitialUser { id: string, customId?: string, name: string email: string, password?: string, validated?: boolean, groups: string[] } export interface WickedUserShortInfo { id: string, customId?: string, email: string, } export interface WickedUserCreateInfo { /** Specify the id of the user in case you are importing from a different system and * want to re-use the user IDs (for whatever reason). */ id?: string, customId?: string, email: string, password?: string, /** Pass "true" if you are creating the user with a pre-hashed password; supported hashing mechanisms are: * - `bcrypt(password)` * - `bcrypt(SHA256(password))` */ passwordIsHashed?: boolean, /** Pass "true" if the user must change the password when logging in the first time. */ mustChangePassword?: boolean, validated?: boolean, groups: string[] } export interface WickedUserInfo extends WickedUserCreateInfo { id: string, applications?: WickedApplication[] } export interface OidcProfile { sub: string, email?: string, email_verified?: boolean, preferred_username?: string, username?: string, name?: string, given_name?: string, family_name?: string, phone?: string, [key: string]: any }; export interface WickedApi { id: string, name: string, desc: string, auth: string, bundle?: string, tags?: string[], authMethods?: string[], registrationPool?: string, requiredGroup?: string, hide_credentials?: boolean, passthroughUsers?: boolean, passthroughScopeUrl?: string, settings: WickedApiSettings, _links?: any } export interface WickedApiCollection { apis: WickedApi[], _links?: any } export interface WickedApiSettings { enable_client_credentials?: boolean, enable_implicit_grant?: boolean, enable_authorization_code?: boolean, enable_password_grant?: boolean, mandatory_scope?: boolean, accept_http_if_terminated?: boolean, token_expiration?: string, refresh_token_ttl?: string, scopes: WickedApiScopes, tags: string[], plans: string[], internal?: boolean } export interface WickedApiScopes { [scope: string]: { description: string } } export interface WickedApiPlan { id: string, name: string, desc: string, needsApproval?: boolean, requiredGroup?: string, config: { plugins: KongPlugin[] } } export interface WickedApiPlanCollection { plans: WickedApiPlan[] } export interface WickedScopeGrant { scope: string, /** This is a date time object */ grantedDate?: string } export interface WickedGrant { userId?: string, apiId?: string, applicationId?: string, grants: WickedScopeGrant[] } export interface WickedAuthMethod { /** Protected Auth Methods aren't displayed in the UI (only for admins) */ protected?: boolean, enabled: string, name: string, type: string, friendlyShort: string, friendlyLong: string, config: any } export interface WickedAuthServer { id: string, name: string, authMethods: WickedAuthMethod[], config: KongApiConfig } export enum WickedOwnerRole { Owner = "owner", Collaborator = "collaborator", Reader = "reader" } export interface WickedOwner { userId: string, email: string, role: WickedOwnerRole } export enum WickedClientType { /** Confidential client, i.e. a client which can keep the client secret securely stored in the backend. Typical session-based applications. */ Confidential = "confidential", /** Public, browser based client. Cannot store a secret confidentially due to lack of backend server component. Typically a single page application. * When using the OAuth2 Authorization Code Grant, PKCE is required, and wicked will **not** return a refresh token. */ Public_SPA = "public_spa", /** Public, e.g. native or mobile application. Cannot store a secret confidentially, but can keep runtime data reasonably secure. * When using the OAuth2 Authorization Code Grant, PKCE is required, but in distinction to the `public_spa` client type, a refresh token * **is issued**. */ Public_Native = "public_native" } export interface WickedApplicationCreateInfo { id: string, name: string, /** Pass in either `redirectUri` or `redirectUris`; the latter is recommended for support of multiple redirect URIs. */ redirectUri?: string, /** Pass in either `redirectUri` or `redirectUris`; the latter is recommended for support of multiple redirect URIs. */ redirectUris?: string[], /** Deprecated; use `clientType` instead. */ confidential?: boolean, clientType?: WickedClientType } export interface WickedApplication extends WickedApplicationCreateInfo { ownerList: WickedOwner[] } export enum WickedAuthType { KeyAuth = "key-auth", OAuth2 = "oauth2" } export enum WickedApplicationRoleType { Admin = "admin", Collaborator = "collaborator", Reader = "reader" } export interface WickedApplicationRole { role: WickedApplicationRoleType, desc: string } export interface WickedSubscriptionCreateInfo { application: string, api: string, plan: string, auth: WickedAuthType, apikey?: string, trusted?: boolean, } export interface WickedSubscription extends WickedSubscriptionCreateInfo { clientId?: string, clientSecret?: string, approved: boolean, allowedScopesMode?: WickedSubscriptionScopeModeType, allowedScopes?: string[], changedBy?: string, changedDate?: string } export enum WickedSubscriptionScopeModeType { All = "all", None = "none", Select = "select" } export interface WickedSubscriptionPatchInfo { approved?: boolean, trusted?: boolean } export interface WickedSubscriptionInfo { application: WickedApplication, subscription: WickedSubscription } export enum WickedPoolPropertyType { String = "string" } export interface WickedPoolProperty { id: string, description: string, type: string, maxLength: number, minLength: number, required: boolean, oidcClaim: string } export interface WickedPool { id: string, name: string, requiresNamespace?: boolean, /** Disable interactive registration */ disableRegister?: boolean, properties: WickedPoolProperty[] } export interface WickedPoolMap { [poolId: string]: WickedPool } export interface WickedRegistration { userId: string, poolId: string, namespace?: string, [key: string]: any } export interface WickedRegistrationMap { pools: { [poolId: string]: WickedRegistration[] } } export interface WickedNamespace { namespace: string, poolId: string, description: string } export interface WickedGroup { id: string, name: string, alt_ids?: string[], adminGroup?: boolean, approverGroup?: boolean } export interface WickedGroupCollection { groups: WickedGroup[] } export interface WickedApproval { id: string, user: { id: string, name: string, email: string }, api: { id: string, name: string }, application: { id: string, name: string }, plan: { id: string, name: string } } export interface WickedVerification { id: string, type: WickedVerificationType, email: string, /** Not needed when creating, is returned on retrieval */ userId?: string, /** The fully qualified link to the verification page, with a placeholder for the ID (mustache {{id}}) */ link?: string } export enum WickedVerificationType { Email = 'email', LostPassword = 'lostpassword' } export interface WickedComponentHealth { name: string, message?: string, uptime: number, healthy: WickedComponentHealthType, pingUrl: string, pendingEvents: number } export enum WickedComponentHealthType { NotHealthy = 0, Healthy = 1, Initializing = 2 } export interface WickedChatbotTemplates { userLoggedIn: string, userSignedUp: string, userValidatedEmail: string, applicationAdded: string, applicationDeleted: string, subscriptionAdded: string, subscriptionDeleted: string, approvalRequired: string, lostPasswordRequest: string, verifyEmailRequest: string } export enum WickedEmailTemplateType { LostPassword = 'lost_password', PendingApproval = 'pending_approval', VerifyEmail = 'verify_email' } export interface WickedWebhookListener { id: string, url: string } export interface WickedEvent { id: string, action: WickedEventActionType, entity: WickedEventEntityType, href?: string, data?: object } export enum WickedEventActionType { Add = 'add', Update = 'update', Delete = 'delete', Password = 'password', Validated = 'validated', Login = 'login', /** Deprecated */ ImportFailed = 'failed', /** Deprecated */ ImportDone = 'done' } export enum WickedEventEntityType { Application = 'application', User = 'user', Subscription = 'subscription', Approval = 'approval', Owner = 'owner', Verification = 'verification', VerificationLostPassword = 'verification_lost_password', VerificationEmail = 'verification_email', /** Deprecated */ Export = 'export', /** Deprecated */ Import = 'import' } // OPTION TYPES /** * Generic parameters for paging collection output. */ export interface WickedGetOptions { /** The offset of the collection items to retrieve. Defaults to `0`. */ offset?: number, /** The maximum number of items a get operation retrieves. Specify `0` to retrieve **all** elements. **Note**: This can be a dangerous operation, depending on the amount of data in your data store. */ limit?: number } /** * Extended options for getting collections. */ export interface WickedGetCollectionOptions extends WickedGetOptions { /** * Specify keys and values to filter for when retrieving information. The filtering is case insensitive, and * searches specifically only for substrings. This does (currently) **not** support wild card searches. * * Example: `{ filter: { name: "herbert" }, order_by: "name ASC" }` */ filter?: { [field: string]: string }, /** Order by clause; syntax: `<field name> <ASC|DESC>`, e.g. `name DESC`. */ order_by?: string, /** * Specify `false` to make sure the paging return values (item count and such) are re-calculated. Otherwise * the wicked API makes use of a cached value for the item count for short amount of time. This option is * usually only used for integration testing, and does not play a role in application development. */ no_cache?: boolean } /** * Extended get options for wicked registrations. */ export interface WickedGetRegistrationOptions extends WickedGetCollectionOptions { /** * The namespace for which to retrieve registrations. In case the registration pool requires * namespaces, this is a required option, otherwise it's a forbidden option. */ namespace?: string } // ==================== // GENERICS // ==================== /** * A wrapper interface for returning typed collections. Contains additional information * which is useful for paging UI scenarios. */ export interface WickedCollection<T> { items: T[], /** The total count of items, disregarding paging (limit and options). */ count: number, /** Contains `true` if the total count (property `count`) was retrieved from the cache. */ count_cached: boolean, /** The offset of the items which were retrieved, if specified, otherwise `0`. */ offset: number, /** The maximum number of items in `items`, if specified, otherwise `0`. */ limit: number } // ==================== // CALLBACK TYPES // ==================== export interface ErrorCallback { (err): void } export interface Callback<T> { (err, t?: T): void } // ==================== // FUNCTION TYPES // ==================== export interface ExpressHandler { (req, res, next?): void } // ==================== // PASSTHROUGH HANDLING TYPES // ==================== /** * For APIs which use the `passthroughScopeUrl` property, this is the type of the * payload which is sent by `POST` to the instance to which the scope decision is * delegated. */ export interface PassthroughScopeRequest { /** If `scope` was passed to the authorize request, the scope is passed on upstream by the Authorization Server. Otherwise `null` or not present. */ scope?: string[], /** The ID of the auth method which is being used for this current request for authorization (new in 1.0.0-rc.8). */ auth_method: string, /** * The OpenID Connect compatible profile of the authenticated user. You will find a unique ID in the `sub` property, * plus other properties, depending on the type of identity provider which was used. */ profile: OidcProfile } /** * This is the expected response type of a service which is used for APIs which have specified * the `passthroughScopeUrl` parameter. Mandatory properties are `allow` and `authenticated_userid`, * which must contain information on whether the operation is allowed and if so, which user id is * to be associated with the access token which is about to be created. */ export interface PassthroughScopeResponse { /** Return `true` to allow the operation to continue, otherwise `false`. */ allow: boolean, /** In case `allow` contains `false`, it is recommended to return an error message stating "why" here. */ error_message?: string, /** Specify which user id is passed as the `X-Authenticated-UserId` to the API backends when presenting the created access token. */ authenticated_userid: string, /** An array of valid scopes for the API; please note that the list of scopes must be configured on the API, otherwise a subsequent error will be generated (by the API Gateway). */ authenticated_scope?: string[] } /** * Interface describing the expected response of a scope lookup request from the portal API, if this * property is set on a specific API. When doing a GET on the specified endpoint, this is the format * of the data which has to be returned. * * Example: * * ``` * { * "scope1": { * "description": "This is scope 1" * }, * "scope2": { * "description": "This is another scope" * } * } * ``` */ export interface ScopeLookupResponse { [scope: string]: { description: string } } /** This is the request which is sent out as a POST to a 3rd party username/password validator * if an auth method of the type "external" is configured. */ export interface ExternalUserPassRequest { /** The username in clear text; this does not necessarily have to be an email address, but may be */ username: string, /** The password in clear text */ password: string } /** * The expected response type, as a JSON object, of a request to the username/password validation end * point, for auth methods using the "external" auth method type. */ export interface ExternalUserPassResponse { /** * Mandatory properties: * - sub * - email * * Can be left empty if request is not successful. */ profile?: OidcProfile, /** Short error message if request was not successful */ error?: string, /** Optional longer error message if request was not successful */ error_description?: string } /** * For auth methods using the ”external" type, this is the payload of requests which are sent to * the backend prior to allowing access tokens to be refreshed. */ export interface ExternalRefreshRequest { /** * The authenticated user ID of the user requesting a refreshed token; depending on whether * the API uses passthrough users or wicked backed users, this is either the value * from the the @ExternalUserPassResponse as `sub=<sub value from profile> (when using * passthrough users), or a field containing `sub=<wicked user id>` (when using wicked backed * users). May also contain a `;namespaces=` property. */ authenticated_userid: string, /** * This is just for information the scope for which the initial access token was created. * Refreshed tokens are created with the same scope, and cannot be changed here. */ authenticated_scope?: string } /** * Expected response (as JSON) of an ExternalRefreshRequest. Contains information on whether * the refresh request shall be allowed or not. */ export interface ExternalRefreshResponse { /** Return true to allow refresh, otherwise false. */ allow_refresh: boolean, /** * Optional error message if allow_refresh is returned as false. This string may be used * in end-user facing communication. */ error?: string, /** * Optional longer error description in case allow_refresh is returned as false. * This string may be used in end-user facing communication. */ error_description?: string, }
the_stack
export namespace TrendPredictionModels { /** * All the information needed to identify a variable. * @export * @interface BasicVariableDefinition */ export interface BasicVariableDefinition { /** * * @type {string} * @memberof BasicVariableDefinition */ entityId: string; /** * * @type {string} * @memberof BasicVariableDefinition */ propertySetName: string; } /** * All the information needed to identify a variable. * @export * @interface BasicVariableDefinitionDirect */ export interface BasicVariableDefinitionDirect { /** * * @type {string} * @memberof BasicVariableDefinitionDirect */ assetId: string; /** * * @type {string} * @memberof BasicVariableDefinitionDirect */ aspectName: string; } /** * All the information needed to identify a variable. * @export * @interface BasicVariableDefinitionPredictDirect */ export interface BasicVariableDefinitionPredictDirect { /** * * @type {string} * @memberof BasicVariableDefinitionPredictDirect */ assetId: string; /** * * @type {string} * @memberof BasicVariableDefinitionPredictDirect */ aspectName: string; /** * * @type {string} * @memberof BasicVariableDefinitionPredictDirect */ variableNames?: string; } /** * * @export * @interface Link */ export interface Link { /** * * @type {string} * @memberof Link */ href?: string; /** * * @type {string} * @memberof Link */ rel?: string; /** * * @type {boolean} * @memberof Link */ templated?: boolean; } /** * A trained regression model. * @export * @interface ModelDto */ export interface ModelDto { /** * * @type {string} * @memberof ModelDto */ id?: string; /** * * @type {MultivarParams} * @memberof ModelDto */ metadataConfiguration?: MultivarParams; /** * * @type {number} * @memberof ModelDto */ intercept?: number; /** * * @type {Array<number>} * @memberof ModelDto */ coefficients?: Array<number>; /** * * @type {string} * @memberof ModelDto */ creationDate?: string; } /** * A trained regression model. * @export * @interface ModelDtoDirect */ export interface ModelDtoDirect { /** * * @type {string} * @memberof ModelDtoDirect */ id?: string; /** * * @type {MultivarParamsDirect} * @memberof ModelDtoDirect */ metadataConfiguration?: MultivarParamsDirect; /** * * @type {number} * @memberof ModelDtoDirect */ intercept?: number; /** * * @type {Array<number>} * @memberof ModelDtoDirect */ coefficients?: Array<number>; /** * * @type {string} * @memberof ModelDtoDirect */ creationDate?: string; } /** * All the information needed to identify both the input and output variables. * @export * @interface MultivarParams */ export interface MultivarParams { /** * * @type {VariableDefinition} * @memberof MultivarParams */ outputVariable?: VariableDefinition; /** * * @type {Array<VariableDefinition>} * @memberof MultivarParams */ inputVariables?: Array<VariableDefinition>; } /** * All the information needed to identify both the input and output variables. * @export * @interface MultivarParamsDirect */ export interface MultivarParamsDirect { /** * * @type {VariableDefinitionDirect} * @memberof MultivarParamsDirect */ outputVariable?: VariableDefinitionDirect; /** * * @type {Array<VariableDefinitionDirect>} * @memberof MultivarParamsDirect */ inputVariables?: Array<VariableDefinitionDirect>; } /** * Data structure containing all information required for predicting future values of a given output variable using a pre-trained regression model. * @export * @interface PredictBody */ export interface PredictBody { /** * * @type {PredictBodyModelConfiguration} * @memberof PredictBody */ modelConfiguration?: PredictBodyModelConfiguration; /** * * @type {Array<VariableToTimeseries>} * @memberof PredictBody */ predictionData?: Array<VariableToTimeseries>; } /** * Data structure containing all information required for predicting future values of a given output variable using a pre-trained regression model. * @export * @interface PredictBodyDirect */ export interface PredictBodyDirect { /** * * @type {PredictBodyModelConfiguration} * @memberof PredictBodyDirect */ modelConfiguration?: PredictBodyModelConfiguration; /** * * @type {Array<VariableToTimeseriesDirect>} * @memberof PredictBodyDirect */ predictionData?: Array<VariableToTimeseriesDirect>; } /** * * @export * @interface PredictBodyModelConfiguration */ export interface PredictBodyModelConfiguration { /** * * @type {string} * @memberof PredictBodyModelConfiguration */ modelId?: string; } /** * An array containing the predicted values of a given output variable. * @export * @interface PredictionDataArray */ export interface PredictionDataArray extends Array<VariableToTimeseries> {} /** * An array containing the predicted values of a given output variable. * @export * @interface PredictionDataArrayDirect */ export interface PredictionDataArrayDirect extends Array<VariableToTimeseriesResponseDirect> {} /** * * @export * @interface Timeseries */ export interface Timeseries { [key: string]: any | any; /** * time * @type {string} * @memberof Timeseries */ time?: string; } /** * Data structure containing all information required for training a regression model. * @export * @interface TrainBody */ export interface TrainBody { /** * * @type {TrainBodyModelConfiguration} * @memberof TrainBody */ modelConfiguration?: TrainBodyModelConfiguration; /** * * @type {MultivarParams} * @memberof TrainBody */ metadataConfiguration?: MultivarParams; /** * * @type {Array<VariableToTimeseries>} * @memberof TrainBody */ trainingData?: Array<VariableToTimeseries>; } /** * Data structure containing all information required for training a regression model. * @export * @interface TrainBodyDirect */ export interface TrainBodyDirect { /** * * @type {TrainBodyModelConfiguration} * @memberof TrainBodyDirect */ modelConfiguration?: TrainBodyModelConfiguration; /** * * @type {MultivarParamsDirect} * @memberof TrainBodyDirect */ metadataConfiguration?: MultivarParamsDirect; } /** * * @export * @interface TrainBodyModelConfiguration */ export interface TrainBodyModelConfiguration { /** * Degree of the polynomial to be fitted. If not specified, a default value 1 (corresponding to the linear regression) will be used. * @type {number} * @memberof TrainBodyModelConfiguration */ polynomialDegree?: number; } /** * Data structure containing all information required for training a regression model and predicting future values of a given output variable. * @export * @interface TrainPredictBody */ export interface TrainPredictBody { /** * * @type {TrainBodyModelConfiguration} * @memberof TrainPredictBody */ modelConfiguration?: TrainBodyModelConfiguration; /** * * @type {MultivarParams} * @memberof TrainPredictBody */ metadataConfiguration?: MultivarParams; /** * * @type {Array<VariableToTimeseries>} * @memberof TrainPredictBody */ trainingData?: Array<VariableToTimeseries>; /** * * @type {Array<VariableToTimeseries>} * @memberof TrainPredictBody */ predictionData?: Array<VariableToTimeseries>; } /** * Data structure containing all information required for training a regression model and predicting future values of a given output variable. * @export * @interface TrainPredictBodyDirect */ export interface TrainPredictBodyDirect { /** * * @type {TrainBodyModelConfiguration} * @memberof TrainPredictBodyDirect */ modelConfiguration?: TrainBodyModelConfiguration; /** * * @type {MultivarParamsDirect} * @memberof TrainPredictBodyDirect */ metadataConfiguration?: MultivarParamsDirect; } /** * All the information needed to identify a variable. * @export * @interface VariableDefinition */ export interface VariableDefinition extends BasicVariableDefinition { /** * * @type {string} * @memberof VariableDefinition */ propertyName?: string; } /** * All the information needed to identify a variable. * @export * @interface VariableDefinitionDirect */ export interface VariableDefinitionDirect extends BasicVariableDefinitionDirect { /** * * @type {string} * @memberof VariableDefinitionDirect */ variableName?: string; } /** * Data structure which allows to map the time series values to a given variable. * @export * @interface VariableToTimeseries */ export interface VariableToTimeseries { /** * * @type {BasicVariableDefinition} * @memberof VariableToTimeseries */ variable?: BasicVariableDefinition; /** * * @type {Array<Timeseries>} * @memberof VariableToTimeseries */ timeSeries?: Array<Timeseries>; } /** * Data structure which allows to map the time series values to a given variable. * @export * @interface VariableToTimeseriesDirect */ export interface VariableToTimeseriesDirect { /** * * @type {BasicVariableDefinitionPredictDirect} * @memberof VariableToTimeseriesDirect */ variable?: BasicVariableDefinitionPredictDirect; } /** * Data structure which allows to map the time series values to a given variable. * @export * @interface VariableToTimeseriesResponseDirect */ export interface VariableToTimeseriesResponseDirect { /** * * @type {BasicVariableDefinitionDirect} * @memberof VariableToTimeseriesResponseDirect */ variable?: BasicVariableDefinitionDirect; /** * * @type {Array<Timeseries>} * @memberof VariableToTimeseriesResponseDirect */ timeSeries?: Array<Timeseries>; } /** * * @export * @interface VndError */ export interface VndError { /** * * @type {Array<Link>} * @memberof VndError */ links?: Array<Link>; /** * * @type {string} * @memberof VndError */ logref?: string; /** * * @type {string} * @memberof VndError */ message?: string; } }
the_stack
import * as $protobuf from 'protobufjs'; /** Namespace cosmos. */ export namespace cosmos { /** Namespace base. */ namespace base { /** Namespace v1beta1. */ namespace v1beta1 { /** Properties of a Coin. */ interface ICoin { /** Coin denom */ denom?: string | null; /** Coin amount */ amount?: string | null; } /** Represents a Coin. */ class Coin implements ICoin { /** * Constructs a new Coin. * @param [p] Properties to set */ constructor(p?: cosmos.base.v1beta1.ICoin); /** Coin denom. */ public denom: string; /** Coin amount. */ public amount: string; /** * Creates a new Coin instance using the specified properties. * @param [properties] Properties to set * @returns Coin instance */ public static create(properties?: cosmos.base.v1beta1.ICoin): cosmos.base.v1beta1.Coin; /** * Encodes the specified Coin message. Does not implicitly {@link cosmos.base.v1beta1.Coin.verify|verify} messages. * @param m Coin message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.base.v1beta1.ICoin, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Coin message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Coin * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): cosmos.base.v1beta1.Coin; /** * Creates a Coin message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Coin */ public static fromObject(d: { [k: string]: any }): cosmos.base.v1beta1.Coin; /** * Creates a plain object from a Coin message. Also converts values to other types if specified. * @param m Coin * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.base.v1beta1.Coin, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Coin to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DecCoin. */ interface IDecCoin { /** DecCoin denom */ denom?: string | null; /** DecCoin amount */ amount?: string | null; } /** Represents a DecCoin. */ class DecCoin implements IDecCoin { /** * Constructs a new DecCoin. * @param [p] Properties to set */ constructor(p?: cosmos.base.v1beta1.IDecCoin); /** DecCoin denom. */ public denom: string; /** DecCoin amount. */ public amount: string; /** * Creates a new DecCoin instance using the specified properties. * @param [properties] Properties to set * @returns DecCoin instance */ public static create(properties?: cosmos.base.v1beta1.IDecCoin): cosmos.base.v1beta1.DecCoin; /** * Encodes the specified DecCoin message. Does not implicitly {@link cosmos.base.v1beta1.DecCoin.verify|verify} messages. * @param m DecCoin message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.base.v1beta1.IDecCoin, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DecCoin message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns DecCoin * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): cosmos.base.v1beta1.DecCoin; /** * Creates a DecCoin message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns DecCoin */ public static fromObject(d: { [k: string]: any }): cosmos.base.v1beta1.DecCoin; /** * Creates a plain object from a DecCoin message. Also converts values to other types if specified. * @param m DecCoin * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.base.v1beta1.DecCoin, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DecCoin to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an IntProto. */ interface IIntProto { /** IntProto int */ int?: string | null; } /** Represents an IntProto. */ class IntProto implements IIntProto { /** * Constructs a new IntProto. * @param [p] Properties to set */ constructor(p?: cosmos.base.v1beta1.IIntProto); /** IntProto int. */ public int: string; /** * Creates a new IntProto instance using the specified properties. * @param [properties] Properties to set * @returns IntProto instance */ public static create(properties?: cosmos.base.v1beta1.IIntProto): cosmos.base.v1beta1.IntProto; /** * Encodes the specified IntProto message. Does not implicitly {@link cosmos.base.v1beta1.IntProto.verify|verify} messages. * @param m IntProto message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.base.v1beta1.IIntProto, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an IntProto message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns IntProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): cosmos.base.v1beta1.IntProto; /** * Creates an IntProto message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns IntProto */ public static fromObject(d: { [k: string]: any }): cosmos.base.v1beta1.IntProto; /** * Creates a plain object from an IntProto message. Also converts values to other types if specified. * @param m IntProto * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.base.v1beta1.IntProto, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this IntProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DecProto. */ interface IDecProto { /** DecProto dec */ dec?: string | null; } /** Represents a DecProto. */ class DecProto implements IDecProto { /** * Constructs a new DecProto. * @param [p] Properties to set */ constructor(p?: cosmos.base.v1beta1.IDecProto); /** DecProto dec. */ public dec: string; /** * Creates a new DecProto instance using the specified properties. * @param [properties] Properties to set * @returns DecProto instance */ public static create(properties?: cosmos.base.v1beta1.IDecProto): cosmos.base.v1beta1.DecProto; /** * Encodes the specified DecProto message. Does not implicitly {@link cosmos.base.v1beta1.DecProto.verify|verify} messages. * @param m DecProto message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.base.v1beta1.IDecProto, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DecProto message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns DecProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): cosmos.base.v1beta1.DecProto; /** * Creates a DecProto message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns DecProto */ public static fromObject(d: { [k: string]: any }): cosmos.base.v1beta1.DecProto; /** * Creates a plain object from a DecProto message. Also converts values to other types if specified. * @param m DecProto * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.base.v1beta1.DecProto, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DecProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } /** Namespace bank. */ namespace bank { /** Namespace v1beta1. */ namespace v1beta1 { /** Properties of a Params. */ interface IParams { /** Params sendEnabled */ sendEnabled?: cosmos.bank.v1beta1.ISendEnabled[] | null; /** Params defaultSendEnabled */ defaultSendEnabled?: boolean | null; } /** Represents a Params. */ class Params implements IParams { /** * Constructs a new Params. * @param [p] Properties to set */ constructor(p?: cosmos.bank.v1beta1.IParams); /** Params sendEnabled. */ public sendEnabled: cosmos.bank.v1beta1.ISendEnabled[]; /** Params defaultSendEnabled. */ public defaultSendEnabled: boolean; /** * Creates a new Params instance using the specified properties. * @param [properties] Properties to set * @returns Params instance */ public static create(properties?: cosmos.bank.v1beta1.IParams): cosmos.bank.v1beta1.Params; /** * Encodes the specified Params message. Does not implicitly {@link cosmos.bank.v1beta1.Params.verify|verify} messages. * @param m Params message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.bank.v1beta1.IParams, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Params message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Params * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): cosmos.bank.v1beta1.Params; /** * Creates a Params message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Params */ public static fromObject(d: { [k: string]: any }): cosmos.bank.v1beta1.Params; /** * Creates a plain object from a Params message. Also converts values to other types if specified. * @param m Params * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.bank.v1beta1.Params, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Params to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a SendEnabled. */ interface ISendEnabled { /** SendEnabled denom */ denom?: string | null; /** SendEnabled enabled */ enabled?: boolean | null; } /** Represents a SendEnabled. */ class SendEnabled implements ISendEnabled { /** * Constructs a new SendEnabled. * @param [p] Properties to set */ constructor(p?: cosmos.bank.v1beta1.ISendEnabled); /** SendEnabled denom. */ public denom: string; /** SendEnabled enabled. */ public enabled: boolean; /** * Creates a new SendEnabled instance using the specified properties. * @param [properties] Properties to set * @returns SendEnabled instance */ public static create(properties?: cosmos.bank.v1beta1.ISendEnabled): cosmos.bank.v1beta1.SendEnabled; /** * Encodes the specified SendEnabled message. Does not implicitly {@link cosmos.bank.v1beta1.SendEnabled.verify|verify} messages. * @param m SendEnabled message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.bank.v1beta1.ISendEnabled, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a SendEnabled message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns SendEnabled * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): cosmos.bank.v1beta1.SendEnabled; /** * Creates a SendEnabled message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns SendEnabled */ public static fromObject(d: { [k: string]: any }): cosmos.bank.v1beta1.SendEnabled; /** * Creates a plain object from a SendEnabled message. Also converts values to other types if specified. * @param m SendEnabled * @param [o] Conversion options * @returns Plain object */ public static toObject( m: cosmos.bank.v1beta1.SendEnabled, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this SendEnabled to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an Input. */ interface IInput { /** Input address */ address?: string | null; /** Input coins */ coins?: cosmos.base.v1beta1.ICoin[] | null; } /** Represents an Input. */ class Input implements IInput { /** * Constructs a new Input. * @param [p] Properties to set */ constructor(p?: cosmos.bank.v1beta1.IInput); /** Input address. */ public address: string; /** Input coins. */ public coins: cosmos.base.v1beta1.ICoin[]; /** * Creates a new Input instance using the specified properties. * @param [properties] Properties to set * @returns Input instance */ public static create(properties?: cosmos.bank.v1beta1.IInput): cosmos.bank.v1beta1.Input; /** * Encodes the specified Input message. Does not implicitly {@link cosmos.bank.v1beta1.Input.verify|verify} messages. * @param m Input message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.bank.v1beta1.IInput, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Input message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Input * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): cosmos.bank.v1beta1.Input; /** * Creates an Input message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Input */ public static fromObject(d: { [k: string]: any }): cosmos.bank.v1beta1.Input; /** * Creates a plain object from an Input message. Also converts values to other types if specified. * @param m Input * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.bank.v1beta1.Input, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Input to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an Output. */ interface IOutput { /** Output address */ address?: string | null; /** Output coins */ coins?: cosmos.base.v1beta1.ICoin[] | null; } /** Represents an Output. */ class Output implements IOutput { /** * Constructs a new Output. * @param [p] Properties to set */ constructor(p?: cosmos.bank.v1beta1.IOutput); /** Output address. */ public address: string; /** Output coins. */ public coins: cosmos.base.v1beta1.ICoin[]; /** * Creates a new Output instance using the specified properties. * @param [properties] Properties to set * @returns Output instance */ public static create(properties?: cosmos.bank.v1beta1.IOutput): cosmos.bank.v1beta1.Output; /** * Encodes the specified Output message. Does not implicitly {@link cosmos.bank.v1beta1.Output.verify|verify} messages. * @param m Output message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.bank.v1beta1.IOutput, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Output message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Output * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): cosmos.bank.v1beta1.Output; /** * Creates an Output message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Output */ public static fromObject(d: { [k: string]: any }): cosmos.bank.v1beta1.Output; /** * Creates a plain object from an Output message. Also converts values to other types if specified. * @param m Output * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.bank.v1beta1.Output, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Output to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Supply. */ interface ISupply { /** Supply total */ total?: cosmos.base.v1beta1.ICoin[] | null; } /** Represents a Supply. */ class Supply implements ISupply { /** * Constructs a new Supply. * @param [p] Properties to set */ constructor(p?: cosmos.bank.v1beta1.ISupply); /** Supply total. */ public total: cosmos.base.v1beta1.ICoin[]; /** * Creates a new Supply instance using the specified properties. * @param [properties] Properties to set * @returns Supply instance */ public static create(properties?: cosmos.bank.v1beta1.ISupply): cosmos.bank.v1beta1.Supply; /** * Encodes the specified Supply message. Does not implicitly {@link cosmos.bank.v1beta1.Supply.verify|verify} messages. * @param m Supply message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.bank.v1beta1.ISupply, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Supply message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Supply * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): cosmos.bank.v1beta1.Supply; /** * Creates a Supply message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Supply */ public static fromObject(d: { [k: string]: any }): cosmos.bank.v1beta1.Supply; /** * Creates a plain object from a Supply message. Also converts values to other types if specified. * @param m Supply * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.bank.v1beta1.Supply, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Supply to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DenomUnit. */ interface IDenomUnit { /** DenomUnit denom */ denom?: string | null; /** DenomUnit exponent */ exponent?: number | null; /** DenomUnit aliases */ aliases?: string[] | null; } /** Represents a DenomUnit. */ class DenomUnit implements IDenomUnit { /** * Constructs a new DenomUnit. * @param [p] Properties to set */ constructor(p?: cosmos.bank.v1beta1.IDenomUnit); /** DenomUnit denom. */ public denom: string; /** DenomUnit exponent. */ public exponent: number; /** DenomUnit aliases. */ public aliases: string[]; /** * Creates a new DenomUnit instance using the specified properties. * @param [properties] Properties to set * @returns DenomUnit instance */ public static create(properties?: cosmos.bank.v1beta1.IDenomUnit): cosmos.bank.v1beta1.DenomUnit; /** * Encodes the specified DenomUnit message. Does not implicitly {@link cosmos.bank.v1beta1.DenomUnit.verify|verify} messages. * @param m DenomUnit message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.bank.v1beta1.IDenomUnit, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DenomUnit message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns DenomUnit * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): cosmos.bank.v1beta1.DenomUnit; /** * Creates a DenomUnit message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns DenomUnit */ public static fromObject(d: { [k: string]: any }): cosmos.bank.v1beta1.DenomUnit; /** * Creates a plain object from a DenomUnit message. Also converts values to other types if specified. * @param m DenomUnit * @param [o] Conversion options * @returns Plain object */ public static toObject( m: cosmos.bank.v1beta1.DenomUnit, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this DenomUnit to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Metadata. */ interface IMetadata { /** Metadata description */ description?: string | null; /** Metadata denomUnits */ denomUnits?: cosmos.bank.v1beta1.IDenomUnit[] | null; /** Metadata base */ base?: string | null; /** Metadata display */ display?: string | null; /** Metadata name */ name?: string | null; /** Metadata symbol */ symbol?: string | null; } /** Represents a Metadata. */ class Metadata implements IMetadata { /** * Constructs a new Metadata. * @param [p] Properties to set */ constructor(p?: cosmos.bank.v1beta1.IMetadata); /** Metadata description. */ public description: string; /** Metadata denomUnits. */ public denomUnits: cosmos.bank.v1beta1.IDenomUnit[]; /** Metadata base. */ public base: string; /** Metadata display. */ public display: string; /** Metadata name. */ public name: string; /** Metadata symbol. */ public symbol: string; /** * Creates a new Metadata instance using the specified properties. * @param [properties] Properties to set * @returns Metadata instance */ public static create(properties?: cosmos.bank.v1beta1.IMetadata): cosmos.bank.v1beta1.Metadata; /** * Encodes the specified Metadata message. Does not implicitly {@link cosmos.bank.v1beta1.Metadata.verify|verify} messages. * @param m Metadata message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.bank.v1beta1.IMetadata, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Metadata message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Metadata * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): cosmos.bank.v1beta1.Metadata; /** * Creates a Metadata message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Metadata */ public static fromObject(d: { [k: string]: any }): cosmos.bank.v1beta1.Metadata; /** * Creates a plain object from a Metadata message. Also converts values to other types if specified. * @param m Metadata * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.bank.v1beta1.Metadata, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Metadata to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } } /** Namespace osmosis. */ export namespace osmosis { /** Namespace gamm. */ namespace gamm { /** Namespace v1beta1. */ namespace v1beta1 { /** Properties of a PoolAsset. */ interface IPoolAsset { /** PoolAsset token */ token?: cosmos.base.v1beta1.ICoin | null; /** PoolAsset weight */ weight?: string | null; } /** Represents a PoolAsset. */ class PoolAsset implements IPoolAsset { /** * Constructs a new PoolAsset. * @param [p] Properties to set */ constructor(p?: osmosis.gamm.v1beta1.IPoolAsset); /** PoolAsset token. */ public token?: cosmos.base.v1beta1.ICoin | null; /** PoolAsset weight. */ public weight: string; /** * Creates a new PoolAsset instance using the specified properties. * @param [properties] Properties to set * @returns PoolAsset instance */ public static create(properties?: osmosis.gamm.v1beta1.IPoolAsset): osmosis.gamm.v1beta1.PoolAsset; /** * Encodes the specified PoolAsset message. Does not implicitly {@link osmosis.gamm.v1beta1.PoolAsset.verify|verify} messages. * @param m PoolAsset message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: osmosis.gamm.v1beta1.IPoolAsset, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PoolAsset message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns PoolAsset * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): osmosis.gamm.v1beta1.PoolAsset; /** * Creates a PoolAsset message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns PoolAsset */ public static fromObject(d: { [k: string]: any }): osmosis.gamm.v1beta1.PoolAsset; /** * Creates a plain object from a PoolAsset message. Also converts values to other types if specified. * @param m PoolAsset * @param [o] Conversion options * @returns Plain object */ public static toObject( m: osmosis.gamm.v1beta1.PoolAsset, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this PoolAsset to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a SmoothWeightChangeParams. */ interface ISmoothWeightChangeParams { /** SmoothWeightChangeParams startTime */ startTime?: google.protobuf.ITimestamp | null; /** SmoothWeightChangeParams duration */ duration?: google.protobuf.IDuration | null; /** SmoothWeightChangeParams initialPoolWeights */ initialPoolWeights?: osmosis.gamm.v1beta1.IPoolAsset[] | null; /** SmoothWeightChangeParams targetPoolWeights */ targetPoolWeights?: osmosis.gamm.v1beta1.IPoolAsset[] | null; } /** Represents a SmoothWeightChangeParams. */ class SmoothWeightChangeParams implements ISmoothWeightChangeParams { /** * Constructs a new SmoothWeightChangeParams. * @param [p] Properties to set */ constructor(p?: osmosis.gamm.v1beta1.ISmoothWeightChangeParams); /** SmoothWeightChangeParams startTime. */ public startTime?: google.protobuf.ITimestamp | null; /** SmoothWeightChangeParams duration. */ public duration?: google.protobuf.IDuration | null; /** SmoothWeightChangeParams initialPoolWeights. */ public initialPoolWeights: osmosis.gamm.v1beta1.IPoolAsset[]; /** SmoothWeightChangeParams targetPoolWeights. */ public targetPoolWeights: osmosis.gamm.v1beta1.IPoolAsset[]; /** * Creates a new SmoothWeightChangeParams instance using the specified properties. * @param [properties] Properties to set * @returns SmoothWeightChangeParams instance */ public static create( properties?: osmosis.gamm.v1beta1.ISmoothWeightChangeParams ): osmosis.gamm.v1beta1.SmoothWeightChangeParams; /** * Encodes the specified SmoothWeightChangeParams message. Does not implicitly {@link osmosis.gamm.v1beta1.SmoothWeightChangeParams.verify|verify} messages. * @param m SmoothWeightChangeParams message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: osmosis.gamm.v1beta1.ISmoothWeightChangeParams, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a SmoothWeightChangeParams message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns SmoothWeightChangeParams * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode( r: $protobuf.Reader | Uint8Array, l?: number ): osmosis.gamm.v1beta1.SmoothWeightChangeParams; /** * Creates a SmoothWeightChangeParams message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns SmoothWeightChangeParams */ public static fromObject(d: { [k: string]: any }): osmosis.gamm.v1beta1.SmoothWeightChangeParams; /** * Creates a plain object from a SmoothWeightChangeParams message. Also converts values to other types if specified. * @param m SmoothWeightChangeParams * @param [o] Conversion options * @returns Plain object */ public static toObject( m: osmosis.gamm.v1beta1.SmoothWeightChangeParams, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this SmoothWeightChangeParams to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PoolParams. */ interface IPoolParams { /** PoolParams swapFee */ swapFee?: string | null; /** PoolParams exitFee */ exitFee?: string | null; /** PoolParams smoothWeightChangeParams */ smoothWeightChangeParams?: osmosis.gamm.v1beta1.ISmoothWeightChangeParams | null; } /** Represents a PoolParams. */ class PoolParams implements IPoolParams { /** * Constructs a new PoolParams. * @param [p] Properties to set */ constructor(p?: osmosis.gamm.v1beta1.IPoolParams); /** PoolParams swapFee. */ public swapFee: string; /** PoolParams exitFee. */ public exitFee: string; /** PoolParams smoothWeightChangeParams. */ public smoothWeightChangeParams?: osmosis.gamm.v1beta1.ISmoothWeightChangeParams | null; /** * Creates a new PoolParams instance using the specified properties. * @param [properties] Properties to set * @returns PoolParams instance */ public static create(properties?: osmosis.gamm.v1beta1.IPoolParams): osmosis.gamm.v1beta1.PoolParams; /** * Encodes the specified PoolParams message. Does not implicitly {@link osmosis.gamm.v1beta1.PoolParams.verify|verify} messages. * @param m PoolParams message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: osmosis.gamm.v1beta1.IPoolParams, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PoolParams message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns PoolParams * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): osmosis.gamm.v1beta1.PoolParams; /** * Creates a PoolParams message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns PoolParams */ public static fromObject(d: { [k: string]: any }): osmosis.gamm.v1beta1.PoolParams; /** * Creates a plain object from a PoolParams message. Also converts values to other types if specified. * @param m PoolParams * @param [o] Conversion options * @returns Plain object */ public static toObject( m: osmosis.gamm.v1beta1.PoolParams, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this PoolParams to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgCreatePool. */ interface IMsgCreatePool { /** MsgCreatePool sender */ sender?: string | null; /** MsgCreatePool poolParams */ poolParams?: osmosis.gamm.v1beta1.IPoolParams | null; /** MsgCreatePool poolAssets */ poolAssets?: osmosis.gamm.v1beta1.IPoolAsset[] | null; /** MsgCreatePool futurePoolGovernor */ futurePoolGovernor?: string | null; } /** Represents a MsgCreatePool. */ class MsgCreatePool implements IMsgCreatePool { /** * Constructs a new MsgCreatePool. * @param [p] Properties to set */ constructor(p?: osmosis.gamm.v1beta1.IMsgCreatePool); /** MsgCreatePool sender. */ public sender: string; /** MsgCreatePool poolParams. */ public poolParams?: osmosis.gamm.v1beta1.IPoolParams | null; /** MsgCreatePool poolAssets. */ public poolAssets: osmosis.gamm.v1beta1.IPoolAsset[]; /** MsgCreatePool futurePoolGovernor. */ public futurePoolGovernor: string; /** * Creates a new MsgCreatePool instance using the specified properties. * @param [properties] Properties to set * @returns MsgCreatePool instance */ public static create(properties?: osmosis.gamm.v1beta1.IMsgCreatePool): osmosis.gamm.v1beta1.MsgCreatePool; /** * Encodes the specified MsgCreatePool message. Does not implicitly {@link osmosis.gamm.v1beta1.MsgCreatePool.verify|verify} messages. * @param m MsgCreatePool message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: osmosis.gamm.v1beta1.IMsgCreatePool, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgCreatePool message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgCreatePool * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): osmosis.gamm.v1beta1.MsgCreatePool; /** * Creates a MsgCreatePool message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgCreatePool */ public static fromObject(d: { [k: string]: any }): osmosis.gamm.v1beta1.MsgCreatePool; /** * Creates a plain object from a MsgCreatePool message. Also converts values to other types if specified. * @param m MsgCreatePool * @param [o] Conversion options * @returns Plain object */ public static toObject( m: osmosis.gamm.v1beta1.MsgCreatePool, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this MsgCreatePool to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgJoinPool. */ interface IMsgJoinPool { /** MsgJoinPool sender */ sender?: string | null; /** MsgJoinPool poolId */ poolId?: Long | null; /** MsgJoinPool shareOutAmount */ shareOutAmount?: string | null; /** MsgJoinPool tokenInMaxs */ tokenInMaxs?: cosmos.base.v1beta1.ICoin[] | null; } /** Represents a MsgJoinPool. */ class MsgJoinPool implements IMsgJoinPool { /** * Constructs a new MsgJoinPool. * @param [p] Properties to set */ constructor(p?: osmosis.gamm.v1beta1.IMsgJoinPool); /** MsgJoinPool sender. */ public sender: string; /** MsgJoinPool poolId. */ public poolId: Long; /** MsgJoinPool shareOutAmount. */ public shareOutAmount: string; /** MsgJoinPool tokenInMaxs. */ public tokenInMaxs: cosmos.base.v1beta1.ICoin[]; /** * Creates a new MsgJoinPool instance using the specified properties. * @param [properties] Properties to set * @returns MsgJoinPool instance */ public static create(properties?: osmosis.gamm.v1beta1.IMsgJoinPool): osmosis.gamm.v1beta1.MsgJoinPool; /** * Encodes the specified MsgJoinPool message. Does not implicitly {@link osmosis.gamm.v1beta1.MsgJoinPool.verify|verify} messages. * @param m MsgJoinPool message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: osmosis.gamm.v1beta1.IMsgJoinPool, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgJoinPool message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgJoinPool * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): osmosis.gamm.v1beta1.MsgJoinPool; /** * Creates a MsgJoinPool message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgJoinPool */ public static fromObject(d: { [k: string]: any }): osmosis.gamm.v1beta1.MsgJoinPool; /** * Creates a plain object from a MsgJoinPool message. Also converts values to other types if specified. * @param m MsgJoinPool * @param [o] Conversion options * @returns Plain object */ public static toObject( m: osmosis.gamm.v1beta1.MsgJoinPool, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this MsgJoinPool to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgExitPool. */ interface IMsgExitPool { /** MsgExitPool sender */ sender?: string | null; /** MsgExitPool poolId */ poolId?: Long | null; /** MsgExitPool shareInAmount */ shareInAmount?: string | null; /** MsgExitPool tokenOutMins */ tokenOutMins?: cosmos.base.v1beta1.ICoin[] | null; } /** Represents a MsgExitPool. */ class MsgExitPool implements IMsgExitPool { /** * Constructs a new MsgExitPool. * @param [p] Properties to set */ constructor(p?: osmosis.gamm.v1beta1.IMsgExitPool); /** MsgExitPool sender. */ public sender: string; /** MsgExitPool poolId. */ public poolId: Long; /** MsgExitPool shareInAmount. */ public shareInAmount: string; /** MsgExitPool tokenOutMins. */ public tokenOutMins: cosmos.base.v1beta1.ICoin[]; /** * Creates a new MsgExitPool instance using the specified properties. * @param [properties] Properties to set * @returns MsgExitPool instance */ public static create(properties?: osmosis.gamm.v1beta1.IMsgExitPool): osmosis.gamm.v1beta1.MsgExitPool; /** * Encodes the specified MsgExitPool message. Does not implicitly {@link osmosis.gamm.v1beta1.MsgExitPool.verify|verify} messages. * @param m MsgExitPool message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: osmosis.gamm.v1beta1.IMsgExitPool, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgExitPool message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgExitPool * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): osmosis.gamm.v1beta1.MsgExitPool; /** * Creates a MsgExitPool message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgExitPool */ public static fromObject(d: { [k: string]: any }): osmosis.gamm.v1beta1.MsgExitPool; /** * Creates a plain object from a MsgExitPool message. Also converts values to other types if specified. * @param m MsgExitPool * @param [o] Conversion options * @returns Plain object */ public static toObject( m: osmosis.gamm.v1beta1.MsgExitPool, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this MsgExitPool to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a SwapAmountInRoute. */ interface ISwapAmountInRoute { /** SwapAmountInRoute poolId */ poolId?: Long | null; /** SwapAmountInRoute tokenOutDenom */ tokenOutDenom?: string | null; } /** Represents a SwapAmountInRoute. */ class SwapAmountInRoute implements ISwapAmountInRoute { /** * Constructs a new SwapAmountInRoute. * @param [p] Properties to set */ constructor(p?: osmosis.gamm.v1beta1.ISwapAmountInRoute); /** SwapAmountInRoute poolId. */ public poolId: Long; /** SwapAmountInRoute tokenOutDenom. */ public tokenOutDenom: string; /** * Creates a new SwapAmountInRoute instance using the specified properties. * @param [properties] Properties to set * @returns SwapAmountInRoute instance */ public static create( properties?: osmosis.gamm.v1beta1.ISwapAmountInRoute ): osmosis.gamm.v1beta1.SwapAmountInRoute; /** * Encodes the specified SwapAmountInRoute message. Does not implicitly {@link osmosis.gamm.v1beta1.SwapAmountInRoute.verify|verify} messages. * @param m SwapAmountInRoute message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: osmosis.gamm.v1beta1.ISwapAmountInRoute, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a SwapAmountInRoute message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns SwapAmountInRoute * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): osmosis.gamm.v1beta1.SwapAmountInRoute; /** * Creates a SwapAmountInRoute message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns SwapAmountInRoute */ public static fromObject(d: { [k: string]: any }): osmosis.gamm.v1beta1.SwapAmountInRoute; /** * Creates a plain object from a SwapAmountInRoute message. Also converts values to other types if specified. * @param m SwapAmountInRoute * @param [o] Conversion options * @returns Plain object */ public static toObject( m: osmosis.gamm.v1beta1.SwapAmountInRoute, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this SwapAmountInRoute to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgSwapExactAmountIn. */ interface IMsgSwapExactAmountIn { /** MsgSwapExactAmountIn sender */ sender?: string | null; /** MsgSwapExactAmountIn routes */ routes?: osmosis.gamm.v1beta1.ISwapAmountInRoute[] | null; /** MsgSwapExactAmountIn tokenIn */ tokenIn?: cosmos.base.v1beta1.ICoin | null; /** MsgSwapExactAmountIn tokenOutMinAmount */ tokenOutMinAmount?: string | null; } /** Represents a MsgSwapExactAmountIn. */ class MsgSwapExactAmountIn implements IMsgSwapExactAmountIn { /** * Constructs a new MsgSwapExactAmountIn. * @param [p] Properties to set */ constructor(p?: osmosis.gamm.v1beta1.IMsgSwapExactAmountIn); /** MsgSwapExactAmountIn sender. */ public sender: string; /** MsgSwapExactAmountIn routes. */ public routes: osmosis.gamm.v1beta1.ISwapAmountInRoute[]; /** MsgSwapExactAmountIn tokenIn. */ public tokenIn?: cosmos.base.v1beta1.ICoin | null; /** MsgSwapExactAmountIn tokenOutMinAmount. */ public tokenOutMinAmount: string; /** * Creates a new MsgSwapExactAmountIn instance using the specified properties. * @param [properties] Properties to set * @returns MsgSwapExactAmountIn instance */ public static create( properties?: osmosis.gamm.v1beta1.IMsgSwapExactAmountIn ): osmosis.gamm.v1beta1.MsgSwapExactAmountIn; /** * Encodes the specified MsgSwapExactAmountIn message. Does not implicitly {@link osmosis.gamm.v1beta1.MsgSwapExactAmountIn.verify|verify} messages. * @param m MsgSwapExactAmountIn message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: osmosis.gamm.v1beta1.IMsgSwapExactAmountIn, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgSwapExactAmountIn message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgSwapExactAmountIn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): osmosis.gamm.v1beta1.MsgSwapExactAmountIn; /** * Creates a MsgSwapExactAmountIn message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgSwapExactAmountIn */ public static fromObject(d: { [k: string]: any }): osmosis.gamm.v1beta1.MsgSwapExactAmountIn; /** * Creates a plain object from a MsgSwapExactAmountIn message. Also converts values to other types if specified. * @param m MsgSwapExactAmountIn * @param [o] Conversion options * @returns Plain object */ public static toObject( m: osmosis.gamm.v1beta1.MsgSwapExactAmountIn, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this MsgSwapExactAmountIn to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a SwapAmountOutRoute. */ interface ISwapAmountOutRoute { /** SwapAmountOutRoute poolId */ poolId?: Long | null; /** SwapAmountOutRoute tokenInDenom */ tokenInDenom?: string | null; } /** Represents a SwapAmountOutRoute. */ class SwapAmountOutRoute implements ISwapAmountOutRoute { /** * Constructs a new SwapAmountOutRoute. * @param [p] Properties to set */ constructor(p?: osmosis.gamm.v1beta1.ISwapAmountOutRoute); /** SwapAmountOutRoute poolId. */ public poolId: Long; /** SwapAmountOutRoute tokenInDenom. */ public tokenInDenom: string; /** * Creates a new SwapAmountOutRoute instance using the specified properties. * @param [properties] Properties to set * @returns SwapAmountOutRoute instance */ public static create( properties?: osmosis.gamm.v1beta1.ISwapAmountOutRoute ): osmosis.gamm.v1beta1.SwapAmountOutRoute; /** * Encodes the specified SwapAmountOutRoute message. Does not implicitly {@link osmosis.gamm.v1beta1.SwapAmountOutRoute.verify|verify} messages. * @param m SwapAmountOutRoute message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: osmosis.gamm.v1beta1.ISwapAmountOutRoute, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a SwapAmountOutRoute message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns SwapAmountOutRoute * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): osmosis.gamm.v1beta1.SwapAmountOutRoute; /** * Creates a SwapAmountOutRoute message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns SwapAmountOutRoute */ public static fromObject(d: { [k: string]: any }): osmosis.gamm.v1beta1.SwapAmountOutRoute; /** * Creates a plain object from a SwapAmountOutRoute message. Also converts values to other types if specified. * @param m SwapAmountOutRoute * @param [o] Conversion options * @returns Plain object */ public static toObject( m: osmosis.gamm.v1beta1.SwapAmountOutRoute, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this SwapAmountOutRoute to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgSwapExactAmountOut. */ interface IMsgSwapExactAmountOut { /** MsgSwapExactAmountOut sender */ sender?: string | null; /** MsgSwapExactAmountOut routes */ routes?: osmosis.gamm.v1beta1.ISwapAmountOutRoute[] | null; /** MsgSwapExactAmountOut tokenInMaxAmount */ tokenInMaxAmount?: string | null; /** MsgSwapExactAmountOut tokenOut */ tokenOut?: cosmos.base.v1beta1.ICoin | null; } /** Represents a MsgSwapExactAmountOut. */ class MsgSwapExactAmountOut implements IMsgSwapExactAmountOut { /** * Constructs a new MsgSwapExactAmountOut. * @param [p] Properties to set */ constructor(p?: osmosis.gamm.v1beta1.IMsgSwapExactAmountOut); /** MsgSwapExactAmountOut sender. */ public sender: string; /** MsgSwapExactAmountOut routes. */ public routes: osmosis.gamm.v1beta1.ISwapAmountOutRoute[]; /** MsgSwapExactAmountOut tokenInMaxAmount. */ public tokenInMaxAmount: string; /** MsgSwapExactAmountOut tokenOut. */ public tokenOut?: cosmos.base.v1beta1.ICoin | null; /** * Creates a new MsgSwapExactAmountOut instance using the specified properties. * @param [properties] Properties to set * @returns MsgSwapExactAmountOut instance */ public static create( properties?: osmosis.gamm.v1beta1.IMsgSwapExactAmountOut ): osmosis.gamm.v1beta1.MsgSwapExactAmountOut; /** * Encodes the specified MsgSwapExactAmountOut message. Does not implicitly {@link osmosis.gamm.v1beta1.MsgSwapExactAmountOut.verify|verify} messages. * @param m MsgSwapExactAmountOut message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: osmosis.gamm.v1beta1.IMsgSwapExactAmountOut, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgSwapExactAmountOut message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgSwapExactAmountOut * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): osmosis.gamm.v1beta1.MsgSwapExactAmountOut; /** * Creates a MsgSwapExactAmountOut message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgSwapExactAmountOut */ public static fromObject(d: { [k: string]: any }): osmosis.gamm.v1beta1.MsgSwapExactAmountOut; /** * Creates a plain object from a MsgSwapExactAmountOut message. Also converts values to other types if specified. * @param m MsgSwapExactAmountOut * @param [o] Conversion options * @returns Plain object */ public static toObject( m: osmosis.gamm.v1beta1.MsgSwapExactAmountOut, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this MsgSwapExactAmountOut to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgJoinSwapExternAmountIn. */ interface IMsgJoinSwapExternAmountIn { /** MsgJoinSwapExternAmountIn sender */ sender?: string | null; /** MsgJoinSwapExternAmountIn poolId */ poolId?: Long | null; /** MsgJoinSwapExternAmountIn tokenIn */ tokenIn?: cosmos.base.v1beta1.ICoin | null; /** MsgJoinSwapExternAmountIn shareOutMinAmount */ shareOutMinAmount?: string | null; } /** Represents a MsgJoinSwapExternAmountIn. */ class MsgJoinSwapExternAmountIn implements IMsgJoinSwapExternAmountIn { /** * Constructs a new MsgJoinSwapExternAmountIn. * @param [p] Properties to set */ constructor(p?: osmosis.gamm.v1beta1.IMsgJoinSwapExternAmountIn); /** MsgJoinSwapExternAmountIn sender. */ public sender: string; /** MsgJoinSwapExternAmountIn poolId. */ public poolId: Long; /** MsgJoinSwapExternAmountIn tokenIn. */ public tokenIn?: cosmos.base.v1beta1.ICoin | null; /** MsgJoinSwapExternAmountIn shareOutMinAmount. */ public shareOutMinAmount: string; /** * Creates a new MsgJoinSwapExternAmountIn instance using the specified properties. * @param [properties] Properties to set * @returns MsgJoinSwapExternAmountIn instance */ public static create( properties?: osmosis.gamm.v1beta1.IMsgJoinSwapExternAmountIn ): osmosis.gamm.v1beta1.MsgJoinSwapExternAmountIn; /** * Encodes the specified MsgJoinSwapExternAmountIn message. Does not implicitly {@link osmosis.gamm.v1beta1.MsgJoinSwapExternAmountIn.verify|verify} messages. * @param m MsgJoinSwapExternAmountIn message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode( m: osmosis.gamm.v1beta1.IMsgJoinSwapExternAmountIn, w?: $protobuf.Writer ): $protobuf.Writer; /** * Decodes a MsgJoinSwapExternAmountIn message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgJoinSwapExternAmountIn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode( r: $protobuf.Reader | Uint8Array, l?: number ): osmosis.gamm.v1beta1.MsgJoinSwapExternAmountIn; /** * Creates a MsgJoinSwapExternAmountIn message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgJoinSwapExternAmountIn */ public static fromObject(d: { [k: string]: any }): osmosis.gamm.v1beta1.MsgJoinSwapExternAmountIn; /** * Creates a plain object from a MsgJoinSwapExternAmountIn message. Also converts values to other types if specified. * @param m MsgJoinSwapExternAmountIn * @param [o] Conversion options * @returns Plain object */ public static toObject( m: osmosis.gamm.v1beta1.MsgJoinSwapExternAmountIn, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this MsgJoinSwapExternAmountIn to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgJoinSwapShareAmountOut. */ interface IMsgJoinSwapShareAmountOut { /** MsgJoinSwapShareAmountOut sender */ sender?: string | null; /** MsgJoinSwapShareAmountOut poolId */ poolId?: Long | null; /** MsgJoinSwapShareAmountOut tokenInDenom */ tokenInDenom?: string | null; /** MsgJoinSwapShareAmountOut shareOutAmount */ shareOutAmount?: string | null; /** MsgJoinSwapShareAmountOut tokenInMaxAmount */ tokenInMaxAmount?: string | null; } /** Represents a MsgJoinSwapShareAmountOut. */ class MsgJoinSwapShareAmountOut implements IMsgJoinSwapShareAmountOut { /** * Constructs a new MsgJoinSwapShareAmountOut. * @param [p] Properties to set */ constructor(p?: osmosis.gamm.v1beta1.IMsgJoinSwapShareAmountOut); /** MsgJoinSwapShareAmountOut sender. */ public sender: string; /** MsgJoinSwapShareAmountOut poolId. */ public poolId: Long; /** MsgJoinSwapShareAmountOut tokenInDenom. */ public tokenInDenom: string; /** MsgJoinSwapShareAmountOut shareOutAmount. */ public shareOutAmount: string; /** MsgJoinSwapShareAmountOut tokenInMaxAmount. */ public tokenInMaxAmount: string; /** * Creates a new MsgJoinSwapShareAmountOut instance using the specified properties. * @param [properties] Properties to set * @returns MsgJoinSwapShareAmountOut instance */ public static create( properties?: osmosis.gamm.v1beta1.IMsgJoinSwapShareAmountOut ): osmosis.gamm.v1beta1.MsgJoinSwapShareAmountOut; /** * Encodes the specified MsgJoinSwapShareAmountOut message. Does not implicitly {@link osmosis.gamm.v1beta1.MsgJoinSwapShareAmountOut.verify|verify} messages. * @param m MsgJoinSwapShareAmountOut message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode( m: osmosis.gamm.v1beta1.IMsgJoinSwapShareAmountOut, w?: $protobuf.Writer ): $protobuf.Writer; /** * Decodes a MsgJoinSwapShareAmountOut message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgJoinSwapShareAmountOut * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode( r: $protobuf.Reader | Uint8Array, l?: number ): osmosis.gamm.v1beta1.MsgJoinSwapShareAmountOut; /** * Creates a MsgJoinSwapShareAmountOut message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgJoinSwapShareAmountOut */ public static fromObject(d: { [k: string]: any }): osmosis.gamm.v1beta1.MsgJoinSwapShareAmountOut; /** * Creates a plain object from a MsgJoinSwapShareAmountOut message. Also converts values to other types if specified. * @param m MsgJoinSwapShareAmountOut * @param [o] Conversion options * @returns Plain object */ public static toObject( m: osmosis.gamm.v1beta1.MsgJoinSwapShareAmountOut, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this MsgJoinSwapShareAmountOut to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgExitSwapShareAmountIn. */ interface IMsgExitSwapShareAmountIn { /** MsgExitSwapShareAmountIn sender */ sender?: string | null; /** MsgExitSwapShareAmountIn poolId */ poolId?: Long | null; /** MsgExitSwapShareAmountIn tokenOutDenom */ tokenOutDenom?: string | null; /** MsgExitSwapShareAmountIn shareInAmount */ shareInAmount?: string | null; /** MsgExitSwapShareAmountIn tokenOutMinAmount */ tokenOutMinAmount?: string | null; } /** Represents a MsgExitSwapShareAmountIn. */ class MsgExitSwapShareAmountIn implements IMsgExitSwapShareAmountIn { /** * Constructs a new MsgExitSwapShareAmountIn. * @param [p] Properties to set */ constructor(p?: osmosis.gamm.v1beta1.IMsgExitSwapShareAmountIn); /** MsgExitSwapShareAmountIn sender. */ public sender: string; /** MsgExitSwapShareAmountIn poolId. */ public poolId: Long; /** MsgExitSwapShareAmountIn tokenOutDenom. */ public tokenOutDenom: string; /** MsgExitSwapShareAmountIn shareInAmount. */ public shareInAmount: string; /** MsgExitSwapShareAmountIn tokenOutMinAmount. */ public tokenOutMinAmount: string; /** * Creates a new MsgExitSwapShareAmountIn instance using the specified properties. * @param [properties] Properties to set * @returns MsgExitSwapShareAmountIn instance */ public static create( properties?: osmosis.gamm.v1beta1.IMsgExitSwapShareAmountIn ): osmosis.gamm.v1beta1.MsgExitSwapShareAmountIn; /** * Encodes the specified MsgExitSwapShareAmountIn message. Does not implicitly {@link osmosis.gamm.v1beta1.MsgExitSwapShareAmountIn.verify|verify} messages. * @param m MsgExitSwapShareAmountIn message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: osmosis.gamm.v1beta1.IMsgExitSwapShareAmountIn, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgExitSwapShareAmountIn message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgExitSwapShareAmountIn * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode( r: $protobuf.Reader | Uint8Array, l?: number ): osmosis.gamm.v1beta1.MsgExitSwapShareAmountIn; /** * Creates a MsgExitSwapShareAmountIn message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgExitSwapShareAmountIn */ public static fromObject(d: { [k: string]: any }): osmosis.gamm.v1beta1.MsgExitSwapShareAmountIn; /** * Creates a plain object from a MsgExitSwapShareAmountIn message. Also converts values to other types if specified. * @param m MsgExitSwapShareAmountIn * @param [o] Conversion options * @returns Plain object */ public static toObject( m: osmosis.gamm.v1beta1.MsgExitSwapShareAmountIn, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this MsgExitSwapShareAmountIn to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgExitSwapExternAmountOut. */ interface IMsgExitSwapExternAmountOut { /** MsgExitSwapExternAmountOut sender */ sender?: string | null; /** MsgExitSwapExternAmountOut poolId */ poolId?: Long | null; /** MsgExitSwapExternAmountOut tokenOut */ tokenOut?: cosmos.base.v1beta1.ICoin | null; /** MsgExitSwapExternAmountOut shareInMaxAmount */ shareInMaxAmount?: string | null; } /** Represents a MsgExitSwapExternAmountOut. */ class MsgExitSwapExternAmountOut implements IMsgExitSwapExternAmountOut { /** * Constructs a new MsgExitSwapExternAmountOut. * @param [p] Properties to set */ constructor(p?: osmosis.gamm.v1beta1.IMsgExitSwapExternAmountOut); /** MsgExitSwapExternAmountOut sender. */ public sender: string; /** MsgExitSwapExternAmountOut poolId. */ public poolId: Long; /** MsgExitSwapExternAmountOut tokenOut. */ public tokenOut?: cosmos.base.v1beta1.ICoin | null; /** MsgExitSwapExternAmountOut shareInMaxAmount. */ public shareInMaxAmount: string; /** * Creates a new MsgExitSwapExternAmountOut instance using the specified properties. * @param [properties] Properties to set * @returns MsgExitSwapExternAmountOut instance */ public static create( properties?: osmosis.gamm.v1beta1.IMsgExitSwapExternAmountOut ): osmosis.gamm.v1beta1.MsgExitSwapExternAmountOut; /** * Encodes the specified MsgExitSwapExternAmountOut message. Does not implicitly {@link osmosis.gamm.v1beta1.MsgExitSwapExternAmountOut.verify|verify} messages. * @param m MsgExitSwapExternAmountOut message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode( m: osmosis.gamm.v1beta1.IMsgExitSwapExternAmountOut, w?: $protobuf.Writer ): $protobuf.Writer; /** * Decodes a MsgExitSwapExternAmountOut message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgExitSwapExternAmountOut * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode( r: $protobuf.Reader | Uint8Array, l?: number ): osmosis.gamm.v1beta1.MsgExitSwapExternAmountOut; /** * Creates a MsgExitSwapExternAmountOut message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgExitSwapExternAmountOut */ public static fromObject(d: { [k: string]: any }): osmosis.gamm.v1beta1.MsgExitSwapExternAmountOut; /** * Creates a plain object from a MsgExitSwapExternAmountOut message. Also converts values to other types if specified. * @param m MsgExitSwapExternAmountOut * @param [o] Conversion options * @returns Plain object */ public static toObject( m: osmosis.gamm.v1beta1.MsgExitSwapExternAmountOut, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this MsgExitSwapExternAmountOut to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } /** Namespace lockup. */ namespace lockup { /** LockQueryType enum. */ enum LockQueryType { ByDuration = 0, ByTime = 1, } /** Properties of a QueryCondition. */ interface IQueryCondition { /** QueryCondition lockQueryType */ lockQueryType?: osmosis.lockup.LockQueryType | null; /** QueryCondition denom */ denom?: string | null; /** QueryCondition duration */ duration?: google.protobuf.IDuration | null; /** QueryCondition timestamp */ timestamp?: google.protobuf.ITimestamp | null; } /** Represents a QueryCondition. */ class QueryCondition implements IQueryCondition { /** * Constructs a new QueryCondition. * @param [p] Properties to set */ constructor(p?: osmosis.lockup.IQueryCondition); /** QueryCondition lockQueryType. */ public lockQueryType: osmosis.lockup.LockQueryType; /** QueryCondition denom. */ public denom: string; /** QueryCondition duration. */ public duration?: google.protobuf.IDuration | null; /** QueryCondition timestamp. */ public timestamp?: google.protobuf.ITimestamp | null; /** * Creates a new QueryCondition instance using the specified properties. * @param [properties] Properties to set * @returns QueryCondition instance */ public static create(properties?: osmosis.lockup.IQueryCondition): osmosis.lockup.QueryCondition; /** * Encodes the specified QueryCondition message. Does not implicitly {@link osmosis.lockup.QueryCondition.verify|verify} messages. * @param m QueryCondition message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: osmosis.lockup.IQueryCondition, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a QueryCondition message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns QueryCondition * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): osmosis.lockup.QueryCondition; /** * Creates a QueryCondition message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns QueryCondition */ public static fromObject(d: { [k: string]: any }): osmosis.lockup.QueryCondition; /** * Creates a plain object from a QueryCondition message. Also converts values to other types if specified. * @param m QueryCondition * @param [o] Conversion options * @returns Plain object */ public static toObject(m: osmosis.lockup.QueryCondition, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this QueryCondition to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgLockTokens. */ interface IMsgLockTokens { /** MsgLockTokens owner */ owner?: string | null; /** MsgLockTokens duration */ duration?: google.protobuf.IDuration | null; /** MsgLockTokens coins */ coins?: cosmos.base.v1beta1.ICoin[] | null; } /** Represents a MsgLockTokens. */ class MsgLockTokens implements IMsgLockTokens { /** * Constructs a new MsgLockTokens. * @param [p] Properties to set */ constructor(p?: osmosis.lockup.IMsgLockTokens); /** MsgLockTokens owner. */ public owner: string; /** MsgLockTokens duration. */ public duration?: google.protobuf.IDuration | null; /** MsgLockTokens coins. */ public coins: cosmos.base.v1beta1.ICoin[]; /** * Creates a new MsgLockTokens instance using the specified properties. * @param [properties] Properties to set * @returns MsgLockTokens instance */ public static create(properties?: osmosis.lockup.IMsgLockTokens): osmosis.lockup.MsgLockTokens; /** * Encodes the specified MsgLockTokens message. Does not implicitly {@link osmosis.lockup.MsgLockTokens.verify|verify} messages. * @param m MsgLockTokens message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: osmosis.lockup.IMsgLockTokens, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgLockTokens message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgLockTokens * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): osmosis.lockup.MsgLockTokens; /** * Creates a MsgLockTokens message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgLockTokens */ public static fromObject(d: { [k: string]: any }): osmosis.lockup.MsgLockTokens; /** * Creates a plain object from a MsgLockTokens message. Also converts values to other types if specified. * @param m MsgLockTokens * @param [o] Conversion options * @returns Plain object */ public static toObject(m: osmosis.lockup.MsgLockTokens, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgLockTokens to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgBeginUnlockingAll. */ interface IMsgBeginUnlockingAll { /** MsgBeginUnlockingAll owner */ owner?: string | null; } /** Represents a MsgBeginUnlockingAll. */ class MsgBeginUnlockingAll implements IMsgBeginUnlockingAll { /** * Constructs a new MsgBeginUnlockingAll. * @param [p] Properties to set */ constructor(p?: osmosis.lockup.IMsgBeginUnlockingAll); /** MsgBeginUnlockingAll owner. */ public owner: string; /** * Creates a new MsgBeginUnlockingAll instance using the specified properties. * @param [properties] Properties to set * @returns MsgBeginUnlockingAll instance */ public static create(properties?: osmosis.lockup.IMsgBeginUnlockingAll): osmosis.lockup.MsgBeginUnlockingAll; /** * Encodes the specified MsgBeginUnlockingAll message. Does not implicitly {@link osmosis.lockup.MsgBeginUnlockingAll.verify|verify} messages. * @param m MsgBeginUnlockingAll message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: osmosis.lockup.IMsgBeginUnlockingAll, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgBeginUnlockingAll message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgBeginUnlockingAll * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): osmosis.lockup.MsgBeginUnlockingAll; /** * Creates a MsgBeginUnlockingAll message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgBeginUnlockingAll */ public static fromObject(d: { [k: string]: any }): osmosis.lockup.MsgBeginUnlockingAll; /** * Creates a plain object from a MsgBeginUnlockingAll message. Also converts values to other types if specified. * @param m MsgBeginUnlockingAll * @param [o] Conversion options * @returns Plain object */ public static toObject( m: osmosis.lockup.MsgBeginUnlockingAll, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this MsgBeginUnlockingAll to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgBeginUnlocking. */ interface IMsgBeginUnlocking { /** MsgBeginUnlocking owner */ owner?: string | null; /** MsgBeginUnlocking ID */ ID?: Long | null; } /** Represents a MsgBeginUnlocking. */ class MsgBeginUnlocking implements IMsgBeginUnlocking { /** * Constructs a new MsgBeginUnlocking. * @param [p] Properties to set */ constructor(p?: osmosis.lockup.IMsgBeginUnlocking); /** MsgBeginUnlocking owner. */ public owner: string; /** MsgBeginUnlocking ID. */ public ID: Long; /** * Creates a new MsgBeginUnlocking instance using the specified properties. * @param [properties] Properties to set * @returns MsgBeginUnlocking instance */ public static create(properties?: osmosis.lockup.IMsgBeginUnlocking): osmosis.lockup.MsgBeginUnlocking; /** * Encodes the specified MsgBeginUnlocking message. Does not implicitly {@link osmosis.lockup.MsgBeginUnlocking.verify|verify} messages. * @param m MsgBeginUnlocking message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: osmosis.lockup.IMsgBeginUnlocking, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgBeginUnlocking message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgBeginUnlocking * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): osmosis.lockup.MsgBeginUnlocking; /** * Creates a MsgBeginUnlocking message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgBeginUnlocking */ public static fromObject(d: { [k: string]: any }): osmosis.lockup.MsgBeginUnlocking; /** * Creates a plain object from a MsgBeginUnlocking message. Also converts values to other types if specified. * @param m MsgBeginUnlocking * @param [o] Conversion options * @returns Plain object */ public static toObject( m: osmosis.lockup.MsgBeginUnlocking, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this MsgBeginUnlocking to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Namespace incentives. */ namespace incentives { /** Properties of a MsgCreateGauge. */ interface IMsgCreateGauge { /** MsgCreateGauge isPerpetual */ isPerpetual?: boolean | null; /** MsgCreateGauge owner */ owner?: string | null; /** MsgCreateGauge distributeTo */ distributeTo?: osmosis.lockup.IQueryCondition | null; /** MsgCreateGauge coins */ coins?: cosmos.base.v1beta1.ICoin[] | null; /** MsgCreateGauge startTime */ startTime?: google.protobuf.ITimestamp | null; /** MsgCreateGauge numEpochsPaidOver */ numEpochsPaidOver?: Long | null; } /** Represents a MsgCreateGauge. */ class MsgCreateGauge implements IMsgCreateGauge { /** * Constructs a new MsgCreateGauge. * @param [p] Properties to set */ constructor(p?: osmosis.incentives.IMsgCreateGauge); /** MsgCreateGauge isPerpetual. */ public isPerpetual: boolean; /** MsgCreateGauge owner. */ public owner: string; /** MsgCreateGauge distributeTo. */ public distributeTo?: osmosis.lockup.IQueryCondition | null; /** MsgCreateGauge coins. */ public coins: cosmos.base.v1beta1.ICoin[]; /** MsgCreateGauge startTime. */ public startTime?: google.protobuf.ITimestamp | null; /** MsgCreateGauge numEpochsPaidOver. */ public numEpochsPaidOver: Long; /** * Creates a new MsgCreateGauge instance using the specified properties. * @param [properties] Properties to set * @returns MsgCreateGauge instance */ public static create(properties?: osmosis.incentives.IMsgCreateGauge): osmosis.incentives.MsgCreateGauge; /** * Encodes the specified MsgCreateGauge message. Does not implicitly {@link osmosis.incentives.MsgCreateGauge.verify|verify} messages. * @param m MsgCreateGauge message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: osmosis.incentives.IMsgCreateGauge, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgCreateGauge message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgCreateGauge * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): osmosis.incentives.MsgCreateGauge; /** * Creates a MsgCreateGauge message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgCreateGauge */ public static fromObject(d: { [k: string]: any }): osmosis.incentives.MsgCreateGauge; /** * Creates a plain object from a MsgCreateGauge message. Also converts values to other types if specified. * @param m MsgCreateGauge * @param [o] Conversion options * @returns Plain object */ public static toObject( m: osmosis.incentives.MsgCreateGauge, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this MsgCreateGauge to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgAddToGauge. */ interface IMsgAddToGauge { /** MsgAddToGauge owner */ owner?: string | null; /** MsgAddToGauge gaugeId */ gaugeId?: Long | null; /** MsgAddToGauge rewards */ rewards?: cosmos.base.v1beta1.ICoin[] | null; } /** Represents a MsgAddToGauge. */ class MsgAddToGauge implements IMsgAddToGauge { /** * Constructs a new MsgAddToGauge. * @param [p] Properties to set */ constructor(p?: osmosis.incentives.IMsgAddToGauge); /** MsgAddToGauge owner. */ public owner: string; /** MsgAddToGauge gaugeId. */ public gaugeId: Long; /** MsgAddToGauge rewards. */ public rewards: cosmos.base.v1beta1.ICoin[]; /** * Creates a new MsgAddToGauge instance using the specified properties. * @param [properties] Properties to set * @returns MsgAddToGauge instance */ public static create(properties?: osmosis.incentives.IMsgAddToGauge): osmosis.incentives.MsgAddToGauge; /** * Encodes the specified MsgAddToGauge message. Does not implicitly {@link osmosis.incentives.MsgAddToGauge.verify|verify} messages. * @param m MsgAddToGauge message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: osmosis.incentives.IMsgAddToGauge, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgAddToGauge message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgAddToGauge * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): osmosis.incentives.MsgAddToGauge; /** * Creates a MsgAddToGauge message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgAddToGauge */ public static fromObject(d: { [k: string]: any }): osmosis.incentives.MsgAddToGauge; /** * Creates a plain object from a MsgAddToGauge message. Also converts values to other types if specified. * @param m MsgAddToGauge * @param [o] Conversion options * @returns Plain object */ public static toObject( m: osmosis.incentives.MsgAddToGauge, o?: $protobuf.IConversionOptions ): { [k: string]: any }; /** * Converts this MsgAddToGauge to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } /** Namespace google. */ export namespace google { /** Namespace protobuf. */ namespace protobuf { /** Properties of a Duration. */ interface IDuration { /** Duration seconds */ seconds?: Long | null; /** Duration nanos */ nanos?: number | null; } /** Represents a Duration. */ class Duration implements IDuration { /** * Constructs a new Duration. * @param [p] Properties to set */ constructor(p?: google.protobuf.IDuration); /** Duration seconds. */ public seconds: Long; /** Duration nanos. */ public nanos: number; /** * Creates a new Duration instance using the specified properties. * @param [properties] Properties to set * @returns Duration instance */ public static create(properties?: google.protobuf.IDuration): google.protobuf.Duration; /** * Encodes the specified Duration message. Does not implicitly {@link google.protobuf.Duration.verify|verify} messages. * @param m Duration message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: google.protobuf.IDuration, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Duration message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Duration * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): google.protobuf.Duration; /** * Creates a Duration message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Duration */ public static fromObject(d: { [k: string]: any }): google.protobuf.Duration; /** * Creates a plain object from a Duration message. Also converts values to other types if specified. * @param m Duration * @param [o] Conversion options * @returns Plain object */ public static toObject(m: google.protobuf.Duration, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Duration to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Timestamp. */ interface ITimestamp { /** Timestamp seconds */ seconds?: Long | null; /** Timestamp nanos */ nanos?: number | null; } /** Represents a Timestamp. */ class Timestamp implements ITimestamp { /** * Constructs a new Timestamp. * @param [p] Properties to set */ constructor(p?: google.protobuf.ITimestamp); /** Timestamp seconds. */ public seconds: Long; /** Timestamp nanos. */ public nanos: number; /** * Creates a new Timestamp instance using the specified properties. * @param [properties] Properties to set * @returns Timestamp instance */ public static create(properties?: google.protobuf.ITimestamp): google.protobuf.Timestamp; /** * Encodes the specified Timestamp message. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages. * @param m Timestamp message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: google.protobuf.ITimestamp, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Timestamp message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Timestamp * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: $protobuf.Reader | Uint8Array, l?: number): google.protobuf.Timestamp; /** * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Timestamp */ public static fromObject(d: { [k: string]: any }): google.protobuf.Timestamp; /** * Creates a plain object from a Timestamp message. Also converts values to other types if specified. * @param m Timestamp * @param [o] Conversion options * @returns Plain object */ public static toObject(m: google.protobuf.Timestamp, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Timestamp to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } }
the_stack
import EXTENT from '../data/extent'; import {SymbolInstanceArray} from '../data/array_types.g'; import type {SymbolInstance} from '../data/array_types.g'; import type {OverscaledTileID} from '../source/tile_id'; import type SymbolBucket from '../data/bucket/symbol_bucket'; import type StyleLayer from '../style/style_layer'; import type Tile from '../source/tile'; /* The CrossTileSymbolIndex generally works on the assumption that a conceptual "unique symbol" can be identified by the text of the label combined with the anchor point. The goal is to assign these conceptual "unique symbols" a shared crossTileID that can be used by Placement to keep fading opacity states consistent and to deduplicate labels. The CrossTileSymbolIndex indexes all the current symbol instances and their crossTileIDs. When a symbol bucket gets added or updated, the index assigns a crossTileID to each of it's symbol instances by either matching it with an existing id or assigning a new one. */ // Round anchor positions to roughly 4 pixel grid const roundingFactor = 512 / EXTENT / 2; class TileLayerIndex { tileID: OverscaledTileID; indexedSymbolInstances: { [_: number]: Array<{ crossTileID: number; coord: { x: number; y: number; }; }>; }; bucketInstanceId: number; constructor(tileID: OverscaledTileID, symbolInstances: SymbolInstanceArray, bucketInstanceId: number) { this.tileID = tileID; this.indexedSymbolInstances = {}; this.bucketInstanceId = bucketInstanceId; for (let i = 0; i < symbolInstances.length; i++) { const symbolInstance = symbolInstances.get(i); const key = symbolInstance.key; if (!this.indexedSymbolInstances[key]) { this.indexedSymbolInstances[key] = []; } // This tile may have multiple symbol instances with the same key // Store each one along with its coordinates this.indexedSymbolInstances[key].push({ crossTileID: symbolInstance.crossTileID, coord: this.getScaledCoordinates(symbolInstance, tileID) }); } } // Converts the coordinates of the input symbol instance into coordinates that be can compared // against other symbols in this index. Coordinates are: // (1) world-based (so after conversion the source tile is irrelevant) // (2) converted to the z-scale of this TileLayerIndex // (3) down-sampled by "roundingFactor" from tile coordinate precision in order to be // more tolerant of small differences between tiles. getScaledCoordinates(symbolInstance: SymbolInstance, childTileID: OverscaledTileID) { const zDifference = childTileID.canonical.z - this.tileID.canonical.z; const scale = roundingFactor / Math.pow(2, zDifference); return { x: Math.floor((childTileID.canonical.x * EXTENT + symbolInstance.anchorX) * scale), y: Math.floor((childTileID.canonical.y * EXTENT + symbolInstance.anchorY) * scale) }; } findMatches(symbolInstances: SymbolInstanceArray, newTileID: OverscaledTileID, zoomCrossTileIDs: { [crossTileID: number]: boolean; }) { const tolerance = this.tileID.canonical.z < newTileID.canonical.z ? 1 : Math.pow(2, this.tileID.canonical.z - newTileID.canonical.z); for (let i = 0; i < symbolInstances.length; i++) { const symbolInstance = symbolInstances.get(i); if (symbolInstance.crossTileID) { // already has a match, skip continue; } const indexedInstances = this.indexedSymbolInstances[symbolInstance.key]; if (!indexedInstances) { // No symbol with this key in this bucket continue; } const scaledSymbolCoord = this.getScaledCoordinates(symbolInstance, newTileID); for (const thisTileSymbol of indexedInstances) { // Return any symbol with the same keys whose coordinates are within 1 // grid unit. (with a 4px grid, this covers a 12px by 12px area) if (Math.abs(thisTileSymbol.coord.x - scaledSymbolCoord.x) <= tolerance && Math.abs(thisTileSymbol.coord.y - scaledSymbolCoord.y) <= tolerance && !zoomCrossTileIDs[thisTileSymbol.crossTileID]) { // Once we've marked ourselves duplicate against this parent symbol, // don't let any other symbols at the same zoom level duplicate against // the same parent (see issue #5993) zoomCrossTileIDs[thisTileSymbol.crossTileID] = true; symbolInstance.crossTileID = thisTileSymbol.crossTileID; break; } } } } } class CrossTileIDs { maxCrossTileID: number; constructor() { this.maxCrossTileID = 0; } generate() { return ++this.maxCrossTileID; } } class CrossTileSymbolLayerIndex { indexes: { [zoom in string | number]: { [tileId in string | number]: TileLayerIndex; }; }; usedCrossTileIDs: { [zoom in string | number]: { [crossTileID: number]: boolean; }; }; lng: number; constructor() { this.indexes = {}; this.usedCrossTileIDs = {}; this.lng = 0; } /* * Sometimes when a user pans across the antimeridian the longitude value gets wrapped. * To prevent labels from flashing out and in we adjust the tileID values in the indexes * so that they match the new wrapped version of the map. */ handleWrapJump(lng: number) { const wrapDelta = Math.round((lng - this.lng) / 360); if (wrapDelta !== 0) { for (const zoom in this.indexes) { const zoomIndexes = this.indexes[zoom]; const newZoomIndex = {}; for (const key in zoomIndexes) { // change the tileID's wrap and add it to a new index const index = zoomIndexes[key]; index.tileID = index.tileID.unwrapTo(index.tileID.wrap + wrapDelta); newZoomIndex[index.tileID.key] = index; } this.indexes[zoom] = newZoomIndex; } } this.lng = lng; } addBucket(tileID: OverscaledTileID, bucket: SymbolBucket, crossTileIDs: CrossTileIDs) { if (this.indexes[tileID.overscaledZ] && this.indexes[tileID.overscaledZ][tileID.key]) { if (this.indexes[tileID.overscaledZ][tileID.key].bucketInstanceId === bucket.bucketInstanceId) { return false; } else { // We're replacing this bucket with an updated version // Remove the old bucket's "used crossTileIDs" now so that // the new bucket can claim them. // The old index entries themselves stick around until // 'removeStaleBuckets' is called. this.removeBucketCrossTileIDs(tileID.overscaledZ, this.indexes[tileID.overscaledZ][tileID.key]); } } for (let i = 0; i < bucket.symbolInstances.length; i++) { const symbolInstance = bucket.symbolInstances.get(i); symbolInstance.crossTileID = 0; } if (!this.usedCrossTileIDs[tileID.overscaledZ]) { this.usedCrossTileIDs[tileID.overscaledZ] = {}; } const zoomCrossTileIDs = this.usedCrossTileIDs[tileID.overscaledZ]; for (const zoom in this.indexes) { const zoomIndexes = this.indexes[zoom]; if (Number(zoom) > tileID.overscaledZ) { for (const id in zoomIndexes) { const childIndex = zoomIndexes[id]; if (childIndex.tileID.isChildOf(tileID)) { childIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs); } } } else { const parentCoord = tileID.scaledTo(Number(zoom)); const parentIndex = zoomIndexes[parentCoord.key]; if (parentIndex) { parentIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs); } } } for (let i = 0; i < bucket.symbolInstances.length; i++) { const symbolInstance = bucket.symbolInstances.get(i); if (!symbolInstance.crossTileID) { // symbol did not match any known symbol, assign a new id symbolInstance.crossTileID = crossTileIDs.generate(); zoomCrossTileIDs[symbolInstance.crossTileID] = true; } } if (this.indexes[tileID.overscaledZ] === undefined) { this.indexes[tileID.overscaledZ] = {}; } this.indexes[tileID.overscaledZ][tileID.key] = new TileLayerIndex(tileID, bucket.symbolInstances, bucket.bucketInstanceId); return true; } removeBucketCrossTileIDs(zoom: string | number, removedBucket: TileLayerIndex) { for (const key in removedBucket.indexedSymbolInstances) { for (const symbolInstance of removedBucket.indexedSymbolInstances[(key as any)]) { delete this.usedCrossTileIDs[zoom][symbolInstance.crossTileID]; } } } removeStaleBuckets(currentIDs: { [k in string | number]: boolean; }) { let tilesChanged = false; for (const z in this.indexes) { const zoomIndexes = this.indexes[z]; for (const tileKey in zoomIndexes) { if (!currentIDs[zoomIndexes[tileKey].bucketInstanceId]) { this.removeBucketCrossTileIDs(z, zoomIndexes[tileKey]); delete zoomIndexes[tileKey]; tilesChanged = true; } } } return tilesChanged; } } class CrossTileSymbolIndex { layerIndexes: {[layerId: string]: CrossTileSymbolLayerIndex}; crossTileIDs: CrossTileIDs; maxBucketInstanceId: number; bucketsInCurrentPlacement: {[_: number]: boolean}; constructor() { this.layerIndexes = {}; this.crossTileIDs = new CrossTileIDs(); this.maxBucketInstanceId = 0; this.bucketsInCurrentPlacement = {}; } addLayer(styleLayer: StyleLayer, tiles: Array<Tile>, lng: number) { let layerIndex = this.layerIndexes[styleLayer.id]; if (layerIndex === undefined) { layerIndex = this.layerIndexes[styleLayer.id] = new CrossTileSymbolLayerIndex(); } let symbolBucketsChanged = false; const currentBucketIDs = {}; layerIndex.handleWrapJump(lng); for (const tile of tiles) { const symbolBucket = (tile.getBucket(styleLayer) as any as SymbolBucket); if (!symbolBucket || styleLayer.id !== symbolBucket.layerIds[0]) continue; if (!symbolBucket.bucketInstanceId) { symbolBucket.bucketInstanceId = ++this.maxBucketInstanceId; } if (layerIndex.addBucket(tile.tileID, symbolBucket, this.crossTileIDs)) { symbolBucketsChanged = true; } currentBucketIDs[symbolBucket.bucketInstanceId] = true; } if (layerIndex.removeStaleBuckets(currentBucketIDs)) { symbolBucketsChanged = true; } return symbolBucketsChanged; } pruneUnusedLayers(usedLayers: Array<string>) { const usedLayerMap = {}; usedLayers.forEach((usedLayer) => { usedLayerMap[usedLayer] = true; }); for (const layerId in this.layerIndexes) { if (!usedLayerMap[layerId]) { delete this.layerIndexes[layerId]; } } } } export default CrossTileSymbolIndex;
the_stack
import * as ObjC from '../objc'; import * as ObjCTypeUtils from '../objc-type-utils'; import * as Maybe from '../maybe'; const UI_GEOMETRY_IMPORT: ObjC.Import = { file: 'UIGeometry.h', isPublic: false, requiresCPlusPlus: false, library: 'UIKit', }; const NSOBJECT_CODING_STATEMENTS: CodingStatements = { codingFunctionImport: null, encodeStatement: 'encodeObject', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueDirectly, decodeStatementGenerator: decodeObjectStatementGenerator, decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueDirectly, }; const UNSUPPORTED_TYPE_CODING_STATEMENTS: CodingStatements = { codingFunctionImport: null, encodeStatement: '', encodeValueStatementGenerator: () => null!, decodeStatementGenerator: () => null!, decodeValueStatementGenerator: () => null!, }; export interface CodingStatements { codingFunctionImport: ObjC.Import | null; decodeStatementGenerator: ( valueClass: ObjC.Type, key: string, secureCoding: boolean, ) => string; decodeValueStatementGenerator: (decodedValueCode: string) => string; encodeStatement: string; encodeValueStatementGenerator: (valueAccessor: string) => string; } function encodeValueStatementGeneratorForEncodingValueDirectly( valueAccessor: string, ): string { return valueAccessor; } function encodeValueStatementGeneratorForEncodingValueAsString( encodingFunction: string, ): (valueAccessor: string) => string { return function (valueAccessor: string): string { return encodingFunction + '(' + valueAccessor + ')'; }; } function decodeValueStatementGeneratorForDecodingValueDirectly( decodedValueCode: string, ): string { return decodedValueCode; } function decodeValueStatementGeneratorForDecodingValueFromString( decodingFunction: string, ): (decodedValueCode: string) => string { return function (decodedValueCode: string): string { return decodingFunction + '(' + decodedValueCode + ')'; }; } function decodeValueSatementGeneratorForValueStoredAsNSString( type: ObjC.Type, key: string, secureCoding: boolean, ): string { if (secureCoding) { return `[aDecoder decodeObjectOfClass:[NSString class] forKey:${key}]`; } else { return `[aDecoder decodeObjectForKey:${key}]`; } } function insecureDecodeValueStatementGeneratorGenerator( decodeStatement: string, ): (type: ObjC.Type, key: string, secureCoding: boolean) => string { return function ( type: ObjC.Type, key: string, secureCoding: boolean, ): string { return `[aDecoder ${decodeStatement}:${key}]`; }; } function decodeObjectStatementGenerator( type: ObjC.Type, key: string, secureCoding: boolean, ) { if (secureCoding) { return `[aDecoder decodeObjectOfClass:[${type.name} class] forKey:${key}]`; } else { return `[aDecoder decodeObjectForKey:${key}]`; } } export function codingStatementsForType(type: ObjC.Type): CodingStatements { return ObjCTypeUtils.matchType( { id: function () { return NSOBJECT_CODING_STATEMENTS; }, NSObject: function () { return NSOBJECT_CODING_STATEMENTS; }, BOOL: function () { return { codingFunctionImport: null, encodeStatement: 'encodeBool', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueDirectly, decodeStatementGenerator: insecureDecodeValueStatementGeneratorGenerator('decodeBoolForKey'), decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueDirectly, }; }, NSInteger: function () { return { codingFunctionImport: null, encodeStatement: 'encodeInteger', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueDirectly, decodeStatementGenerator: insecureDecodeValueStatementGeneratorGenerator( 'decodeIntegerForKey', ), decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueDirectly, }; }, NSUInteger: function () { return { codingFunctionImport: null, encodeStatement: 'encodeInteger', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueDirectly, decodeStatementGenerator: insecureDecodeValueStatementGeneratorGenerator( 'decodeIntegerForKey', ), decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueDirectly, }; }, double: function () { return { codingFunctionImport: null, encodeStatement: 'encodeDouble', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueDirectly, decodeStatementGenerator: insecureDecodeValueStatementGeneratorGenerator( 'decodeDoubleForKey', ), decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueDirectly, }; }, float: function () { return { codingFunctionImport: null, encodeStatement: 'encodeFloat', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueDirectly, decodeStatementGenerator: insecureDecodeValueStatementGeneratorGenerator('decodeFloatForKey'), decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueDirectly, }; }, CGFloat: function () { return { codingFunctionImport: null, encodeStatement: 'encodeFloat', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueDirectly, decodeStatementGenerator: insecureDecodeValueStatementGeneratorGenerator('decodeFloatForKey'), decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueDirectly, }; }, NSTimeInterval: function () { return { codingFunctionImport: null, encodeStatement: 'encodeDouble', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueDirectly, decodeStatementGenerator: insecureDecodeValueStatementGeneratorGenerator( 'decodeDoubleForKey', ), decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueDirectly, }; }, uintptr_t: function () { return { codingFunctionImport: null, encodeStatement: 'encodeInteger', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueDirectly, decodeStatementGenerator: insecureDecodeValueStatementGeneratorGenerator( 'decodeIntegerForKey', ), decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueDirectly, }; }, uint32_t: function () { return { codingFunctionImport: null, encodeStatement: 'encodeInt32', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueDirectly, decodeStatementGenerator: insecureDecodeValueStatementGeneratorGenerator('decodeInt32ForKey'), decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueDirectly, }; }, uint64_t: function () { return { codingFunctionImport: null, encodeStatement: 'encodeInt64', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueDirectly, decodeStatementGenerator: insecureDecodeValueStatementGeneratorGenerator('decodeInt64ForKey'), decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueDirectly, }; }, int32_t: function () { return { codingFunctionImport: null, encodeStatement: 'encodeInt32', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueDirectly, decodeStatementGenerator: insecureDecodeValueStatementGeneratorGenerator('decodeInt32ForKey'), decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueDirectly, }; }, int64_t: function () { return { codingFunctionImport: null, encodeStatement: 'encodeInt64', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueDirectly, decodeStatementGenerator: insecureDecodeValueStatementGeneratorGenerator('decodeInt64ForKey'), decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueDirectly, }; }, SEL: function () { return { codingFunctionImport: null, encodeStatement: 'encodeObject', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueAsString( 'NSStringFromSelector', ), decodeStatementGenerator: decodeValueSatementGeneratorForValueStoredAsNSString, decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueFromString( 'NSSelectorFromString', ), }; }, NSRange: function () { return { codingFunctionImport: null, encodeStatement: 'encodeObject', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueAsString( 'NSStringFromRange', ), decodeStatementGenerator: decodeValueSatementGeneratorForValueStoredAsNSString, decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueFromString( 'NSRangeFromString', ), }; }, CGRect: function () { return { codingFunctionImport: UI_GEOMETRY_IMPORT, encodeStatement: 'encodeObject', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueAsString( 'NSStringFromCGRect', ), decodeStatementGenerator: decodeValueSatementGeneratorForValueStoredAsNSString, decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueFromString( 'CGRectFromString', ), }; }, CGPoint: function () { return { codingFunctionImport: UI_GEOMETRY_IMPORT, encodeStatement: 'encodeObject', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueAsString( 'NSStringFromCGPoint', ), decodeStatementGenerator: decodeValueSatementGeneratorForValueStoredAsNSString, decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueFromString( 'CGPointFromString', ), }; }, CGSize: function () { return { codingFunctionImport: UI_GEOMETRY_IMPORT, encodeStatement: 'encodeObject', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueAsString( 'NSStringFromCGSize', ), decodeStatementGenerator: decodeValueSatementGeneratorForValueStoredAsNSString, decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueFromString( 'CGSizeFromString', ), }; }, UIEdgeInsets: function () { return { codingFunctionImport: UI_GEOMETRY_IMPORT, encodeStatement: 'encodeObject', encodeValueStatementGenerator: encodeValueStatementGeneratorForEncodingValueAsString( 'NSStringFromUIEdgeInsets', ), decodeStatementGenerator: decodeValueSatementGeneratorForValueStoredAsNSString, decodeValueStatementGenerator: decodeValueStatementGeneratorForDecodingValueFromString( 'UIEdgeInsetsFromString', ), }; }, Class: function () { return UNSUPPORTED_TYPE_CODING_STATEMENTS; }, dispatch_block_t: function () { return UNSUPPORTED_TYPE_CODING_STATEMENTS; }, unmatchedType: function () { return null!; }, }, type, ); } export const supportsSecureCodingMethod: ObjC.Method = { preprocessors: [], belongsToProtocol: 'NSSecureCoding', code: ['return YES;'], comments: [], compilerAttributes: [], keywords: [ { name: 'supportsSecureCoding', argument: null, }, ], returnType: { type: { name: 'BOOL', reference: 'BOOL', }, modifiers: [], }, };
the_stack
module android.view { import Activity = android.app.Activity; import KeyEvent = android.view.KeyEvent; import MenuItem = android.view.MenuItem; import ArrayList = java.util.ArrayList; import Context = android.content.Context; /** * Interface for managing the items in a menu. * <p> * By default, every Activity supports an options menu of actions or options. * You can add items to this menu and handle clicks on your additions. The * easiest way of adding menu items is inflating an XML file into the * {@link Menu} via {@link MenuInflater}. The easiest way of attaching code to * clicks is via {@link Activity#onOptionsItemSelected(MenuItem)} and * {@link Activity#onContextItemSelected(MenuItem)}. * <p> * Different menu types support different features: * <ol> * <li><b>Context menus</b>: Do not support item shortcuts and item icons. * <li><b>Options menus</b>: The <b>icon menus</b> do not support item check * marks and only show the item's * {@link MenuItem#setTitleCondensed(CharSequence) condensed title}. The * <b>expanded menus</b> (only available if six or more menu items are visible, * reached via the 'More' item in the icon menu) do not show item icons, and * item check marks are discouraged. * <li><b>Sub menus</b>: Do not support item icons, or nested sub menus. * </ol> * * <div class="special reference"> * <h3>Developer Guides</h3> * <p>For more information about creating menus, read the * <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p> * </div> */ export class Menu { /** * Contains all of the items for this menu */ private mItems = new ArrayList<MenuItem>(); private mVisibleItems = new ArrayList<MenuItem>(); /** * Callback that will receive the various menu-related events generated by this class. Use * getCallback to get a reference to the callback. */ private mCallback:Menu.Callback; private mContext:Context; constructor(context:Context) { this.mContext = context; } getContext():Context { return this.mContext; } /** * Add a new item to the menu. This item displays the given title for its * label. * * @param title The text to display for the item. * @return The newly added menu item. */ add(title:string):MenuItem ; /** * Add a new item to the menu. This item displays the given title for its * label. * * @param groupId The group identifier that this item should be part of. * This can be used to define groups of items for batch state * changes. Normally use {@link #NONE} if an item should not be in a * group. * @param itemId Unique item ID. Use {@link #NONE} if you do not need a * unique ID. * @param order The order for the item. Use {@link #NONE} if you do not care * about the order. See {@link MenuItem#getOrder()}. * @param title The text to display for the item. * @return The newly added menu item. */ add(groupId:number, itemId:number, order:number, title:string):MenuItem ; add(...args):MenuItem { if(args.length==1) return this.addInternal(0, 0, 0, args[0]); return this.addInternal(args[0], args[1], args[2], args[3]); } ///** // * Add a new item to the menu. This item displays the given title for its // * label. // * // * @param titleRes Resource identifier of title string. // * @return The newly added menu item. // */ //add(titleRes:number):MenuItem ; ///** // * Variation on {@link #add(int, int, int, CharSequence)} that takes a // * string resource identifier instead of the string itself. // * // * @param groupId The group identifier that this item should be part of. // * This can also be used to define groups of items for batch state // * changes. Normally use {@link #NONE} if an item should not be in a // * group. // * @param itemId Unique item ID. Use {@link #NONE} if you do not need a // * unique ID. // * @param order The order for the item. Use {@link #NONE} if you do not care // * about the order. See {@link MenuItem#getOrder()}. // * @param titleRes Resource identifier of title string. // * @return The newly added menu item. // */ //add(groupId:number, itemId:number, order:number, titleRes:number):MenuItem ; /** * Adds an item to the menu. The other add methods funnel to this. */ private addInternal(group:number, id:number, categoryOrder:number, title:string):MenuItem { const ordering:number = 0;//MenuBuilder.getOrdering(categoryOrder); const item:MenuItem = new MenuItem(this, group, id, categoryOrder, ordering, title); //if (this.mCurrentMenuInfo != null) { // // Pass along the current menu info // item.setMenuInfo(this.mCurrentMenuInfo); //} this.mItems.add(/*MenuBuilder.findInsertIndex(this.mItems, ordering), */item); this.onItemsChanged(true); return item; } ///** // * Add a new sub-menu to the menu. This item displays the given title for // * its label. To modify other attributes on the submenu's menu item, use // * {@link SubMenu#getItem()}. // * // * @param title The text to display for the item. // * @return The newly added sub-menu // */ //addSubMenu(title:string):SubMenu ; // ///** // * Add a new sub-menu to the menu. This item displays the given title for // * its label. To modify other attributes on the submenu's menu item, use // * {@link SubMenu#getItem()}. // * // * @param titleRes Resource identifier of title string. // * @return The newly added sub-menu // */ //addSubMenu(titleRes:number):SubMenu ; // ///** // * Add a new sub-menu to the menu. This item displays the given // * <var>title</var> for its label. To modify other attributes on the // * submenu's menu item, use {@link SubMenu#getItem()}. // *<p> // * Note that you can only have one level of sub-menus, i.e. you cannnot add // * a subMenu to a subMenu: An {@link UnsupportedOperationException} will be // * thrown if you try. // * // * @param groupId The group identifier that this item should be part of. // * This can also be used to define groups of items for batch state // * changes. Normally use {@link #NONE} if an item should not be in a // * group. // * @param itemId Unique item ID. Use {@link #NONE} if you do not need a // * unique ID. // * @param order The order for the item. Use {@link #NONE} if you do not care // * about the order. See {@link MenuItem#getOrder()}. // * @param title The text to display for the item. // * @return The newly added sub-menu // */ //addSubMenu(groupId:number, itemId:number, order:number, title:string):SubMenu ; // ///** // * Variation on {@link #addSubMenu(int, int, int, CharSequence)} that takes // * a string resource identifier for the title instead of the string itself. // * // * @param groupId The group identifier that this item should be part of. // * This can also be used to define groups of items for batch state // * changes. Normally use {@link #NONE} if an item should not be in a group. // * @param itemId Unique item ID. Use {@link #NONE} if you do not need a unique ID. // * @param order The order for the item. Use {@link #NONE} if you do not care about the // * order. See {@link MenuItem#getOrder()}. // * @param titleRes Resource identifier of title string. // * @return The newly added sub-menu // */ //addSubMenu(groupId:number, itemId:number, order:number, titleRes:number):SubMenu ; // ///** // * Add a group of menu items corresponding to actions that can be performed // * for a particular Intent. The Intent is most often configured with a null // * action, the data that the current activity is working with, and includes // * either the {@link Intent#CATEGORY_ALTERNATIVE} or // * {@link Intent#CATEGORY_SELECTED_ALTERNATIVE} to find activities that have // * said they would like to be included as optional action. You can, however, // * use any Intent you want. // * // * <p> // * See {@link android.content.pm.PackageManager#queryIntentActivityOptions} // * for more * details on the <var>caller</var>, <var>specifics</var>, and // * <var>intent</var> arguments. The list returned by that function is used // * to populate the resulting menu items. // * // * <p> // * All of the menu items of possible options for the intent will be added // * with the given group and id. You can use the group to control ordering of // * the items in relation to other items in the menu. Normally this function // * will automatically remove any existing items in the menu in the same // * group and place a divider above and below the added items; this behavior // * can be modified with the <var>flags</var> parameter. For each of the // * generated items {@link MenuItem#setIntent} is called to associate the // * appropriate Intent with the item; this means the activity will // * automatically be started for you without having to do anything else. // * // * @param groupId The group identifier that the items should be part of. // * This can also be used to define groups of items for batch state // * changes. Normally use {@link #NONE} if the items should not be in // * a group. // * @param itemId Unique item ID. Use {@link #NONE} if you do not need a // * unique ID. // * @param order The order for the items. Use {@link #NONE} if you do not // * care about the order. See {@link MenuItem#getOrder()}. // * @param caller The current activity component name as defined by // * queryIntentActivityOptions(). // * @param specifics Specific items to place first as defined by // * queryIntentActivityOptions(). // * @param intent Intent describing the kinds of items to populate in the // * list as defined by queryIntentActivityOptions(). // * @param flags Additional options controlling how the items are added. // * @param outSpecificItems Optional array in which to place the menu items // * that were generated for each of the <var>specifics</var> that were // * requested. Entries may be null if no activity was found for that // * specific action. // * @return The number of menu items that were added. // * // * @see #FLAG_APPEND_TO_GROUP // * @see MenuItem#setIntent // * @see android.content.pm.PackageManager#queryIntentActivityOptions // */ //addIntentOptions(groupId:number, itemId:number, order:number, caller:ComponentName, specifics:Intent[], intent:Intent, flags:number, outSpecificItems:MenuItem[]):number ; /** * Remove the item with the given identifier. * * @param id The item to be removed. If there is no item with this * identifier, nothing happens. */ removeItem(id:number):void { this.removeItemAtInt(this.findItemIndex(id), true); } /** * Remove all items in the given group. * * @param groupId The group to be removed. If there are no items in this * group, nothing happens. */ removeGroup(groupId:number):void { const i:number = this.findGroupIndex(groupId); if (i >= 0) { const maxRemovable:number = this.mItems.size() - i; let numRemoved:number = 0; while ((numRemoved++ < maxRemovable) && (this.mItems.get(i).getGroupId() == groupId)) { // Don't force update for each one, this method will do it at the end this.removeItemAtInt(i, false); } // Notify menu views this.onItemsChanged(true); } } /** * Remove the item at the given index and optionally forces menu views to update. * * @param index The index of the item to be removed. If this index is * invalid an exception is thrown. * @param updateChildrenOnMenuViews Whether to force update on menu views. Please make sure you * eventually call this after your batch of removals. */ private removeItemAtInt(index:number, updateChildrenOnMenuViews:boolean):void { if ((index < 0) || (index >= this.mItems.size())) { return; } this.mItems.remove(index); if (updateChildrenOnMenuViews) { this.onItemsChanged(true); } } /** * Remove all existing items from the menu, leaving it empty as if it had * just been created. */ clear():void { this.mItems.clear(); this.onItemsChanged(true); } ///** // * Control whether a particular group of items can show a check mark. This // * is similar to calling {@link MenuItem#setCheckable} on all of the menu items // * with the given group identifier, but in addition you can control whether // * this group contains a mutually-exclusive set items. This should be called // * after the items of the group have been added to the menu. // * // * @param group The group of items to operate on. // * @param checkable Set to true to allow a check mark, false to // * disallow. The default is false. // * @param exclusive If set to true, only one item in this group can be // * checked at a time; checking an item will automatically // * uncheck all others in the group. If set to false, each // * item can be checked independently of the others. // * // * @see MenuItem#setCheckable // * @see MenuItem#setChecked // */ //setGroupCheckable(group:number, checkable:boolean, exclusive:boolean):void ; /** * Show or hide all menu items that are in the given group. * * @param group The group of items to operate on. * @param visible If true the items are visible, else they are hidden. * * @see MenuItem#setVisible */ setGroupVisible(group:number, visible:boolean):void { const N:number = this.mItems.size(); // We handle the notification of items being changed ourselves, so we use setVisibleInt // rather than setVisible and at the end notify of items being changed let changedAtLeastOneItem:boolean = false; for (let i:number = 0; i < N; i++) { let item:MenuItem = this.mItems.get(i); if (item.getGroupId() == group) { if (item.setVisible(visible)) {//androidui modify: setVisibleInt changedAtLeastOneItem = true; } } } if (changedAtLeastOneItem) { this.onItemsChanged(true); } } /** * Enable or disable all menu items that are in the given group. * * @param group The group of items to operate on. * @param enabled If true the items will be enabled, else they will be disabled. * * @see MenuItem#setEnabled */ setGroupEnabled(group:number, enabled:boolean):void { const N:number = this.mItems.size(); for (let i:number = 0; i < N; i++) { let item:MenuItem = this.mItems.get(i); if (item.getGroupId() == group) { item.setEnabled(enabled); } } } /** * Return whether the menu currently has item items that are visible. * * @return True if there is one or more item visible, * else false. */ hasVisibleItems():boolean { const size:number = this.size(); for (let i:number = 0; i < size; i++) { let item:MenuItem = this.mItems.get(i); if (item.isVisible()) { return true; } } return false; } /** * Return the menu item with a particular identifier. * * @param id The identifier to find. * * @return The menu item object, or null if there is no item with * this identifier. */ findItem(id:number):MenuItem { const size:number = this.size(); for (let i:number = 0; i < size; i++) { let item:MenuItem = this.mItems.get(i); if (item.getItemId() == id) { return item; } //else if (item.hasSubMenu()) { // let possibleItem:MenuItem = item.getSubMenu().findItem(id); // if (possibleItem != null) { // return possibleItem; // } //} } return null; } findItemIndex(id:number):number { const size:number = this.size(); for (let i:number = 0; i < size; i++) { let item:MenuItem = this.mItems.get(i); if (item.getItemId() == id) { return i; } } return -1; } findGroupIndex(group:number, start=0):number { const size:number = this.size(); if (start < 0) { start = 0; } for (let i:number = start; i < size; i++) { const item:MenuItem = this.mItems.get(i); if (item.getGroupId() == group) { return i; } } return -1; } /** * Get the number of items in the menu. Note that this will change any * times items are added or removed from the menu. * * @return The item count. */ size():number { return this.mItems.size(); } /** * Gets the menu item at the given index. * * @param index The index of the menu item to return. * @return The menu item. * @exception IndexOutOfBoundsException * when {@code index < 0 || >= size()} */ getItem(index:number):MenuItem { return this.mItems.get(index); } ///** // * Closes the menu, if open. // */ //close():void ; // ///** // * Execute the menu item action associated with the given shortcut // * character. // * // * @param keyCode The keycode of the shortcut key. // * @param event Key event message. // * @param flags Additional option flags or 0. // * // * @return If the given shortcut exists and is shown, returns // * true; else returns false. // * // * @see #FLAG_PERFORM_NO_CLOSE // */ //performShortcut(keyCode:number, event:KeyEvent, flags:number):boolean ; // ///** // * Is a keypress one of the defined shortcut keys for this window. // * @param keyCode the key code from {@link KeyEvent} to check. // * @param event the {@link KeyEvent} to use to help check. // */ //isShortcutKey(keyCode:number, event:KeyEvent):boolean ; // ///** // * Execute the menu item action associated with the given menu identifier. // * // * @param id Identifier associated with the menu item. // * @param flags Additional option flags or 0. // * // * @return If the given identifier exists and is shown, returns // * true; else returns false. // * // * @see #FLAG_PERFORM_NO_CLOSE // */ //performIdentifierAction(id:number, flags:number):boolean ; // ///** // * Control whether the menu should be running in qwerty mode (alphabetic // * shortcuts) or 12-key mode (numeric shortcuts). // * // * @param isQwerty If true the menu will use alphabetic shortcuts; else it // * will use numeric shortcuts. // */ //setQwertyMode(isQwerty:boolean):void ; /** * Called when an item is added or removed. * * @param structureChanged true if the menu structure changed, false if only item properties * changed. (Visibility is a structural property since it affects * layout.) */ onItemsChanged(structureChanged:boolean):void { //if (!this.mPreventDispatchingItemsChanged) { // if (structureChanged) { // this.mIsVisibleItemsStale = true; // this.mIsActionItemsStale = true; // } // this.dispatchPresenterUpdate(structureChanged); //} else { // this.mItemsChangedWhileDispatchPrevented = true; //} } /** * Gets the root menu (if this is a submenu, find its root menu). * * @return The root menu. */ getRootMenu():Menu { return this; } setCallback(cb:Menu.Callback):void { this.mCallback = cb; } dispatchMenuItemSelected(menu:Menu, item:MenuItem):boolean { return this.mCallback != null && this.mCallback.onMenuItemSelected(menu, item); } getVisibleItems():ArrayList<MenuItem> { this.mVisibleItems.clear(); const itemsSize:number = this.mItems.size(); let item:MenuItem; for (let i:number = 0; i < itemsSize; i++) { item = this.mItems.get(i); if (item.isVisible()) { this.mVisibleItems.add(item); } } return this.mVisibleItems; } } export module Menu{ /** * This is the part of an order integer that the user can provide. * @hide */ export var USER_MASK:number = 0x0000ffff; /** * Bit shift of the user portion of the order integer. * @hide */ export var USER_SHIFT:number = 0; /** * This is the part of an order integer that supplies the category of the * item. * @hide */ export var CATEGORY_MASK:number = 0xffff0000; /** * Bit shift of the category portion of the order integer. * @hide */ export var CATEGORY_SHIFT:number = 16; /** * Value to use for group and item identifier integers when you don't care * about them. */ export var NONE:number = 0; /** * First value for group and item identifier integers. */ export var FIRST:number = 1; // Implementation note: Keep these CATEGORY_* in sync with the category enum // in attrs.xml /** * Category code for the order integer for items/groups that are part of a * container -- or/add this with your base value. */ export var CATEGORY_CONTAINER:number = 0x00010000; /** * Category code for the order integer for items/groups that are provided by * the system -- or/add this with your base value. */ export var CATEGORY_SYSTEM:number = 0x00020000; /** * Category code for the order integer for items/groups that are * user-supplied secondary (infrequently used) options -- or/add this with * your base value. */ export var CATEGORY_SECONDARY:number = 0x00030000; /** * Category code for the order integer for items/groups that are * alternative actions on the data that is currently displayed -- or/add * this with your base value. */ export var CATEGORY_ALTERNATIVE:number = 0x00040000; /** * Flag for {@link #addIntentOptions}: if set, do not automatically remove * any existing menu items in the same group. */ export var FLAG_APPEND_TO_GROUP:number = 0x0001; /** * Flag for {@link #performShortcut}: if set, do not close the menu after * executing the shortcut. */ export var FLAG_PERFORM_NO_CLOSE:number = 0x0001; /** * Flag for {@link #performShortcut(int, KeyEvent, int)}: if set, always * close the menu after executing the shortcut. Closing the menu also resets * the prepared state. */ export var FLAG_ALWAYS_PERFORM_CLOSE:number = 0x0002; /** * Called by menu to notify of close and selection changes. * @hide */ export interface Callback { /** * Called when a menu item is selected. * * @param menu The menu that is the parent of the item * @param item The menu item that is selected * @return whether the menu item selection was handled */ onMenuItemSelected(menu:Menu, item:MenuItem):boolean ; ///** // * Called when the mode of the menu changes (for example, from icon to expanded). // * // * @param menu the menu that has changed modes // */ //onMenuModeChange(menu:MenuBuilder):void ; } } }
the_stack
import { Component, Input, Output, OnChanges, SimpleChanges, EventEmitter } from '@angular/core'; import uniq from 'lodash-es/uniq'; import isArray from 'lodash-es/isArray'; import replace from 'lodash-es/replace'; import get from 'lodash-es/get'; import { WorkflowHelper } from '../services/workflowhelper.service'; const d3 = require('d3'); import dagreD3 from 'dagre-d3'; import $ from 'jquery'; @Component({ selector: 'steps-viewer', templateUrl: 'stepsviewer.html', }) export class StepsViewerComponent implements OnChanges { @Input() steps: any[]; @Output() public select: EventEmitter<any> = new EventEmitter(); @Input() selectParam; constructor( private WorkflowHelper: WorkflowHelper ) { } error: any = null; graph: any = { dimensions: null }; done = false; selectedNode: any; ngOnChanges(changes: SimpleChanges) { if (changes.steps) { this.init(); this.unselectAll(); this.selectedNode = null; this.select.emit(null); } } init() { try { if (this.checkData()) { const dagreGraph = new dagreD3.graphlib.Graph().setGraph({}); this.createNodesAndEdges(dagreGraph); const renderGraph = new dagreD3.render(); this.applyShapes(renderGraph); const svg = d3.select('svg'); const innerSVG = svg.select('g'); const zoom = d3.zoom().on('zoom', () => { innerSVG.attr('transform', d3.event.transform); }); svg.call(zoom); renderGraph(innerSVG, dagreGraph); const self = this; innerSVG.selectAll('g.node') .attr('title', v => dagreGraph.node(v).tooltip) .on('click', function (v: any) { self.doSelection(innerSVG, this, v); }) // .each(function () { // $(this).tipsy(); // }); this.graph.dimensions = { width: dagreGraph.graph().width, height: dagreGraph.graph().height }; this.center(svg, this.graph.dimensions, zoom); this.error = null; } } catch (exc) { this.error = 'An error occured, the template is invalid'; } } unselectAll() { $('.node_selected').removeClass('node_selected'); $('.node_unselected').removeClass('node_unselected'); $('.edge_unselected').removeClass('edge_unselected'); $('.label_unselected').removeClass('label_unselected'); } doSelection(inner, nodeHtmlELement, stepName) { this.unselectAll(); if (this.selectedNode === stepName) { this.selectedNode = null; } else { this.selectedNode = stepName; const list = []; inner.selectAll('g.edgePath').each(function (edge) { if (stepName !== edge.v && stepName !== edge.w) { $(this).addClass('edge_unselected'); } else { if (list.indexOf(edge.v) === -1) { list.push(edge.v); } if (list.indexOf(edge.w) === -1) { list.push(edge.w); } } }); inner.selectAll('g.node').each(function (node) { if (list.indexOf(node) === -1 && stepName !== node) { $(this).addClass('node_unselected'); } }); $(nodeHtmlELement).addClass('node_selected'); inner.selectAll('g.edgeLabel').each(function (label) { if (stepName !== label.v && stepName !== label.w) { $(this).addClass('label_unselected'); } }); } this.select.emit(this.selectedNode); } checkData() { let response = true; const keys = this.steps.map((s: any) => s.key); if (!isArray(this.steps)) { this.error = 'The steps list is not an array'; return false; } else if (this.steps.length === 0) { this.error = 'The steps list is empty or invalid'; return false; } else if (uniq(keys).length !== this.steps.length) { this.error = 'Duplicate steps name'; return false; } this.steps.forEach((step: any) => { const dependencies = get(step.data, 'dependencies', []); if (dependencies && dependencies.length) { dependencies.forEach((dep: any) => { let d = dep.split(':')[0]; if (keys.indexOf(d) === -1) { this.error = `Step '${step.key}' have a dependency to '${d}' which don't exist`; response = false; } }); } }); return response; } createNodesAndEdges(g: any) { this.steps.forEach((step: any) => { g.setNode(step.key, { shape: step.data.state ? this.WorkflowHelper.getState(step.data.state).shape : 'shape_black', label: replace(step.key, /[A-Z]{1,}/g, s => ` ${s}`), // labelType: 'html', labelStyle: ` font-size:18px;font-weight:400;text-transform:capitalize;fill:${this.WorkflowHelper.getState(step.data.state).fontColor };`, tooltip: ` <h4 class='cp_h4'>${step.key}${step.data.state ? ' : ' : '' }${step.data.state ? step.data.state : ''}</h4> <p>${step.data.description}</p> ` }); if (this.done) { (step.data.dependencies || []).forEach((d: any) => { let stepName = d; let stepCondition = ''; if (d.indexOf(':') > -1) { stepName = d.split(':')[0]; stepCondition = d.split(':')[1]; } let arrow: any = {}; if (stepCondition === 'ANY') { arrow = { rx: 5, ry: 5, label: 'WAIT', labelStyle: 'fill:purple;font-size:18px;', /* label: '', labelStyle: 'font-family: 'Font Awesome 5 Free';fill:orange;font-size:18px;', */ arrowhead: 'undirected', style: 'stroke: black;fill:transparent;stroke-width: 2px;' }; } else { arrow = { rx: 5, ry: 5, arrowhead: 'vee', style: 'stroke: black;fill:transparent;stroke-width: 2px;' }; } if (stepCondition === 'ANY') { arrow.style += 'stroke: #ad0067;'; } else { let fromState = this.getStateFromStepname(stepName); let colorArrow = ''; if ( [ 'TO_RETRY', 'RUNNING', 'TODO', 'EXPANDED', 'CLIENT_ERROR' ].indexOf(fromState) > -1 ) { colorArrow = this.WorkflowHelper.getState(step.data.state).color; } else { colorArrow = this.WorkflowHelper.getState(fromState).color; } arrow.style += `stroke: ${colorArrow};fill:transparent;`; arrow.arrowheadStyle = `fill: ${colorArrow};stroke: ${colorArrow};`; } g.setEdge(stepName, step.key, arrow); }); } else { (step.data.dependencies || []).forEach((d: any) => { let stepName = d; let stepCondition = ''; if (d.indexOf(':') > -1) { stepName = d.split(':')[0]; stepCondition = d.split(':')[1]; } if (stepCondition === 'ANY') { g.setEdge(stepName, step.key, { rx: 5, ry: 5, style: 'stroke: #333;fill:transparent;', labelStyle: 'fill: #333;' }); } else { g.setEdge(stepName, step.key, { label: !this.done ? stepCondition || 'DONE' : ' ', rx: 5, ry: 5, style: 'stroke: #333;fill:transparent;stroke-width: 2px; stroke-dasharray: 2, 2;', labelStyle: 'fill: #333;' }); } }); } }); } getStateFromStepname(stepName: any) { return get(this.steps.find(s => s.key === stepName), 'data.state'); } applyShapes(render: any) { this.WorkflowHelper.shapes.forEach(shape => { render.shapes()[shape.pattern] = function ( parent: any, bbox: any, node: any ) { var w = bbox.width; var h = bbox.height; var points = [ // Bottom left { x: 0, y: 0 }, // Bottom right { x: w, y: 0 }, // Top Right { x: w, y: -h }, // Top Left { x: 0, y: -h } ]; var shapeSvg = parent .insert('polygon', ':first-child') .attr('points', points.map(d => `${d.x},${d.y}`).join(' ')) .attr('transform', `translate(${-w / 2},${h / 2})`) .attr('fill', `url(#${shape.pattern})`) .attr('stroke', shape.stroke) .attr('stroke-width', 0) .attr(' :opacity', '1'); node.intersect = function (point: any) { return dagreD3.intersect.polygon(node, points, point); }; return shapeSvg; }; }); } center(svg: any, dimensions: any, zoom: any) { let svgDimensions = { width: svg._groups[0][0].width.animVal.value, height: svg._groups[0][0].height.animVal.value }; let initialScale = 0.6; svg.call( zoom.transform, d3.zoomIdentity .translate( -(dimensions.width * initialScale - svgDimensions.width) / 2, -(dimensions.height * initialScale - svgDimensions.height) / 2 ) .scale(initialScale) ); } }
the_stack
import * as httpStatus from 'http-status'; import { Injectable } from 'injection-js'; import 'reflect-metadata'; import { Cache, CacheService } from '../../caching'; import { DocumentNotFoundException, Exception } from '../../error'; import { isNilOrWhiteSpace } from '../../utils'; import { Dictionary } from '../../utils/dictionary'; import { slugify } from '../../utils/slugify'; import { ContentVersionService } from '../content/content-version.service'; import { ContentService } from '../content/content.service'; import { VersionStatus } from "../content/version-status"; import { LanguageService } from '../language'; import { SiteDefinitionService } from '../site-definition/site-definition.service'; import { IPageVersionDocument, PageVersionModel } from "./models/page-version.model"; import { IPageDocument, IPageLanguageDocument, PageModel } from "./models/page.model"; export class PageVersionService extends ContentVersionService<IPageVersionDocument> { constructor() { super(PageVersionModel); } } @Injectable() export class PageService extends ContentService<IPageDocument, IPageLanguageDocument, IPageVersionDocument> { private static readonly PrefixCacheKey: string = 'Page'; constructor(private siteDefinitionService: SiteDefinitionService, private languageService: LanguageService, private cacheService: CacheService) { super(PageModel, PageVersionModel); } /** * Get page version detail * * If the version Id is not provided, the primary version based on language will be used instead * @param id (`Required`) The content's id * @param versionId (`Required` but null is allowed) the version id, if value is null, the primary version based on language will be used * @param language (`Required`) The language code (ex 'en', 'de'...) * @param host (`Required`) The host name */ async getContentVersion(id: string, versionId: string, language: string, host: string): Promise<IPageDocument & IPageVersionDocument> { const primaryVersion = await super.getContentVersion(id, versionId, language); const siteDefinition = await this.siteDefinitionService.getCurrentSiteDefinition(host); const { _id, parentPath, urlSegment } = primaryVersion; const linkTuple = await this.buildLinkUrlTuple(_id.toString(), parentPath, urlSegment, language, siteDefinition); primaryVersion.linkUrl = linkTuple[1]; return primaryVersion; } /** * Gets page children by parent id * @param parentId * @param language * @param [host] * @param select The fields select syntax like 'a,-b,c' * @returns The array of children */ async getContentChildren(parentId: string, language: string, host?: string, select?: string): Promise<Array<IPageDocument & IPageLanguageDocument>> { const pageChildren = await super.getContentChildren(parentId, language, host, select) if (pageChildren.length == 0) return []; const linkArray: Array<[string, string]> = await this.buildManyLinkTuples(pageChildren, language, host); pageChildren.forEach(page => { const linkTuple = linkArray.find(x => x[0] == page._id.toString()); if (linkTuple) page.linkUrl = linkTuple[1]; }) return pageChildren; } async getAncestors(id: string, language: string, host?: string, select?: string) { const ancestors = await super.getAncestors(id, language, host, select); if (ancestors.length == 0) return []; const linkArray: Array<[string, string]> = await this.buildManyLinkTuples(ancestors, language, host); ancestors.forEach(page => { const linkTuple = linkArray.find(x => x[0] == page._id.toString()); if (linkTuple) page.linkUrl = linkTuple[1]; }) return ancestors; } /** * Gets link urls of multi pages * @param ids * @param language * @param host * @returns page with url */ async getPageUrls(ids: string[], language: string, host: string): Promise<Array<IPageDocument & IPageLanguageDocument>> { const statuses = [VersionStatus.Published]; const project = { _id: 1, parentPath: 1, language: 1, urlSegment: 1 }; const filter = { _id: { $in: ids }, status: { $in: statuses }, language } const queryResult = (await this.queryContent(filter, project)); const linkArray: Array<[string, string]> = await this.buildManyLinkTuples(queryResult.docs, language, host); queryResult.docs.forEach(page => { const linkItem = linkArray.find(x => x[0] == page._id.toString()); if (linkItem) page.linkUrl = linkItem[1]; }) return queryResult.docs; } private async buildManyLinkTuples(pages: Array<IPageDocument & IPageLanguageDocument>, language: string, host: string): Promise<Array<[string, string]>> { const siteDefinition = await this.siteDefinitionService.getCurrentSiteDefinition(host); const fetchLinkPromises: Promise<any>[] = pages.map(page => { const { _id, parentPath, urlSegment } = page; const buildUrlPromise = this.buildLinkUrlTuple(_id.toString(), parentPath, urlSegment, language, siteDefinition); return buildUrlPromise; }) return Promise.all(fetchLinkPromises); } /** * Build link url * @param currentId * @param parentPath * @param currentUrlSegment * @param language * @param siteDefinition ([startPageId, defaultLang]) * @returns [contentId, url] */ @Cache({ prefixKey: PageService.PrefixCacheKey, suffixKey: (args) => `${args[0]}:${args[1]}:${args[2]}:${args[3]}:${args[4][0]}:${args[4][1]}` }) private async buildLinkUrlTuple(currentId: string, parentPath: string, currentUrlSegment: string, language: string, siteDefinition: [string, string]): Promise<[string, string]> { const parentIds = parentPath ? parentPath.split(',').filter(id => !isNilOrWhiteSpace(id)) : []; const [startPageId, defaultLang] = siteDefinition; const urlSegments: string[] = []; if (defaultLang !== language) { urlSegments.push(language); } const matchStartIndex = parentIds.indexOf(startPageId); const queryParentIds = parentIds.filter(id => parentIds.indexOf(id) > matchStartIndex); const urlSegmentDic = await this.getUrlSegmentByPageIds(queryParentIds, language); for (let i = matchStartIndex + 1; i < parentIds.length; i++) { urlSegments.push(urlSegmentDic[parentIds[i]]); } if (currentId != startPageId) { urlSegments.push(currentUrlSegment); } return [currentId, `/${urlSegments.filter(segment => !isNilOrWhiteSpace(segment)).join('/')}`]; } private async getUrlSegmentByPageIds(ids: string[], language: string): Promise<Dictionary<string>> { const project = { language: 1, urlSegment: 1 }; const filter = { _id: { $in: ids }, language } const queryResult = await this.queryContent(filter, project); const dictionaryUrl: Dictionary<string> = {}; queryResult.docs.forEach(page => { dictionaryUrl[page._id] = page.urlSegment; }) return dictionaryUrl; } /** * Resolve page data via url * @param encodedUrl */ getPublishedPageByUrl = async (encodedUrl: string): Promise<IPageDocument & IPageLanguageDocument> => { //get domain from url const url = Buffer.from(encodedUrl, 'base64').toString(); const urlObj = new URL(url); // --> https://www.example.org:80/abc/xyz?123 const host = urlObj.host; // --> www.example.org:80 const pathName = urlObj.pathname; // --> /abc/xyz //get site definition from domain const [startPageId, defaultLanguage] = await this.siteDefinitionService.getCurrentSiteDefinition(host); if (startPageId === '0') throw new DocumentNotFoundException(url, 'The site definition is not found') // get language from url, fallback to default language of current host const language = await this.getLanguageFromUrl(urlObj, defaultLanguage); if (!language) throw new DocumentNotFoundException(url, 'The language is not found') const urlSegments = this.splitPathNameToUrlSegments(pathName, language); return await this.resolvePageContentFromUrlSegments(startPageId, urlSegments, language); } private splitPathNameToUrlSegments = (pathname: string, language: string): string[] => { if (!pathname) return []; const paths = pathname.split('/').filter(id => !isNilOrWhiteSpace(id)); if (paths.length == 0) return []; if (paths[0] == language) paths.splice(0, 1); return paths; } private resolvePageContentFromUrlSegments = async (startPageId: string, segments: string[], language: string): Promise<IPageDocument & IPageLanguageDocument> => { if (!segments || segments.length == 0) return await this.getContent(startPageId, language, [VersionStatus.Published]); return await this.recursiveResolvePageByUrlSegment(startPageId, segments, language, 0); } private recursiveResolvePageByUrlSegment = async (parentPageId: string, segments: string[], language: string, index: number): Promise<IPageDocument & IPageLanguageDocument> => { // get page children const select = '_id,urlSegment,language,status'; const childrenPage = (await super.getContentChildren(parentPageId, language, null, select)); if (!childrenPage || childrenPage.length == 0) return null; const matchPage = childrenPage.find(page => page.urlSegment == segments[index]); if (!matchPage) return null; if (index == segments.length - 1) return await this.getContent(matchPage._id.toString(), language, [VersionStatus.Published]); return await this.recursiveResolvePageByUrlSegment(matchPage._id.toString(), segments, language, index + 1); } /** * Extract language code from url with fallback language * @param url * @param fallbackLanguage */ private getLanguageFromUrl = async (url: URL, fallbackLanguage: string): Promise<string> => { const pathUrl = url.pathname; // --> /abc/xyz const paths = pathUrl.split('/').filter(id => !isNilOrWhiteSpace(id)); if (paths.length > 0) { const languageCode = paths[0]; //TODO should get languages from cache then find one const language = await this.languageService.getLanguageByCode(languageCode); if (language) return language.language; } const langDoc = await this.languageService.getLanguageByCode(fallbackLanguage); return langDoc ? langDoc.language : undefined; } public executeCreateContentFlow = async (pageObj: IPageDocument & IPageLanguageDocument, language: string, userId: string): Promise<IPageDocument & IPageVersionDocument> => { //get page's parent const parentPage = await this.findById(pageObj.parentId).exec(); //generate url segment pageObj.urlSegment = await this.generateUrlSegment(0, slugify(pageObj.name), parentPage ? parentPage._id.toString() : null, language); //Step3: create new page const savedPage = await super.executeCreateContentFlow(pageObj, language, userId); //Step4: update parent page's has children property if (savedPage) await this.updateHasChildren(parentPage); return savedPage; } private generateUrlSegment = async (seed: number, originalUrl: string, parentId: string, language: string, generatedNameInUrl?: string): Promise<string> => { const urlSegment = generatedNameInUrl ? generatedNameInUrl : originalUrl; //Find existing page has the same url segment const existPages = await this.find({ isDeleted: false, contentLanguages: { $elemMatch: { urlSegment, language } } }, { lean: true }) .select('parentId') .exec(); const count = existPages.filter(x => (!x.parentId && !parentId) || (x.parentId && x.parentId!.toString() == parentId)).length; if (count <= 0) return generatedNameInUrl ? generatedNameInUrl : originalUrl; return await this.generateUrlSegment(seed + 1, originalUrl, parentId, language, `${originalUrl}${seed + 1}`); } public executePublishContentFlow = async (id: string, versionId: string, userId: string, host: string): Promise<IPageDocument & IPageVersionDocument> => { await this.throwIfUrlSegmentDuplicated(id, versionId); const publishedContent = await super.executePublishContentFlow(id, versionId, userId); const siteDefinition = await this.siteDefinitionService.getCurrentSiteDefinition(host); const { _id, parentPath, urlSegment, language } = publishedContent; const linkTuple = await this.buildLinkUrlTuple(_id.toString(), parentPath, urlSegment, language, siteDefinition); publishedContent.linkUrl = linkTuple[1]; return publishedContent; } private throwIfUrlSegmentDuplicated = async (pageId: string, versionId: string): Promise<void> => { const pageVersion = await this.contentVersionService.getVersionById(versionId); const pageContent = pageVersion.contentId as IPageDocument; const { language, urlSegment } = pageVersion; //Find published page has the same url segment const existPages = await this.find({ _id: { $ne: pageId }, isDeleted: false, contentLanguages: { $elemMatch: { urlSegment, language, status: VersionStatus.Published } } }, { lean: true }) .exec(); const parentId = pageContent.parentId; const duplicatedUrlSegmentPages = existPages.filter(x => JSON.stringify(x.parentId) === JSON.stringify(parentId) ); if (duplicatedUrlSegmentPages.length > 0) { const pageInfo = duplicatedUrlSegmentPages.map(x => { const pageLang = x.contentLanguages.find(y => y.language == language && y.urlSegment == urlSegment); return { id: x._id, name: pageLang?.name } }); const message = `The url segment ${urlSegment} has been used in pages ${JSON.stringify(pageInfo)}`; throw new Exception(httpStatus.BAD_REQUEST, message); } } }
the_stack
import { EventEmitter } from "../../EventEmitter"; import { Util } from "../../Util.class"; import { Protocol } from "../../Protocol.static"; import { Socket } from "./Socket"; var http, qs, webrtc; if (Util.isNodejs) { qs = require('querystring'); http = require('http'); try { webrtc = require('wrtc'); } catch (e) { //console.error("wrtc module not found : WebRTC support will not be available"); //process.exit(e.code); webrtc = { unavailable: true, error: e }; } } var PeerConnection = Util.isNodejs ? webrtc.RTCPeerConnection : window['RTCPeerConnection'] || window['mozRTCPeerConnection'] || window['webkitRTCPeerConnection']; var SessionDescription = Util.isNodejs ? webrtc.RTCSessionDescription : window['RTCSessionDescription'] || window['mozRTCSessionDescription'] || window['webkitRTCSessionDescription']; export class Peer extends EventEmitter { public id = Util.randomID(); public peerConnection: RTCPeerConnection = null; public channel: RTCDataChannel = null; public tSocket: Socket; public pendingDataChannels = {}; public dataChannels = {} //const configuration = {"iceServers":[{"url":"stun:stun.ideasip.com","urls":["stun:stun.ideasip.com"]},{"url":"stun:stun.voipstunt.com","urls":["stun:stun.voipstunt.com"]}]} public remainingRetries = 10; public peerSettings = { iceServers: [ //{"url": "stun:stun.services.mozilla.com"}, //{"urls": "stun:stun.l.google.com:19302"}, //{"urls": "stun:stun1.l.google.com:19302"}, //{"urls": "stun:stun2.l.google.com:19302"}, ] }; //public con = { 'optional': [{ 'DtlsSrtpKeyAgreement': true }] }; public channelSettings = { reliable: true, ordered: true, maxRetransmits: null } constructor(private settings: any = { reliable: true }) { super(); if (webrtc && webrtc.unavailable) { console.error("wrtc module not found\n"); console.error(" * Please follow instructions here https://github.com/js-platform/node-webrtc to install wrtc\n"); console.error(" * Note : WebRTC is only supported on x64 platforms\n"); process.exit(); } if (typeof settings.reliable != 'undefined') this.channelSettings.reliable = settings.reliable; if (typeof settings.maxRetransmits != 'undefined') this.channelSettings.maxRetransmits = settings.maxRetransmits; if (typeof settings.ordered !== 'undefined') this.channelSettings.ordered = settings.ordered; if (settings.iceServers instanceof Array) this.peerSettings.iceServers = settings.iceServers; } //we use HTTP for signaling public signal() { const wrtcSettings = this.settings; const uri = wrtcSettings.uri; //a timeout can occure while the datachannel is estabilishing the connection. //if already connected, dont restart negociation if (this.lastState == 'connected' && this.channel.readyState == 'open') return; if (this.channel) { this.channel.close(); this.lastState = 'retry'; } if (this.remainingRetries <= 0) { this.tSocket.emit('close'); return; } this.remainingRetries--; this.makeOffer().then((pc: RTCPeerConnection) => { if (Util.isNodejs) { const url = require("url"); const postDataObj = {}; postDataObj[Protocol.signal] = JSON.stringify(pc.localDescription); const post_data = qs.stringify(postDataObj); const parsedURI = url.parse(uri); const post_options = { host: parsedURI.hostname, port: parsedURI.port, path: '/wrtc-' + wrtcSettings.prefix, method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': post_data.length } }; const post_req = http.request(post_options, (res) => { res.setEncoding('utf8'); res.on('data', (chunk) => { const resp = JSON.parse(chunk); this.getAnswer(resp[Protocol.signal]); this.remainingRetries = wrtcSettings.retries; }); }); post_req.write(post_data); post_req.end(); post_req.on('error', (error) => { setTimeout(() => this.signal(), 3000); }); // } else { const xhr = new XMLHttpRequest(); const params = Protocol.signal + '=' + JSON.stringify(pc.localDescription); const parser = document.createElement('a'); parser.href = uri; xhr.open("POST", '//' + parser.hostname + ':' + parser.port + '/wrtc-' + wrtcSettings.prefix, true); //Send the proper header information along with the request xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //xhr.setRequestHeader("Content-length", params.length.toString()); //xhr.setRequestHeader("Connection", "close"); xhr.onreadystatechange = () => {//Call a function when the state changes. if (xhr.readyState == 4 && xhr.status == 200) { const resp = JSON.parse(xhr.responseText); this.getAnswer(resp[Protocol.signal]); this.remainingRetries = wrtcSettings.retries; } else { if (xhr.readyState == 4 && xhr.status != 200) { setTimeout(() => this.signal(), 3000); } } }; xhr.send(params); } this.tSocket.update(this.channel); }) .catch((error) => this.tSocket.emit('error', error)); } public makeOffer() { return new Promise((resolve, reject) => { const pc = new PeerConnection(this.peerSettings); this.peerConnection = pc; //this.makeDataChannel(); pc.onsignalingstatechange = this.onSignalingStateChange.bind(this); pc.oniceconnectionstatechange = this.onICEConnectionStateChange.bind(this); pc.onicegatheringstatechange = this.onICEGatheringStateChange.bind(this); pc.onicecandidate = function (candidate) { // Firing this callback with a null candidate indicates that // trickle ICE gathering has finished, and all the candidates // are now present in pc.localDescription. Waiting until now // to create the answer saves us from having to send offer + // answer + iceCandidates separately. if (candidate.candidate == null) { resolve(pc); } } // If you don't make a datachannel *before* making your offer (such // that it's included in the offer), then when you try to make one // afterwards it just stays in "connecting" state forever. This is // my least favorite thing about the datachannel API. var channel = pc.createDataChannel('eureca.io', { /**/ reliable: this.channelSettings.reliable, maxRetransmits: this.channelSettings.maxRetransmits, ordered: this.channelSettings.ordered }); this.channel = channel; pc.createOffer().then(desc => pc.setLocalDescription(desc), reject); }) } public getAnswer(pastedAnswer) { const data = typeof pastedAnswer == 'string' ? JSON.parse(pastedAnswer) : pastedAnswer; const answer = new SessionDescription(data); this.peerConnection.setRemoteDescription(answer); } public getOffer(pastedOffer, request) { return new Promise((resolve, reject) => { const data = typeof pastedOffer === 'object' ? pastedOffer : JSON.parse(pastedOffer); const pc = new PeerConnection(this.peerSettings); this.peerConnection = pc; pc.onsignalingstatechange = this.onSignalingStateChange.bind(this); pc.oniceconnectionstatechange = this.onICEConnectionStateChange.bind(this); pc.onicegatheringstatechange = this.onICEGatheringStateChange.bind(this); pc.onicecandidate = (candidate) => { // null candidate indicates that // trickle ICE gathering has finished, and all the candidates // are now present in pc.localDescription. Waiting until now // to create the answer saves us from having to send offer + // answer + iceCandidates separately. if (candidate.candidate == null) { resolve(pc); } } //var labels = Object.keys(this.dataChannelSettings); pc.ondatachannel = (evt) => { const channel = evt.channel; channel.request = request; //__this.channel = channel; const label = channel.label; this.pendingDataChannels[label] = channel; channel.binaryType = 'arraybuffer'; channel.onopen = () => { this.dataChannels[label] = channel; delete this.pendingDataChannels[label]; this.emit('datachannel', channel); }; }; const offer = new SessionDescription(data); pc.setRemoteDescription(offer) .then(() => pc.createAnswer(), this.doHandleError) .then(desc => pc.setLocalDescription(desc), this.doHandleError); }) } public lastState = ''; private stateTimeout; public onICEConnectionStateChange(state) { const pc = this.peerConnection; this.emit('stateChange', pc.iceConnectionState); this.lastState = pc.iceConnectionState; if (this.stateTimeout != undefined) clearTimeout(this.stateTimeout); if (pc.iceConnectionState == 'disconnected' || pc.iceConnectionState == 'failed') { this.emit('disconnected'); } if (pc.iceConnectionState == 'completed' || pc.iceConnectionState == 'connected') { //trigger a timeout to check if client successfully connected this.stateTimeout = setTimeout(() => this.emit('timeout'), 500); } else { this.stateTimeout = setTimeout(() => this.emit('timeout'), 5000); } } public onICEGatheringStateChange(state) { //console.info('ice gathering state change:', state); } public onSignalingStateChange(state) { //console.log('signal state = ', state); } public doHandleError(error) { this.emit('error', error); } }
the_stack
import * as dotenv from 'dotenv'; import * as fs from 'fs'; import Manifest from '../src/Manifest'; import Traveler from '../src/Traveler'; import { TypeDefinition } from '../src/type-definitions/additions'; import { BungieMembershipType } from '../src/type-definitions/app'; import { DestinyComponentType, PlatformErrorCodes, DestinyStatsGroupType } from '../src/type-definitions/destiny2'; import { OAuthError } from '../src/errors'; dotenv.config(); const traveler = new Traveler({ apikey: process.env.API_KEY as string, debug: true, oauthClientId: process.env.OAUTH_ID, oauthClientSecret: process.env.OAUTH_SECRET, userAgent: '' }); jest.setTimeout(30000); // 30 second timeout afterAll(() => { fs.unlink(`./manifest.content`, err => { if (err) { console.log('Error deleting content file'); } console.log('Everyting tidied up'); }); }); describe('traveler.global#getGlobalAlerts', () => { test('Respond with current global alerts', async () => { const result = await traveler.global.getGlobalAlerts(); expect(typeof result.Response).toBe('object'); }); }); describe('traveler.destiny2#getDestinyManifest', () => { test('Respond with current manifest formatted in JSON', async () => { const result = await traveler.destiny2.getDestinyManifest(); expect(typeof result.Response).toBe('object'); }); test('Object contains all required keys', async () => { const result = await traveler.destiny2.getDestinyManifest(); expect(Object.keys(result.Response)).toEqual( expect.arrayContaining([ 'mobileAssetContentPath', 'mobileClanBannerDatabasePath', 'mobileClanBannerDatabasePath', 'mobileGearAssetDataBases', 'mobileGearCDN', 'mobileWorldContentPaths', 'version' ]) ); }); }); describe('traveler.destiny2#getDestinyEntityDefinition', () => { test('Respond with JSON data about the weapon called Blue Shift', async () => { const result = await traveler.destiny2.getDestinyEntityDefinition( TypeDefinition.DestinyInventoryItemDefinition, '417474226' ); return expect(result.Response.hash).toEqual(417474226); }); test('Get rejected due to wrong parameters', async () => { expect.assertions(1); try { await traveler.destiny2.getDestinyEntityDefinition(TypeDefinition.DestinyInventoryItemDefinition, ''); } catch (e) { expect(e.statusCode).toEqual(404); } }); describe('traveler.destiny2#searchDestinyPlayer', () => { test('Respond with matching player', async () => { const result = await traveler.destiny2.searchDestinyPlayer(BungieMembershipType.All, 'playername'); expect(result.Response[0].displayName.toLowerCase()).toEqual('playername'); }); test('Get rejected due to wrong parameters', async () => { expect.assertions(1); try { await traveler.destiny2.searchDestinyPlayer(BungieMembershipType.All, ''); } catch (e) { expect(e.statusCode).toEqual(404); } }); }); describe('traveler.destiny2#getLinkedProfiles', () => { test('Respond with matching linked accounts', async () => { const result = await traveler.destiny2.getLinkedProfiles(BungieMembershipType.TigerPsn, '4611686018452033461'); expect(typeof result.Response.profiles[0]).toEqual('object'); }); }); describe('traveler.destiny2#getProfile', () => { test('Respond with the matching profile', async () => { const result = await traveler.destiny2.getProfile(BungieMembershipType.TigerPsn, '4611686018452033461', { components: [DestinyComponentType.Profiles] }); expect(Object.keys(result.Response)).toEqual(expect.arrayContaining(['profile'])); }); test('Get rejected due to requesting TigerPsn profile data but providing XBOX member type and wrong id', async () => { try { await traveler.destiny2.getProfile(BungieMembershipType.TigerPsn, '', { components: [DestinyComponentType.Profiles] }); } catch (e) { expect(e.statusCode).toEqual(404); } }); }); describe('traveler.destiny2#getCharacter', () => { test('Respond with matching character and only character components', async () => { const result = await traveler.destiny2.getCharacter( BungieMembershipType.TigerPsn, '4611686018452033461', '2305843009265042115', { components: [ DestinyComponentType.Characters, DestinyComponentType.CharacterInventories, DestinyComponentType.CharacterProgressions, DestinyComponentType.CharacterRenderData, DestinyComponentType.CharacterActivities, DestinyComponentType.CharacterEquipment ] } ); expect(Object.keys(result.Response)).toEqual( expect.arrayContaining([ 'inventory', 'character', 'progressions', 'renderData', 'activities', 'character', 'equipment' ]) ); }); }); // TODO: make rejected test }); describe('traveler.destiny2#getClanWeeklyRewardState', () => { test('Respond with information on the weekly clan reward', async () => { const result = await traveler.destiny2.getClanWeeklyRewardState('1812014'); return expect(result.ErrorCode).toEqual(PlatformErrorCodes.Success); }); test('Fail to respond with information of the weekly clan reward', async () => { try { await traveler.destiny2.getClanWeeklyRewardState('-1'); } catch (e) { expect(e.ErrorCode).toEqual(622); } }); }); describe('traveler.destiny2#getItem', () => { test('Respond with matching item', async () => { const result = await traveler.destiny2.getItem( BungieMembershipType.TigerPsn, '4611686018452033461', '6917529033189743362', { components: [DestinyComponentType.ItemCommonData] } ); expect(Object.keys(result.Response.item.data)).toEqual( expect.arrayContaining([ 'itemHash', 'itemInstanceId', 'quantity', 'bindStatus', 'location', 'bucketHash', 'transferStatus', 'lockable', 'state' ]) ); }); }); // TODO: getVendors (not yet final) // TODO: getVendor (not yet final) describe('traveler.destiny2#getPublicVendors', () => { test('Respond with matching vendors', async () => { const result = await traveler.destiny2.getPublicVendors({ components: [DestinyComponentType.Vendors] }); expect(result.Response.vendorGroups).toBeDefined(); }); }); // TODO: getPostGameCarnageReport describe('traveler.destiny2#getHistoricalStatsDefinition', () => { test('Respond with matching historical stat definitions', async () => { const result = await traveler.destiny2.getHistoricalStatsDefinition(); expect(result.ErrorCode).toEqual(PlatformErrorCodes.Success); }); }); // TODO: getCLanLeaderboards (not yet final) // TODO: getClanAggregratedStats (not yet final) // TODO: getLeaderboards (not yet final) // TODO: getLeaderboardsForCharacter (not yet final) describe('traveler.destiny2#searchDestinyEntities', () => { test('Respond with matching search results for sunshot', async () => { const result = await traveler.destiny2.searchDestinyEntities( 'sunshot', TypeDefinition.DestinyInventoryItemDefinition, { page: 0 } ); return expect(result.Response.suggestedWords).toContain('sunshot'); }); }); describe('traveler.destiny2#getHistoricalStats', () => { it('Respond with historical stats', async () => { const result = await traveler.destiny2.getHistoricalStats( BungieMembershipType.TigerPsn, '4611686018452033461', '2305843009265042115', { dayend: '2017-09-30', daystart: '2017-09-20', groups: [DestinyStatsGroupType.Activity] } ); return expect(result.ErrorCode).toEqual(PlatformErrorCodes.Success); }); test('Fail to respond with historical stats due to invalid date parameter', async () => { try { await traveler.destiny2.getHistoricalStats( BungieMembershipType.TigerPsn, '4611686018452033461', '2305843009265042115', { dayend: '2017-09-40', daystart: '2017-09-20', groups: [DestinyStatsGroupType.Activity] } ); } catch (e) { expect(e.ErrorCode).toEqual(7); } }); }); // TODO: getHistoricalStatsForAccount (not yet final) // TODO: getActivityHistory (not yet final) // TODO: getUniqueWeaponHistory (not yet final) // TODO: getAggregateActivityStats (not yet final) describe('traveler.destiny2#getPublicMilestoneContent', () => { test('Respond with public milestone content for milestone hash 202035466', async () => { const result = await traveler.destiny2.getPublicMilestoneContent('202035466'); return expect(result.ErrorCode).toEqual(PlatformErrorCodes.Success); }); }); describe('traveler.destiny2#getPublicMilestones', () => { test('Respond with public milestones', async () => { const result = await traveler.destiny2.getPublicMilestones(); return expect(result.ErrorCode).toEqual(PlatformErrorCodes.Success); }); }); // TODO: equipItem describe('OAuthError#constructor', () => { it('creates a new OAuth error', async () => { return expect(new OAuthError('New OauthError')).toBeInstanceOf(Error); }); }); describe('Traveler#downloadManifest and Manifest#constructor and Manifest#queryManifest', () => { test('Download the manifest, remove .zip and queries it with a simple query', async () => { const result = await traveler.destiny2.getDestinyManifest(); const filepath = await traveler.destiny2.downloadManifest( result.Response.mobileWorldContentPaths.en, './manifest.content' ); const manifest = new Manifest(filepath); const queryResult = await manifest.queryManifest('SELECT name FROM sqlite_master WHERE type="table"'); expect(typeof queryResult).toEqual('object'); }); }); describe('Manifest', () => { test('Fails to create an instance', async () => { return expect(() => { const manifest = new Manifest('./test'); }).toThrow; }); it('Fails to query an invalid db', async () => { try { await new Manifest('./output.gif').queryManifest('SELECT name FROM sqlite_master WHERE type="table"'); } catch (e) { expect(e.code).toEqual('SQLITE_NOTADB'); } }); });
the_stack
import { BaseResource, CloudError } from "ms-rest-azure"; import * as moment from "moment"; export { BaseResource, CloudError }; /** * The Resource definition */ export interface Resource extends BaseResource { /** * Resource Id */ readonly id?: string; /** * Resource name */ readonly name?: string; /** * Resource type */ readonly type?: string; } /** * Definition of Resource */ export interface TrackedResource extends Resource { /** * Resource location */ location?: string; /** * Resource tags */ tags?: { [propertyName: string]: string }; } /** * SKU parameters supplied to the create namespace operation */ export interface Sku { /** * Name of this SKU. Possible values include: 'Basic', 'Standard' */ name: string; /** * The billing tier of this particular SKU. Possible values include: 'Basic', 'Standard' */ tier?: string; /** * The Event Hubs throughput units, value should be 0 to 20 throughput units. */ capacity?: number; } /** * Single Namespace item in List or Get Operation */ export interface EHNamespace extends TrackedResource { /** * Properties of sku resource */ sku?: Sku; /** * Provisioning state of the Namespace. */ readonly provisioningState?: string; /** * The time the Namespace was created. */ readonly createdAt?: Date; /** * The time the Namespace was updated. */ readonly updatedAt?: Date; /** * Endpoint you can use to perform Service Bus operations. */ readonly serviceBusEndpoint?: string; /** * Identifier for Azure Insights metrics. */ readonly metricId?: string; /** * Value that indicates whether AutoInflate is enabled for eventhub namespace. */ isAutoInflateEnabled?: boolean; /** * Upper limit of throughput units when AutoInflate is enabled, value should be within 0 to 20 * throughput units. ( '0' if AutoInflateEnabled = true) */ maximumThroughputUnits?: number; /** * Value that indicates whether Kafka is enabled for eventhub namespace. */ kafkaEnabled?: boolean; } /** * Single item in a List or Get AuthorizationRule operation */ export interface AuthorizationRule extends Resource { /** * The rights associated with the rule. */ rights: string[]; } /** * Namespace/EventHub Connection String */ export interface AccessKeys { /** * Primary connection string of the created namespace AuthorizationRule. */ readonly primaryConnectionString?: string; /** * Secondary connection string of the created namespace AuthorizationRule. */ readonly secondaryConnectionString?: string; /** * Primary connection string of the alias if GEO DR is enabled */ readonly aliasPrimaryConnectionString?: string; /** * Secondary connection string of the alias if GEO DR is enabled */ readonly aliasSecondaryConnectionString?: string; /** * A base64-encoded 256-bit primary key for signing and validating the SAS token. */ readonly primaryKey?: string; /** * A base64-encoded 256-bit primary key for signing and validating the SAS token. */ readonly secondaryKey?: string; /** * A string that describes the AuthorizationRule. */ readonly keyName?: string; } /** * Parameters supplied to the Regenerate Authorization Rule operation, specifies which key needs to * be reset. */ export interface RegenerateAccessKeyParameters { /** * The access key to regenerate. Possible values include: 'PrimaryKey', 'SecondaryKey' */ keyType: string; /** * Optional, if the key value provided, is set for KeyType or autogenerated Key value set for * keyType */ key?: string; } /** * Capture storage details for capture description */ export interface Destination { /** * Name for capture destination */ name?: string; /** * Resource id of the storage account to be used to create the blobs */ storageAccountResourceId?: string; /** * Blob container Name */ blobContainer?: string; /** * Blob naming convention for archive, e.g. * {Namespace}/{EventHub}/{PartitionId}/{Year}/{Month}/{Day}/{Hour}/{Minute}/{Second}. Here all * the parameters (Namespace,EventHub .. etc) are mandatory irrespective of order */ archiveNameFormat?: string; } /** * Properties to configure capture description for eventhub */ export interface CaptureDescription { /** * A value that indicates whether capture description is enabled. */ enabled?: boolean; /** * Enumerates the possible values for the encoding format of capture description. Note: * 'AvroDeflate' will be deprecated in New API Version. Possible values include: 'Avro', * 'AvroDeflate' */ encoding?: string; /** * The time window allows you to set the frequency with which the capture to Azure Blobs will * happen, value should between 60 to 900 seconds */ intervalInSeconds?: number; /** * The size window defines the amount of data built up in your Event Hub before an capture * operation, value should be between 10485760 to 524288000 bytes */ sizeLimitInBytes?: number; /** * Properties of Destination where capture will be stored. (Storage Account, Blob Names) */ destination?: Destination; /** * A value that indicates whether to Skip Empty Archives */ skipEmptyArchives?: boolean; } /** * Single item in List or Get Event Hub operation */ export interface Eventhub extends Resource { /** * Current number of shards on the Event Hub. */ readonly partitionIds?: string[]; /** * Exact time the Event Hub was created. */ readonly createdAt?: Date; /** * The exact time the message was updated. */ readonly updatedAt?: Date; /** * Number of days to retain the events for this Event Hub, value should be 1 to 7 days */ messageRetentionInDays?: number; /** * Number of partitions created for the Event Hub, allowed values are from 1 to 32 partitions. */ partitionCount?: number; /** * Enumerates the possible values for the status of the Event Hub. Possible values include: * 'Active', 'Disabled', 'Restoring', 'SendDisabled', 'ReceiveDisabled', 'Creating', 'Deleting', * 'Renaming', 'Unknown' */ status?: string; /** * Properties of capture description */ captureDescription?: CaptureDescription; } /** * Single item in List or Get Consumer group operation */ export interface ConsumerGroup extends Resource { /** * Exact time the message was created. */ readonly createdAt?: Date; /** * The exact time the message was updated. */ readonly updatedAt?: Date; /** * User Metadata is a placeholder to store user-defined string data with maximum length 1024. * e.g. it can be used to store descriptive data, such as list of teams and their contact * information also user-defined configuration settings can be stored. */ userMetadata?: string; } /** * Parameter supplied to check Namespace name availability operation */ export interface CheckNameAvailabilityParameter { /** * Name to check the namespace name availability */ name: string; } /** * The Result of the CheckNameAvailability operation */ export interface CheckNameAvailabilityResult { /** * The detailed info regarding the reason associated with the Namespace. */ readonly message?: string; /** * Value indicating Namespace is availability, true if the Namespace is available; otherwise, * false. */ nameAvailable?: boolean; /** * The reason for unavailability of a Namespace. Possible values include: 'None', 'InvalidName', * 'SubscriptionIsDisabled', 'NameInUse', 'NameInLockdown', * 'TooManyNamespaceInCurrentSubscription' */ reason?: string; } /** * The object that represents the operation. */ export interface OperationDisplay { /** * Service provider: Microsoft.EventHub */ readonly provider?: string; /** * Resource on which the operation is performed: Invoice, etc. */ readonly resource?: string; /** * Operation type: Read, write, delete, etc. */ readonly operation?: string; } /** * A Event Hub REST API operation */ export interface Operation { /** * Operation name: {provider}/{resource}/{operation} */ readonly name?: string; /** * The object that represents the operation. */ display?: OperationDisplay; } /** * Error response indicates EventHub service is not able to process the incoming request. The * reason is provided in the error message. */ export interface ErrorResponse { /** * Error code. */ code?: string; /** * Error message indicating why the operation failed. */ message?: string; } /** * Single item in List or Get Alias(Disaster Recovery configuration) operation */ export interface ArmDisasterRecovery extends Resource { /** * Provisioning state of the Alias(Disaster Recovery configuration) - possible values 'Accepted' * or 'Succeeded' or 'Failed'. Possible values include: 'Accepted', 'Succeeded', 'Failed' */ readonly provisioningState?: string; /** * ARM Id of the Primary/Secondary eventhub namespace name, which is part of GEO DR pairing */ partnerNamespace?: string; /** * Alternate name specified when alias and namespace names are same. */ alternateName?: string; /** * role of namespace in GEO DR - possible values 'Primary' or 'PrimaryNotReplicating' or * 'Secondary'. Possible values include: 'Primary', 'PrimaryNotReplicating', 'Secondary' */ readonly role?: string; /** * Number of entities pending to be replicated. */ readonly pendingReplicationOperationsCount?: number; } export interface MessagingRegionsProperties { /** * Region code */ readonly code?: string; /** * Full name of the region */ readonly fullName?: string; } /** * Messaging Region */ export interface MessagingRegions extends TrackedResource { properties?: MessagingRegionsProperties; } /** * Messaging Plan for the namespace */ export interface MessagingPlan extends TrackedResource { /** * Sku type */ readonly sku?: number; /** * Selected event hub unit */ readonly selectedEventHubUnit?: number; /** * The exact time the messaging plan was updated. */ readonly updatedAt?: Date; /** * revision number */ readonly revision?: number; } /** * Properties supplied for Subnet */ export interface Subnet { /** * Resource ID of Virtual Network Subnet */ id: string; } /** * Description of NetWorkRuleSet - IpRules resource. */ export interface NWRuleSetIpRules { /** * IP Mask */ ipMask?: string; /** * The IP Filter Action. Possible values include: 'Allow' */ action?: string; } /** * Description of VirtualNetworkRules - NetworkRules resource. */ export interface NWRuleSetVirtualNetworkRules { /** * Subnet properties */ subnet?: Subnet; /** * Value that indicates whether to ignore missing VNet Service Endpoint */ ignoreMissingVnetServiceEndpoint?: boolean; } /** * Description of NetworkRuleSet resource. */ export interface NetworkRuleSet extends Resource { /** * Default Action for Network Rule Set. Possible values include: 'Allow', 'Deny' */ defaultAction?: string; /** * List VirtualNetwork Rules */ virtualNetworkRules?: NWRuleSetVirtualNetworkRules[]; /** * List of IpRules */ ipRules?: NWRuleSetIpRules[]; } /** * Result of the request to list Event Hub operations. It contains a list of operations and a URL * link to get the next set of results. */ export interface OperationListResult extends Array<Operation> { /** * URL to get the next set of operation list results if there are any. */ readonly nextLink?: string; } /** * The response of the List Namespace operation */ export interface EHNamespaceListResult extends Array<EHNamespace> { /** * Link to the next set of results. Not empty if Value contains incomplete list of namespaces. */ nextLink?: string; } /** * The response from the List namespace operation. */ export interface AuthorizationRuleListResult extends Array<AuthorizationRule> { /** * Link to the next set of results. Not empty if Value contains an incomplete list of * Authorization Rules */ nextLink?: string; } /** * The result of the List Alias(Disaster Recovery configuration) operation. */ export interface ArmDisasterRecoveryListResult extends Array<ArmDisasterRecovery> { /** * Link to the next set of results. Not empty if Value contains incomplete list of Alias(Disaster * Recovery configuration) */ readonly nextLink?: string; } /** * The result of the List EventHubs operation. */ export interface EventHubListResult extends Array<Eventhub> { /** * Link to the next set of results. Not empty if Value contains incomplete list of EventHubs. */ nextLink?: string; } /** * The result to the List Consumer Group operation. */ export interface ConsumerGroupListResult extends Array<ConsumerGroup> { /** * Link to the next set of results. Not empty if Value contains incomplete list of Consumer Group */ nextLink?: string; } /** * The response of the List MessagingRegions operation. */ export interface MessagingRegionsListResult extends Array<MessagingRegions> { /** * Link to the next set of results. Not empty if Value contains incomplete list of * MessagingRegions. */ readonly nextLink?: string; }
the_stack
import { aws_apigateway, aws_iam } from "aws-cdk-lib"; import { APIGatewayProxyEvent, APIGatewayProxyResult, APIGatewayEventRequestContext, } from "aws-lambda"; import { FunctionDecl, validateFunctionDecl } from "./declaration"; import { ErrorCodes, SynthError } from "./error-code"; import { CallExpr, Expr, Identifier } from "./expression"; import { Function } from "./function"; import { isReturnStmt, isPropAccessExpr, isNullLiteralExpr, isUndefinedLiteralExpr, isBooleanLiteralExpr, isNumberLiteralExpr, isStringLiteralExpr, isArrayLiteralExpr, isArgument, isCallExpr, isParameterDecl, isFunctionDecl, isElementAccessExpr, isObjectLiteralExpr, isPropAssignExpr, isVariableStmt, isIdentifier, } from "./guards"; import { findIntegration, IntegrationImpl } from "./integration"; import { Stmt } from "./statement"; import { AnyFunction, singletonConstruct } from "./util"; import { VTL } from "./vtl"; /** * HTTP Methods that API Gateway supports. */ export type HttpMethod = | "ANY" | "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "OPTIONS"; /** * Properties for configuring an API Gateway Method Integration. * * Both the Method's properties and the underlying Integration are configured with these properties. */ export interface MethodProps extends Omit< aws_apigateway.IntegrationOptions, "requestTemplates" | "integrationResponses" | "requestParameters" >, Omit< aws_apigateway.MethodOptions, "requestParameters" | "operationName" | "methodResponses" > { /** * The HTTP Method of this API Method Integration. */ httpMethod: HttpMethod; /** * The API Gateway Resource this Method implements. */ resource: aws_apigateway.IResource; /** * The IAM Role to use for authorizing this Method's integration requests. * * If you choose to pass an IAM Role, make sure it can be assumed by API * Gateway's service principal - `"apigateway.amazonaws.com"`. * * ```ts * new aws_iam.Role(scope, id, { * assumedBy: new aws_iam.ServicePrincipal("apigateway.amazonaws.com"), * }) * ``` * * @default - one is created for you. */ credentialsRole?: aws_iam.IRole; } /** * Data types allowed for an API path, query or header parameter. */ export type ApiParameter = undefined | null | boolean | number | string; /** * A collection of {@link ApiParameter}s. */ export type ApiParameters = Record<string, string>; /** * Type of data allowed as the body in an API. */ export type ApiBody = | ApiParameter | ApiBody[] | { [propertyName in string]: ApiBody; }; /** * Request to an API Gateway method. Parameters can be passed in via * the path, query string or headers, and the body is a JSON object. * None of these are required. */ export interface ApiRequest< Path extends ApiParameters = ApiParameters, Body extends ApiBody = any, Query extends ApiParameters = ApiParameters, Header extends ApiParameters = ApiParameters > { /** * Parameters in the path. */ path?: Path; /** * Body of the request. */ body?: Body; /** * Parameters in the query string. */ query?: Query; /** * Parameters in the headers. */ headers?: Header; } export type ApiMethodKind = "AwsMethod" | "MockMethod"; export function isApiMethodKind(a: any): a is ApiMethodKind { return a === "AwsMethod" || a === "MockMethod"; } /** * Base class of an AWS API Gateway Method. * * @see {@link MockMethod} * @see {@link AwsMethod} */ export abstract class ApiMethod<Kind extends ApiMethodKind> { /** * Identify subclasses as API integrations to the Functionless plugin */ public static readonly FunctionlessType = "ApiIntegration"; constructor( /** * */ readonly kind: Kind, /** * The underlying Method Construct. */ readonly method: aws_apigateway.Method ) {} } /** * Constructs the IAM Role to be used by an API Integration. * * You can pass in their own IAM Role if they choose. If they do, it is their responsibility to * ensure that Role can be assumed by the `apigateway.amazonaws.com` service principal. * * By default, a new Role is created for you. * * @param props the {@link MethodProps} for this Method Integration. * @returns the IAM Role used for authorizing the API Method Integration requests. */ function getRole(props: MethodProps) { if (props.credentialsRole) { // use the IAM Role passed in by the user. // TODO: should we try our best to ensure that the passed in Role has the correct assumedBy policy or leave it up to the user? // -> if this is an IRole, we can't do anything // -> if this is a Role, we can check the underlying CfnResource's policy and update it return props.credentialsRole; } // by default, create a Role for each Resource's HTTP Method // the Method's Role is stored as a singleton on the HTTP Resource using the naming convention, `Role_<method>`, e.g. `Role_GET`. const roleResourceName = `Role_${props.httpMethod}`; return singletonConstruct( props.resource, roleResourceName, (scope, id) => new aws_iam.Role(scope, id, { assumedBy: new aws_iam.ServicePrincipal("apigateway.amazonaws.com"), }) ); } /** * A Mock integration lets you return pre-configured responses by status code. * No backend service is invoked. * * To use you provide a `request` function that returns a status code from the * request and a `responses` object that maps a status code to a function * returning the pre-configured response for that status code. Functionless will * convert these functions to VTL mapping templates and configure the necessary * method responses. * * ```ts * new MockApiIntegration( * { * httpMethod: "GET", * resource: api.root, * }, * ($input) => ({ * statusCode: $input.params("code") as number, * }), * { * 200: () => ({ * response: "OK", * }), * 500: () => ({ * response: "BAD", * }), * } * ); * ``` * * Only `application/json` is supported. To workaround this limitation, use the [API Gateway Construct Library](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-apigateway-readme.html) * * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-integration-types.html */ export class MockMethod< Request extends ApiRequest, StatusCode extends number > extends ApiMethod<"MockMethod"> { constructor( props: MethodProps, /** * Map API request to a status code. This code will be used by API Gateway * to select the response to return. * * Functionless's API Gateway only supports JSON data at this time. */ request: ( $input: ApiGatewayInput<Request>, $context: ApiGatewayContext ) => { statusCode: StatusCode }, /** * Map of status codes to response to return. * * Functionless's API Gateway only supports JSON data at this time. */ responses: { [C: number]: ( $input: ApiGatewayInput<Request>, $context: ApiGatewayContext ) => any; } ) { const requestDecl = validateFunctionDecl(request, "MockMethod Request"); const responseDecls = Object.fromEntries( Object.entries(responses).map(([k, v]) => [ k, validateFunctionDecl(v, `MockMethod Response ${k}`), ]) ) as { [K in 200]: FunctionDecl }; const role = getRole(props); const requestTemplate = new APIGatewayVTL(role, "request"); requestTemplate.eval(requestDecl.body); const integrationResponses: aws_apigateway.IntegrationResponse[] = Object.entries(responseDecls).map(([statusCode, fn]) => { const responseTemplate = new APIGatewayVTL(role, "response"); responseTemplate.eval((fn as FunctionDecl).body); return { statusCode, responseTemplates: { "application/json": responseTemplate.toVTL(), }, selectionPattern: `^${statusCode}$`, }; }); const integration = new aws_apigateway.MockIntegration({ ...props, requestTemplates: { "application/json": requestTemplate.toVTL(), }, integrationResponses, }); const methodResponses = Object.keys(responseDecls).map((statusCode) => ({ statusCode, })); super( "MockMethod", props.resource.addMethod(props.httpMethod, integration, { methodResponses, }) ); } } /** * An AWS API Gateway Method that fulfils requests by invoking APIs on other AWS Resources. * * Integration logic is written in pure TypeScript and transformed into Apache Velocity Templates * that is then applied by the AWS API Gateway service to to transform requests and responses. * * ```ts * new AwsApiIntegration( * { * httpMethod: "GET", * resource: api.root, * }, * ( * $input: ApiGatewayInput<{ * query: Request; * }> * ) => * sfn({ * input: { * num: $input.params("num"), * str: $input.params("str"), * }, * }), * ($input, $context) => { * if ($input.data.status === "SUCCEEDED") { * return $input.data.output; * } else { * $context.responseOverride.status = 500; * return $input.data.error; * } * }, * { * 404: () => ({ * message: "Item not Found" * }) * } * ); * ``` * * The second argument is a function that transforms the incoming request into a call to an integration. * It must always end with a call to an Integration and no code can execute after the call. * * ```ts * ( * $input: ApiGatewayInput<{ * query: Request; * }> * ) => * sfn({ * input: { * num: $input.params("num"), * str: $input.params("str"), * }, * }), * ``` * * The third argument is a function that transforms the response data from the downstream Integration * into the final data sent to the API caller. This code runs when the integration responds with * a 200 status code. * * ```ts * ($input, $context) => { * if ($input.data.status === "SUCCEEDED") { * return $input.data.output; * } else { * $context.responseOverride.status = 500; * return $input.data.error; * } * } * ``` * * The fourth argument is an optional object with mapping functions for error status codes. The corresponding * callback will be executed when the downstream integration responds with that status code. * * ```ts * { * 404: () => ({ * message: "Item not Found" * }) * } * ``` * * Only `application/json` is supported. To workaround this limitation, use the [API Gateway Construct Library](https://docs.aws.amazon.com/cdk/api/v1/docs/aws-apigateway-readme.html) * * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-integration-types.html * @tparam Request - an {@link ApiRequest} type that specifies the allowed path, query, header and body parameters and their types. * @tparam MethodResponse - the type of data returned by the Integration. This is the type of data that will be processed by the response template. * @tparam IntegrationResponse - the type of data returned by this API */ export class AwsMethod< Request extends ApiRequest, MethodResponse, IntegrationResponse > extends ApiMethod<"AwsMethod"> { constructor( /** * The {@link MethodProps} for configuring how this method behaves at runtime. */ readonly props: MethodProps, /** * Function that maps an API request to an integration request and calls an * integration. This will be compiled to a VTL request mapping template and * an API GW integration. * * There are limitations on what is allowed within this Function: * 1. the integration call must be returned * * ```ts * () => { * // VALID * return lambda(); * } * * // VALID * () => lambda(); * * // INVALID - API Gateway always returns the integration response * lambda(); * * // INVALID * const result = lambda() * result... // the request mapping template terminates when the call is made * ``` * 2. an integration must be at the top-level * * ```ts * () => { * // valid * lambda(); * return lambda(); * * if (condition) { * // INVALID - conditional integrations are not supported by AWS * lambda(); * } * * while (condition) { * // INVALID - API Gateway only supports one call per integration * lambda(); * } * }} * ``` */ request: ( $input: ApiGatewayInput<Request>, $context: ApiGatewayContext ) => IntegrationResponse, /** * Function that maps an integration response to a 200 method response. * * Example 1 - return the exact payload received from the integration * ```ts * ($input) => { * return $input.data; * } * ``` * * Example 2 - modify the data returned * ```ts * ($input) => { * return { * status: "success" * name: $input.data.name * }; * } * ``` * * Example 3 - return a different payload based on a condition * * ```ts * ($input) => { * if ($input.data.status === "SUCCESS") { * return $input.data; * } else { * return null; * } * } * ``` */ response: ( $input: ApiGatewayInput< { body: IntegrationResponse } & Omit<Request, "body"> >, $context: ApiGatewayContext ) => MethodResponse, /** * Map of status codes to a function defining the response to return. This is used * to configure the failure path method responses, for e.g. when an integration fails. * * Example 1 - return the exact payload received from the integration * ```ts * ($input) => { * return $input.data; * } * ``` * * Example 2 - modify the data returned * ```ts * ($input) => { * return { * status: "success" * name: $input.data.name * }; * } * ``` * * Example 3 - return a different payload based on a condition * * ```ts * ($input) => { * if ($input.data.status === "SUCCESS") { * return $input.data; * } else { * return null; * } * } * ``` */ errors?: { [statusCode: number]: ( $input: ApiGatewayInput<Request>, $context: ApiGatewayContext ) => any; } ) { const requestDecl = validateFunctionDecl(request, "AwsMethod Request"); const responseDecl = validateFunctionDecl(response, "AwsMethod Response"); const errorDecls = Object.fromEntries( Object.entries(errors ?? {}).map(([k, v]) => [ k, validateFunctionDecl(v, `AwsMethod ${k}`), ]) ); const role = getRole(props); const responseTemplate = new APIGatewayVTL(role, "response"); responseTemplate.eval(responseDecl.body); const requestTemplate = new APIGatewayVTL(role, "request"); requestTemplate.eval(requestDecl.body); const integration = requestTemplate.integration; const errorResponses: aws_apigateway.IntegrationResponse[] = Object.entries( errorDecls ).map(([statusCode, fn]) => { const errorTemplate = new APIGatewayVTL(role, "response"); errorTemplate.eval(fn.body, "response"); return { statusCode: statusCode, selectionPattern: `^${statusCode}$`, responseTemplates: { "application/json": errorTemplate.toVTL(), }, }; }); const integrationResponses: aws_apigateway.IntegrationResponse[] = [ { statusCode: "200", responseTemplates: { "application/json": responseTemplate.toVTL(), }, }, ...errorResponses, ]; // TODO: resource is not the right scope, prevents adding 2 methods to the resource // because of the IAM roles created // should `this` be a Method? const apiGwIntegration = integration!.apiGWVtl.createIntegration({ credentialsRole: role, requestTemplates: { "application/json": requestTemplate.toVTL(), }, integrationResponses, }); const methodResponses = [ { statusCode: "200" }, ...Object.keys(errorDecls).map((statusCode) => ({ statusCode, })), ]; super( "AwsMethod", props.resource.addMethod(props.httpMethod, apiGwIntegration, { methodResponses, }) ); } } /** * API Gateway's VTL interpreter. API Gateway has limited VTL support and differing behavior to Appsync, * so this class overrides its behavior while sharing as much as it can. */ export class APIGatewayVTL extends VTL { public integration: IntegrationImpl<AnyFunction> | undefined; constructor( readonly role: aws_iam.IRole, readonly location: "request" | "response", ...statements: string[] ) { super(...statements); } /** * Called during VTL synthesis. This function will capture the API Gateway request's integration * and return a string that will emit the request payload into the VTL template. * * @param target the integration * @param call the {@link CallExpr} representing the integration instance. * @returns */ protected integrate( target: IntegrationImpl<AnyFunction>, call: CallExpr ): string { if (this.location === "response") { throw new SynthError( ErrorCodes.API_gateway_response_mapping_template_cannot_call_integration ); } const response = target.apiGWVtl.renderRequest(call, this); // ew, mutation // TODO: refactor to pure functions this.integration = target; return response; } public eval(node?: Expr, returnVar?: string): string; public eval(node: Stmt, returnVar?: string): void; public eval(node?: Expr | Stmt, returnVar?: string): string | void { if (isReturnStmt(node)) { return this.add(this.exprToJson(node.expr)); } else if ( isPropAccessExpr(node) && isInputBody(node.expr) && node.name === "data" ) { // $input.data maps to `$input.path('$')` // this returns a VTL object representing the root payload data return `$input.path('$')`; } return super.eval(node as any, returnVar); } /** * Renders a VTL string that will emit a JSON String representation of the {@link expr} to the VTL output. * * @param expr the {@link Expr} to convert to JSON * @returns a VTL string that emits the {@link expr} as JSON */ public exprToJson(expr: Expr): string { const context = this; const jsonPath = toJsonPath(expr); if (jsonPath) { return `$input.json('${jsonPath}')`; } else if (isNullLiteralExpr(expr) || isUndefinedLiteralExpr(expr)) { // Undefined is not the same as null. In JSON terms, `undefined` is the absence of a value where-as `null` is a present null value. return "null"; } else if (isBooleanLiteralExpr(expr)) { return expr.value ? "true" : "false"; } else if (isNumberLiteralExpr(expr)) { return expr.value.toString(10); } else if (isStringLiteralExpr(expr)) { return `"${expr.value}"`; } else if (isArrayLiteralExpr(expr)) { if (expr.items.length === 0) { return "[]"; } else { return `[${expr.items.map((item) => this.exprToJson(item)).join(`,`)}]`; } } else if (isArgument(expr)) { if (expr.expr) { return this.exprToJson(expr.expr); } } else if (isCallExpr(expr)) { const integration = findIntegration(expr); if (integration !== undefined) { return this.integrate(integration, expr); } else if (isIdentifier(expr.expr) && expr.expr.name === "Number") { return this.exprToJson(expr.args[0]); } else if (isPropAccessExpr(expr.expr) && expr.expr.name === "params") { if (isIdentifier(expr.expr.expr)) { const ref = expr.expr.expr.lookup(); if ( isParameterDecl(ref) && isFunctionDecl(ref.parent) && ref.parent.parent === undefined && ref.parent.parameters.findIndex((param) => param === ref) === 0 ) { // the first argument of the FunctionDecl is the `$input`, regardless of what it is named if (expr.args.length === 0 || expr.args[0]?.expr === undefined) { const key = this.newLocalVarName(); return `{#foreach(${key} in $input.params().keySet())"${key}": "$input.params("${key}")"#if($foreach.hasNext),#end#end}`; } else if (expr.args.length === 1) { const argName = expr.args[0].expr!; if (isStringLiteralExpr(argName)) { if ( isArgument(expr.parent) && isIdentifier(expr.parent.parent.expr) && expr.parent.parent.expr.name === "Number" ) { // this parameter is surrounded by a cast to Number, so omit the quotes return `$input.params('${argName.value}')`; } return `"$input.params('${argName.value}')"`; } } } } } } else if (isElementAccessExpr(expr)) { const jsonPath = toJsonPath(expr); if (jsonPath) { return `$input.json('${jsonPath}')`; } else { toJsonPath(expr); } } else if (isObjectLiteralExpr(expr)) { if (expr.properties.length === 0) { return "{}"; } return `{${expr.properties .map((prop) => { if (isPropAssignExpr(prop)) { if (isIdentifier(prop.name) || isStringLiteralExpr(prop.name)) { return `"${ isIdentifier(prop.name) ? prop.name.name : prop.name.value }":${this.exprToJson(prop.expr)}`; } } else { const key = context.newLocalVarName(); const map = this.eval(prop.expr); return `#foreach(${key} in ${map}.keySet())"${key}":${this.json( `${map}.get(${key})` )}#if($foreach.hasNext),#end#end`; } return "#stop"; }) .join(`,`)}}`; } else { // this Expr is a computation that cannot be expressed as JSON Path // we must therefore evaluate it and use a brute force approach to convert it into JSON // TODO: this will always throw an error because API Gateway does not have $util.toJson return this.json(this.eval(expr)); } throw new Error(`unsupported expression ${expr.kind}`); /** * Translates an {@link Expr} into JSON Path if this expression references values * on the root `$input.body` object. * * @param expr the {@link Expr} to convert to JSON. * @returns a JSON Path `string` if this {@link Expr} can be evaluated as a JSON Path from the `$input`, otherwise `undefined`. */ function toJsonPath(expr: Expr): string | undefined { if (isInputBody(expr)) { return "$"; } else if (isIdentifier(expr)) { // this is a reference to an intermediate value, cannot be expressed as JSON Path return undefined; } else if (isPropAccessExpr(expr)) { if (expr.name === "data" && isInputBody(expr.expr)) { return "$"; } const exprJsonPath = toJsonPath(expr.expr); if (exprJsonPath !== undefined) { return `${exprJsonPath}.${expr.name}`; } } else if ( isElementAccessExpr(expr) && isNumberLiteralExpr(expr.element) ) { const exprJsonPath = toJsonPath(expr.expr); if (exprJsonPath !== undefined) { return `${exprJsonPath}[${expr.element.value}]`; } } return undefined; } } /** * Renders VTL that will emit a JSON expression for a variable reference within VTL. * * API Gateway does not have a `$util.toJson` helper function, so we render a series of * #if statements that check the class of the value and render the JSON value appropriately. * * We only support primitive types such as `null`, `boolean`, `number` and `string`. This is * because it is not possible to implement recursive functions in VTL and API Gateway has a * constraint of maximum 1000 foreach iterations and a maximum limit in VTL size. * * We could implement a brute-force heuristic that handles n-depth lists and objects, but this * seems particularly fragile with catastrophic consequences for API implementors. So instead, * we encourage developers to use `$input.json(<path>)` wherever possible as we can support * any depth transformations this way. * * @param reference the name of the VTL variable to emit as JSON. * @returns VTL that emits the JSON expression. */ public json(reference: string): string { return `#if(${reference} == $null) null #elseif(${reference}.class.name === 'java.lang.String') \"$util.escapeJavaScript(${reference})\" #elseif(${reference}.class.name === 'java.lang.Integer' || ${reference}.class.name === 'java.lang.Double' || ${reference}.class.name === 'java.lang.Boolean') ${reference} #else #set($context.responseOverride.status = 500) "Internal Server Error - can only primitives to JSON" #stop #end`; } /** * Dereferences an {@link Identifier} to a VTL string that points to the value at runtime. * * @param id the {@link Identifier} expression. * @returns a VTL string that points to the value at runtime. */ public override dereference(id: Identifier): string { const ref = id.lookup(); if (isVariableStmt(ref)) { return `$${id.name}`; } else if (isParameterDecl(ref) && isFunctionDecl(ref.parent)) { const paramIndex = ref.parent.parameters.indexOf(ref); if (paramIndex === 0) { return `$input.path('$')`; } else if (paramIndex === 1) { return "$context"; } else { throw new Error(`unknown argument`); } } if (id.name.startsWith("$")) { return id.name; } else { return `$${id.name}`; } } } // checks if this is a reference to the `$input` argument function isInputBody(expr: Expr): expr is Identifier { if (isIdentifier(expr)) { const ref = expr.lookup(); return ( isParameterDecl(ref) && isFunctionDecl(ref.parent) && ref.parent.parent === undefined ); } return false; } /** * Hooks used to create API Gateway integrations. */ export interface ApiGatewayVtlIntegration { /** * Render the Request Payload as a VTL string. */ renderRequest: (call: CallExpr, context: APIGatewayVTL) => string; /** * Construct an API GW integration. */ createIntegration: ( options: aws_apigateway.IntegrationOptions & { credentialsRole: aws_iam.IRole; } ) => aws_apigateway.Integration; } /** * Configuration properties for a {@link LambdaMethod}. */ export interface LambdaMethodProps extends Omit< aws_apigateway.LambdaIntegrationOptions, | "requestParameters" | "requestTemplates" | "integrationResponses" | "passthroughBehavior" | "proxy" > { /** * The {@link HttpMethod} this integration is for. */ readonly httpMethod: HttpMethod; /** * The REST Resource ({@link aws_apigateway.IResource}) to implement the Method for. */ readonly resource: aws_apigateway.IResource; /** * The {@link Function} to proxy the HTTP request to. * * This Function must accept a {@link APIGatewayProxyEvent} request payload and * return a {@link APIGatewayProxyResult} response payload. */ readonly function: Function<APIGatewayProxyEvent, APIGatewayProxyResult>; } /** * Creates a {@link api_gateway.Method} implemented by a {@link Function}. * * HTTP requests are proxied directly to a {@link Function}. * * @see {@link APIGatewayProxyEvent} * @see {@link APIGatewayProxyResult} */ export class LambdaMethod { /** * The {@link Function} that will process the HTTP request. */ readonly function; /** * The underlying {@link aws_apigateway.Method} configuration. */ readonly method; constructor(private readonly props: LambdaMethodProps) { this.function = props.function; this.method = props.resource.addMethod( props.httpMethod, new aws_apigateway.LambdaIntegration(this.function.resource, { ...this.props, proxy: true, }) ); } } type ExcludeNullOrUndefined<T> = T extends undefined | null | infer X ? X : T; type IfNever<T, Default> = T extends never ? Default : T; type Params<Request extends ApiRequest> = Exclude< IfNever< ExcludeNullOrUndefined<Request["path"]> & ExcludeNullOrUndefined<Request["query"]>, ApiParameters >, undefined >; /** * The `$input` VTL variable containing all of the request data available in API Gateway's VTL engine. * * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#input-variable-reference */ export interface ApiGatewayInput<Request extends ApiRequest> { /** * Parsed form of the {@link body} */ readonly data: Request["body"]; /** * The raw request payload as a string. */ readonly body: string; /** * This function evaluates a JSONPath expression and returns the results as a JSON. * * For example, `$input.json('$.pets')` returns a JSON string representing the pets structure. * * @param jsonPath JSONPath expression to select data from the body. * @see http://goessner.net/articles/JsonPath/ * @see https://github.com/jayway/JsonPath */ json(jsonPath: string): any; /** * Returns the value of a method request parameter from the path, query string, * or header value (searched in that order), given a parameter name string x. * We recommend that you use $util.escapeJavaScript to sanitize the parameter * to avoid a potential injection attack. For full control of parameter * sanitization, use a proxy integration without a template and handle request * sanitization in your integration. * * @param name name of the path. */ params<ParamName extends keyof Params<Request>>( name: ParamName ): Params<Request>[ParamName]; /** * Takes a JSONPath expression string (x) and returns a JSON object representation * of the result. This allows you to access and manipulate elements of the payload * natively in Apache Velocity Template Language (VTL). * * @param jsonPath */ path(jsonPath: string): any; } /** * Type of the `$context` variable available within Velocity Templates in API Gateway. * * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#context-variable-reference */ export interface ApiGatewayContext extends APIGatewayEventRequestContext { /** * The AWS endpoint's request ID. */ readonly awsEndpointRequestId: string; /** * API Gateway error information. */ readonly error: APIGatewayError; /** * The HTTP method used. */ readonly httpMethod: HttpMethod; /** * The response received from AWS WAF: WAF_ALLOW or WAF_BLOCK. Will not be set if the * stage is not associated with a web ACL. For more information, see Using AWS WAF to * protect your APIs. */ readonly wafResponseCode?: "WAF_ALLOW" | "WAF_BLOCK"; /** * The complete ARN of the web ACL that is used to decide whether to allow or block * the request. Will not be set if the stage is not associated with a web ACL. For * more information, see Using AWS WAF to protect your APIs. */ readonly webaclArn?: string; /** * Request properties that can be overridden. * * Overrides are final. An override may only be applied to each parameter once. Trying to override the same parameter multiple times will result in 5XX responses from Amazon API Gateway. If you must override the same parameter multiple times throughout the template, we recommend creating a variable and applying the override at the end of the template. Note that the template is applied only after the entire template is parsed. */ readonly requestOverride: APIGatewayRequestOverride; /** * Response properties that can be overridden. * * Overrides are final. An override may only be applied to each parameter once. Trying to override the same parameter multiple times will result in 5XX responses from Amazon API Gateway. If you must override the same parameter multiple times throughout the template, we recommend creating a variable and applying the override at the end of the template. Note that the template is applied only after the entire template is parsed. */ readonly responseOverride: ApiGatewayResponseOverride; } export interface APIGatewayError { /** * A string containing an API Gateway error message. This variable can only be used * for simple variable substitution in a GatewayResponse body-mapping template, which * is not processed by the Velocity Template Language engine, and in access logging. * For more information, see Monitoring WebSocket API execution with CloudWatch * metrics and Setting up gateway responses to customize error responses. */ readonly message: string; /** * The quoted value of $context.error.message, namely "$context.error.message". */ readonly messageString: string; /** * A type of GatewayResponse. This variable can only be used for simple variable * substitution in a GatewayResponse body-mapping template, which is not processed * by the Velocity Template Language engine, and in access logging. For more * information, see Monitoring WebSocket API execution with CloudWatch metrics and * Setting up gateway responses to customize error responses. */ readonly responseType: string; /** * A string containing a detailed validation error message. */ readonly validationErrorString: string; } export interface APIGatewayRequestOverride { /** * The request header override. If this parameter is defined, it contains the headers * to be used instead of the HTTP Headers that are defined in the Integration Request * pane. */ readonly header: Record<string, string>; /** * The request path override. If this parameter is defined, it contains the request * path to be used instead of the URL Path Parameters that are defined in the * Integration Request pane. */ readonly path: Record<string, string>; /** * The request query string override. If this parameter is defined, it contains the * request query strings to be used instead of the URL Query String Parameters that * are defined in the Integration Request pane. */ readonly querystring: Record<string, string>; } export interface ApiGatewayResponseOverride { /** * The response header override. If this parameter is defined, it contains the header * to be returned instead of the Response header that is defined as the Default mapping * in the Integration Response pane. */ readonly header: Record<string, string>; /** * The response status code override. If this parameter is defined, it contains the * status code to be returned instead of the Method response status that is defined * as the Default mapping in the Integration Response pane. * * @see https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-override-request-response-parameters.html */ status: number; }
the_stack
import { expect } from 'chai' import { constructArnInOtherRegion, isMultiRegionAwsKmsArn, mrkAwareAwsKmsKeyIdCompare, parseAwsKmsKeyArn, parseAwsKmsResource, validAwsKmsIdentifier, isMultiRegionAwsKmsIdentifier, } from '../src/arn_parsing' describe('parseAwsKmsKeyArn', () => { it('parses a valid ARN', async () => { const keyId = 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012' const parsedKeyArn = parseAwsKmsKeyArn(keyId) expect(parsedKeyArn && parsedKeyArn.Partition).to.equal('aws') expect(parsedKeyArn && parsedKeyArn.Region).to.equal('us-east-1') expect(parsedKeyArn && parsedKeyArn.AccountId).to.equal('123456789012') expect(parsedKeyArn && parsedKeyArn.ResourceType).to.equal('key') expect(parsedKeyArn && parsedKeyArn.ResourceId).to.equal( '12345678-1234-1234-1234-123456789012' ) }) it('parses a valid MRK ARN', async () => { const keyId = 'arn:aws:kms:us-east-1:123456789012:key/mrk-12345678123412341234123456789012' const parsedKeyArn = parseAwsKmsKeyArn(keyId) expect(parsedKeyArn && parsedKeyArn.Partition).to.equal('aws') expect(parsedKeyArn && parsedKeyArn.Region).to.equal('us-east-1') expect(parsedKeyArn && parsedKeyArn.AccountId).to.equal('123456789012') expect(parsedKeyArn && parsedKeyArn.ResourceType).to.equal('key') expect(parsedKeyArn && parsedKeyArn.ResourceId).to.equal( 'mrk-12345678123412341234123456789012' ) }) it('parses a valid alias ARN', async () => { const keyId = 'arn:aws:kms:us-east-1:123456789012:alias/example-alias' const parsedKeyArn = parseAwsKmsKeyArn(keyId) expect(parsedKeyArn && parsedKeyArn.Partition).to.equal('aws') expect(parsedKeyArn && parsedKeyArn.Region).to.equal('us-east-1') expect(parsedKeyArn && parsedKeyArn.AccountId).to.equal('123456789012') expect(parsedKeyArn && parsedKeyArn.ResourceType).to.equal('alias') expect(parsedKeyArn && parsedKeyArn.ResourceId).to.equal('example-alias') }) it('Precondition: A KMS Key Id must be a non-null string.', async () => { const bad = {} as any expect(() => parseAwsKmsKeyArn(bad)).to.throw( 'KMS key arn must be a non-null string.' ) expect(() => parseAwsKmsKeyArn('')).to.throw( 'KMS key arn must be a non-null string.' ) }) it('Exceptional Postcondition: Only a valid AWS KMS resource.', () => { expect(() => parseAwsKmsKeyArn('not/an/alias')).to.throw( 'Malformed resource.' ) }) it('Check for early return (Postcondition): A valid ARN has 6 parts.', async () => { expect(parseAwsKmsKeyArn('mrk-12345678123412341234123456789012')).to.equal( false ) }) it('AWS KMS only accepts / as a resource delimiter.', async () => { const keyId = 'alias:example-alias' expect(() => parseAwsKmsKeyArn(keyId)).to.throw('Malformed arn.') }) it('returns false on a valid alias with "/"', async () => { const keyId = 'alias/example-alias' expect(parseAwsKmsKeyArn(keyId)).to.equal(false) }) it('throws an error for an invalid KeyId', async () => { const keyId = 'Not:an/arn' expect(() => parseAwsKmsKeyArn(keyId)).to.throw('Malformed arn.') }) //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 //= type=test //# MUST start with string "arn" it('throws an error for an ARN that does not start with arn', async () => { const keyId = 'arn-not:aws:not-kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012' expect(() => parseAwsKmsKeyArn(keyId)).to.throw('Malformed arn.') }) //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 //= type=test //# The partition MUST be a non-empty it('throws an error for a missing partition ARN', async () => { const keyId = 'arn::kms::123456789012:key/12345678-1234-1234-1234-123456789012' expect(() => parseAwsKmsKeyArn(keyId)).to.throw('Malformed arn.') }) //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 //= type=test //# The service MUST be the string "kms" it('throws an error for an ARN without kms as service', async () => { const keyId = 'arn:aws:not-kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012' expect(() => parseAwsKmsKeyArn(keyId)).to.throw('Malformed arn.') }) //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 //= type=test //# The region MUST be a non-empty string it('throws an error for a missing region ARN', async () => { const keyId = 'arn:aws:kms::123456789012:key/12345678-1234-1234-1234-123456789012' expect(() => parseAwsKmsKeyArn(keyId)).to.throw('Malformed arn.') }) //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 //= type=test //# The account MUST be a non-empty string it('throws an error for a missing account ARN', async () => { const keyId = 'arn:aws:kms:us-east-1::key/12345678-1234-1234-1234-123456789012' expect(() => parseAwsKmsKeyArn(keyId)).to.throw('Malformed arn.') }) //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 //= type=test //# The resource section MUST be non-empty and MUST be split by a //# single "/" any additional "/" are included in the resource id describe('Resource section', () => { it('throws if the resource is missing', async () => { const keyId = 'arn:aws:kms:us-east-1:123456789012:' expect(() => parseAwsKmsKeyArn(keyId)).to.throw('Malformed arn.') }) it('throws if the resource is delimited with ":".', async () => { const keyId = 'arn:aws:kms:us-east-1:123456789012:key:12345678-1234-1234-1234-123456789012' expect(() => parseAwsKmsKeyArn(keyId)).to.throw('Malformed arn.') }) it('an alias can contain slashes', async () => { const keyId = 'arn:aws:kms:us-east-1:123456789012:alias/with/extra/slashes' const { ResourceId } = parseAwsKmsKeyArn(keyId) || {} expect(ResourceId).to.equal('with/extra/slashes') }) //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 //= type=test //# The resource type MUST be either "alias" or "key" it('throws if the resource type is not alias or key', async () => { const keyId = 'arn:aws:kms:us-east-1:123456789012:key-not/12345678-1234-1234-1234-123456789012' expect(() => parseAwsKmsKeyArn(keyId)).to.throw('Malformed arn.') }) //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.5 //= type=test //# The resource id MUST be a non-empty string it('throws if the resource id is missing', async () => { const keyId = 'arn:aws:kms:us-east-1:123456789012:key' expect(() => parseAwsKmsKeyArn(keyId)).to.throw('Malformed arn.') }) }) }) describe('isMultiRegionAwsKmsArn', () => { //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 //= type=test //# This function MUST take a single AWS KMS ARN // //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 //= type=test //# If resource type is "key" and resource ID starts with //# "mrk-", this is a AWS KMS multi-Region key ARN and MUST return true. it('returns true for an MRK ARN', async () => { const key = 'arn:aws:kms:us-west-2:123456789012:key/mrk-12345678123412341234123456789012' expect(isMultiRegionAwsKmsArn(key)).to.equal(true) // @ts-expect-error should be a valid arn expect(isMultiRegionAwsKmsArn(parseAwsKmsKeyArn(key))).to.equal(true) }) //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 //= type=test //# If the input is an invalid AWS KMS ARN this function MUST error. it('invalid arn will throw', () => { expect(() => isMultiRegionAwsKmsArn('Not:an/arn')).to.throw( 'Malformed arn.' ) }) it('Precondition: The kmsIdentifier must be an ARN.', () => { expect(() => isMultiRegionAwsKmsArn('mrk-12345678123412341234123456789012') ).to.throw('AWS KMS identifier is not an ARN') }) //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 //= type=test //# If resource type is "alias", this is an AWS KMS alias ARN and MUST //# return false. it('returns false for an alias ARN with "mrk-"', async () => { const key = 'arn:aws:kms:us-west-2:123456789012:alias/mrk-12345678123412341234123456789012' expect(isMultiRegionAwsKmsArn(key)).to.equal(false) // @ts-expect-error should be a valid arn expect(isMultiRegionAwsKmsArn(parseAwsKmsKeyArn(key))).to.equal(false) }) //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.8 //= type=test //# If resource type is "key" and resource ID does not start with "mrk-", //# this is a (single-region) AWS KMS key ARN and MUST return false. it('returns false for a non-MRK ARN', async () => { const key = 'arn:aws:kms:us-west-2:123456789012:key/12345678-1234-1234-1234-123456789012' expect(isMultiRegionAwsKmsArn(key)).to.equal(false) // @ts-expect-error should be a valid arn expect(isMultiRegionAwsKmsArn(parseAwsKmsKeyArn(key))).to.equal(false) }) }) describe('isMultiRegionAwsKmsIdentifier', () => { //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 //= type=test //# This function MUST take a single AWS KMS identifier it('can identify an ARN', () => { const key = 'arn:aws:kms:us-west-2:123456789012:key/mrk-12345678123412341234123456789012' expect(isMultiRegionAwsKmsIdentifier(key)).to.equal(true) }) //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 //= type=test //# If the input starts with "arn:", this MUST return the output of //# identifying an an AWS KMS multi-Region ARN (aws-kms-key- //# arn.md#identifying-an-an-aws-kms-multi-region-arn) called with this //# input. it('can identify and arn', () => { const key = 'arn:aws:kms:us-west-2:123456789012:key/mrk-12345678123412341234123456789012' expect(isMultiRegionAwsKmsIdentifier(key)).to.equal(true) const arn = 'arn:aws:dynamodb:us-east-2:123456789012:table/myDynamoDBTable' expect(() => isMultiRegionAwsKmsIdentifier(arn)).to.throw('Malformed arn.') }) //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 //= type=test //# If the input starts with "alias/", this an AWS KMS alias and //# not a multi-Region key id and MUST return false. it('is not confused by an alias', () => { const alias = 'alias/mrk-12345678123412341234123456789012' expect(isMultiRegionAwsKmsIdentifier(alias)).to.equal(false) }) //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 //= type=test //# If the input starts //# with "mrk-", this is a multi-Region key id and MUST return true. it('identifed a raw mulit region key resource', () => { const keyId = 'mrk-12345678123412341234123456789012' expect(isMultiRegionAwsKmsIdentifier(keyId)).to.equal(true) }) //= compliance/framework/aws-kms/aws-kms-key-arn.txt#2.9 //= type=test //# If //# the input does not start with any of the above, this is not a multi- //# Region key id and MUST return false. it('is not confused by a single region key', () => { const keyId = 'b3537ef1-d8dc-4780-9f5a-55776cbb2f7f' expect(isMultiRegionAwsKmsIdentifier(keyId)).to.equal(false) }) }) describe('mrkAwareAwsKmsKeyIdCompare', () => { //= compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 //= type=test //# The caller MUST provide: // //= compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 //= type=test //# If both identifiers are identical, this function MUST return "true". it('returns true comparing two identical IDs', async () => { const keyId = 'arn:aws:kms:us-east-1:123456789012:key/mrk-12345678123412341234123456789012' expect(mrkAwareAwsKmsKeyIdCompare(keyId, keyId)).to.equal(true) const keyAlias = 'alias/someAlias' expect(mrkAwareAwsKmsKeyIdCompare(keyAlias, keyAlias)).to.equal(true) }) it('returns true comparing two MRK ARNs that are identical except region', async () => { const usEast1Key = 'arn:aws:kms:us-east-1:123456789012:key/mrk-12345678123412341234123456789012' const usWest2Key = 'arn:aws:kms:us-west-2:123456789012:key/mrk-12345678123412341234123456789012' expect(mrkAwareAwsKmsKeyIdCompare(usEast1Key, usWest2Key)).to.equal(true) }) //= compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 //= type=test //# Otherwise if either input is not identified as a multi-Region key //# (aws-kms-key-arn.md#identifying-an-aws-kms-multi-region-key), then //# this function MUST return "false". it('returns false for different identifiers that are not multi-Region keys.', () => { expect( mrkAwareAwsKmsKeyIdCompare( 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012', 'arn:aws:kms:us-west-1:123456789012:key/12345678-1234-1234-1234-123456789012' ) ).to.equal(false) }) //= compliance/framework/aws-kms/aws-kms-mrk-match-for-decrypt.txt#2.5 //= type=test //# Otherwise if both inputs are //# identified as a multi-Region keys (aws-kms-key-arn.md#identifying-an- //# aws-kms-multi-region-key), this function MUST return the result of //# comparing the "partition", "service", "accountId", "resourceType", //# and "resource" parts of both ARN inputs. it('returns false comparing two MRK ARNs that differ in more than region', async () => { const keyId = 'arn:aws:kms:us-east-1:123456789012:key/mrk-12345678123412341234123456789012' const otherAccountKey = 'arn:aws:kms:us-east-1:000000000000:key/mrk-12345678123412341234123456789012' const otherPartitionKey = 'arn:not-aws:kms:us-east-1:123456789012:key/mrk-12345678123412341234123456789012' const otherResource = 'arn:aws:kms:us-east-1:123456789012:key/mrk-00000000-0000-0000-0000-000000000000' expect(mrkAwareAwsKmsKeyIdCompare(keyId, otherAccountKey)).to.equal(false) expect(mrkAwareAwsKmsKeyIdCompare(keyId, otherPartitionKey)).to.equal(false) expect(mrkAwareAwsKmsKeyIdCompare(keyId, otherResource)).to.equal(false) }) it('returns false comparing an alias with a key ARN', async () => { const keyAlias = 'alias/SomeKeyAlias' const keyId = 'arn:aws:kms:us-east-1:123456789012:key/mrk-12345678123412341234123456789012' const keyAliasArn = 'arn:aws:kms:us-east-1:123456789012:alias/SomeKeyAlias' expect(mrkAwareAwsKmsKeyIdCompare(keyAlias, keyId)).to.equal(false) expect(mrkAwareAwsKmsKeyIdCompare(keyAlias, keyAliasArn)).to.equal(false) }) it('returns false comparing two distinct aliases', async () => { const keyAlias = 'alias/SomeKeyAlias' const otherKeyAlias = 'alias/SomeOtherKeyAlias' expect(mrkAwareAwsKmsKeyIdCompare(keyAlias, otherKeyAlias)).to.equal(false) }) it('throws an error comparing an invalid ID', async () => { const keyId = 'arn:aws:kms:us-east-1:123456789012:key/mrk-12345678123412341234123456789012' const badId = 'Not:an/Arn' expect(() => mrkAwareAwsKmsKeyIdCompare(keyId, badId)).to.throw() }) }) describe('parseAwsKmsResource', () => { it('basic use', () => { const info = parseAwsKmsResource('12345678-1234-1234-1234-123456789012') expect(info.ResourceId).to.equal('12345678-1234-1234-1234-123456789012') expect(info.ResourceType).to.equal('key') }) it('works on an alias', () => { const info = parseAwsKmsResource('alias/my-alias') expect(info.ResourceId).to.equal('my-alias') expect(info.ResourceType).to.equal('alias') }) it('works on an alias', () => { const info = parseAwsKmsResource('alias/my/alias/with/slashes') expect(info.ResourceId).to.equal('my/alias/with/slashes') expect(info.ResourceType).to.equal('alias') }) it('Precondition: An AWS KMS resource can not have a `:`.', () => { const keyId = 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012' expect(() => parseAwsKmsResource(keyId)).to.throw('Malformed resource.') }) it('Precondition: A raw identifer is only an alias or a key.', () => { expect(() => parseAwsKmsResource('anything/with a slash')).to.throw( 'Malformed resource.' ) }) }) describe('validAwsKmsIdentifier', () => { it('is able to parse valid identifiers', () => { expect( !!validAwsKmsIdentifier( 'arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012' ) ).to.equal(true) expect( !!validAwsKmsIdentifier( 'arn:aws:kms:us-west-2:658956600833:key/mrk-80bd8ecdcd4342aebd84b7dc9da498a7' ) ).to.equal(true) expect( !!validAwsKmsIdentifier( 'arn:aws:kms:us-east-1:123456789012:alias/example-alias' ) ).to.equal(true) expect(!!validAwsKmsIdentifier('alias/my/alias/with/slashes')).to.equal( true ) expect( !!validAwsKmsIdentifier('12345678-1234-1234-1234-123456789012') ).to.equal(true) expect( !!validAwsKmsIdentifier('mrk-80bd8ecdcd4342aebd84b7dc9da498a7') ).to.equal(true) }) it('throws for invalid identifiers', () => { expect(() => validAwsKmsIdentifier('Not:an/arn')).to.throw('Malformed arn') expect(() => validAwsKmsIdentifier('alias:no')).to.throw('Malformed arn') expect(() => validAwsKmsIdentifier( 'arn:aws:dynamodb:us-east-2:123456789012:table/myDynamoDBTable' ) ).to.throw('Malformed arn') expect(() => validAwsKmsIdentifier('')).to.throw( 'KMS key arn must be a non-null string.' ) }) }) describe('constructArnInOtherRegion', () => { it('returns new ARN with region replaced', async () => { const parsedArn = { Partition: 'aws', Region: 'us-west-2', AccountId: '123456789012', ResourceType: 'key', ResourceId: 'mrk-12345678123412341234123456789012', } const region = 'us-east-1' const expectedArn = 'arn:aws:kms:us-east-1:123456789012:key/mrk-12345678123412341234123456789012' expect(constructArnInOtherRegion(parsedArn, region)).to.equal(expectedArn) }) it('Precondition: Only reconstruct a multi region ARN.', async () => { const parsedArn = { Partition: 'aws', Region: 'us-west-2', AccountId: '123456789012', ResourceType: 'key', ResourceId: '12345678-1234-1234-1234-123456789012', } const region = 'us-east-1' expect(() => constructArnInOtherRegion(parsedArn, region)).to.throw( 'Cannot attempt to construct an ARN in a new region from an non-MRK ARN.' ) }) })
the_stack
import { Injectable } from '@angular/core'; import { Observable, BehaviorSubject } from 'rxjs'; import { NotificationService } from '../../../notification/notification.service'; import { Status } from '../../../common/status'; import { ApiError, ApiErrorType } from '../../../error/api-error'; import { HttpClient } from '../../../common/http-client'; import { UrlRewrite, InboundSection, InboundRule, OutboundSection, OutboundRule, AllowedServerVariablesSection, RewriteMapsSection, RewriteMap, Provider, ProvidersSection } from '../url-rewrite'; import { GlobalService } from './global.service'; import { InboundService } from './inbound.service'; import { ActivatedRoute } from '@angular/router'; import { IsWebServerScope } from 'runtime/runtime'; @Injectable() export class UrlRewriteService { public error: ApiError; public outboundError: ApiError; public rewriteMapsError: ApiError; public providersError: ApiError; public serverVariablesError: ApiError; private static URL = "/webserver/url-rewrite/"; private _webserverScope: boolean; private _status: Status = Status.Unknown; private _urlRewrite: BehaviorSubject<UrlRewrite> = new BehaviorSubject<UrlRewrite>(null); private _outboundSettings: BehaviorSubject<OutboundSection> = new BehaviorSubject<OutboundSection>(null); private _outboundRules: BehaviorSubject<Array<OutboundRule>> = new BehaviorSubject<Array<OutboundRule>>([]); private _rewriteMapSettings: BehaviorSubject<RewriteMapsSection> = new BehaviorSubject<RewriteMapsSection>(null); private _rewriteMaps: BehaviorSubject<Array<RewriteMap>> = new BehaviorSubject<Array<RewriteMap>>([]); private _providersSettings: BehaviorSubject<ProvidersSection> = new BehaviorSubject<ProvidersSection>(null); private _providers: BehaviorSubject<Array<Provider>> = new BehaviorSubject<Array<Provider>>([]); private _serverVariablesSettings: BehaviorSubject<AllowedServerVariablesSection> = new BehaviorSubject<AllowedServerVariablesSection>(null); private _inboundService: InboundService; private _globalService: GlobalService; constructor( private _route: ActivatedRoute, private _http: HttpClient, private _notificationService: NotificationService, ){ this._webserverScope = IsWebServerScope(this._route); this._inboundService = new InboundService(this._http, this._notificationService); this._globalService = new GlobalService(this._http, this._notificationService); } public get inboundError(): ApiError { return this.inboundService.error; } public get globalError(): ApiError { return this.globalService.error; } public get status(): Status { return this._status; } public get webserverScope(): boolean { return this._webserverScope; } public get urlRewrite(): Observable<UrlRewrite> { return this._urlRewrite.asObservable(); } public get inboundSettings(): Observable<InboundSection> { return this.webserverScope ? this.globalService.settings : this._inboundService.settings; } public get inboundRules(): Observable<Array<InboundRule>> { return this.webserverScope ? this.globalService.rules : this._inboundService.rules; } public get outboundSettings(): Observable<OutboundSection> { return this._outboundSettings.asObservable(); } public get outboundRules(): Observable<Array<OutboundRule>> { return this._outboundRules.asObservable(); } public get rewriteMapSettings(): Observable<RewriteMapsSection> { return this._rewriteMapSettings.asObservable(); } public get rewriteMaps(): Observable<Array<RewriteMap>> { return this._rewriteMaps.asObservable(); } public get providersSettings(): Observable<ProvidersSection> { return this._providersSettings.asObservable(); } public get providers(): Observable<Array<Provider>> { return this._providers.asObservable(); } public get serverVariablesSettings(): Observable<AllowedServerVariablesSection> { return this._serverVariablesSettings.asObservable(); } public get inboundService(): InboundService { return this._inboundService; } public get globalService(): GlobalService { return this._globalService; } public revertInbound(): void { this.webserverScope ? this.globalService.revert() : this._inboundService.revert(); } public revertOutbound(): void { this._http.delete(this._outboundSettings.getValue()._links.self.href.replace("/api", "")) .then(_ => { this.loadOutboundSettings().then(set => this.loadOutboundRules()); }); } public revertServerVariables(): void { this._http.delete(this._serverVariablesSettings.getValue()._links.self.href.replace("/api", "")) .then(_ => { this.loadServerVariableSettings(); }); } public revertRewriteMaps(): void { this._http.delete(this._rewriteMapSettings.getValue()._links.self.href.replace("/api", "")) .then(_ => { this.loadRewriteMapSection().then(set => this.loadRewriteMaps()); }); } public revertProviders(): void { this._http.delete(this._providersSettings.getValue()._links.self.href.replace("/api", "")) .then(_ => { this.loadProvidersSettings().then(set => this.loadProviders()); }); } public install(): Promise<any> { this._status = Status.Starting; return this._http.post(UrlRewriteService.URL, "") .then((feature: UrlRewrite) => { this._status = Status.Started; this.initialize(feature.id); }) .catch(e => { this.error = e; throw e; }); } public uninstall(): Promise<any> { this._status = Status.Stopping; let id = this._urlRewrite.getValue().id; this._urlRewrite.next(null); return this._http.delete(UrlRewriteService.URL + id) .then(() => { this._status = Status.Stopped; }) .catch(e => { this.error = e; throw e; }); } public initialize(id: string) { this.load(id).then(feature => { // // Inbound rules if (!feature.scope) { // // Global rules exposed at webserver this.globalService.initialize(feature); } else { this.inboundService.initialize(feature); } // // Outbound rules this.loadOutboundSettings().then(set => this.loadOutboundRules()); // // Rewrite Maps this.loadRewriteMapSection().then(set => this.loadRewriteMaps()); // // Providers this.loadProvidersSettings().then(set => this.loadProviders()); // // Allowed server variables this.loadServerVariableSettings(); }); } private load(id: string): Promise<UrlRewrite> { return this._http.get(UrlRewriteService.URL + id) .then(feature => { this._status = Status.Started; this._urlRewrite.next(feature); return feature; }) .catch(e => { this.error = e; if (e.type && e.type == ApiErrorType.FeatureNotInstalled) { this._status = Status.Stopped; return; } throw e; }); } // // Inbound public saveInbound(settings: InboundSection): Promise<InboundSection> { return this.webserverScope ? this.globalService.saveSettings(settings) : this.inboundService.saveSettings(settings); } public addInboundRule(rule: InboundRule): Promise<InboundRule> { return this.webserverScope ? this.globalService.addRule(rule) : this.inboundService.addRule(rule); } public saveInboundRule(rule: InboundRule): Promise<InboundRule> { return this.webserverScope ? this.globalService.saveRule(rule) : this.inboundService.saveRule(rule); } public deleteInboundRule(rule: InboundRule): void { this.webserverScope ? this.globalService.deleteRule(rule) : this.inboundService.deleteRule(rule); } public copyInboundRule(rule: InboundRule): Promise<InboundRule> { return this.webserverScope ? this.globalService.copyRule(rule) : this.inboundService.copyRule(rule); } public moveInboundUp(rule: InboundRule) { this.webserverScope ? this.globalService.moveUp(rule) : this.inboundService.moveUp(rule); } public moveInboundDown(rule: InboundRule) { this.webserverScope ? this.globalService.moveDown(rule) : this.inboundService.moveDown(rule); } // // Outbound private loadOutboundSettings(): Promise<OutboundSection> { let feature = this._urlRewrite.getValue(); let outboundLink: string = feature._links.outbound.href; return this._http.get(outboundLink.replace('/api', '')) .then((settings: OutboundSection) => { this._outboundSettings.next(settings); return settings; }) .catch(e => { this.outboundError = e; throw e; }); } private loadOutboundRules(): Promise<Array<OutboundRule>> { let settings = this._outboundSettings.getValue(); let rulesLink: string = settings._links.rules.href; return this._http.get(rulesLink.replace('/api', '') + "&fields=*") .then(rulesObj => { let rules = rulesObj.rules; this._outboundRules.next(rules); return rules; }); } public saveOutbound(settings: OutboundSection): Promise<OutboundSection> { return this._http.patch(settings._links.self.href.replace('/api', ''), JSON.stringify(settings)) .then((s: OutboundSection) => { Object.assign(settings, s); this.loadOutboundRules(); return settings; }); } public addOutboundRule(rule: OutboundRule): Promise<OutboundRule> { let settings = this._outboundSettings.getValue(); let rulesLink: string = settings._links.rules.href; rule.url_rewrite = this._urlRewrite.getValue(); return this._http.post(rulesLink.replace('/api', ''), JSON.stringify(rule)) .then((newRule: OutboundRule) => { let rules = this._outboundRules.getValue(); rules.push(newRule); this._outboundRules.next(rules); return newRule; }); } public saveOutboundRule(rule: OutboundRule): Promise<OutboundRule> { return this._http.patch(rule._links.self.href.replace('/api', ''), JSON.stringify(rule)) .then((r: OutboundRule) => { Object.assign(rule, r); return rule; }); } public deleteOutboundRule(rule: OutboundRule): void { this._http.delete(rule._links.self.href.replace('/api', '')) .then(() => { let rules = this._outboundRules.getValue(); rules = rules.filter(r => r.id != rule.id); this._outboundRules.next(rules); }); } public copyOutboundRule(rule: OutboundRule): Promise<OutboundRule> { let copy: OutboundRule = JSON.parse(JSON.stringify(rule)); let i = 2; copy.name = rule.name + " - Copy"; copy.priority = null; while (this._outboundRules.getValue().find(r => r.name.toLocaleLowerCase() == copy.name.toLocaleLowerCase()) != null) { copy.name = rule.name + " - Copy (" + (i++) + ")"; } return this.addOutboundRule(copy); } public moveOutboundUp(rule: OutboundRule) { if (rule.priority == 0) { return; } let oldPriority = rule.priority; rule.priority = oldPriority - 1; this.saveOutboundRule(rule).then(r => { let rules = this._outboundRules.getValue(); // // Move the rule in the client view of rules list rules.splice(oldPriority, 1); // // Update the index of the rule which got pushed down rules[rule.priority].priority++; rules.splice(rule.priority, 0, rule); this._outboundRules.next(rules); }); } public moveOutboundDown(rule: OutboundRule) { let oldPriority = rule.priority; if (oldPriority + 1 == this._outboundRules.getValue().length) { return; } rule.priority = oldPriority + 1; this.saveOutboundRule(rule).then(r => { let rules = this._outboundRules.getValue(); rules.splice(oldPriority, 1); rules[oldPriority].priority--; rules.splice(rule.priority, 0, rule); this._outboundRules.next(rules); }); } // // Rewrite Maps private loadRewriteMapSection(): Promise<RewriteMapsSection> { let feature = this._urlRewrite.getValue(); let rewriteMapLink: string = feature._links.rewrite_maps.href; return this._http.get(rewriteMapLink.replace('/api', '')) .then(settings => { this._rewriteMapSettings.next(settings); return settings; }) .catch(e => { this.rewriteMapsError = e; throw e; }); } private loadRewriteMaps(): Promise<Array<RewriteMap>> { let settings = this._rewriteMapSettings.getValue(); let mapsLink: string = settings._links.entries.href; return this._http.get(mapsLink.replace('/api', '') + "&fields=*") .then(mapsObj => { let entries = mapsObj.entries; this._rewriteMaps.next(entries); return entries; }); } public saveRewriteMapSettings(settings: RewriteMapsSection): Promise<RewriteMapsSection> { return this._http.patch(settings._links.self.href.replace('/api', ''), JSON.stringify(settings)) .then((s: RewriteMapsSection) => { Object.assign(settings, s); this.loadRewriteMaps(); return settings; }); } public addRewriteMap(map: RewriteMap): Promise<RewriteMap> { let settings = this._rewriteMapSettings.getValue(); let mapsLink: string = settings._links.entries.href; map.url_rewrite = this._urlRewrite.getValue(); return this._http.post(mapsLink.replace('/api', ''), JSON.stringify(map)) .then((newRule: RewriteMap) => { let maps = this._rewriteMaps.getValue(); maps.push(newRule); this._rewriteMaps.next(maps); return newRule; }); } public saveRewriteMap(map: RewriteMap): Promise<RewriteMap> { return this._http.patch(map._links.self.href.replace('/api', ''), JSON.stringify(map)) .then((r: RewriteMap) => { Object.assign(map, r); return map; }); } public deleteRewriteMap(map: RewriteMap): void { this._http.delete(map._links.self.href.replace('/api', '')) .then(() => { let maps = this._rewriteMaps.getValue(); maps = maps.filter(r => r.id != map.id); this._rewriteMaps.next(maps); }); } public copyRewriteMap(map: RewriteMap): Promise<RewriteMap> { let copy: RewriteMap = JSON.parse(JSON.stringify(map)); let i = 2; copy.name = map.name + " - Copy"; while (this._rewriteMaps.getValue().find(r => r.name.toLocaleLowerCase() == copy.name.toLocaleLowerCase()) != null) { copy.name = map.name + " - Copy (" + (i++) + ")"; } return this.addRewriteMap(copy); } // // Providers private loadProvidersSettings(): Promise<ProvidersSection> { let feature = this._urlRewrite.getValue(); let providersLink: string = feature._links.providers.href; return this._http.get(providersLink.replace('/api', '')) .then(settings => { this._providersSettings.next(settings); return settings; }) .catch(e => { this.providersError = e; throw e; }); } private loadProviders(): Promise<Array<Provider>> { let settings = this._providersSettings.getValue(); let providersLink: string = settings._links.entries.href; return this._http.get(providersLink.replace('/api', '') + "&fields=*") .then(providersObj => { let providers = providersObj.entries; this._providers.next(providers); return providers; }); } public saveProviders(settings: ProvidersSection): Promise<ProvidersSection> { return this._http.patch(settings._links.self.href.replace('/api', ''), JSON.stringify(settings)) .then((s: ProvidersSection) => { Object.assign(settings, s); this.loadProviders(); return settings; }); } public addProvider(provider: Provider): Promise<Provider> { let settings = this._providersSettings.getValue(); let providersLink: string = settings._links.entries.href; provider.url_rewrite = this._urlRewrite.getValue(); return this._http.post(providersLink.replace('/api', ''), JSON.stringify(provider)) .then((newProvider: Provider) => { let providers = this._providers.getValue(); providers.push(newProvider); this._providers.next(providers); return newProvider; }); } public saveProvider(provider: Provider): Promise<Provider> { return this._http.patch(provider._links.self.href.replace('/api', ''), JSON.stringify(provider)) .then((r: Provider) => { Object.assign(provider, r); return provider; }); } public deleteProvider(provider: Provider): void { this._http.delete(provider._links.self.href.replace('/api', '')) .then(() => { let providers = this._providers.getValue(); providers = providers.filter(r => r.id != provider.id); this._providers.next(providers); }); } public copyProvider(provider: Provider): Promise<Provider> { let copy: Provider = JSON.parse(JSON.stringify(provider)); let i = 2; copy.name = provider.name + " - Copy"; while (this._providers.getValue().find(r => r.name.toLocaleLowerCase() == copy.name.toLocaleLowerCase()) != null) { copy.name = provider.name + " - Copy (" + (i++) + ")"; } return this.addProvider(copy); } // // Server Variables private loadServerVariableSettings(): Promise<AllowedServerVariablesSection> { let feature = this._urlRewrite.getValue(); let serverVariablesLink: string = feature._links.allowed_server_variables.href; return this._http.get(serverVariablesLink.replace('/api', '')) .then(settings => { this._serverVariablesSettings.next(settings); return settings; }) .catch(e => { this.serverVariablesError = e; throw e; }); } public saveServerVariables(settings: AllowedServerVariablesSection): Promise<AllowedServerVariablesSection> { return this._http.patch(settings._links.self.href.replace('/api', ''), JSON.stringify(settings)) .then((s: AllowedServerVariablesSection) => { Object.assign(settings, s); return settings; }); } }
the_stack
import { write } from './domUtils'; /** * XML HTTP request wrapper. See also: {@link mxUtils.get}, {@link mxUtils.post} and * {@link mxUtils.load}. This class provides a cross-browser abstraction for Ajax * requests. * * ### Encoding: * * For encoding parameter values, the built-in encodeURIComponent JavaScript * method must be used. For automatic encoding of post data in {@link Editor} the * {@link Editor.escapePostData} switch can be set to true (default). The encoding * will be carried out using the conte type of the page. That is, the page * containting the editor should contain a meta tag in the header, eg. * <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> * * @example * ```JavaScript * var onload = function(req) * { * mxUtils.alert(req.getDocumentElement()); * } * * var onerror = function(req) * { * mxUtils.alert('Error'); * } * new MaxXmlRequest(url, 'key=value').send(onload, onerror); * ``` * * Sends an asynchronous POST request to the specified URL. * * @example * ```JavaScript * var req = new MaxXmlRequest(url, 'key=value', 'POST', false); * req.send(); * mxUtils.alert(req.getDocumentElement()); * ``` * * Sends a synchronous POST request to the specified URL. * * @example * ```JavaScript * var encoder = new Codec(); * var result = encoder.encode(graph.getDataModel()); * var xml = encodeURIComponent(mxUtils.getXml(result)); * new MaxXmlRequest(url, 'xml='+xml).send(); * ``` * * Sends an encoded graph model to the specified URL using xml as the * parameter name. The parameter can then be retrieved in C# as follows: * * ```javascript * string xml = HttpUtility.UrlDecode(context.Request.Params["xml"]); * ``` * * Or in Java as follows: * * ```javascript * String xml = URLDecoder.decode(request.getParameter("xml"), "UTF-8").replace(" ", "&#xa;"); * ``` * * Note that the linefeeds should only be replaced if the XML is * processed in Java, for example when creating an image. */ class MaxXmlRequest { constructor( url: string, params: string | null=null, method: 'GET' | 'POST'='POST', async: boolean=true, username: string | null=null, password: string | null=null ) { this.url = url; this.params = params; this.method = method || 'POST'; this.async = async; this.username = username; this.password = password; } /** * Holds the target URL of the request. */ url: string; /** * Holds the form encoded data for the POST request. */ params: string | null; /** * Specifies the request method. Possible values are POST and GET. Default * is POST. */ method: 'GET' | 'POST'; /** * Boolean indicating if the request is asynchronous. */ async: boolean; /** * Boolean indicating if the request is binary. This option is ignored in IE. * In all other browsers the requested mime type is set to * text/plain; charset=x-user-defined. Default is false. * * @default false */ binary: boolean = false; /** * Specifies if withCredentials should be used in HTML5-compliant browsers. Default is false. * * @default false */ withCredentials: boolean = false; /** * Specifies the username to be used for authentication. */ username: string | null; /** * Specifies the password to be used for authentication. */ password: string | null; /** * Holds the inner, browser-specific request object. */ request: any = null; /** * Specifies if request values should be decoded as URIs before setting the * textarea value in {@link simulate}. Defaults to false for backwards compatibility, * to avoid another decode on the server this should be set to true. */ decodeSimulateValues: boolean = false; /** * Returns {@link binary}. */ isBinary(): boolean { return this.binary; } /** * Sets {@link binary}. * * @param value */ setBinary(value: boolean): void { this.binary = value; } /** * Returns the response as a string. */ getText(): string { return this.request.responseText; } /** * Returns true if the response is ready. */ isReady(): boolean { return this.request.readyState === 4; } /** * Returns the document element of the response XML document. */ getDocumentElement(): HTMLElement | null { const doc = this.getXml(); if (doc != null) { return doc.documentElement; } return null; } /** * Returns the response as an XML document. Use {@link getDocumentElement} to get * the document element of the XML document. */ getXml(): XMLDocument { let xml = this.request.responseXML; // Handles missing response headers in IE, the first condition handles // the case where responseXML is there, but using its nodes leads to // type errors in the CellCodec when putting the nodes into a new // document. This happens in IE9 standards mode and with XML user // objects only, as they are used directly as values in cells. if (xml == null || xml.documentElement == null) { xml = new DOMParser().parseFromString(this.request.responseText, 'text/xml'); } return xml; } /** * Returns the status as a number, eg. 404 for "Not found" or 200 for "OK". * Note: The NS_ERROR_NOT_AVAILABLE for invalid responses cannot be cought. */ getStatus(): number { return this.request != null ? this.request.status : null; } /** * Creates and returns the inner {@link request} object. */ create(): any { const req = new XMLHttpRequest(); // TODO: Check for overrideMimeType required here? if (this.isBinary() && req.overrideMimeType) { req.overrideMimeType('text/plain; charset=x-user-defined'); } return req; } /** * Send the <request> to the target URL using the specified functions to * process the response asychronously. * * Note: Due to technical limitations, onerror is currently ignored. * * @param onload Function to be invoked if a successful response was received. * @param onerror Function to be called on any error. Unused in this implementation, intended for overriden function. * @param timeout Optional timeout in ms before calling ontimeout. * @param ontimeout Optional function to execute on timeout. */ send( onload: Function | null=null, onerror: Function | null=null, timeout: number | null=null, ontimeout: Function | null=null ): void { this.request = this.create(); if (this.request != null) { if (onload != null) { this.request.onreadystatechange = () => { if (this.isReady()) { onload(this); this.request.onreadystatechange = null; } }; } this.request.open( this.method, this.url, this.async, this.username, this.password ); this.setRequestHeaders(this.request, this.params); if (window.XMLHttpRequest && this.withCredentials) { this.request.withCredentials = 'true'; } if ( window.XMLHttpRequest && timeout != null && ontimeout != null ) { this.request.timeout = timeout; this.request.ontimeout = ontimeout; } this.request.send(this.params); } } /** * Sets the headers for the given request and parameters. This sets the * content-type to application/x-www-form-urlencoded if any params exist. * * @example * ```JavaScript * request.setRequestHeaders = function(request, params) * { * if (params != null) * { * request.setRequestHeader('Content-Type', * 'multipart/form-data'); * request.setRequestHeader('Content-Length', * params.length); * } * }; * ``` * * Use the code above before calling {@link send} if you require a * multipart/form-data request. * * @param request * @param params */ setRequestHeaders(request: any, params: any): void { if (params != null) { request.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' ); } } /** * Creates and posts a request to the given target URL using a dynamically * created form inside the given document. * * @param doc Document that contains the form element. * @param target Target to send the form result to. */ simulate(doc: any, target: string | null=null): void { doc = doc || document; let old = null; if (doc === document) { old = window.onbeforeunload; window.onbeforeunload = null; } const form = doc.createElement('form'); form.setAttribute('method', this.method); form.setAttribute('action', this.url); if (target != null) { form.setAttribute('target', target); } form.style.display = 'none'; form.style.visibility = 'hidden'; const params = <string>this.params; const pars = params.indexOf('&') > 0 ? params.split('&') : params.split(' '); // Adds the parameters as textareas to the form for (let i = 0; i < pars.length; i += 1) { const pos = pars[i].indexOf('='); if (pos > 0) { const name = pars[i].substring(0, pos); let value = pars[i].substring(pos + 1); if (this.decodeSimulateValues) { value = decodeURIComponent(value); } const textarea = doc.createElement('textarea'); textarea.setAttribute('wrap', 'off'); textarea.setAttribute('name', name); write(textarea, value); form.appendChild(textarea); } } doc.body.appendChild(form); form.submit(); if (form.parentNode != null) { form.parentNode.removeChild(form); } if (old != null) { window.onbeforeunload = old; } } } /** * Loads the specified URL *synchronously* and returns the <MaxXmlRequest>. * Throws an exception if the file cannot be loaded. See {@link Utils#get} for * an asynchronous implementation. * * Example: * * ```javascript * try * { * let req = mxUtils.load(filename); * let root = req.getDocumentElement(); * // Process XML DOM... * } * catch (ex) * { * mxUtils.alert('Cannot load '+filename+': '+ex); * } * ``` * * @param url URL to get the data from. */ export const load = (url: string) => { const req = new MaxXmlRequest(url, null, 'GET', false); req.send(); return req; } /** * Loads the specified URL *asynchronously* and invokes the given functions * depending on the request status. Returns the <MaxXmlRequest> in use. Both * functions take the <MaxXmlRequest> as the only parameter. See * {@link Utils#load} for a synchronous implementation. * * Example: * * ```javascript * mxUtils.get(url, (req)=> * { * let node = req.getDocumentElement(); * // Process XML DOM... * }); * ``` * * So for example, to load a diagram into an existing graph model, the * following code is used. * * ```javascript * mxUtils.get(url, (req)=> * { * let node = req.getDocumentElement(); * let dec = new Codec(node.ownerDocument); * dec.decode(node, graph.getDataModel()); * }); * ``` * * @param url URL to get the data from. * @param onload Optional function to execute for a successful response. * @param onerror Optional function to execute on error. * @param binary Optional boolean parameter that specifies if the request is * binary. * @param timeout Optional timeout in ms before calling ontimeout. * @param ontimeout Optional function to execute on timeout. * @param headers Optional with headers, eg. {'Authorization': 'token xyz'} */ export const get = ( url: string, onload: Function | null=null, onerror: Function | null=null, binary: boolean=false, timeout: number | null=null, ontimeout: Function | null=null, headers: { [key: string]: string } | null=null ) => { const req = new MaxXmlRequest(url, null, 'GET'); const { setRequestHeaders } = req; if (headers) { req.setRequestHeaders = (request, params) => { setRequestHeaders.apply(this, [request, params]); for (const key in headers) { request.setRequestHeader(key, headers[key]); } }; } if (binary != null) { req.setBinary(binary); } req.send(onload, onerror, timeout, ontimeout); return req; } /** * Loads the URLs in the given array *asynchronously* and invokes the given function * if all requests returned with a valid 2xx status. The error handler is invoked * once on the first error or invalid response. * * @param urls Array of URLs to be loaded. * @param onload Callback with array of {@link XmlRequests}. * @param onerror Optional function to execute on error. */ export const getAll = ( urls: string[], onload: (arg0: any) => void, onerror: () => void ) => { let remain = urls.length; const result: MaxXmlRequest[] = []; let errors = 0; const err = () => { if (errors == 0 && onerror != null) { onerror(); } errors++; }; for (let i = 0; i < urls.length; i += 1) { ((url, index) => { get( url, (req: MaxXmlRequest) => { const status = req.getStatus(); if (status < 200 || status > 299) { err(); } else { result[index] = req; remain--; if (remain == 0) { onload(result); } } }, err ); })(urls[i], i); } if (remain == 0) { onload(result); } } /** * Posts the specified params to the given URL *asynchronously* and invokes * the given functions depending on the request status. Returns the * <MaxXmlRequest> in use. Both functions take the <MaxXmlRequest> as the * only parameter. Make sure to use encodeURIComponent for the parameter * values. * * Example: * * ```javascript * mxUtils.post(url, 'key=value', (req)=> * { * mxUtils.alert('Ready: '+req.isReady()+' Status: '+req.getStatus()); * // Process req.getDocumentElement() using DOM API if OK... * }); * ``` * * @param url URL to get the data from. * @param params Parameters for the post request. * @param onload Optional function to execute for a successful response. * @param onerror Optional function to execute on error. */ export const post = ( url: string, params: string | null=null, onload: Function, onerror: Function | null=null ) => { return new MaxXmlRequest(url, params).send(onload, onerror); } /** * Submits the given parameters to the specified URL using * <MaxXmlRequest.simulate> and returns the <MaxXmlRequest>. * Make sure to use encodeURIComponent for the parameter * values. * * @param url URL to get the data from. * @param params Parameters for the form. * @param doc Document to create the form in. * @param target Target to send the form result to. */ export const submit = (url: string, params: string, doc: XMLDocument, target: string) => { return new MaxXmlRequest(url, params).simulate(doc, target); }; export default MaxXmlRequest;
the_stack
import { Provider } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick, } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { MatButtonModule } from '@angular/material/button'; import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatDialog, MatDialogModule } from '@angular/material/dialog'; import { MatExpansionModule } from '@angular/material/expansion'; import { MatFormFieldModule } from '@angular/material/form-field'; import { MatIconModule } from '@angular/material/icon'; import { MatInputModule } from '@angular/material/input'; import { MatTooltipModule } from '@angular/material/tooltip'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { Router } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { ReplaySubject, Subject } from 'rxjs'; import { ScoredItem, SocialMediaItem } from '../../common-types'; import { routes } from '../app-routing.module'; import { AuthGuardService } from '../auth-guard.service'; import { CommentInfoComponent } from '../comment-info/comment-info.component'; import { CommentLinkComponent } from '../comment-link/comment-link.component'; import { DialogRefStub } from '../common/test_utils'; import { OauthApiService } from '../oauth_api.service'; import { ReportService } from '../report.service'; import { TweetImageComponent } from '../tweet-image/tweet-image.component'; import { ReviewReportComponent } from './review-report.component'; describe('ReviewReportComponent', () => { let router: Router; let component: ReviewReportComponent; let fixture: ComponentFixture<ReviewReportComponent>; const commentsForReportTestSubject = new ReplaySubject< Array<ScoredItem<SocialMediaItem>> >(1); const reportContextChangedSubject = new Subject<string>(); const reportReasonsChangedSubject = new Subject<string[]>(); let mockAuthGuardService: jasmine.SpyObj<AuthGuardService>; let mockReportService: jasmine.SpyObj<ReportService>; const twitterSignInTestSubject = new ReplaySubject<boolean>(1); const mockOauthApiService = { twitterSignInChange: twitterSignInTestSubject.asObservable(), }; mockAuthGuardService = jasmine.createSpyObj<AuthGuardService>( 'authGuardService', ['canActivate'] ); mockAuthGuardService.canActivate.and.returnValue(true); const comments = [ { item: { id_str: 'a', text: 'your mother was a hamster', date: new Date(), authorScreenName: 'user1', authorName: 'User 1', }, scores: { TOXICITY: 0.8, INSULT: 0.8, }, }, { item: { id_str: 'b', text: 'and your father smelt of elderberries', date: new Date(), authorScreenName: 'user2', authorName: 'User 2', }, scores: { TOXICITY: 0.88, INSULT: 0.5, }, }, { item: { id_str: 'c', text: 'Now go away or I will taunt you a second time!', date: new Date(), authorScreenName: 'user1', authorName: 'User 1', }, scores: { TOXICITY: 0.9, INSULT: 0.3, PROFANITY: 0.1, }, }, ]; function createComponent(providers: Provider[] = []) { TestBed.configureTestingModule({ declarations: [ CommentInfoComponent, CommentLinkComponent, ReviewReportComponent, TweetImageComponent, ], imports: [ FormsModule, MatButtonModule, MatCheckboxModule, MatDialogModule, MatExpansionModule, MatIconModule, MatInputModule, MatFormFieldModule, MatTooltipModule, NoopAnimationsModule, RouterTestingModule.withRoutes(routes), ], providers: [ { provide: AuthGuardService, useValue: mockAuthGuardService, }, { provide: ReportService, useValue: mockReportService, }, { provide: OauthApiService, useValue: mockOauthApiService, }, ...providers, ], }).compileComponents(); fixture = TestBed.createComponent(ReviewReportComponent); component = fixture.componentInstance; fixture.detectChanges(); commentsForReportTestSubject.next(comments); router = TestBed.inject(Router); } beforeEach(() => { mockReportService = jasmine.createSpyObj<ReportService>( 'reportService', ['setContext', 'setReportReasons', 'clearReport'], { reportCommentsChanged: commentsForReportTestSubject, reportContextChanged: reportContextChangedSubject, reportReasonsChanged: reportReasonsChangedSubject, } ); }); it('should create', () => { createComponent(); expect(component).toBeTruthy(); }); it('should save context and report reasons on updates (Twitter version)', fakeAsync(() => { createComponent(); // The fixture needs to be updated after setting the platform to twitter // so that the other functions can access the filled in reportReasons array. twitterSignInTestSubject.next(true); fixture.detectChanges(); // Note that we have to click on the label of the checkbox to trigger the // change event in tests; see https://stackoverflow.com/a/44935499 const reportReasonsCheckboxes = fixture.debugElement.queryAll( By.css('.report-reasons-checkbox label') ); reportReasonsCheckboxes[0].nativeElement.click(); reportReasonsCheckboxes[2].nativeElement.click(); const contextTextarea = fixture.debugElement.query(By.css('.context')) .nativeElement; contextTextarea.value = 'Here is some context'; contextTextarea.dispatchEvent(new Event('input')); // Wait for 500 ms to pass so that the input event is handled. tick(500); fixture.detectChanges(); expect(component.hasReportReasons).toEqual([ true, false, true, false, false, ]); expect(component.context).toEqual('Here is some context'); // Check that the report setContext and setReportReasons was called. expect(mockReportService.setReportReasons).toHaveBeenCalledWith([ 'Harassment', 'Exposed private information or photo', ]); expect(mockReportService.setContext).toHaveBeenCalledWith( 'Here is some context' ); })); it('should load report reasons and context (Twitter)', () => { createComponent(); // The fixture needs to be updated after setting the platform to Twitter // so that the other functions can access the filled in reportReasons array. twitterSignInTestSubject.next(true); fixture.detectChanges(); expect(component.hasReportReasons).toEqual([ false, false, false, false, false, ]); reportReasonsChangedSubject.next(['Harassment']); fixture.detectChanges(); expect(component.hasReportReasons).toEqual([ true, false, false, false, false, ]); expect(component.context).toEqual(''); reportContextChangedSubject.next('Here is some context'); fixture.detectChanges(); expect(component.context).toEqual('Here is some context'); }); it('should show twitter only checkboxes', () => { createComponent(); // The fixture needs to be updated after setting the platform to twitter // so that the other functions can access the filled in reportReasons array. twitterSignInTestSubject.next(true); fixture.detectChanges(); expect(component.reportReasonOptions).toEqual( component.reportReasonOptionsTwitter ); expect(component.hasReportReasons).toEqual([ false, false, false, false, false, ]); }); it('should compute report summary for Twitter', () => { createComponent(); twitterSignInTestSubject.next(true); const expectedUsers = new Map(); expectedUsers.set('user1', 2); expectedUsers.set('user2', 1); expect(component.averageToxicity).toBeCloseTo(0.86); expect(component.usersInReport).toEqual(expectedUsers); expect(component.toxicityTypes).toEqual(new Set(['TOXICITY', 'INSULT'])); }); it('shows and hides comments on button click', () => { createComponent(); const nativeElement = fixture.nativeElement; const debugElement = fixture.debugElement; expect(nativeElement.querySelectorAll('app-comment-info').length).toEqual( 0 ); let commentSummaryElem = debugElement.nativeElement.querySelector( '.comment-summary' ); expect(commentSummaryElem.textContent).not.toContain(comments[0].item.text); expect(commentSummaryElem.textContent).not.toContain(comments[1].item.text); nativeElement.querySelector('.show-comments-button').click(); fixture.detectChanges(); expect(nativeElement.querySelectorAll('app-comment-info').length).toEqual( 3 ); commentSummaryElem = debugElement.nativeElement.querySelector( '.comment-summary' ); expect(commentSummaryElem.textContent).toContain(comments[0].item.text); expect(commentSummaryElem.textContent).toContain(comments[1].item.text); nativeElement.querySelector('.show-comments-button').click(); fixture.detectChanges(); expect(nativeElement.querySelectorAll('app-comment-info').length).toEqual( 0 ); commentSummaryElem = debugElement.nativeElement.querySelector( '.comment-summary' ); expect(commentSummaryElem.textContent).not.toContain(comments[0].item.text); expect(commentSummaryElem.textContent).not.toContain(comments[1].item.text); }); it('shows dialog when clear report button is clicked', () => { const dialogCloseTrigger = new Subject<boolean>(); createComponent([ { provide: MatDialog, useValue: { open(componentName: string) { return new DialogRefStub<boolean>(dialogCloseTrigger); }, }, }, ]); const showCommentsButton = fixture.debugElement.query( By.css('.show-comments-button') ); showCommentsButton.nativeElement.click(); fixture.detectChanges(); const clearReportButton = fixture.debugElement.query( By.css('.remove-all-button') ); clearReportButton.nativeElement.click(); fixture.detectChanges(); expect(component.clearReportDialogOpen).toBe(true); dialogCloseTrigger.next(true); fixture.detectChanges(); expect(component.clearReportDialogOpen).toBe(false); expect(mockReportService.clearReport).toHaveBeenCalled(); }); });
the_stack
import type { SubmitBody } from '../../typings/pinejs-client-core'; import type { InjectedDependenciesParam, InjectedOptionsParam, PineOptions, PineTypedResult, Application, ApplicationTag, ApplicationVariable, BuildVariable, Device, } from '..'; import type { CurrentService, CurrentServiceWithCommit, DeviceWithServiceDetails, } from '../util/device-service-details'; import * as url from 'url'; import once = require('lodash/once'); import * as errors from 'balena-errors'; import { isId, isNoApplicationForKeyResponse, isNotFoundResponse, mergePineOptions, treatAsMissingApplication, withSupervisorLockedError, } from '../util'; import { normalizeDeviceOsVersion } from '../util/device-os-version'; import { getCurrentServiceDetailsPineExpand, generateCurrentServiceDetails, } from '../util/device-service-details'; const getApplicationModel = function ( deps: InjectedDependenciesParam, opts: InjectedOptionsParam, ) { const { request, pine } = deps; const { apiUrl } = opts; const deviceModel = once(() => (require('./device') as typeof import('./device')).default(deps, opts), ); const releaseModel = once(() => (require('./release') as typeof import('./release')).default(deps, opts), ); const membershipModel = ( require('./application-membership') as typeof import('./application-membership') ).default(deps, (...args: Parameters<typeof exports.get>) => exports.get(...args), ); const inviteModel = ( require('./application-invite') as typeof import('./application-invite') ).default(deps, opts, (...args: Parameters<typeof exports.get>) => exports.get(...args), ); const { addCallbackSupportToModule } = require('../util/callbacks') as typeof import('../util/callbacks'); const { buildDependentResource } = require('../util/dependent-resource') as typeof import('../util/dependent-resource'); const tagsModel = buildDependentResource<ApplicationTag>( { pine }, { resourceName: 'application_tag', resourceKeyField: 'tag_key', parentResourceName: 'application', async getResourceId(nameOrSlugOrId: string | number): Promise<number> { const { id } = await exports.get(nameOrSlugOrId, { $select: 'id' }); return id; }, }, ); const configVarModel = buildDependentResource<ApplicationVariable>( { pine }, { resourceName: 'application_config_variable', resourceKeyField: 'name', parentResourceName: 'application', async getResourceId(nameOrSlugOrId: string | number): Promise<number> { const { id } = await exports.get(nameOrSlugOrId, { $select: 'id' }); return id; }, }, ); const envVarModel = buildDependentResource<ApplicationVariable>( { pine }, { resourceName: 'application_environment_variable', resourceKeyField: 'name', parentResourceName: 'application', async getResourceId(nameOrSlugOrId: string | number): Promise<number> { const { id } = await exports.get(nameOrSlugOrId, { $select: 'id' }); return id; }, }, ); const buildVarModel = buildDependentResource<BuildVariable>( { pine }, { resourceName: 'build_environment_variable', resourceKeyField: 'name', parentResourceName: 'application', async getResourceId(nameOrSlugOrId: string | number): Promise<number> { const { id } = await exports.get(nameOrSlugOrId, { $select: 'id' }); return id; }, }, ); // Infer dashboardUrl from apiUrl if former is undefined const dashboardUrl = opts.dashboardUrl ?? apiUrl!.replace(/api/, 'dashboard'); // Internal method for name/id disambiguation // Note that this throws an exception for missing names, but not missing ids const getId = async (nameOrSlugOrId: string | number) => { if (isId(nameOrSlugOrId)) { return nameOrSlugOrId; } else { const { id } = await exports.get(nameOrSlugOrId, { $select: 'id' }); return id; } }; const normalizeApplication = function (application: Application) { if (Array.isArray(application.owns__device)) { application.owns__device.forEach((device) => normalizeDeviceOsVersion(device), ); } return application; }; const exports = { _getId: getId, /** * @summary Get Dashboard URL for a specific application * @function getDashboardUrl * @memberof balena.models.application * * @param {Number} id - Application id * * @returns {String} - Dashboard URL for the specific application * @throws Exception if the id is not a finite number * * @example * balena.models.application.get('MyApp').then(function(application) { * const dashboardApplicationUrl = balena.models.application.getDashboardUrl(application.id); * console.log(dashboardApplicationUrl); * }); */ getDashboardUrl(id: number): string { if (typeof id !== 'number' || !Number.isFinite(id)) { throw new Error('The id option should be a finite number'); } return url.resolve(dashboardUrl, `/apps/${id}`); }, /** * @summary Get all applications * @name getAll * @public * @function * @memberof balena.models.application * * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - applications * @returns {Promise} * * @example * balena.models.application.getAll().then(function(applications) { * console.log(applications); * }); * * @example * balena.models.application.getAll(function(error, applications) { * if (error) throw error; * console.log(applications); * }); */ async getAll(options?: PineOptions<Application>): Promise<Application[]> { if (options == null) { options = {}; } const apps = await pine.get({ resource: 'application', options: mergePineOptions( { $filter: { is_directly_accessible_by__user: { $any: { $alias: 'dau', $expr: { 1: 1, }, }, }, }, $orderby: 'app_name asc', }, options, ), }); return apps.map(normalizeApplication); }, /** * @summary Get applications and their devices, along with each device's * associated services' essential details * @name getAllWithDeviceServiceDetails * @public * @function * @memberof balena.models.application * @deprecated * * @description * This method does not map exactly to the underlying model: it runs a * larger prebuilt query, and reformats it into an easy to use and * understand format. If you want more control, or to see the raw model * directly, use `application.getAll(options)` instead. * **NOTE:** In contrast with device.getWithServiceDetails() the service details * in the result of this method do not include the associated commit. * * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - applications * @returns {Promise} * * @example * balena.models.application.getAllWithDeviceServiceDetails().then(function(applications) { * console.log(applications); * }) * * @example * balena.models.application.getAllWithDeviceServiceDetails(function(error, applications) { * if (error) throw error; * console.log(applications); * }); */ async getAllWithDeviceServiceDetails( options?: PineOptions<Application>, ): Promise< Array< Application & { owns__device: Array<DeviceWithServiceDetails<CurrentService>>; } > > { if (options == null) { options = {}; } const serviceOptions = mergePineOptions( { $expand: [ { owns__device: { $expand: getCurrentServiceDetailsPineExpand(false), }, }, ], }, options, ); const apps = (await exports.getAll(serviceOptions)) as Array< Application & { owns__device: Array<DeviceWithServiceDetails<CurrentService>>; } >; apps.forEach((app) => { app.owns__device = app.owns__device.map(generateCurrentServiceDetails); }); return apps; }, /** * @summary Get a single application * @name get * @public * @function * @memberof balena.models.application * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object} - application * @returns {Promise} * * @example * balena.models.application.get('myorganization/myapp').then(function(application) { * console.log(application); * }); * * @example * // Deprecated in favor of application slug * balena.models.application.get('MyApp').then(function(application) { * console.log(application); * }); * * @example * balena.models.application.get(123).then(function(application) { * console.log(application); * }); * * @example * balena.models.application.get('myorganization/myapp', function(error, application) { * if (error) throw error; * console.log(application); * }); */ async get( nameOrSlugOrId: string | number, options?: PineOptions<Application>, ): Promise<Application> { if (options == null) { options = {}; } if (nameOrSlugOrId == null) { throw new errors.BalenaApplicationNotFound(nameOrSlugOrId); } let application; if (isId(nameOrSlugOrId)) { application = await pine.get({ resource: 'application', id: nameOrSlugOrId, options: mergePineOptions({}, options), }); if (application == null) { throw new errors.BalenaApplicationNotFound(nameOrSlugOrId); } } else { const applications = await pine.get({ resource: 'application', options: mergePineOptions( { $filter: { $or: { app_name: nameOrSlugOrId, slug: nameOrSlugOrId.toLowerCase(), }, }, }, options, ), }); if (applications.length === 0) { throw new errors.BalenaApplicationNotFound(nameOrSlugOrId); } if (applications.length > 1) { throw new errors.BalenaAmbiguousApplication(nameOrSlugOrId); } application = applications[0]; } return normalizeApplication(application); }, /** * @summary Get a single application and its devices, along with each device's * associated services' essential details * @name getWithDeviceServiceDetails * @public * @function * @memberof balena.models.application * * @description * This method does not map exactly to the underlying model: it runs a * larger prebuilt query, and reformats it into an easy to use and * understand format. If you want more control, or to see the raw model * directly, use `application.get(uuidOrId, options)` instead. * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object} - application * @returns {Promise} * * @example * balena.models.application.getWithDeviceServiceDetails('myorganization/myapp').then(function(device) { * console.log(device); * }) * * @example * balena.models.application.getWithDeviceServiceDetails(123).then(function(device) { * console.log(device); * }) * * @example * balena.models.application.getWithDeviceServiceDetails('myorganization/myapp', function(error, device) { * if (error) throw error; * console.log(device); * }); */ async getWithDeviceServiceDetails( nameOrSlugOrId: string | number, options?: PineOptions<Application>, ): Promise< Application & { owns__device: Array<DeviceWithServiceDetails<CurrentServiceWithCommit>>; } > { if (options == null) { options = {}; } const serviceOptions = mergePineOptions( { $expand: [ { owns__device: { $expand: getCurrentServiceDetailsPineExpand(true), }, }, ], }, options, ); const app = (await exports.get( nameOrSlugOrId, serviceOptions, )) as Application & { owns__device: Array<DeviceWithServiceDetails<CurrentServiceWithCommit>>; }; if (app && app.owns__device) { app.owns__device = app.owns__device.map((d) => generateCurrentServiceDetails<CurrentServiceWithCommit>(d), ); } return app; }, /** * @summary Get a single application using the appname and the handle of the owning organization * @name getAppByName * @public * @function * @memberof balena.models.application * * @param {String} appName - application name * @param {Object} [options={}] - extra pine options to use * @fulfil {Object} - application * @returns {Promise} * * @example * balena.models.application.getAppByName('MyApp').then(function(application) { * console.log(application); * }); */ async getAppByName( appName: string, options?: PineOptions<Application>, ): Promise<Application> { if (options == null) { options = {}; } const applications = await pine.get({ resource: 'application', options: mergePineOptions( { $filter: { app_name: appName, }, }, options, ), }); if (applications.length === 0) { throw new errors.BalenaApplicationNotFound(appName); } if (applications.length > 1) { throw new errors.BalenaAmbiguousApplication(appName); } const [application] = applications; return normalizeApplication(application); }, /** * @summary Get a single application using the appname and the handle of the owning organization * @name getAppByOwner * @public * @function * @memberof balena.models.application * * @param {String} appName - application name * @param {String} owner - The handle of the owning organization * @param {Object} [options={}] - extra pine options to use * @fulfil {Object} - application * @returns {Promise} * * @example * balena.models.application.getAppByOwner('MyApp', 'MyOrg').then(function(application) { * console.log(application); * }); */ async getAppByOwner( appName: string, owner: string, options?: PineOptions<Application>, ): Promise<Application> { if (options == null) { options = {}; } appName = appName.toLowerCase(); owner = owner.toLowerCase(); const application = await pine.get({ resource: 'application', id: { slug: `${owner}/${appName}`, }, options, }); if (application == null) { throw new errors.BalenaApplicationNotFound(`${owner}/${appName}`); } return normalizeApplication(application); }, /** * @summary Check if an application exists * @name has * @public * @function * @memberof balena.models.application * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @fulfil {Boolean} - has application * @returns {Promise} * * @example * balena.models.application.has('MyApp').then(function(hasApp) { * console.log(hasApp); * }); * * @example * balena.models.application.has(123).then(function(hasApp) { * console.log(hasApp); * }); * * @example * balena.models.application.has('MyApp', function(error, hasApp) { * if (error) throw error; * console.log(hasApp); * }); */ has: async (nameOrSlugOrId: string | number): Promise<boolean> => { try { await exports.get(nameOrSlugOrId, { $select: ['id'] }); return true; } catch (err) { if (err instanceof errors.BalenaApplicationNotFound) { return false; } throw err; } }, /** * @summary Check if the user has any applications * @name hasAny * @public * @function * @memberof balena.models.application * * @fulfil {Boolean} - has any applications * @returns {Promise} * * @example * balena.models.application.hasAny().then(function(hasAny) { * console.log('Has any?', hasAny); * }); * * @example * balena.models.application.hasAny(function(error, hasAny) { * if (error) throw error; * console.log('Has any?', hasAny); * }); */ hasAny: async (): Promise<boolean> => { const applications = await exports.getAll({ $select: ['id'] }); return applications.length !== 0; }, /** * @summary Create an application * @name create * @public * @function * @memberof balena.models.application * * @param {Object} options - application creation parameters * @param {String} options.name - application name * @param {String} [options.applicationType] - application type slug e.g. microservices-starter * @param {String} options.deviceType - device type slug * @param {(Number|String)} [options.parent] - parent application name or id * @param {(String|Number)} options.organization - handle (string) or id (number) of the organization that the application will belong to or null * * @fulfil {Object} - application * @returns {Promise} * * @example * balena.models.application.create({ name: 'My App', applicationType: 'essentials', deviceType: 'raspberry-pi' }).then(function(application) { * console.log(application); * }); * * @example * balena.models.application.create({ name: 'My App', applicationType: 'microservices', deviceType: 'raspberry-pi', parent: 'ParentApp' }).then(function(application) { * console.log(application); * }); * * @example * balena.models.application.create({ name: 'My App', applicationType: 'microservices-starter', deviceType: 'raspberry-pi' }, function(error, application) { * if (error) throw error; * console.log(application); * }); */ async create({ name, applicationType, deviceType, parent, organization, }: { name: string; applicationType?: string; deviceType: string; parent?: number | string; organization: number | string; }): Promise<Application> { if (organization == null) { throw new errors.BalenaInvalidParameterError( 'organization', organization, ); } const applicationTypePromise = !applicationType ? undefined : pine .get({ resource: 'application_type', id: { slug: applicationType, }, options: { $select: 'id', }, }) .then(function (appType) { if (!appType) { throw new Error(`Invalid application type: ${applicationType}`); } return appType.id; }); const parentAppPromise = parent ? exports.get(parent, { $select: ['id'] }) : undefined; const deviceTypeIdPromise = deviceModel() .getDeviceSlug(deviceType) .then(async function (deviceTypeSlug) { if (deviceTypeSlug == null) { throw new errors.BalenaInvalidDeviceType(deviceType); } const dt = await pine.get({ resource: 'device_type', id: { // this way we get the un-aliased device type slug slug: deviceTypeSlug, }, options: { $select: 'id', $expand: { is_default_for__application: { $select: 'is_archived', $filter: { is_host: true, }, }, }, }, }); if (dt == null) { throw new errors.BalenaInvalidDeviceType(deviceType); } const hostApps = dt.is_default_for__application; // TODO: We are now checking whether all returned hostApps are marked as archived so that we // do not break open-balena. Once open-balena gets hostApps, we can change this to just a $filter on is_archived. if ( hostApps.length > 0 && hostApps.every((hostApp) => hostApp.is_archived) ) { throw new errors.BalenaDiscontinuedDeviceType(deviceType); } return dt.id; }); const organizationPromise = pine .get({ resource: 'organization', id: { [isId(organization) ? 'id' : 'handle']: organization, }, options: { $select: ['id'], }, }) .then(function (org) { if (!org) { throw new errors.BalenaOrganizationNotFound(organization); } return org.id; }); const [ deviceTypeId, applicationTypeId, parentApplication, organizationId, ] = await Promise.all([ deviceTypeIdPromise, applicationTypePromise, parentAppPromise, organizationPromise, ]); const body: SubmitBody<Application> = { app_name: name, is_for__device_type: deviceTypeId, }; if (parentApplication) { body.depends_on__application = parentApplication.id; } if (applicationTypeId) { body.application_type = applicationTypeId; } if (organizationId) { body.organization = organizationId; } return await pine.post({ resource: 'application', body, }); }, /** * @summary Remove application * @name remove * @public * @function * @memberof balena.models.application * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @returns {Promise} * * @example * balena.models.application.remove('MyApp'); * * @example * balena.models.application.remove(123); * * @example * balena.models.application.remove('MyApp', function(error) { * if (error) throw error; * }); */ remove: async (nameOrSlugOrId: string | number): Promise<void> => { try { const applicationId = await getId(nameOrSlugOrId); await pine.delete({ resource: 'application', id: applicationId, }); } catch (err) { if (isNotFoundResponse(err)) { treatAsMissingApplication(nameOrSlugOrId, err); } throw err; } }, /** * @summary Rename application * @name rename * @public * @function * @memberof balena.models.application * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {String} newName - new application name (string) * @returns {Promise} * * @example * balena.models.application.rename('MyApp', 'MyRenamedApp'); * * @example * balena.models.application.rename(123, 'MyRenamedApp'); * * @example * balena.models.application.rename('MyApp', 'MyRenamedApp', function(error) { * if (error) throw error; * }); */ rename: async ( nameOrSlugOrId: string | number, newAppName: string, ): Promise<void> => { try { const applicationId = await getId(nameOrSlugOrId); await pine.patch({ resource: 'application', id: applicationId, body: { app_name: newAppName, }, }); } catch (err) { if (isNotFoundResponse(err)) { treatAsMissingApplication(nameOrSlugOrId, err); } throw err; } }, /** * @summary Restart application * @name restart * @public * @function * @memberof balena.models.application * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @returns {Promise} * * @example * balena.models.application.restart('MyApp'); * * @example * balena.models.application.restart(123); * * @example * balena.models.application.restart('MyApp', function(error) { * if (error) throw error; * }); */ restart: (nameOrSlugOrId: string | number): Promise<void> => withSupervisorLockedError(async () => { try { const applicationId = await getId(nameOrSlugOrId); await request.send({ method: 'POST', url: `/application/${applicationId}/restart`, baseUrl: apiUrl, }); } catch (err) { if (isNotFoundResponse(err)) { treatAsMissingApplication(nameOrSlugOrId, err); } throw err; } }), /** * @summary Generate an API key for a specific application * @name generateApiKey * @public * @function * @memberof balena.models.application * @deprecated * @description * Generally you shouldn't use this method: if you're provisioning a recent BalenaOS * version (2.4.0+) then generateProvisioningKey should work just as well, but * be more secure. * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @fulfil {String} - api key * @returns {Promise} * * @example * balena.models.application.generateApiKey('MyApp').then(function(apiKey) { * console.log(apiKey); * }); * * @example * balena.models.application.generateApiKey(123).then(function(apiKey) { * console.log(apiKey); * }); * * @example * balena.models.application.generateApiKey('MyApp', function(error, apiKey) { * if (error) throw error; * console.log(apiKey); * }); */ generateApiKey: async ( nameOrSlugOrId: string | number, ): Promise<string> => { // Do a full get, not just getId, because the actual api endpoint doesn't fail if the id // doesn't exist. TODO: Can use getId once https://github.com/balena-io/balena-api/issues/110 is resolved const { id } = await exports.get(nameOrSlugOrId, { $select: 'id' }); const { body } = await request.send({ method: 'POST', url: `/application/${id}/generate-api-key`, baseUrl: apiUrl, }); return body; }, /** * @summary Generate a device provisioning key for a specific application * @name generateProvisioningKey * @public * @function * @memberof balena.models.application * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {String} [keyName] - Provisioning key name * @fulfil {String} - device provisioning key * @returns {Promise} * * @example * balena.models.application.generateProvisioningKey('MyApp').then(function(key) { * console.log(key); * }); * * @example * balena.models.application.generateProvisioningKey(123).then(function(key) { * console.log(key); * }); * * @example * balena.models.application.generateProvisioningKey('MyApp', function(error, key) { * if (error) throw error; * console.log(key); * }); */ generateProvisioningKey: async ( nameOrSlugOrId: string | number, keyName?: string, ): Promise<string> => { try { const applicationId = await getId(nameOrSlugOrId); const { body } = await request.send({ method: 'POST', url: '/api-key/v1/', baseUrl: apiUrl, body: { actorType: 'application', actorTypeId: applicationId, roles: ['provisioning-api-key'], name: keyName, }, }); return body; } catch (err) { if (isNoApplicationForKeyResponse(err)) { treatAsMissingApplication(nameOrSlugOrId, err); } throw err; } }, /** * @summary Purge devices by application id * @name purge * @public * @function * @memberof balena.models.application * * @param {Number} appId - application id * @returns {Promise} * * @example * balena.models.application.purge(123); * * @example * balena.models.application.purge(123, function(error) { * if (error) throw error; * }); */ purge: (appId: number): Promise<void> => withSupervisorLockedError(async () => { await request.send({ method: 'POST', url: '/supervisor/v1/purge', baseUrl: apiUrl, body: { appId, data: { appId: `${appId}`, }, }, }); }), /** * @summary Shutdown devices by application id * @name shutdown * @public * @function * @memberof balena.models.application * * @param {Number} appId - application id * @param {Object} [options] - options * @param {Boolean} [options.force=false] - override update lock * @returns {Promise} * * @example * balena.models.application.shutdown(123); * * @example * balena.models.application.shutdown(123, function(error) { * if (error) throw error; * }); */ shutdown: (appId: number, options?: { force?: boolean }): Promise<void> => withSupervisorLockedError(async () => { if (options == null) { options = {}; } await request.send({ method: 'POST', url: '/supervisor/v1/shutdown', baseUrl: apiUrl, body: { appId, data: { force: Boolean(options.force), }, }, }); }), /** * @summary Reboot devices by application id * @name reboot * @public * @function * @memberof balena.models.application * * @param {Number} appId - application id * @param {Object} [options] - options * @param {Boolean} [options.force=false] - override update lock * @returns {Promise} * * @example * balena.models.application.reboot(123); * * @example * balena.models.application.reboot(123, function(error) { * if (error) throw error; * }); */ reboot: (appId: number, options?: { force?: boolean }): Promise<void> => withSupervisorLockedError(async () => { if (options == null) { options = {}; } await request.send({ method: 'POST', url: '/supervisor/v1/reboot', baseUrl: apiUrl, body: { appId, data: { force: Boolean(options.force), }, }, }); }), /** * @summary Get whether the application is configured to receive updates whenever a new release is available * @name willTrackNewReleases * @public * @function * @memberof balena.models.application * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @fulfil {Boolean} - is tracking the latest release * @returns {Promise} * * @example * balena.models.application.willTrackNewReleases('MyApp').then(function(isEnabled) { * console.log(isEnabled); * }); * * @example * balena.models.application.willTrackNewReleases(123).then(function(isEnabled) { * console.log(isEnabled); * }); * * @example * balena.models.application.willTrackNewReleases('MyApp', function(error, isEnabled) { * console.log(isEnabled); * }); */ willTrackNewReleases: async ( nameOrSlugOrId: string | number, ): Promise<boolean> => { const { should_track_latest_release } = await exports.get( nameOrSlugOrId, { $select: 'should_track_latest_release' }, ); return should_track_latest_release; }, /** * @summary Get whether the application is up to date and is tracking the latest finalized release for updates * @name isTrackingLatestRelease * @public * @function * @memberof balena.models.application * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @fulfil {Boolean} - is tracking the latest release * @returns {Promise} * * @example * balena.models.application.isTrackingLatestRelease('MyApp').then(function(isEnabled) { * console.log(isEnabled); * }); * * @example * balena.models.application.isTrackingLatestRelease(123).then(function(isEnabled) { * console.log(isEnabled); * }); * * @example * balena.models.application.isTrackingLatestRelease('MyApp', function(error, isEnabled) { * console.log(isEnabled); * }); */ isTrackingLatestRelease: async ( nameOrSlugOrId: string | number, ): Promise<boolean> => { const appOptions = { $select: 'should_track_latest_release', $expand: { should_be_running__release: { $select: 'id' }, owns__release: { $select: 'id', $top: 1, $filter: { is_final: true, is_passing_tests: true, is_invalidated: false, status: 'success', }, $orderby: 'created_at desc', }, }, } as const; const application = (await exports.get( nameOrSlugOrId, appOptions, )) as PineTypedResult<Application, typeof appOptions>; const trackedRelease = application.should_be_running__release[0]; const latestRelease = application.owns__release[0]; return ( application.should_track_latest_release && (!latestRelease || trackedRelease?.id === latestRelease.id) ); }, /** * @summary Set a specific application to run a particular release * @name pinToRelease * @public * @function * @memberof balena.models.application * * @description Configures the application to run a particular release * and not get updated when the latest release changes. * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {String} fullReleaseHash - the hash of a successful release (string) * @returns {Promise} * * @example * balena.models.application.pinToRelease('MyApp', 'f7caf4ff80114deeaefb7ab4447ad9c661c50847').then(function() { * ... * }); * * @example * balena.models.application.pinToRelease(123, 'f7caf4ff80114deeaefb7ab4447ad9c661c50847').then(function() { * ... * }); * * @example * balena.models.application.pinToRelease('MyApp', 'f7caf4ff80114deeaefb7ab4447ad9c661c50847', function(error) { * if (error) throw error; * ... * }); */ pinToRelease: async ( nameOrSlugOrId: string | number, fullReleaseHash: string, ): Promise<void> => { const applicationId = await getId(nameOrSlugOrId); const release = await releaseModel().get(fullReleaseHash, { $select: 'id', $top: 1, $filter: { belongs_to__application: applicationId, status: 'success', }, }); await pine.patch({ resource: 'application', id: applicationId, body: { should_be_running__release: release.id, should_track_latest_release: false, }, }); }, /** * @summary Get the hash of the current release for a specific application * @name getTargetReleaseHash * @public * @function * @memberof balena.models.application * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @fulfil {String|undefined} - The release hash of the current release * @returns {Promise} * * @example * balena.models.application.getTargetReleaseHash('MyApp').then(function(release) { * console.log(release); * }); * * @example * balena.models.application.getTargetReleaseHash(123).then(function(release) { * console.log(release); * }); * * @example * balena.models.application.getTargetReleaseHash('MyApp', function(release) { * console.log(release); * }); */ getTargetReleaseHash: async ( nameOrSlugOrId: string | number, ): Promise<string | undefined> => { const appOptions = { $select: 'id', $expand: { should_be_running__release: { $select: 'commit' } }, } as const; const application = (await exports.get( nameOrSlugOrId, appOptions, )) as PineTypedResult<Application, typeof appOptions>; return application.should_be_running__release[0]?.commit; }, /** * @summary Configure a specific application to track the latest finalized available release * @name trackLatestRelease * @public * @function * @memberof balena.models.application * * @description The application's current release will be updated with each new successfully built release. * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @returns {Promise} * * @example * balena.models.application.trackLatestRelease('MyApp').then(function() { * ... * }); * * @example * balena.models.application.trackLatestRelease(123).then(function() { * ... * }); * * @example * balena.models.application.trackLatestRelease('MyApp', function(error) { * if (error) throw error; * ... * }); */ trackLatestRelease: async ( nameOrSlugOrId: string | number, ): Promise<void> => { const appOptions = { $select: 'id', $expand: { owns__release: { $select: 'id', $top: 1, $filter: { is_final: true, is_passing_tests: true, is_invalidated: false, status: 'success', }, $orderby: 'created_at desc', }, }, } as const; const application = (await exports.get( nameOrSlugOrId, appOptions, )) as PineTypedResult<Application, typeof appOptions>; const body: SubmitBody<Application> = { should_track_latest_release: true, }; const latestRelease = application.owns__release[0]; if (latestRelease) { body.should_be_running__release = latestRelease.id; } await pine.patch({ resource: 'application', id: application.id, body, }); }, /** * @summary Enable device urls for all devices that belong to an application * @name enableDeviceUrls * @public * @function * @memberof balena.models.application * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @returns {Promise} * * @example * balena.models.application.enableDeviceUrls('MyApp'); * * @example * balena.models.application.enableDeviceUrls(123); * * @example * balena.models.device.enableDeviceUrls('MyApp', function(error) { * if (error) throw error; * }); */ enableDeviceUrls: async ( nameOrSlugOrId: string | number, ): Promise<void> => { const { id } = await exports.get(nameOrSlugOrId, { $select: 'id' }); await pine.patch<Device>({ resource: 'device', body: { is_web_accessible: true, }, options: { $filter: { belongs_to__application: id, }, }, }); }, /** * @summary Disable device urls for all devices that belong to an application * @name disableDeviceUrls * @public * @function * @memberof balena.models.application * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @returns {Promise} * * @example * balena.models.application.disableDeviceUrls('MyApp'); * * @example * balena.models.application.disableDeviceUrls(123); * * @example * balena.models.device.disableDeviceUrls('MyApp', function(error) { * if (error) throw error; * }); */ disableDeviceUrls: async ( nameOrSlugOrId: string | number, ): Promise<void> => { const { id } = await exports.get(nameOrSlugOrId, { $select: 'id' }); await pine.patch<Device>({ resource: 'device', body: { is_web_accessible: false, }, options: { $filter: { belongs_to__application: id, }, }, }); }, /** * @summary Grant support access to an application until a specified time * @name grantSupportAccess * @public * @function * @memberof balena.models.application * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {Number} expiryTimestamp - a timestamp in ms for when the support access will expire * @returns {Promise} * * @example * balena.models.application.grantSupportAccess('MyApp', Date.now() + 3600 * 1000); * * @example * balena.models.application.grantSupportAccess(123, Date.now() + 3600 * 1000); * * @example * balena.models.application.grantSupportAccess('MyApp', Date.now() + 3600 * 1000, function(error) { * if (error) throw error; * }); */ async grantSupportAccess( nameOrSlugOrId: string | number, expiryTimestamp: number, ): Promise<void> { if (expiryTimestamp == null || expiryTimestamp <= Date.now()) { throw new errors.BalenaInvalidParameterError( 'expiryTimestamp', expiryTimestamp, ); } try { const applicationId = await getId(nameOrSlugOrId); await pine.patch({ resource: 'application', id: applicationId, body: { is_accessible_by_support_until__date: expiryTimestamp }, }); } catch (err) { if (isNotFoundResponse(err)) { treatAsMissingApplication(nameOrSlugOrId, err); } throw err; } }, /** * @summary Revoke support access to an application * @name revokeSupportAccess * @public * @function * @memberof balena.models.application * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @returns {Promise} * * @example * balena.models.application.revokeSupportAccess('MyApp'); * * @example * balena.models.application.revokeSupportAccess(123); * * @example * balena.models.application.revokeSupportAccess('MyApp', function(error) { * if (error) throw error; * }); */ revokeSupportAccess: async ( nameOrSlugOrId: string | number, ): Promise<void> => { try { const applicationId = await getId(nameOrSlugOrId); await pine.patch({ resource: 'application', id: applicationId, body: { is_accessible_by_support_until__date: null }, }); } catch (err) { if (isNotFoundResponse(err)) { treatAsMissingApplication(nameOrSlugOrId, err); } throw err; } }, /** * @namespace balena.models.application.tags * @memberof balena.models.application */ tags: addCallbackSupportToModule({ /** * @summary Get all application tags for an application * @name getAllByApplication * @public * @function * @memberof balena.models.application.tags * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - application tags * @returns {Promise} * * @example * balena.models.application.tags.getAllByApplication('MyApp').then(function(tags) { * console.log(tags); * }); * * @example * balena.models.application.tags.getAllByApplication(999999).then(function(tags) { * console.log(tags); * }); * * @example * balena.models.application.tags.getAllByApplication('MyApp', function(error, tags) { * if (error) throw error; * console.log(tags) * }); */ getAllByApplication: tagsModel.getAllByParent, /** * @summary Get all application tags * @name getAll * @public * @function * @memberof balena.models.application.tags * * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - application tags * @returns {Promise} * * @example * balena.models.application.tags.getAll().then(function(tags) { * console.log(tags); * }); * * @example * balena.models.application.tags.getAll(function(error, tags) { * if (error) throw error; * console.log(tags) * }); */ getAll: tagsModel.getAll, /** * @summary Set an application tag * @name set * @public * @function * @memberof balena.models.application.tags * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {String} tagKey - tag key * @param {String|undefined} value - tag value * * @returns {Promise} * * @example * balena.models.application.tags.set('myorganization/myapp', 'EDITOR', 'vim'); * * @example * balena.models.application.tags.set(123, 'EDITOR', 'vim'); * * @example * balena.models.application.tags.set('myorganization/myapp', 'EDITOR', 'vim', function(error) { * if (error) throw error; * }); */ set: tagsModel.set, /** * @summary Remove an application tag * @name remove * @public * @function * @memberof balena.models.application.tags * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {String} tagKey - tag key * @returns {Promise} * * @example * balena.models.application.tags.remove('myorganization/myapp', 'EDITOR'); * * @example * balena.models.application.tags.remove('myorganization/myapp', 'EDITOR', function(error) { * if (error) throw error; * }); */ remove: tagsModel.remove, }), /** * @namespace balena.models.application.configVar * @memberof balena.models.application */ configVar: addCallbackSupportToModule({ /** * @summary Get all config variables for an application * @name getAllByApplication * @public * @function * @memberof balena.models.application.configVar * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - application config variables * @returns {Promise} * * @example * balena.models.application.configVar.getAllByApplication('MyApp').then(function(vars) { * console.log(vars); * }); * * @example * balena.models.application.configVar.getAllByApplication(999999).then(function(vars) { * console.log(vars); * }); * * @example * balena.models.application.configVar.getAllByApplication('MyApp', function(error, vars) { * if (error) throw error; * console.log(vars) * }); */ getAllByApplication: configVarModel.getAllByParent, /** * @summary Get the value of a specific config variable * @name get * @public * @function * @memberof balena.models.application.configVar * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {String} key - config variable name * @fulfil {String|undefined} - the config variable value (or undefined) * @returns {Promise} * * @example * balena.models.application.configVar.get('MyApp', 'BALENA_VAR').then(function(value) { * console.log(value); * }); * * @example * balena.models.application.configVar.get(999999, 'BALENA_VAR').then(function(value) { * console.log(value); * }); * * @example * balena.models.application.configVar.get('MyApp', 'BALENA_VAR', function(error, value) { * if (error) throw error; * console.log(value) * }); */ get: configVarModel.get, /** * @summary Set the value of a specific config variable * @name set * @public * @function * @memberof balena.models.application.configVar * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {String} key - config variable name * @param {String} value - config variable value * @returns {Promise} * * @example * balena.models.application.configVar.set('MyApp', 'BALENA_VAR', 'newvalue').then(function() { * ... * }); * * @example * balena.models.application.configVar.set(999999, 'BALENA_VAR', 'newvalue').then(function() { * ... * }); * * @example * balena.models.application.configVar.set('MyApp', 'BALENA_VAR', 'newvalue', function(error) { * if (error) throw error; * ... * }); */ set: configVarModel.set, /** * @summary Clear the value of a specific config variable * @name remove * @public * @function * @memberof balena.models.application.configVar * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {String} key - config variable name * @returns {Promise} * * @example * balena.models.application.configVar.remove('MyApp', 'BALENA_VAR').then(function() { * ... * }); * * @example * balena.models.application.configVar.remove(999999, 'BALENA_VAR').then(function() { * ... * }); * * @example * balena.models.application.configVar.remove('MyApp', 'BALENA_VAR', function(error) { * if (error) throw error; * ... * }); */ remove: configVarModel.remove, }), /** * @namespace balena.models.application.envVar * @memberof balena.models.application */ envVar: addCallbackSupportToModule({ /** * @summary Get all environment variables for an application * @name getAllByApplication * @public * @function * @memberof balena.models.application.envVar * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - application environment variables * @returns {Promise} * * @example * balena.models.application.envVar.getAllByApplication('MyApp').then(function(vars) { * console.log(vars); * }); * * @example * balena.models.application.envVar.getAllByApplication(999999).then(function(vars) { * console.log(vars); * }); * * @example * balena.models.application.envVar.getAllByApplication('MyApp', function(error, vars) { * if (error) throw error; * console.log(vars) * }); */ getAllByApplication: envVarModel.getAllByParent, /** * @summary Get the value of a specific environment variable * @name get * @public * @function * @memberof balena.models.application.envVar * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {String} key - environment variable name * @fulfil {String|undefined} - the environment variable value (or undefined) * @returns {Promise} * * @example * balena.models.application.envVar.get('MyApp', 'VAR').then(function(value) { * console.log(value); * }); * * @example * balena.models.application.envVar.get(999999, 'VAR').then(function(value) { * console.log(value); * }); * * @example * balena.models.application.envVar.get('MyApp', 'VAR', function(error, value) { * if (error) throw error; * console.log(value) * }); */ get: envVarModel.get, /** * @summary Set the value of a specific environment variable * @name set * @public * @function * @memberof balena.models.application.envVar * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {String} key - environment variable name * @param {String} value - environment variable value * @returns {Promise} * * @example * balena.models.application.envVar.set('MyApp', 'VAR', 'newvalue').then(function() { * ... * }); * * @example * balena.models.application.envVar.set(999999, 'VAR', 'newvalue').then(function() { * ... * }); * * @example * balena.models.application.envVar.set('MyApp', 'VAR', 'newvalue', function(error) { * if (error) throw error; * ... * }); */ set: envVarModel.set, /** * @summary Clear the value of a specific environment variable * @name remove * @public * @function * @memberof balena.models.application.envVar * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {String} key - environment variable name * @returns {Promise} * * @example * balena.models.application.envVar.remove('MyApp', 'VAR').then(function() { * ... * }); * * @example * balena.models.application.envVar.remove(999999, 'VAR').then(function() { * ... * }); * * @example * balena.models.application.envVar.remove('MyApp', 'VAR', function(error) { * if (error) throw error; * ... * }); */ remove: envVarModel.remove, }), /** * @namespace balena.models.application.buildVar * @memberof balena.models.application */ buildVar: addCallbackSupportToModule({ /** * @summary Get all build environment variables for an application * @name getAllByApplication * @public * @function * @memberof balena.models.application.buildVar * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - application build environment variables * @returns {Promise} * * @example * balena.models.application.buildVar.getAllByApplication('MyApp').then(function(vars) { * console.log(vars); * }); * * @example * balena.models.application.buildVar.getAllByApplication(999999).then(function(vars) { * console.log(vars); * }); * * @example * balena.models.application.buildVar.getAllByApplication('MyApp', function(error, vars) { * if (error) throw error; * console.log(vars) * }); */ getAllByApplication: buildVarModel.getAllByParent, /** * @summary Get the value of a specific build environment variable * @name get * @public * @function * @memberof balena.models.application.buildVar * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {String} key - build environment variable name * @fulfil {String|undefined} - the build environment variable value (or undefined) * @returns {Promise} * * @example * balena.models.application.buildVar.get('MyApp', 'VAR').then(function(value) { * console.log(value); * }); * * @example * balena.models.application.buildVar.get(999999, 'VAR').then(function(value) { * console.log(value); * }); * * @example * balena.models.application.buildVar.get('MyApp', 'VAR', function(error, value) { * if (error) throw error; * console.log(value) * }); */ get: buildVarModel.get, /** * @summary Set the value of a specific build environment variable * @name set * @public * @function * @memberof balena.models.application.buildVar * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {String} key - build environment variable name * @param {String} value - build environment variable value * @returns {Promise} * * @example * balena.models.application.buildVar.set('MyApp', 'VAR', 'newvalue').then(function() { * ... * }); * * @example * balena.models.application.buildVar.set(999999, 'VAR', 'newvalue').then(function() { * ... * }); * * @example * balena.models.application.buildVar.set('MyApp', 'VAR', 'newvalue', function(error) { * if (error) throw error; * ... * }); */ set: buildVarModel.set, /** * @summary Clear the value of a specific build environment variable * @name remove * @public * @function * @memberof balena.models.application.buildVar * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {String} key - build environment variable name * @returns {Promise} * * @example * balena.models.application.buildVar.remove('MyApp', 'VAR').then(function() { * ... * }); * * @example * balena.models.application.buildVar.remove(999999, 'VAR').then(function() { * ... * }); * * @example * balena.models.application.buildVar.remove('MyApp', 'VAR', function(error) { * if (error) throw error; * ... * }); */ remove: buildVarModel.remove, }), /** * @namespace balena.models.application.membership * @memberof balena.models.application */ membership: addCallbackSupportToModule(membershipModel), /** * @namespace balena.models.application.invite * @memberof balena.models.application */ invite: addCallbackSupportToModule(inviteModel), }; return exports; }; export { getApplicationModel as default };
the_stack
import * as React from 'react'; import * as ReactDOM from "react-dom"; import './App.css'; import JqxButton from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxbuttons'; import JqxTooltip from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxtooltip'; import JqxTreeGrid, { ITreeGridProps, jqx } from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxtreegrid'; class App extends React.PureComponent<{}, ITreeGridProps> { private myTreeGrid = React.createRef<JqxTreeGrid>(); private addButton = React.createRef<JqxButton>(); private editButton = React.createRef<JqxButton>(); private deleteButton = React.createRef<JqxButton>(); private cancelButton = React.createRef<JqxButton>(); private updateButton = React.createRef<JqxButton>(); private rowKey: any = ''; private newRowID: any = null; constructor(props: {}) { super(props); this.rowSelect = this.rowSelect.bind(this); this.rowUnselect = this.rowUnselect.bind(this); this.rowBeginEdit = this.rowBeginEdit.bind(this); this.rowEndEdit = this.rowEndEdit.bind(this); const source: any = { addRow: (rowID?: any, rowData?: any, position?: any, parentID?: any, commit?: any) => { // synchronize with the server - send insert command // call commit with parameter true if the synchronization with the server is successful // and with parameter false if the synchronization failed. // you can pass additional argument to the commit callback which represents the new ID if it is generated from a DB. this.newRowID = rowID; commit(true); }, dataFields: [ { name: 'Id', type: 'number' }, { name: 'Name', type: 'string' }, { name: 'ParentID', type: 'number' }, { name: 'Population', type: 'number' } ], dataType: 'tab', deleteRow: (rowID?: any, commit?: any) => { // synchronize with the server - send delete command // call commit with parameter true if the synchronization with the server is successful // and with parameter false if the synchronization failed. commit(true); }, hierarchy: { keyDataField: { name: 'Id' }, parentDataField: { name: 'ParentID' } }, id: 'Id', updateRow: (rowID?: any, rowData?: any, commit?: any) => { // synchronize with the server - send update command // call commit with parameter true if the synchronization with the server is successful // and with parameter false if the synchronization failed. commit(true); }, url: './assets/sampledata/locations.tsv' }; const dataAdapter: any = new jqx.dataAdapter(source); this.state = { columns: [ { text: 'Location Name', dataField: 'Name', align: 'center', width: '50%' }, { text: 'Population', dataField: 'Population', align: 'right', cellsAlign: 'right', width: '50%' } ], renderToolbar: (toolBar: any) => { const toTheme = (className: string) => { // @ts-ignore if (theme === "") { return className; } // @ts-ignore return className + "-" + theme + " " + className; }; const container = document.createElement('div'); container.style.cssText = 'overflow: hidden; position: relative; height: 100%; width: 100%;'; const createButton = () => { const button = document.createElement('div'); button.style.cssText = 'float: left; padding: 0px; margin: 0px;'; return button; }; toolBar[0].appendChild(container); const addButtonDom = createButton(); const editButtonDom = createButton(); const deleteButtonDom = createButton(); const cancelButtonDom = createButton(); const updateButtonDom = createButton(); container.appendChild(addButtonDom); container.appendChild(editButtonDom); container.appendChild(deleteButtonDom); container.appendChild(cancelButtonDom); container.appendChild(updateButtonDom); const isDisabled = (button: any) => { return button.current!.getOptions('disabled'); }; const addHandler = () => { if (!isDisabled(this.addButton)) { this.myTreeGrid.current!.expandRow(this.rowKey); // add new empty row. this.myTreeGrid.current!.addRow(null, {}, 'first', this.rowKey); // select the first row and clear the selection. this.myTreeGrid.current!.clearSelection(); this.myTreeGrid.current!.selectRow(this.newRowID); // edit the new row. this.myTreeGrid.current!.beginRowEdit(this.newRowID); // this.updateButtons('add'); this.updateButtons('Add'); } }; const editHandler = () => { if (!this.editButton.current!.props!.disabled) { this.myTreeGrid.current!.beginRowEdit(this.rowKey); this.updateButtons('Edit'); } }; const deleteHandler = () => { if (!isDisabled(this.deleteButton)) { const selection = this.myTreeGrid.current!.getSelection(); if (selection.length > 1) { for (const key of selection) { this.myTreeGrid.current!.deleteRow(key.Id); } } else { this.myTreeGrid.current!.deleteRow(this.rowKey); } this.updateButtons('Delete'); } }; const cancelHandler = () => { if (!isDisabled(this.cancelButton)) { // cancel changes. this.myTreeGrid.current!.endRowEdit(this.rowKey, true); } }; const updateHandler = () => { if (!isDisabled(this.updateButton)) { this.myTreeGrid.current!.endRowEdit(this.rowKey, false); } }; const iconStyle = { margin: '4px', width: '16px', height: '16px' }; const addComponent = <JqxTooltip theme={'material-purple'} position={'bottom'} content={'Add'}> <JqxButton theme={'material-purple'} ref={this.addButton} onClick={addHandler} disabled={true} height={25} width={25}> <div className={toTheme('jqx-icon-plus')} style={iconStyle} /> </JqxButton> </JqxTooltip>; const editComponent = <JqxTooltip theme={'material-purple'} position={'bottom'} content={'Edit'}> <JqxButton theme={'material-purple'} ref={this.editButton} onClick={editHandler} disabled={true} height={25} width={25}> <div className={toTheme('jqx-icon-edit')} style={iconStyle} /> </JqxButton> </JqxTooltip>; const deleteComponent = <JqxTooltip theme={'material-purple'} position={'bottom'} content={'Delete'}> <JqxButton theme={'material-purple'} ref={this.deleteButton} onClick={deleteHandler} disabled={true} height={25} width={25}> <div className={toTheme('jqx-icon-delete')} style={iconStyle} /> </JqxButton> </JqxTooltip>; const cancelComponent = <JqxTooltip theme={'material-purple'} position={'bottom'} content={'Cancel'}> <JqxButton theme={'material-purple'} ref={this.cancelButton} onClick={cancelHandler} disabled={true} height={25} width={25}> <div className={toTheme('jqx-icon-cancel')} style={iconStyle} /> </JqxButton> </JqxTooltip>; const updateComponent = <JqxTooltip theme={'material-purple'} position={'bottom'} content={'Update'}> <JqxButton theme={'material-purple'} ref={this.updateButton} onClick={updateHandler} disabled={true} height={25} width={25}> <div className={toTheme('jqx-icon-save')} style={iconStyle} /> </JqxButton> </JqxTooltip>; ReactDOM.render(addComponent, addButtonDom); ReactDOM.render(editComponent, editButtonDom); ReactDOM.render(deleteComponent, deleteButtonDom); ReactDOM.render(cancelComponent, cancelButtonDom); ReactDOM.render(updateComponent, updateButtonDom); }, source: dataAdapter } } public render() { return ( <JqxTreeGrid theme={'material-purple'} ref={this.myTreeGrid} onRowSelect={this.rowSelect} onRowUnselect={this.rowUnselect} onRowBeginEdit={this.rowBeginEdit} onRowEndEdit={this.rowEndEdit} // @ts-ignore width={'100%'} source={this.state.source} pageable={true} editable={true} showToolbar={true} altRows={true} pagerButtonsCount={8} toolbarHeight={35} renderToolbar={this.state.renderToolbar} columns={this.state.columns} /> ); } private setButtonState = (button: any, state: boolean) => { button.current!.setOptions({ disabled: state }); }; private updateButtons = (action: string, buttons?: any) => { switch (action) { case 'Select': this.setButtonState(this.addButton, false); this.setButtonState(this.deleteButton, false); this.setButtonState(this.editButton, false); this.setButtonState(this.cancelButton, false); this.setButtonState(this.updateButton, false); break; case 'Unselect': this.setButtonState(this.addButton, true); this.setButtonState(this.deleteButton, true); this.setButtonState(this.editButton, true); this.setButtonState(this.cancelButton, true); this.setButtonState(this.updateButton, true); break; case 'Edit': this.setButtonState(this.addButton, true); this.setButtonState(this.deleteButton, true); this.setButtonState(this.editButton, true); this.setButtonState(this.cancelButton, false); this.setButtonState(this.updateButton, false); break; case 'End Edit': this.setButtonState(this.addButton, false); this.setButtonState(this.deleteButton, false); this.setButtonState(this.editButton, false); this.setButtonState(this.cancelButton, true); this.setButtonState(this.updateButton, true); break; } }; // Event handling private rowSelect(event: any): void { const args = event.args; this.rowKey = args.key; this.updateButtons('Select'); } private rowUnselect(event: any): void { this.updateButtons('Unselect'); } private rowBeginEdit(event: any): void { this.updateButtons('Edit'); } private rowEndEdit(event: any): void { this.updateButtons('End Edit'); } } export default App;
the_stack
import type InjectedScript from './injectedScript'; import { elementText } from './selectorEvaluator'; type SelectorToken = { engine: string; selector: string; score: number; // Lower is better. }; const cacheAllowText = new Map<Element, SelectorToken[] | null>(); const cacheDisallowText = new Map<Element, SelectorToken[] | null>(); export function querySelector(injectedScript: InjectedScript, selector: string, ownerDocument: Document): { selector: string, elements: Element[] } { try { const parsedSelector = injectedScript.parseSelector(selector); return { selector, elements: injectedScript.querySelectorAll(parsedSelector, ownerDocument) }; } catch (e) { return { selector, elements: [], }; } } export function generateSelector(injectedScript: InjectedScript, targetElement: Element): { selector: string, elements: Element[] } { injectedScript._evaluator.begin(); try { targetElement = targetElement.closest('button,select,input,[role=button],[role=checkbox],[role=radio]') || targetElement; const targetTokens = generateSelectorFor(injectedScript, targetElement); const bestTokens = targetTokens || [cssFallback(injectedScript, targetElement)]; const selector = joinTokens(bestTokens); const parsedSelector = injectedScript.parseSelector(selector); return { selector, elements: injectedScript.querySelectorAll(parsedSelector, targetElement.ownerDocument) }; } finally { cacheAllowText.clear(); cacheDisallowText.clear(); injectedScript._evaluator.end(); } } function filterRegexTokens(textCandidates: SelectorToken[][]): SelectorToken[][] { // Filter out regex-based selectors for better performance. return textCandidates.filter(c => c[0].selector[0] !== '/'); } function generateSelectorFor(injectedScript: InjectedScript, targetElement: Element): SelectorToken[] | null { if (targetElement.ownerDocument.documentElement === targetElement) return [{ engine: 'css', selector: 'html', score: 1 }]; const calculate = (element: Element, allowText: boolean): SelectorToken[] | null => { const allowNthMatch = element === targetElement; let textCandidates = allowText ? buildTextCandidates(injectedScript, element, element === targetElement).map(token => [token]) : []; if (element !== targetElement) { // Do not use regex for parent elements (for performance). textCandidates = filterRegexTokens(textCandidates); } const noTextCandidates = buildCandidates(injectedScript, element).map(token => [token]); // First check all text and non-text candidates for the element. let result = chooseFirstSelector(injectedScript, targetElement.ownerDocument, element, [...textCandidates, ...noTextCandidates], allowNthMatch); // Do not use regex for chained selectors (for performance). textCandidates = filterRegexTokens(textCandidates); const checkWithText = (textCandidatesToUse: SelectorToken[][]) => { // Use the deepest possible text selector - works pretty good and saves on compute time. const allowParentText = allowText && !textCandidatesToUse.length; const candidates = [...textCandidatesToUse, ...noTextCandidates].filter(c => { if (!result) return true; return combineScores(c) < combineScores(result); }); // This is best theoretically possible candidate from the current parent. // We use the fact that widening the scope to grand-parent makes any selector // even less likely to match. let bestPossibleInParent: SelectorToken[] | null = candidates[0]; if (!bestPossibleInParent) return; for (let parent = parentElementOrShadowHost(element); parent; parent = parentElementOrShadowHost(parent)) { const parentTokens = calculateCached(parent, allowParentText); if (!parentTokens) continue; // Even the best selector won't be too good - skip this parent. if (result && combineScores([...parentTokens, ...bestPossibleInParent]) >= combineScores(result)) continue; // Update the best candidate that finds "element" in the "parent". bestPossibleInParent = chooseFirstSelector(injectedScript, parent, element, candidates, allowNthMatch); if (!bestPossibleInParent) return; const combined = [...parentTokens, ...bestPossibleInParent]; if (!result || combineScores(combined) < combineScores(result)) result = combined; } }; checkWithText(textCandidates); // Allow skipping text on the target element, and using text on one of the parents. if (element === targetElement && textCandidates.length) checkWithText([]); return result; }; const calculateCached = (element: Element, allowText: boolean): SelectorToken[] | null => { const cache = allowText ? cacheAllowText : cacheDisallowText; let value = cache.get(element); if (value === undefined) { value = calculate(element, allowText); cache.set(element, value); } return value; }; return calculateCached(targetElement, true); } function buildCandidates(injectedScript: InjectedScript, element: Element): SelectorToken[] { const candidates: SelectorToken[] = []; for (const attribute of ['data-testid', 'data-test-id', 'data-test']) { if (element.hasAttribute(attribute)) candidates.push({ engine: 'css', selector: `[${attribute}=${quoteString(element.getAttribute(attribute)!)}]`, score: 1 }); } if (element.nodeName === 'INPUT') { const input = element as HTMLInputElement; if (input.placeholder) candidates.push({ engine: 'css', selector: `[placeholder=${quoteString(input.placeholder)}]`, score: 10 }); } if (element.hasAttribute('aria-label')) candidates.push({ engine: 'css', selector: `[aria-label=${quoteString(element.getAttribute('aria-label')!)}]`, score: 10 }); if (element.getAttribute('alt') && ['APPLET', 'AREA', 'IMG', 'INPUT'].includes(element.nodeName)) candidates.push({ engine: 'css', selector: `${CSS.escape(element.nodeName.toLowerCase())}[alt=${quoteString(element.getAttribute('alt')!)}]`, score: 10 }); if (element.hasAttribute('role')) candidates.push({ engine: 'css', selector: `${CSS.escape(element.nodeName.toLowerCase())}[role=${quoteString(element.getAttribute('role')!)}]` , score: 50 }); if (element.getAttribute('name') && ['BUTTON', 'FORM', 'FIELDSET', 'IFRAME', 'INPUT', 'KEYGEN', 'OBJECT', 'OUTPUT', 'SELECT', 'TEXTAREA', 'MAP', 'META', 'PARAM'].includes(element.nodeName)) candidates.push({ engine: 'css', selector: `${CSS.escape(element.nodeName.toLowerCase())}[name=${quoteString(element.getAttribute('name')!)}]`, score: 50 }); if (['INPUT', 'TEXTAREA'].includes(element.nodeName) && element.getAttribute('type') !== 'hidden') { if (element.getAttribute('type')) candidates.push({ engine: 'css', selector: `${CSS.escape(element.nodeName.toLowerCase())}[type=${quoteString(element.getAttribute('type')!)}]`, score: 50 }); } if (['INPUT', 'TEXTAREA', 'SELECT'].includes(element.nodeName)) candidates.push({ engine: 'css', selector: CSS.escape(element.nodeName.toLowerCase()), score: 50 }); const idAttr = element.getAttribute('id'); if (idAttr && !isGuidLike(idAttr)) candidates.push({ engine: 'css', selector: makeSelectorForId(idAttr), score: 100 }); candidates.push({ engine: 'css', selector: CSS.escape(element.nodeName.toLowerCase()), score: 200 }); return candidates; } function buildTextCandidates(injectedScript: InjectedScript, element: Element, allowHasText: boolean): SelectorToken[] { if (element.nodeName === 'SELECT') return []; const text = elementText(injectedScript._evaluator, element).full.trim().replace(/\s+/g, ' ').substring(0, 80); if (!text) return []; const candidates: SelectorToken[] = []; let escaped = text; if (text.includes('"') || text.includes('>>') || text[0] === '/') escaped = `/.*${escapeForRegex(text)}.*/`; candidates.push({ engine: 'text', selector: escaped, score: 10 }); if (allowHasText && escaped === text) { let prefix = element.nodeName.toLowerCase(); if (element.hasAttribute('role')) prefix += `[role=${quoteString(element.getAttribute('role')!)}]`; candidates.push({ engine: 'css', selector: `${prefix}:has-text("${text}")`, score: 30 }); } return candidates; } function parentElementOrShadowHost(element: Element): Element | null { if (element.parentElement) return element.parentElement; if (!element.parentNode) return null; if (element.parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE && (element.parentNode as ShadowRoot).host) return (element.parentNode as ShadowRoot).host; return null; } function makeSelectorForId(id: string) { return /^[a-zA-Z][a-zA-Z0-9\-\_]+$/.test(id) ? '#' + id : `[id="${CSS.escape(id)}"]`; } function cssFallback(injectedScript: InjectedScript, targetElement: Element): SelectorToken { const kFallbackScore = 10000000; const root: Node = targetElement.ownerDocument; const tokens: string[] = []; function uniqueCSSSelector(prefix?: string): string | undefined { const path = tokens.slice(); if (prefix) path.unshift(prefix); const selector = path.join(' '); const parsedSelector = injectedScript.parseSelector(selector); const node = injectedScript.querySelector(parsedSelector, targetElement.ownerDocument, false); return node === targetElement ? selector : undefined; } for (let element: Element | null = targetElement; element && element !== root; element = parentElementOrShadowHost(element)) { const nodeName = element.nodeName.toLowerCase(); // Element ID is the strongest signal, use it. let bestTokenForLevel: string = ''; if (element.id) { const token = makeSelectorForId(element.id); const selector = uniqueCSSSelector(token); if (selector) return { engine: 'css', selector, score: kFallbackScore }; bestTokenForLevel = token; } const parent = element.parentNode as (Element | ShadowRoot); // Combine class names until unique. const classes = [...element.classList]; for (let i = 0; i < classes.length; ++i) { const token = '.' + classes.slice(0, i + 1).join('.'); const selector = uniqueCSSSelector(token); if (selector) return { engine: 'css', selector, score: kFallbackScore }; // Even if not unique, does this subset of classes uniquely identify node as a child? if (!bestTokenForLevel && parent) { const sameClassSiblings = parent.querySelectorAll(token); if (sameClassSiblings.length === 1) bestTokenForLevel = token; } } // Ordinal is the weakest signal. if (parent) { const siblings = [...parent.children]; const sameTagSiblings = siblings.filter(sibling => (sibling).nodeName.toLowerCase() === nodeName); const token = sameTagSiblings.indexOf(element) === 0 ? CSS.escape(nodeName) : `${CSS.escape(nodeName)}:nth-child(${1 + siblings.indexOf(element)})`; const selector = uniqueCSSSelector(token); if (selector) return { engine: 'css', selector, score: kFallbackScore }; if (!bestTokenForLevel) bestTokenForLevel = token; } else if (!bestTokenForLevel) { bestTokenForLevel = nodeName; } tokens.unshift(bestTokenForLevel); } return { engine: 'css', selector: uniqueCSSSelector()!, score: kFallbackScore }; } function escapeForRegex(text: string): string { return text.replace(/[.*+?^>${}()|[\]\\]/g, '\\$&'); } function quoteString(text: string): string { return `"${CSS.escape(text)}"`; } function joinTokens(tokens: SelectorToken[]): string { const parts = []; let lastEngine = ''; for (const { engine, selector } of tokens) { if (parts.length && (lastEngine !== 'css' || engine !== 'css' || selector.startsWith(':nth-match('))) parts.push('>>'); lastEngine = engine; if (engine === 'css') parts.push(selector); else parts.push(`${engine}=${selector}`); } return parts.join(' '); } function combineScores(tokens: SelectorToken[]): number { let score = 0; for (let i = 0; i < tokens.length; i++) score += tokens[i].score * (tokens.length - i); return score; } function chooseFirstSelector(injectedScript: InjectedScript, scope: Element | Document, targetElement: Element, selectors: SelectorToken[][], allowNthMatch: boolean): SelectorToken[] | null { const joined = selectors.map(tokens => ({ tokens, score: combineScores(tokens) })); joined.sort((a, b) => a.score - b.score); let bestWithIndex: SelectorToken[] | null = null; for (const { tokens } of joined) { const parsedSelector = injectedScript.parseSelector(joinTokens(tokens)); const result = injectedScript.querySelectorAll(parsedSelector, scope); const index = result.indexOf(targetElement); if (index === 0) { // We are the first match - found the best selector. return tokens; } // Otherwise, perhaps we can get nth-match? if (!allowNthMatch || bestWithIndex || index === -1 || result.length > 5) continue; // To use nth-match, we must convert everything to css. const allCss = tokens.map(token => { if (token.engine !== 'text') return token; if (token.selector.startsWith('/') && token.selector.endsWith('/')) return { engine: 'css', selector: `:text-matches("${token.selector.substring(1, token.selector.length - 1)}")`, score: token.score }; return { engine: 'css', selector: `:text("${token.selector}")`, score: token.score }; }); const combined = joinTokens(allCss); bestWithIndex = [{ engine: 'css', selector: `:nth-match(${combined}, ${index + 1})`, score: combineScores(allCss) + 1000 }]; } return bestWithIndex; } function isGuidLike(id: string): boolean { let lastCharacterType: 'lower' | 'upper' | 'digit' | 'other' | undefined; let transitionCount = 0; for (let i = 0; i < id.length; ++i) { const c = id[i]; let characterType: 'lower' | 'upper' | 'digit' | 'other'; if (c === '-' || c === '_') continue; if (c >= 'a' && c <= 'z') characterType = 'lower'; else if (c >= 'A' && c <= 'Z') characterType = 'upper'; else if (c >= '0' && c <= '9') characterType = 'digit'; else characterType = 'other'; if (characterType === 'lower' && lastCharacterType === 'upper') { lastCharacterType = characterType; continue; } if (lastCharacterType && lastCharacterType !== characterType) ++transitionCount; lastCharacterType = characterType; } return transitionCount >= id.length / 4; }
the_stack
import { Component, ComponentInterface, Element, Event, EventEmitter, h, Host, Listen, Method, Prop, State, Watch, } from '@stencil/core'; import { SuperTabsConfig } from '../interface'; import { checkGesture, debugLog, getNormalizedScrollX, pointerCoord, scrollEl, STCoord } from '../utils'; @Component({ tag: 'super-tabs-toolbar', styleUrl: 'super-tabs-toolbar.component.scss', shadow: true, }) export class SuperTabsToolbarComponent implements ComponentInterface { @Element() el!: HTMLSuperTabsToolbarElement; /** @internal */ @Prop({ mutable: true }) config?: SuperTabsConfig; /** * Whether to show the indicator. Defaults to `true` */ @Prop() showIndicator: boolean = true; /** * Background color. Defaults to `'primary'` */ @Prop() color: string | undefined = 'primary'; /** * Whether the toolbar is scrollable. Defaults to `false`. */ @Prop({ reflectToAttr: true }) scrollable: boolean = false; /** * If scrollable is set to true, there will be an added padding * to the left of the buttons. * * Setting this property to false will remove that padding. * * The padding is also configurable via a CSS variable. */ @Prop({ reflectToAttr: true }) scrollablePadding: boolean = true; /** * Emits an event when a button is clicked * Event data contains the clicked SuperTabButton component */ @Event() buttonClick!: EventEmitter<HTMLSuperTabButtonElement>; @State() buttons: HTMLSuperTabButtonElement[] = []; width!: number; offsetLeft!: number; /** * Current indicator position. * This value is undefined until the component is fully initialized. * @private */ private indicatorPosition: number | undefined; /** * Current indicator width. * This value is undefined until the component is fully initialized. * @private */ private indicatorWidth: number | undefined; /** * Reference to the current active button * @private */ private activeButton?: HTMLSuperTabButtonElement; private activeTabIndex: number = 0; private indicatorEl: HTMLSuperTabIndicatorElement | undefined; private buttonsContainerEl: HTMLDivElement | undefined; private initialCoords?: STCoord; private lastPosX: number | undefined; private touchStartTs: number = 0; private lastClickTs: number = 0; private isDragging: boolean | undefined; private leftThreshold: number = 0; private rightThreshold: number = 0; private slot!: HTMLSlotElement; private hostCls: any = {}; async componentDidLoad() { this.setHostCls(); await this.queryButtons(); this.slot = this.el.shadowRoot!.querySelector('slot') as HTMLSlotElement; this.slot.addEventListener('slotchange', this.onSlotChange.bind(this)); this.updateWidth(); requestAnimationFrame(() => { this.setActiveTab(this.activeTabIndex, true, false); }); } componentWillUpdate() { this.debug('componentWillUpdate'); this.updateThresholds(); } componentDidRender() { this.updateWidth(); } private updateWidth() { const cr = this.el.getBoundingClientRect(); this.width = Math.round(cr.width * 100) / 100; this.offsetLeft = cr.left; } /** @internal */ @Method() setActiveTab(index: number, align?: boolean, animate?: boolean): Promise<void> { index = Math.max(0, Math.min(Math.round(index), this.buttons.length - 1)); this.debug('setActiveTab', index, align, animate); this.activeTabIndex = index; this.markButtonActive(this.buttons[index]); if (align) { this.alignIndicator(index, animate); } return Promise.resolve(); } /** @internal */ @Method() setSelectedTab(index: number, animate?: boolean): Promise<void> { this.alignIndicator(index, animate); return Promise.resolve(); } /** @internal */ @Method() moveContainer(scrollX: number, animate?: boolean): Promise<void> { if (!this.buttonsContainerEl) { this.debug('moveContainer called before this.buttonsContainerEl was defined'); return Promise.resolve(); } scrollEl(this.buttonsContainerEl, scrollX, this.config!.nativeSmoothScroll!, animate ? this.config!.transitionDuration : 0); return Promise.resolve(); } private getButtonFromEv(ev: any): HTMLSuperTabButtonElement | undefined { let button: HTMLSuperTabButtonElement = ev.target; const tag = button.tagName.toLowerCase(); if (tag !== 'super-tab-button') { if (tag === 'super-tabs-toolbar') { return; } button = button.closest('super-tab-button') as HTMLSuperTabButtonElement; } return button; } @Listen('click') onClick(ev: any) { if (!ev || !ev.target) { this.debug('Got a click event with no target!', ev); return; } if (Date.now() - this.touchStartTs <= 150) { return; } const button = this.getButtonFromEv(ev); if (!button) { return; } this.onButtonClick(button); } private onButtonClick(button: HTMLSuperTabButtonElement) { this.lastClickTs = Date.now(); this.setActiveTab(button.index as number, true, true); this.buttonClick.emit(button); } @Listen('touchstart') async onTouchStart(ev: TouchEvent) { if (!this.scrollable) { return; } this.debug('onTouchStart', ev); const coords = pointerCoord(ev); const vw = this.width; if (coords.x < this.leftThreshold || coords.x > vw - this.rightThreshold) { // ignore this gesture, it started in the side menu touch zone return; } this.touchStartTs = Date.now(); this.initialCoords = coords; this.lastPosX = coords.x; } @Listen('touchmove', { passive: true, capture: true }) async onTouchMove(ev: TouchEvent) { if (!this.buttonsContainerEl || !this.scrollable || !this.initialCoords || typeof this.lastPosX !== 'number') { return; } const coords = pointerCoord(ev); if (!this.isDragging) { const shouldCapture = checkGesture(coords, this.initialCoords!, this.config!); if (!shouldCapture) { if (Math.abs(coords.y - this.initialCoords.y) > 100) { this.initialCoords = void 0; this.lastPosX = void 0; } return; } // gesture is good, let's capture all next onTouchMove events this.isDragging = true; } if (!this.isDragging) { return; } ev.stopImmediatePropagation(); // get delta X const deltaX: number = this.lastPosX - coords.x; if (deltaX === 0) { return; } // update last X value this.lastPosX = coords.x; requestAnimationFrame(() => { if (!this.isDragging) { // when swiping fast; this might run after we're already done scrolling // which leads to "choppy" animations since this instantly scrolls to location return; } // scroll container const scrollX = getNormalizedScrollX(this.buttonsContainerEl!, this.buttonsContainerEl!.clientWidth, deltaX); if (scrollX === this.buttonsContainerEl!.scrollLeft) { return; } this.buttonsContainerEl!.scroll(scrollX, 0); }); } @Listen('touchend', { passive: false, capture: true }) async onTouchEnd(ev: TouchEvent) { if (this.lastClickTs < this.touchStartTs && Date.now() - this.touchStartTs <= 150) { const coords = pointerCoord(ev); if (Math.abs(coords.x - this.initialCoords?.x!) < this.config?.dragThreshold!) { const button = this.getButtonFromEv(ev); if (!button) { return; } this.onButtonClick(button); } } this.isDragging = false; this.initialCoords = void 0; this.lastPosX = void 0; } @Watch('color') async onColorUpdate() { this.setHostCls(); } private setHostCls() { const cls: any = {}; if (typeof this.color === 'string' && this.color.trim().length > 0) { cls['ion-color-' + this.color.trim()] = true; } this.hostCls = cls; } private async onSlotChange() { this.debug('onSlotChange'); this.updateWidth(); await this.queryButtons(); await this.setActiveTab(this.activeTabIndex, true); } private async queryButtons() { this.debug('Querying buttons'); const buttons = Array.from(this.el.querySelectorAll('super-tab-button')); await Promise.all(buttons.map(b => b.componentOnReady())); if (buttons) { for (let i = 0; i < buttons.length; i++) { const button = buttons[i]; button.index = i; button.scrollableContainer = this.scrollable; button.active = this.activeTabIndex === i; if (button.active) { this.activeButton = button; } } } this.buttons = buttons; } private updateThresholds() { if (!this.config) { return; } if (this.config!.sideMenu === 'both' || this.config!.sideMenu === 'left') { this.leftThreshold = this.config!.sideMenuThreshold!; } if (this.config!.sideMenu === 'both' || this.config!.sideMenu === 'right') { this.rightThreshold = this.config!.sideMenuThreshold!; } } private markButtonActive(button: HTMLSuperTabButtonElement) { if (!button) { this.debug('markButtonActive', 'button was undefined!'); return; } if (this.activeButton) { this.activeButton.active = false; } button.active = true; this.activeButton = button; } private setButtonsContainerEl(el: HTMLDivElement) { if (el) { this.buttonsContainerEl = el; } } private adjustContainerScroll(animate: boolean) { if (!this.buttonsContainerEl) { this.debug('adjustContainerScroll called before this.buttonsContainerEl was defined'); return; } let pos: number; const ip = this.indicatorPosition!; const iw = this.indicatorWidth!; const mw = this.buttonsContainerEl.clientWidth; const sp = this.buttonsContainerEl.scrollLeft; const centerDelta = ((mw / 2 - iw / 2)); const a = Math.floor((ip + iw + centerDelta)); const b = Math.floor((ip - centerDelta)); const c = Math.floor((mw + sp)); if (a > c) { // we need to move the segment container to the left pos = ip + iw + centerDelta - mw; } else if (b < sp) { // we need to move the segment container to the right pos = Math.max(ip - centerDelta, 0); pos = pos > ip ? ip - mw + iw : pos; } else { return; } if (!animate) { scrollEl(this.buttonsContainerEl, pos!, false, 50); } else { this.moveContainer(pos!, animate); } } /** * Align the indicator with the selected button. * This will adjust the width and the position of the indicator element. * @param index {number} the active tab index * @param [animate] {boolean=false} whether to animate the transition */ private async alignIndicator(index: number, animate: boolean = false) { if (!this.showIndicator || !this.indicatorEl) { return; } this.debug('Aligning indicator', index); const remainder = index % 1; const isDragging = this.isDragging = remainder > 0; const floor = Math.floor(index), ceil = Math.ceil(index); const button = this.buttons[floor]; if (!button) { return; } let position = button.offsetLeft; let width = button.clientWidth; if (isDragging && floor !== ceil) { const buttonB = this.buttons[ceil]; if (!buttonB) { // the scroll position we received is higher than the max possible position // this could happen due to bad CSS (by developer or this module) // or bad scrolling logic? return; } const buttonBPosition = buttonB.offsetLeft; const buttonBWidth = buttonB.clientWidth; position += remainder * (buttonBPosition - position); width += remainder * (buttonBWidth - width); } requestAnimationFrame(() => { this.indicatorPosition = position; this.indicatorWidth = width; if (this.scrollable) { this.adjustContainerScroll(animate || !isDragging); } this.indicatorEl!.style.setProperty('--st-indicator-position-x', this.indicatorPosition + 'px'); this.indicatorEl!.style.setProperty('--st-indicator-scale-x', String(this.indicatorWidth! / 100)); this.indicatorEl!.style.setProperty('--st-indicator-transition-duration', this.isDragging ? '0' : `${this.config!.transitionDuration}ms`); }); } /** * Internal method to output values in debug mode. */ private debug(...vals: any[]) { debugLog(this.config!, 'toolbar', vals); } render() { return ( <Host role="navigation" class={this.hostCls}> <div class="buttons-container" ref={(ref: any) => this.setButtonsContainerEl(ref)}> <slot/> {this.showIndicator && <super-tab-indicator ref={(ref: any) => this.indicatorEl = ref} toolbarPosition={this.el!.assignedSlot!.name as any}/>} </div> </Host> ); } }
the_stack
import { Modal, Tag, Typography, Button, message } from 'antd'; import React, { useState } from 'react'; import { Link } from 'react-router-dom'; import styled from 'styled-components'; import { BookOutlined, PlusOutlined } from '@ant-design/icons'; import { useEntityRegistry } from '../../useEntityRegistry'; import { Domain, EntityType, GlobalTags, GlossaryTerms, SubResourceType } from '../../../types.generated'; import { StyledTag } from '../../entity/shared/components/styled/StyledTag'; import { EMPTY_MESSAGES, ANTD_GRAY } from '../../entity/shared/constants'; import { useRemoveTagMutation, useRemoveTermMutation } from '../../../graphql/mutations.generated'; import { DomainLink } from './DomainLink'; import { TagProfileDrawer } from './TagProfileDrawer'; import AddTagsTermsModal from './AddTagsTermsModal'; type Props = { uneditableTags?: GlobalTags | null; editableTags?: GlobalTags | null; editableGlossaryTerms?: GlossaryTerms | null; uneditableGlossaryTerms?: GlossaryTerms | null; domain?: Domain | null; canRemove?: boolean; canAddTag?: boolean; canAddTerm?: boolean; showEmptyMessage?: boolean; buttonProps?: Record<string, unknown>; onOpenModal?: () => void; maxShow?: number; entityUrn?: string; entityType?: EntityType; entitySubresource?: string; refetch?: () => Promise<any>; }; const TermLink = styled(Link)` display: inline-block; margin-bottom: 8px; `; const TagLink = styled.span` display: inline-block; margin-bottom: 8px; `; const NoElementButton = styled(Button)` :not(:last-child) { margin-right: 8px; } `; const TagText = styled.span` color: ${ANTD_GRAY[7]}; margin: 0 7px 0 0; `; export default function TagTermGroup({ uneditableTags, editableTags, canRemove, canAddTag, canAddTerm, showEmptyMessage, buttonProps, onOpenModal, maxShow, uneditableGlossaryTerms, editableGlossaryTerms, domain, entityUrn, entityType, entitySubresource, refetch, }: Props) { const entityRegistry = useEntityRegistry(); const [showAddModal, setShowAddModal] = useState(false); const [addModalType, setAddModalType] = useState(EntityType.Tag); const tagsEmpty = !editableTags?.tags?.length && !uneditableTags?.tags?.length && !editableGlossaryTerms?.terms?.length && !uneditableGlossaryTerms?.terms?.length; const [removeTagMutation] = useRemoveTagMutation(); const [removeTermMutation] = useRemoveTermMutation(); const [tagProfileDrawerVisible, setTagProfileDrawerVisible] = useState(false); const [addTagUrn, setAddTagUrn] = useState(''); const removeTag = (urnToRemove: string) => { onOpenModal?.(); const tagToRemove = editableTags?.tags?.find((tag) => tag.tag.urn === urnToRemove); Modal.confirm({ title: `Do you want to remove ${tagToRemove?.tag.name} tag?`, content: `Are you sure you want to remove the ${tagToRemove?.tag.name} tag?`, onOk() { if (entityUrn) { removeTagMutation({ variables: { input: { tagUrn: urnToRemove, resourceUrn: entityUrn, subResource: entitySubresource, subResourceType: entitySubresource ? SubResourceType.DatasetField : null, }, }, }) .then(({ errors }) => { if (!errors) { message.success({ content: 'Removed Tag!', duration: 2 }); } }) .then(refetch) .catch((e) => { message.destroy(); message.error({ content: `Failed to remove tag: \n ${e.message || ''}`, duration: 3 }); }); } }, onCancel() {}, okText: 'Yes', maskClosable: true, closable: true, }); }; const removeTerm = (urnToRemove: string) => { onOpenModal?.(); const termToRemove = editableGlossaryTerms?.terms?.find((term) => term.term.urn === urnToRemove); const termName = termToRemove && entityRegistry.getDisplayName(termToRemove.term.type, termToRemove.term); Modal.confirm({ title: `Do you want to remove ${termName} term?`, content: `Are you sure you want to remove the ${termName} term?`, onOk() { if (entityUrn) { removeTermMutation({ variables: { input: { termUrn: urnToRemove, resourceUrn: entityUrn, subResource: entitySubresource, subResourceType: entitySubresource ? SubResourceType.DatasetField : null, }, }, }) .then(({ errors }) => { if (!errors) { message.success({ content: 'Removed Term!', duration: 2 }); } }) .then(refetch) .catch((e) => { message.destroy(); message.error({ content: `Failed to remove term: \n ${e.message || ''}`, duration: 3 }); }); } }, onCancel() {}, okText: 'Yes', maskClosable: true, closable: true, }); }; let renderedTags = 0; const showTagProfileDrawer = (urn: string) => { setTagProfileDrawerVisible(true); setAddTagUrn(urn); }; const closeTagProfileDrawer = () => { setTagProfileDrawerVisible(false); }; return ( <> {domain && ( <DomainLink urn={domain.urn} name={entityRegistry.getDisplayName(EntityType.Domain, domain) || ''} /> )} {uneditableGlossaryTerms?.terms?.map((term) => { renderedTags += 1; if (maxShow && renderedTags === maxShow + 1) return ( <TagText> {uneditableGlossaryTerms?.terms ? `+${uneditableGlossaryTerms?.terms?.length - maxShow}` : null} </TagText> ); if (maxShow && renderedTags > maxShow) return null; return ( <TermLink to={entityRegistry.getEntityUrl(EntityType.GlossaryTerm, term.term.urn)} key={term.term.urn} > <Tag closable={false}> <BookOutlined style={{ marginRight: '3%' }} /> {entityRegistry.getDisplayName(EntityType.GlossaryTerm, term.term)} </Tag> </TermLink> ); })} {editableGlossaryTerms?.terms?.map((term) => ( <TermLink to={entityRegistry.getEntityUrl(EntityType.GlossaryTerm, term.term.urn)} key={term.term.urn}> <Tag closable={canRemove} onClose={(e) => { e.preventDefault(); removeTerm(term.term.urn); }} > <BookOutlined style={{ marginRight: '3%' }} /> {entityRegistry.getDisplayName(EntityType.GlossaryTerm, term.term)} </Tag> </TermLink> ))} {/* uneditable tags are provided by ingestion pipelines exclusively */} {uneditableTags?.tags?.map((tag) => { renderedTags += 1; if (maxShow && renderedTags === maxShow + 1) return ( <TagText>{uneditableTags?.tags ? `+${uneditableTags?.tags?.length - maxShow}` : null}</TagText> ); if (maxShow && renderedTags > maxShow) return null; return ( <TagLink key={tag?.tag?.urn}> <StyledTag onClick={() => showTagProfileDrawer(tag?.tag?.urn)} $colorHash={tag?.tag?.urn} $color={tag?.tag?.properties?.colorHex} closable={false} > {entityRegistry.getDisplayName(EntityType.Tag, tag.tag)} </StyledTag> </TagLink> ); })} {/* editable tags may be provided by ingestion pipelines or the UI */} {editableTags?.tags?.map((tag) => { renderedTags += 1; if (maxShow && renderedTags > maxShow) return null; return ( <TagLink> <StyledTag style={{ cursor: 'pointer' }} onClick={() => showTagProfileDrawer(tag?.tag?.urn)} $colorHash={tag?.tag?.urn} $color={tag?.tag?.properties?.colorHex} closable={canRemove} onClose={(e) => { e.preventDefault(); removeTag(tag?.tag?.urn); }} > {tag?.tag?.name} </StyledTag> </TagLink> ); })} {tagProfileDrawerVisible && ( <TagProfileDrawer closeTagProfileDrawer={closeTagProfileDrawer} tagProfileDrawerVisible={tagProfileDrawerVisible} urn={addTagUrn} /> )} {showEmptyMessage && canAddTag && tagsEmpty && ( <Typography.Paragraph type="secondary"> {EMPTY_MESSAGES.tags.title}. {EMPTY_MESSAGES.tags.description} </Typography.Paragraph> )} {showEmptyMessage && canAddTerm && tagsEmpty && ( <Typography.Paragraph type="secondary"> {EMPTY_MESSAGES.terms.title}. {EMPTY_MESSAGES.terms.description} </Typography.Paragraph> )} {canAddTag && (uneditableTags?.tags?.length || 0) + (editableTags?.tags?.length || 0) < 10 && ( <NoElementButton type={showEmptyMessage && tagsEmpty ? 'default' : 'text'} onClick={() => { setAddModalType(EntityType.Tag); setShowAddModal(true); }} {...buttonProps} > <PlusOutlined /> <span>Add Tags</span> </NoElementButton> )} {canAddTerm && (uneditableGlossaryTerms?.terms?.length || 0) + (editableGlossaryTerms?.terms?.length || 0) < 10 && ( <NoElementButton type={showEmptyMessage && tagsEmpty ? 'default' : 'text'} onClick={() => { setAddModalType(EntityType.GlossaryTerm); setShowAddModal(true); }} {...buttonProps} > <PlusOutlined /> <span>Add Terms</span> </NoElementButton> )} {showAddModal && !!entityUrn && !!entityType && ( <AddTagsTermsModal type={addModalType} visible onCloseModal={() => { onOpenModal?.(); setShowAddModal(false); refetch?.(); }} entityUrn={entityUrn} entityType={entityType} entitySubresource={entitySubresource} /> )} </> ); }
the_stack
import { AwaitTransactionSuccessOpts, EncoderOverrides, ContractFunctionObj, ContractTxFunctionObj, SendTransactionOpts, BaseContract, PromiseWithTransactionHash, methodAbiToFunctionSignature, linkLibrariesInBytecode, } from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, BlockParamLiteral, BlockRange, CallData, ContractAbi, ContractArtifact, DecodedLogArgs, MethodAbi, TransactionReceiptWithDecodedLogs, TxData, TxDataPayable, TxAccessListWithGas, SupportedProvider, } from 'ethereum-types'; import { AbiEncoder, BigNumber, classUtils, EncodingRules, hexUtils, logUtils, providerUtils } from '@0x/utils'; import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; // tslint:enable:no-unused-variable /* istanbul ignore next */ // tslint:disable:array-type // tslint:disable:no-parameter-reassignment // tslint:disable-next-line:class-name export class ILiquidityProviderContract extends BaseContract { /** * @ignore */ public static deployedBytecode: string | undefined; public static contractName = 'ILiquidityProvider'; private readonly _methodABIIndex: { [name: string]: number } = {}; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, supportedProvider: SupportedProvider, txDefaults: Partial<TxData>, logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, ): Promise<ILiquidityProviderContract> { assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema); if (artifact.compilerOutput === undefined) { throw new Error('Compiler output not found in the artifact file'); } const provider = providerUtils.standardizeOrThrow(supportedProvider); const bytecode = artifact.compilerOutput.evm.bytecode.object; const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; if (Object.keys(logDecodeDependencies) !== undefined) { for (const key of Object.keys(logDecodeDependencies)) { logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; } } return ILiquidityProviderContract.deployAsync( bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly, ); } public static async deployWithLibrariesFrom0xArtifactAsync( artifact: ContractArtifact, libraryArtifacts: { [libraryName: string]: ContractArtifact }, supportedProvider: SupportedProvider, txDefaults: Partial<TxData>, logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, ): Promise<ILiquidityProviderContract> { assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema); if (artifact.compilerOutput === undefined) { throw new Error('Compiler output not found in the artifact file'); } const provider = providerUtils.standardizeOrThrow(supportedProvider); const abi = artifact.compilerOutput.abi; const logDecodeDependenciesAbiOnly: { [contractName: string]: ContractAbi } = {}; if (Object.keys(logDecodeDependencies) !== undefined) { for (const key of Object.keys(logDecodeDependencies)) { logDecodeDependenciesAbiOnly[key] = logDecodeDependencies[key].compilerOutput.abi; } } const libraryAddresses = await ILiquidityProviderContract._deployLibrariesAsync( artifact, libraryArtifacts, new Web3Wrapper(provider), txDefaults, ); const bytecode = linkLibrariesInBytecode(artifact, libraryAddresses); return ILiquidityProviderContract.deployAsync( bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly, ); } public static async deployAsync( bytecode: string, abi: ContractAbi, supportedProvider: SupportedProvider, txDefaults: Partial<TxData>, logDecodeDependencies: { [contractName: string]: ContractAbi }, ): Promise<ILiquidityProviderContract> { assert.isHexString('bytecode', bytecode); assert.doesConformToSchema('txDefaults', txDefaults, schemas.txDataSchema); const provider = providerUtils.standardizeOrThrow(supportedProvider); const constructorAbi = BaseContract._lookupConstructorAbi(abi); [] = BaseContract._formatABIDataItemList(constructorAbi.inputs, [], BaseContract._bigNumberToString); const iface = new ethers.utils.Interface(abi); const deployInfo = iface.deployFunction; const txData = deployInfo.encode(bytecode, []); const web3Wrapper = new Web3Wrapper(provider); const txDataWithDefaults = await BaseContract._applyDefaultsToContractTxDataAsync( { data: txData, ...txDefaults, }, web3Wrapper.estimateGasAsync.bind(web3Wrapper), ); const txHash = await web3Wrapper.sendTransactionAsync(txDataWithDefaults); logUtils.log(`transactionHash: ${txHash}`); const txReceipt = await web3Wrapper.awaitTransactionSuccessAsync(txHash); logUtils.log(`ILiquidityProvider successfully deployed at ${txReceipt.contractAddress}`); const contractInstance = new ILiquidityProviderContract( txReceipt.contractAddress as string, provider, txDefaults, logDecodeDependencies, ); contractInstance.constructorArgs = []; return contractInstance; } /** * @returns The contract ABI */ public static ABI(): ContractAbi { const abi = [ { constant: false, inputs: [ { name: 'tokenAddress', type: 'address', }, { name: 'from', type: 'address', }, { name: 'to', type: 'address', }, { name: 'amount', type: 'uint256', }, { name: 'bridgeData', type: 'bytes', }, ], name: 'bridgeTransferFrom', outputs: [ { name: 'success', type: 'bytes4', }, ], payable: false, stateMutability: 'nonpayable', type: 'function', }, { constant: true, inputs: [ { name: 'takerToken', type: 'address', }, { name: 'makerToken', type: 'address', }, { name: 'buyAmount', type: 'uint256', }, ], name: 'getBuyQuote', outputs: [ { name: 'takerTokenAmount', type: 'uint256', }, ], payable: false, stateMutability: 'view', type: 'function', }, { constant: true, inputs: [ { name: 'takerToken', type: 'address', }, { name: 'makerToken', type: 'address', }, { name: 'sellAmount', type: 'uint256', }, ], name: 'getSellQuote', outputs: [ { name: 'makerTokenAmount', type: 'uint256', }, ], payable: false, stateMutability: 'view', type: 'function', }, ] as ContractAbi; return abi; } protected static async _deployLibrariesAsync( artifact: ContractArtifact, libraryArtifacts: { [libraryName: string]: ContractArtifact }, web3Wrapper: Web3Wrapper, txDefaults: Partial<TxData>, libraryAddresses: { [libraryName: string]: string } = {}, ): Promise<{ [libraryName: string]: string }> { const links = artifact.compilerOutput.evm.bytecode.linkReferences; // Go through all linked libraries, recursively deploying them if necessary. for (const link of Object.values(links)) { for (const libraryName of Object.keys(link)) { if (!libraryAddresses[libraryName]) { // Library not yet deployed. const libraryArtifact = libraryArtifacts[libraryName]; if (!libraryArtifact) { throw new Error(`Missing artifact for linked library "${libraryName}"`); } // Deploy any dependent libraries used by this library. await ILiquidityProviderContract._deployLibrariesAsync( libraryArtifact, libraryArtifacts, web3Wrapper, txDefaults, libraryAddresses, ); // Deploy this library. const linkedLibraryBytecode = linkLibrariesInBytecode(libraryArtifact, libraryAddresses); const txDataWithDefaults = await BaseContract._applyDefaultsToContractTxDataAsync( { data: linkedLibraryBytecode, ...txDefaults, }, web3Wrapper.estimateGasAsync.bind(web3Wrapper), ); const txHash = await web3Wrapper.sendTransactionAsync(txDataWithDefaults); logUtils.log(`transactionHash: ${txHash}`); const { contractAddress } = await web3Wrapper.awaitTransactionSuccessAsync(txHash); logUtils.log(`${libraryArtifact.contractName} successfully deployed at ${contractAddress}`); libraryAddresses[libraryArtifact.contractName] = contractAddress as string; } } } return libraryAddresses; } public getFunctionSignature(methodName: string): string { const index = this._methodABIIndex[methodName]; const methodAbi = ILiquidityProviderContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion const functionSignature = methodAbiToFunctionSignature(methodAbi); return functionSignature; } public getABIDecodedTransactionData<T>(methodName: string, callData: string): T { const functionSignature = this.getFunctionSignature(methodName); const self = (this as any) as ILiquidityProviderContract; const abiEncoder = self._lookupAbiEncoder(functionSignature); const abiDecodedCallData = abiEncoder.strictDecode<T>(callData); return abiDecodedCallData; } public getABIDecodedReturnData<T>(methodName: string, callData: string): T { if (this._encoderOverrides.decodeOutput) { return this._encoderOverrides.decodeOutput(methodName, callData); } const functionSignature = this.getFunctionSignature(methodName); const self = (this as any) as ILiquidityProviderContract; const abiEncoder = self._lookupAbiEncoder(functionSignature); const abiDecodedCallData = abiEncoder.strictDecodeReturnValue<T>(callData); return abiDecodedCallData; } public getSelector(methodName: string): string { const functionSignature = this.getFunctionSignature(methodName); const self = (this as any) as ILiquidityProviderContract; const abiEncoder = self._lookupAbiEncoder(functionSignature); return abiEncoder.getSelector(); } /** * Transfers `amount` of the ERC20 `tokenAddress` from `from` to `to`. * @param tokenAddress The address of the ERC20 token to transfer. * @param from Address to transfer asset from. * @param to Address to transfer asset to. * @param amount Amount of asset to transfer. * @param bridgeData Arbitrary asset data needed by the bridge contract. * @returns success The magic bytes &#x60;0xdc1600f3&#x60; if successful. */ public bridgeTransferFrom( tokenAddress: string, from: string, to: string, amount: BigNumber, bridgeData: string, ): ContractTxFunctionObj<string> { const self = (this as any) as ILiquidityProviderContract; assert.isString('tokenAddress', tokenAddress); assert.isString('from', from); assert.isString('to', to); assert.isBigNumber('amount', amount); assert.isString('bridgeData', bridgeData); const functionSignature = 'bridgeTransferFrom(address,address,address,uint256,bytes)'; return { async sendTransactionAsync( txData?: Partial<TxData> | undefined, opts: SendTransactionOpts = { shouldValidate: true }, ): Promise<string> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync( { data: this.getABIEncodedTransactionData(), ...txData }, this.estimateGasAsync.bind(this), ); if (opts.shouldValidate !== false) { await this.callAsync(txDataWithDefaults); } return self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); }, awaitTransactionSuccessAsync( txData?: Partial<TxData>, opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, ): PromiseWithTransactionHash<TransactionReceiptWithDecodedLogs> { return self._promiseWithTransactionHash(this.sendTransactionAsync(txData, opts), opts); }, async estimateGasAsync(txData?: Partial<TxData> | undefined): Promise<number> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({ data: this.getABIEncodedTransactionData(), ...txData, }); return self._web3Wrapper.estimateGasAsync(txDataWithDefaults); }, async createAccessListAsync( txData?: Partial<TxData> | undefined, defaultBlock?: BlockParam, ): Promise<TxAccessListWithGas> { const txDataWithDefaults = await self._applyDefaultsToTxDataAsync({ data: this.getABIEncodedTransactionData(), ...txData, }); return self._web3Wrapper.createAccessListAsync(txDataWithDefaults, defaultBlock); }, async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<string> { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { data: this.getABIEncodedTransactionData(), ...callData }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); return abiEncoder.strictDecodeReturnValue<string>(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, [ tokenAddress.toLowerCase(), from.toLowerCase(), to.toLowerCase(), amount, bridgeData, ]); }, }; } /** * Quotes the amount of `takerToken` that would need to be sold in * order to obtain `buyAmount` of `makerToken`. * @param takerToken Address of the taker token (what to sell). * @param makerToken Address of the maker token (what to buy). * @param buyAmount Amount of `makerToken` to buy. * @returns takerTokenAmount Amount of &#x60;takerToken&#x60; that would need to be sold. */ public getBuyQuote(takerToken: string, makerToken: string, buyAmount: BigNumber): ContractFunctionObj<BigNumber> { const self = (this as any) as ILiquidityProviderContract; assert.isString('takerToken', takerToken); assert.isString('makerToken', makerToken); assert.isBigNumber('buyAmount', buyAmount); const functionSignature = 'getBuyQuote(address,address,uint256)'; return { async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<BigNumber> { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { data: this.getABIEncodedTransactionData(), ...callData }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); return abiEncoder.strictDecodeReturnValue<BigNumber>(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, [ takerToken.toLowerCase(), makerToken.toLowerCase(), buyAmount, ]); }, }; } /** * Quotes the amount of `makerToken` that would be obtained by * selling `sellAmount` of `takerToken`. * @param takerToken Address of the taker token (what to sell). * @param makerToken Address of the maker token (what to buy). * @param sellAmount Amount of `takerToken` to sell. * @returns makerTokenAmount Amount of &#x60;makerToken&#x60; that would be obtained. */ public getSellQuote(takerToken: string, makerToken: string, sellAmount: BigNumber): ContractFunctionObj<BigNumber> { const self = (this as any) as ILiquidityProviderContract; assert.isString('takerToken', takerToken); assert.isString('makerToken', makerToken); assert.isBigNumber('sellAmount', sellAmount); const functionSignature = 'getSellQuote(address,address,uint256)'; return { async callAsync(callData: Partial<CallData> = {}, defaultBlock?: BlockParam): Promise<BigNumber> { BaseContract._assertCallParams(callData, defaultBlock); const rawCallResult = await self._performCallAsync( { data: this.getABIEncodedTransactionData(), ...callData }, defaultBlock, ); const abiEncoder = self._lookupAbiEncoder(functionSignature); BaseContract._throwIfUnexpectedEmptyCallResult(rawCallResult, abiEncoder); return abiEncoder.strictDecodeReturnValue<BigNumber>(rawCallResult); }, getABIEncodedTransactionData(): string { return self._strictEncodeArguments(functionSignature, [ takerToken.toLowerCase(), makerToken.toLowerCase(), sellAmount, ]); }, }; } constructor( address: string, supportedProvider: SupportedProvider, txDefaults?: Partial<TxData>, logDecodeDependencies?: { [contractName: string]: ContractAbi }, deployedBytecode: string | undefined = ILiquidityProviderContract.deployedBytecode, encoderOverrides?: Partial<EncoderOverrides>, ) { super( 'ILiquidityProvider', ILiquidityProviderContract.ABI(), address, supportedProvider, txDefaults, logDecodeDependencies, deployedBytecode, encoderOverrides, ); classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); ILiquidityProviderContract.ABI().forEach((item, index) => { if (item.type === 'function') { const methodAbi = item as MethodAbi; this._methodABIIndex[methodAbi.name] = index; } }); } } // tslint:disable:max-file-line-count // tslint:enable:no-unbound-method no-parameter-reassignment no-consecutive-blank-lines ordered-imports align // tslint:enable:trailing-comma whitespace no-trailing-whitespace
the_stack
/*global Observer*/ interface RequestFn { (src: string, responseCallback, callContext: RequestHandlerCallContext) : void; }; interface RequestOwner { request: RequestFn; }; interface RequestOnLoadCB { (asset: any, status: number, callContext: RequestHandlerCallContext): void; } interface RequestHandlerResponseFilter { (callContext: RequestHandlerCallContext, makeRequest: { (): void; }, responseAsset: string, status: number): boolean; }; interface RequestHandlerCallContext { onload : RequestOnLoadCB; src : string; requestFn? : RequestFn; requestOwner? : RequestOwner; responseFilter? : RequestHandlerResponseFilter; } interface RequestHandlerHandlers { eventOnload: any[]; [index: string]: any[]; } class RequestHandler { initialRetryTime: number; notifyTime: number; maxRetryTime: number; notifiedConnectionLost: boolean; connected: boolean; reconnectedObserver: Observer; reconnectTest: any; connectionLostTime: number; destroyed: boolean; onReconnected: { (reason: number, reconnectTest: any): void; }; onRequestTimeout: { (reason: number, callContext: RequestHandlerCallContext): void; }; handlers: RequestHandlerHandlers; responseFilter: { (callContext: RequestHandlerCallContext, makeRequest: { (): void; }, responseAsset: any, status: number): void; }; reasonConnectionLost = 0; reasonServiceBusy = 1; retryExponential(callContext, requestFn, status) { if (!this.notifiedConnectionLost && TurbulenzEngine.time - this.connectionLostTime > (this.notifyTime * 0.001)) { this.notifiedConnectionLost = true; var reason; if (status === 0) { reason = this.reasonConnectionLost; } else { reason = this.reasonServiceBusy; } callContext.reason = reason; this.onRequestTimeout(reason, callContext); } // only the first request with a lost connection continues // all following requests wait for a reconnection if (this.connected) { this.connectionLostTime = TurbulenzEngine.time; this.notifiedConnectionLost = false; this.connected = false; this.reconnectTest = callContext; callContext.status = status; } else if (this.reconnectTest !== callContext) { var reconnectedObserver = this.reconnectedObserver; var onReconnected = function onReconnectedFn() { reconnectedObserver.unsubscribe(onReconnected); requestFn(); }; reconnectedObserver.subscribe(onReconnected); return; } if (callContext.expTime) { callContext.expTime = 2 * callContext.expTime; if (callContext.expTime > this.maxRetryTime) { callContext.expTime = this.maxRetryTime; } } else { callContext.expTime = this.initialRetryTime; } if (callContext.retries) { callContext.retries += 1; } else { callContext.retries = 1; } TurbulenzEngine.setTimeout(requestFn, callContext.expTime); } retryAfter(callContext, retryAfter, requestFn, status) { if (callContext.retries) { callContext.retries += 1; } else { callContext.firstRetry = TurbulenzEngine.time; callContext.retries = 1; } if (!callContext.notifiedMaxRetries && TurbulenzEngine.time - callContext.firstRetry + retryAfter > this.notifyTime) { callContext.notifiedMaxRetries = true; var reason = this.reasonServiceBusy; callContext.reason = reason; this.onRequestTimeout(reason, callContext); } TurbulenzEngine.setTimeout(requestFn, retryAfter * 1000); } request(callContext: RequestHandlerCallContext) { var makeRequest; var that = this; var responseCallback = function responseCallbackFn(responseAsset, status) { if (that.destroyed) { return; } var sendEventToHandlers = that.sendEventToHandlers; var handlers = that.handlers; // 0 Connection Lost // 408 Request Timeout // 429 Too Many Requests // 480 Temporarily Unavailable // 504 Gateway timeout if (status === 0 || status === 408 || status === 429 || status === 480 || status === 504) { that.retryExponential(callContext, makeRequest, status); return; } if (!that.connected) { // Reconnected! that.connected = true; if (that.reconnectTest === callContext && that.notifiedConnectionLost) { that.onReconnected(that.reconnectTest.reason, that.reconnectTest); } that.reconnectTest = null; that.reconnectedObserver.notify(); } if (callContext.responseFilter && !callContext.responseFilter.call(this, callContext, makeRequest, responseAsset, status)) { return; } if (that.responseFilter && !that.responseFilter(callContext, makeRequest, responseAsset, status)) { return; } if (callContext.onload) { var nameStr; if (responseAsset && responseAsset.name) { nameStr = responseAsset.name; } else { nameStr = callContext.src; } sendEventToHandlers(handlers.eventOnload, {eventType: "eventOnload", name: nameStr}); callContext.onload(responseAsset, status, callContext); callContext.onload = null; } callContext = null; }; makeRequest = function makeRequestFn() { if (that.destroyed) { return; } if (callContext.requestFn) { if (callContext.requestOwner) { callContext.requestFn.call(callContext.requestOwner, callContext.src, responseCallback, callContext); } else { callContext.requestFn(callContext.src, responseCallback, callContext); } } else if (callContext.requestOwner) { callContext.requestOwner.request(callContext.src, responseCallback, callContext); } else { TurbulenzEngine.request(callContext.src, responseCallback); } }; makeRequest(); } addEventListener(eventType, eventListener) { var i; var length; var eventHandlers; if (this.handlers.hasOwnProperty(eventType)) { eventHandlers = this.handlers[eventType]; if (eventListener) { // Check handler is not already stored length = eventHandlers.length; for (i = 0; i < length; i += 1) { if (eventHandlers[i] === eventListener) { // Event handler has already been added return; } } eventHandlers.push(eventListener); } } } removeEventListener(eventType, eventListener) { var i; var length; var eventHandlers; if (this.handlers.hasOwnProperty(eventType)) { eventHandlers = this.handlers[eventType]; if (eventListener) { length = eventHandlers.length; for (i = 0; i < length; i += 1) { if (eventHandlers[i] === eventListener) { eventHandlers.splice(i, 1); break; } } } } } sendEventToHandlers(eventHandlers, arg0) { var i; var length = eventHandlers.length; if (length) { for (i = 0; i < length; i += 1) { eventHandlers[i](arg0); } } } destroy() { this.destroyed = true; this.handlers = null; this.onReconnected = null; this.onRequestTimeout = null; } static create(params: any) { var rh = new RequestHandler(); rh.initialRetryTime = params.initialRetryTime || 0.5 * 1000; rh.notifyTime = params.notifyTime || 4 * 1000; rh.maxRetryTime = params.maxRetryTime || 8 * 1000; rh.notifiedConnectionLost = false; rh.connected = true; rh.reconnectedObserver = Observer.create(); rh.reconnectTest = null; /* tslint:disable:no-empty */ rh.onReconnected = params.onReconnected || function onReconnectedFn() {}; rh.onRequestTimeout = params.onRequestTimeout || function onRequestTimeoutFn(/* callContext */) {}; /* tslint:enable:no-empty */ var handlers = <RequestHandlerHandlers>({ eventOnload: [] }); rh.handlers = handlers; return rh; } }
the_stack
import { fireEvent, render } from '@testing-library/react' import React from 'react' import { Table, XTable } from './table' import { wave } from './ui' const name = 'table', cell11 = 'Quick brown fox.', cell21 = 'Jumps over a dog.', cell31 = 'Wooo hooo.' let tableProps: Table describe('Table.tsx', () => { beforeEach(() => { tableProps = { name, columns: [ { name: 'colname1', label: 'Col1', sortable: true, searchable: true }, { name: 'colname2', label: 'Col2', sortable: true, filterable: true }, ], rows: [ { name: 'rowname1', cells: [cell11, '2'] }, { name: 'rowname2', cells: [cell21, '1'] }, { name: 'rowname3', cells: [cell31, '3'] } ] } jest.clearAllMocks() wave.args[name] = null }) it('Renders data-test attr', () => { const { queryByTestId } = render(<XTable model={tableProps} />) expect(queryByTestId(name)).toBeInTheDocument() }) it('Renders time column correctly', () => { tableProps = { ...tableProps, rows: [{ name: 'rowname1', cells: ['1971-07-08T23:09:33'] }], columns: [{ name: 'colname1', label: 'Col1', sortable: true, searchable: true, data_type: 'time' }] } const { getAllByRole } = render(<XTable model={tableProps} />) expect(getAllByRole('gridcell')[0].textContent).toBe('7/8/1971, 11:09:33 PM') }) describe('Height compute', () => { it('Computes properly for simple table - header, rows', () => { tableProps = { ...tableProps, columns: [ { name: 'colname1', label: 'Col1' }, { name: 'colname2', label: 'Col2' }, ], } const { getByTestId } = render(<XTable model={tableProps} />) expect(getByTestId(name).style.height).toBe('189px') }) it('Computes properly for searchable table - toptoolbar, header, rows, footer', () => { tableProps = { ...tableProps, columns: [ { name: 'colname1', label: 'Col1', searchable: true }, { name: 'colname2', label: 'Col2' }, ], } const { getByTestId } = render(<XTable model={tableProps} />) expect(getByTestId(name).style.height).toBe('293px') }) it('Computes properly for custom progress cell - toptoolbar, header, rows, footer', () => { tableProps = { ...tableProps, columns: [ { name: 'colname1', label: 'Col1', searchable: true }, { name: 'colname2', label: 'Col2', cell_type: { progress: {} } }, ], } const { getByTestId } = render(<XTable model={tableProps} />) expect(getByTestId(name).style.height).toBe('368px') }) it('Computes properly for custom icon cell - toptoolbar, header, rows, footer', () => { tableProps = { ...tableProps, columns: [ { name: 'colname1', label: 'Col1', searchable: true }, { name: 'colname2', label: 'Col2', cell_type: { icon: {} } }, ], rows: [ { name: 'rowname1', cells: [cell11, 'BoxMultiplySolid'] }, { name: 'rowname2', cells: [cell21, 'BoxMultiplySolid'] }, { name: 'rowname3', cells: [cell31, 'BoxMultiplySolid'] } ] } const { getByTestId } = render(<XTable model={tableProps} />) expect(getByTestId(name).style.height).toBe('314px') }) }) describe('Q calls', () => { it('Sets args on init - values not specified', () => { render(<XTable model={tableProps} />) expect(wave.args[name]).toMatchObject([]) }) it('Sets args on init - values specified', () => { render(<XTable model={{ ...tableProps, values: ['rowname1'], multiple: true }} />) expect(wave.args[name]).toMatchObject(['rowname1']) }) it('Sets args and calls sync on doubleclick', () => { const pushMock = jest.fn() wave.push = pushMock const { getAllByRole } = render(<XTable model={tableProps} />) fireEvent.doubleClick(getAllByRole('row')[1]) expect(wave.args[name]).toMatchObject(['rowname1']) expect(pushMock).toHaveBeenCalled() }) it('Sets args and calls sync on first col click', () => { const pushMock = jest.fn() wave.push = pushMock const { getByText } = render(<XTable model={tableProps} />) fireEvent.click(getByText(cell21)) expect(wave.args[name]).toMatchObject(['rowname2']) expect(pushMock).toHaveBeenCalled() }) it('Sets args - multiple selection', () => { const { getAllByRole } = render(<XTable model={{ ...tableProps, multiple: true }} />) const checkboxes = getAllByRole('checkbox') fireEvent.click(checkboxes[1]) fireEvent.click(checkboxes[2]) expect(wave.args[name]).toMatchObject(['rowname1', 'rowname2']) }) it('Clicks a column - link set on second col', () => { tableProps = { ...tableProps, columns: [ { name: 'colname1', label: 'Col1' }, { name: 'colname2', label: 'Col2', link: true }, ] } const pushMock = jest.fn() wave.push = pushMock const { getByText } = render(<XTable model={tableProps} />) fireEvent.click(getByText(cell21)) expect(pushMock).not.toHaveBeenCalled() fireEvent.click(getByText('1')) expect(wave.args[name]).toMatchObject(['rowname2']) expect(pushMock).toHaveBeenCalled() }) }) it('Does not click a column - link exlpicitly turned off', () => { tableProps = { ...tableProps, columns: [ { name: 'colname1', label: 'Col1', link: false }, { name: 'colname2', label: 'Col2' }, ] } const pushMock = jest.fn() wave.push = pushMock const { getByText } = render(<XTable model={tableProps} />) fireEvent.click(getByText(cell21)) expect(pushMock).not.toHaveBeenCalled() expect(wave.args[name]).toMatchObject([]) }) describe('sort', () => { it('Sorts by column - string', () => { const { container, getAllByRole } = render(<XTable model={tableProps} />) expect(getAllByRole('gridcell')[0].textContent).toBe(cell11) fireEvent.click(container.querySelector('i[class*=sortingIcon]')!) expect(getAllByRole('gridcell')[0].textContent).toBe(cell21) fireEvent.click(container.querySelector('i[class*=sortingIcon]')!) expect(getAllByRole('gridcell')[0].textContent).toBe(cell31) }) it('Sorts by column - iso date', () => { const date1 = '1971-07-08T23:09:33', date2 = '1976-11-05T19:12:18', date3 = '2001-03-28T03:09:31' tableProps = { ...tableProps, rows: [ { name: 'rowname1', cells: [date3] }, { name: 'rowname2', cells: [date2] }, { name: 'rowname3', cells: [date1] } ], columns: [{ name: 'colname1', label: 'Col1', sortable: true, searchable: true, data_type: 'time' }] } const { container, getAllByRole } = render(<XTable model={tableProps} />) expect(getAllByRole('gridcell')[0].textContent).toBe('3/28/2001, 3:09:31 AM') fireEvent.click(container.querySelector('i[class*=sortingIcon]')!) expect(getAllByRole('gridcell')[0].textContent).toBe('7/8/1971, 11:09:33 PM') fireEvent.click(container.querySelector('i[class*=sortingIcon]')!) expect(getAllByRole('gridcell')[0].textContent).toBe('3/28/2001, 3:09:31 AM') }) it('Sorts by column and rerenders icon col', () => { const xIcon = 'BoxMultiplySolid', checkIcon = 'BoxCheckmarkSolid' tableProps = { ...tableProps, columns: [ { name: 'colname1', label: 'Col1', sortable: true }, { name: 'colname2', label: 'Col2', cell_type: { icon: {} } }, ], rows: [ { name: 'rowname1', cells: [cell11, xIcon] }, { name: 'rowname2', cells: [cell21, checkIcon] }, { name: 'rowname3', cells: [cell31, xIcon] } ] } const { container, getAllByRole } = render(<XTable model={tableProps} />) expect(getAllByRole('gridcell')[1].querySelector('i')?.getAttribute('data-icon-name')).toBe(xIcon) fireEvent.click(container.querySelector('i[class*=sortingIcon]')!) expect(getAllByRole('gridcell')[1].querySelector('i')?.getAttribute('data-icon-name')).toBe(checkIcon) fireEvent.click(container.querySelector('i[class*=sortingIcon]')!) expect(getAllByRole('gridcell')[1].querySelector('i')?.getAttribute('data-icon-name')).toBe(xIcon) }) it('Sorts by column - number', () => { tableProps = { ...tableProps, rows: [ { name: 'rowname1', cells: ['111'] }, { name: 'rowname2', cells: ['25'] }, { name: 'rowname3', cells: ['9'] } ], columns: [ { name: 'colname1', label: 'Col1', sortable: true, searchable: true, data_type: 'number' }, { name: 'colname2', label: 'Col2', sortable: true, filterable: true, data_type: 'number' }, ], } const { container, getAllByRole } = render(<XTable model={tableProps} />) expect(getAllByRole('gridcell')[0].textContent).toBe('111') fireEvent.click(container.querySelector('i[class*=sortingIcon]')!) expect(getAllByRole('gridcell')[0].textContent).toBe('9') fireEvent.click(container.querySelector('i[class*=sortingIcon]')!) expect(getAllByRole('gridcell')[0].textContent).toBe('111') }) }) describe('search', () => { it('Searches correctly', () => { const { getByTestId, getAllByRole } = render(<XTable model={tableProps} />) // Header row is row as well so expect + 1. expect(getAllByRole('row')).toHaveLength(tableProps.rows.length + 1) fireEvent.change(getByTestId('search'), { target: { value: cell21 } }) expect(getAllByRole('row')).toHaveLength(2) }) it('Searches correctly - no match', () => { const { getByTestId, getAllByRole } = render(<XTable model={tableProps} />) // Header row is row as well so expect + 1. expect(getAllByRole('row')).toHaveLength(tableProps.rows.length + 1) fireEvent.change(getByTestId('search'), { target: { value: 'No match!' } }) expect(getAllByRole('row')).toHaveLength(1) }) it('Searches correctly - clear search', () => { const { getByTestId, getAllByRole } = render(<XTable model={tableProps} />) // Header row is row as well so expect + 1. expect(getAllByRole('row')).toHaveLength(tableProps.rows.length + 1) fireEvent.change(getByTestId('search'), { target: { value: 'No match!' } }) expect(getAllByRole('row')).toHaveLength(1) fireEvent.change(getByTestId('search'), { target: { value: '' } }) expect(getAllByRole('row')).toHaveLength(tableProps.rows.length + 1) }) it('Searches correctly - search uppercase, contain lowercase', () => { const { getByTestId, getAllByRole } = render(<XTable model={tableProps} />) // Header row is row as well so expect + 1. expect(getAllByRole('row')).toHaveLength(tableProps.rows.length + 1) fireEvent.change(getByTestId('search'), { target: { value: cell21.toUpperCase() } }) expect(getAllByRole('row')).toHaveLength(2) }) it('Searches correctly - search lowercase, contain uppercase', () => { const { getByTestId, getAllByRole } = render(<XTable model={tableProps} />) // Header row is row as well so expect + 1. expect(getAllByRole('row')).toHaveLength(tableProps.rows.length + 1) fireEvent.change(getByTestId('search'), { target: { value: cell21.toLowerCase() } }) expect(getAllByRole('row')).toHaveLength(2) }) it('Does not render search when no col is searchable', () => { tableProps = { ...tableProps, columns: [ { name: 'colname1', label: 'col1' }, { name: 'colname2', label: 'col2' }, ] } const { queryByTestId } = render(<XTable model={tableProps} />) expect(queryByTestId('search')).not.toBeInTheDocument() }) }) describe('filter', () => { it('Filters correctly - single option', () => { const { container, getAllByText, getAllByRole } = render(<XTable model={tableProps} />) // Header row is row as well so expect + 1. expect(getAllByRole('row')).toHaveLength(tableProps.rows.length + 1) fireEvent.click(container.querySelector('.ms-DetailsHeader-filterChevron')!) fireEvent.click(getAllByText('1')[1].parentElement!) expect(getAllByRole('row')).toHaveLength(2) }) it('Filters correctly - multiple options', () => { const { container, getAllByText, getAllByRole } = render(<XTable model={tableProps} />) // Header row is row as well so expect + 1. expect(getAllByRole('row')).toHaveLength(tableProps.rows.length + 1) fireEvent.click(container.querySelector('.ms-DetailsHeader-filterChevron')!) fireEvent.click(getAllByText('1')[1].parentElement!) fireEvent.click(getAllByText('2')[0].parentElement!) expect(getAllByRole('row')).toHaveLength(tableProps.rows.length) }) it('Filters correctly - multiple filters', () => { tableProps = { ...tableProps, columns: [ { name: 'colname1', label: 'col1', searchable: true }, { name: 'colname2', label: 'col2', filterable: true }, { name: 'colname3', label: 'col3', filterable: true }, ], rows: [ { name: 'rowname1', cells: [cell11, '2', 'On'] }, { name: 'rowname2', cells: [cell21, '1', 'Off'] }, { name: 'rowname3', cells: [cell31, '3', 'On'] } ] } const { container, getAllByText, getAllByRole } = render(<XTable model={tableProps} />) // Header row is row as well so expect + 1. expect(getAllByRole('row')).toHaveLength(tableProps.rows.length + 1) fireEvent.click(container.querySelector('.ms-DetailsHeader-filterChevron')!) fireEvent.click(getAllByText('1')[1].parentElement!) fireEvent.click(getAllByText('2')[0].parentElement!) expect(getAllByRole('row')).toHaveLength(tableProps.rows.length) }) }) describe('filter & search combination', () => { beforeEach(() => { tableProps = { ...tableProps, columns: [ { name: 'colname1', label: 'col1', searchable: true }, { name: 'colname2', label: 'col2', filterable: true }, ], rows: [ { name: 'rowname1', cells: [cell11, '2'] }, { name: 'rowname2', cells: [cell21, '1'] }, { name: 'rowname3', cells: [cell31, '1'] } ] } }) it('Filter -> search', () => { const { container, getAllByText, getAllByRole, getByTestId } = render(<XTable model={tableProps} />) // Header row is row as well so expect + 1. expect(getAllByRole('row')).toHaveLength(tableProps.rows.length + 1) fireEvent.click(container.querySelector('.ms-DetailsHeader-filterChevron')!) fireEvent.click(getAllByText('1')[2].parentElement!) expect(getAllByRole('row')).toHaveLength(3) fireEvent.change(getByTestId('search'), { target: { value: cell21 } }) expect(getAllByRole('row')).toHaveLength(2) }) it('Filter -> search - no search match', () => { const { container, getAllByText, getAllByRole, getByTestId } = render(<XTable model={tableProps} />) // Header row is row as well so expect + 1. expect(getAllByRole('row')).toHaveLength(tableProps.rows.length + 1) fireEvent.click(container.querySelector('.ms-DetailsHeader-filterChevron')!) fireEvent.click(getAllByText('1')[2].parentElement!) expect(getAllByRole('row')).toHaveLength(3) fireEvent.change(getByTestId('search'), { target: { value: cell11 } }) expect(getAllByRole('row')).toHaveLength(1) }) it('Filter -> search clear', () => { const { container, getAllByText, getAllByRole, getByTestId } = render(<XTable model={tableProps} />) // Header row is row as well so expect + 1. expect(getAllByRole('row')).toHaveLength(tableProps.rows.length + 1) fireEvent.click(container.querySelector('.ms-DetailsHeader-filterChevron')!) fireEvent.click(getAllByText('1')[2].parentElement!) expect(getAllByRole('row')).toHaveLength(3) fireEvent.change(getByTestId('search'), { target: { value: cell21 } }) expect(getAllByRole('row')).toHaveLength(2) fireEvent.change(getByTestId('search'), { target: { value: '' } }) expect(getAllByRole('row')).toHaveLength(3) }) it('Search -> filter', () => { const { container, getAllByText, getAllByRole, getByTestId } = render(<XTable model={tableProps} />) // Header row is row as well so expect + 1. expect(getAllByRole('row')).toHaveLength(tableProps.rows.length + 1) fireEvent.change(getByTestId('search'), { target: { value: 'w' } }) expect(getAllByRole('row')).toHaveLength(3) fireEvent.click(container.querySelector('.ms-DetailsHeader-filterChevron')!) fireEvent.click(getAllByText('1')[1].parentElement!) expect(getAllByRole('row')).toHaveLength(2) }) it('Search -> filter clear', () => { const { container, getAllByText, getAllByRole, getByTestId } = render(<XTable model={tableProps} />) // Header row is row as well so expect + 1. expect(getAllByRole('row')).toHaveLength(tableProps.rows.length + 1) fireEvent.change(getByTestId('search'), { target: { value: 'w' } }) expect(getAllByRole('row')).toHaveLength(3) fireEvent.click(container.querySelector('.ms-DetailsHeader-filterChevron')!) fireEvent.click(getAllByText('1')[1].parentElement!) expect(getAllByRole('row')).toHaveLength(2) fireEvent.click(getAllByText('1')[1].parentElement!) expect(getAllByRole('row')).toHaveLength(3) }) }) describe('Group by', () => { beforeEach(() => { tableProps = { ...tableProps, groupable: true, rows: [ { name: 'rowname1', cells: [cell11, 'Group1'] }, { name: 'rowname2', cells: [cell21, 'Group1'] }, { name: 'rowname3', cells: [cell31, 'Group2'] } ] } }) it('Renders grouped list after selection', () => { const { container, getAllByText, getByTestId } = render(<XTable model={tableProps} />) fireEvent.click(getByTestId('groupby')) fireEvent.click(getAllByText('Col1')[1]!) expect(container.querySelectorAll('.ms-GroupedList-group')).toHaveLength(tableProps.rows.length) }) it('Renders alphabetically sorted group by list - strings', () => { const { container, getAllByText, getByTestId } = render(<XTable model={tableProps} />) fireEvent.click(getByTestId('groupby')) fireEvent.click(getAllByText('Col1')[1]!) const groupHeaders = container.querySelectorAll('.ms-GroupHeader-title') expect(groupHeaders[0]).toHaveTextContent(`${cell21}(1)`) expect(groupHeaders[1]).toHaveTextContent(`${cell11}(1)`) expect(groupHeaders[2]).toHaveTextContent(`${cell31}(1)`) }) it('Renders alphabetically sorted group by list - numbers', () => { tableProps = { ...tableProps, rows: [ { name: 'rowname1', cells: ['2', 'Group1'] }, { name: 'rowname2', cells: ['3', 'Group1'] }, { name: 'rowname3', cells: ['1', 'Group2'] } ] } const { container, getAllByText, getByTestId } = render(<XTable model={tableProps} />) fireEvent.click(getByTestId('groupby')) fireEvent.click(getAllByText('Col1')[1]!) const groupHeaders = container.querySelectorAll('.ms-GroupHeader-title') expect(groupHeaders[0]).toHaveTextContent('1(1)') expect(groupHeaders[1]).toHaveTextContent('2(1)') expect(groupHeaders[2]).toHaveTextContent('3(1)') }) it('Renders alphabetically sorted group by list - dates', () => { tableProps = { ...tableProps, rows: [ { name: 'rowname1', cells: ['1994-04-19T23:56:40', 'Group1'] }, { name: 'rowname2', cells: ['2012-09-14T18:26:01', 'Group1'] }, { name: 'rowname3', cells: ['1970-04-30T18:02:01', 'Group2'] } ] } const { container, getAllByText, getByTestId } = render(<XTable model={tableProps} />) fireEvent.click(getByTestId('groupby')) fireEvent.click(getAllByText('Col1')[1]!) const groupHeaders = container.querySelectorAll('.ms-GroupHeader-title') expect(groupHeaders[0]).toHaveTextContent(`${new Date('1970-04-30T18:02:01').toLocaleString()}(1)`) expect(groupHeaders[1]).toHaveTextContent(`${new Date('1994-04-19T23:56:40').toLocaleString()}(1)`) expect(groupHeaders[2]).toHaveTextContent(`${new Date('2012-09-14T18:26:01').toLocaleString()}(1)`) }) it('Sorts grouped list', () => { const { container, getAllByText, getByTestId, getAllByRole } = render(<XTable model={tableProps} />) fireEvent.click(getByTestId('groupby')) fireEvent.click(getAllByText('Col2')[1]!) fireEvent.click(container.querySelector('.ms-GroupHeader-expand')!) let gridcell1 = getAllByRole('gridcell')[3] expect(gridcell1.textContent).toBe(cell11) fireEvent.click(container.querySelector('.ms-DetailsHeader-cellTitle i[class*=sortingIcon]')!) gridcell1 = getAllByRole('gridcell')[3] expect(gridcell1.textContent).toBe(cell21) }) it('Searches grouped list', () => { const { container, getAllByText, getByTestId, getAllByRole } = render(<XTable model={tableProps} />) fireEvent.click(getByTestId('groupby')) fireEvent.click(getAllByText('Col2')[1]!) fireEvent.click(container.querySelector('.ms-GroupHeader-expand')!) // Count header and group header rows so + 2. expect(getAllByRole('row')).toHaveLength(tableProps.rows.length + 2) fireEvent.change(getByTestId('search'), { target: { value: cell21 } }) expect(getAllByRole('row')).toHaveLength(2) }) it('Filters grouped list - single option', () => { const { container, getAllByText, getByTestId, getAllByRole } = render(<XTable model={tableProps} />) fireEvent.click(getByTestId('groupby')) fireEvent.click(getAllByText('Col2')[1]!) fireEvent.click(container.querySelector('.ms-GroupHeader-expand')!) // Count header and group header rows so + 2. expect(getAllByRole('row')).toHaveLength(tableProps.rows.length + 2) fireEvent.click(container.querySelector('.ms-DetailsHeader-filterChevron')!) fireEvent.click(getAllByText('Group2')[1].parentElement!) expect(getAllByRole('row')).toHaveLength(2) }) it('Filters grouped list - multiple options', () => { const { container, getAllByText, getByTestId, getAllByRole } = render(<XTable model={tableProps} />) fireEvent.click(getByTestId('groupby')) fireEvent.click(getAllByText('Col2')[1]!) fireEvent.click(container.querySelector('.ms-GroupHeader-expand')!) // Count header and group header rows so + 2. expect(getAllByRole('row')).toHaveLength(tableProps.rows.length + 2) fireEvent.click(container.querySelector('.ms-DetailsHeader-filterChevron')!) fireEvent.click(getAllByText('Group1')[1].parentElement!) fireEvent.click(getAllByText('Group2')[0].parentElement!) expect(getAllByRole('row')).toHaveLength(tableProps.rows.length + 2) }) }) })
the_stack
import * as path from 'path'; import * as fs from 'fs'; import * as Color from 'color'; import {template} from 'lodash'; import {promisify} from 'util'; import {TwaManifest} from './TwaManifest'; import {ShortcutInfo} from './ShortcutInfo'; import {Log} from './Log'; import {ImageHelper, IconDefinition} from './ImageHelper'; import {FeatureManager} from './features/FeatureManager'; import {rmdir, escapeGradleString, escapeJsonString, toAndroidScreenOrientation} from './util'; import {fetchUtils} from './FetchUtils'; const COPY_FILE_LIST = [ 'settings.gradle', 'gradle.properties', 'build.gradle', 'gradlew', 'gradlew.bat', 'gradle/wrapper/gradle-wrapper.jar', 'gradle/wrapper/gradle-wrapper.properties', 'app/src/main/res/values/colors.xml', 'app/src/main/res/xml/filepaths.xml', 'app/src/main/res/xml/shortcuts.xml', 'app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml', 'app/src/main/res/drawable-anydpi/shortcut_legacy_background.xml', ]; const TEMPLATE_FILE_LIST = [ 'app/build.gradle', 'app/src/main/AndroidManifest.xml', 'app/src/main/res/values/strings.xml', ]; const JAVA_DIR = 'app/src/main/java/'; const JAVA_FILE_LIST = [ 'LauncherActivity.java', 'Application.java', 'DelegationService.java', ]; const DELETE_PROJECT_FILE_LIST = [ 'settings.gradle', 'gradle.properties', 'build.gradle', 'gradlew', 'gradlew.bat', 'store_icon.png', 'gradle/', 'app/', ]; const DELETE_FILE_LIST = [ 'app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml', ]; const SPLASH_IMAGES: IconDefinition[] = [ {dest: 'app/src/main/res/drawable-mdpi/splash.png', size: 300}, {dest: 'app/src/main/res/drawable-hdpi/splash.png', size: 450}, {dest: 'app/src/main/res/drawable-xhdpi/splash.png', size: 600}, {dest: 'app/src/main/res/drawable-xxhdpi/splash.png', size: 900}, {dest: 'app/src/main/res/drawable-xxxhdpi/splash.png', size: 1200}, ]; const IMAGES: IconDefinition[] = [ {dest: 'app/src/main/res/mipmap-mdpi/ic_launcher.png', size: 48}, {dest: 'app/src/main/res/mipmap-hdpi/ic_launcher.png', size: 72}, {dest: 'app/src/main/res/mipmap-xhdpi/ic_launcher.png', size: 96}, {dest: 'app/src/main/res/mipmap-xxhdpi/ic_launcher.png', size: 144}, {dest: 'app/src/main/res/mipmap-xxxhdpi/ic_launcher.png', size: 192}, {dest: 'store_icon.png', size: 512}, ]; const ADAPTIVE_IMAGES: IconDefinition[] = [ {dest: 'app/src/main/res/mipmap-mdpi/ic_maskable.png', size: 82}, {dest: 'app/src/main/res/mipmap-hdpi/ic_maskable.png', size: 123}, {dest: 'app/src/main/res/mipmap-xhdpi/ic_maskable.png', size: 164}, {dest: 'app/src/main/res/mipmap-xxhdpi/ic_maskable.png', size: 246}, {dest: 'app/src/main/res/mipmap-xxxhdpi/ic_maskable.png', size: 328}, ]; const NOTIFICATION_IMAGES: IconDefinition[] = [ {dest: 'app/src/main/res/drawable-mdpi/ic_notification_icon.png', size: 24}, {dest: 'app/src/main/res/drawable-hdpi/ic_notification_icon.png', size: 36}, {dest: 'app/src/main/res/drawable-xhdpi/ic_notification_icon.png', size: 48}, {dest: 'app/src/main/res/drawable-xxhdpi/ic_notification_icon.png', size: 72}, {dest: 'app/src/main/res/drawable-xxxhdpi/ic_notification_icon.png', size: 96}, ]; const WEB_MANIFEST_LOCATION = '/app/src/main/res/raw/'; const WEB_MANIFEST_FILE_NAME = 'web_app_manifest.json'; type ShareTargetIntentFilter = { actions: string[]; mimeTypes: string[]; }; function shortcutMaskableTemplateFileMap(assetName: string): Record<string, string> { return { 'app/src/main/res/drawable-anydpi-v26/shortcut_maskable.xml': `app/src/main/res/drawable-anydpi-v26/${assetName}.xml`, }; } function shortcutMonochromeTemplateFileMap(assetName: string): Record<string, string> { return { 'app/src/main/res/drawable-anydpi/shortcut_monochrome.xml': `app/src/main/res/drawable-anydpi/${assetName}.xml`, 'app/src/main/res/drawable-anydpi-v26/shortcut_monochrome.xml': `app/src/main/res/drawable-anydpi-v26/${assetName}.xml`, }; } function shortcutImages(assetName: string): IconDefinition[] { return [ {dest: `app/src/main/res/drawable-mdpi/${assetName}.png`, size: 48}, {dest: `app/src/main/res/drawable-hdpi/${assetName}.png`, size: 72}, {dest: `app/src/main/res/drawable-xhdpi/${assetName}.png`, size: 96}, {dest: `app/src/main/res/drawable-xxhdpi/${assetName}.png`, size: 144}, {dest: `app/src/main/res/drawable-xxxhdpi/${assetName}.png`, size: 192}, ]; } // fs.promises is marked as experimental. This should be replaced when stable. const fsMkDir = promisify(fs.mkdir); const fsCopyFile = promisify(fs.copyFile); const fsWriteFile = promisify(fs.writeFile); const fsReadFile = promisify(fs.readFile); export type twaGeneratorProgress = (progress: number, total: number) => void; // eslint-disable-next-line @typescript-eslint/no-empty-function const noOpProgress: twaGeneratorProgress = () => {}; /** * An utility class to help ensure progress tracking is consistent. */ class Progress { private current = 0; constructor(private total: number, private progress: twaGeneratorProgress) { this.progress(this.current, this.total); } /** * Updates the progress. Increments current by 1. */ update(): void { if (this.current === this.total) { throw new Error('Progress already reached total.' + ` current: ${this.current}, total: ${this.total}`); } this.current++; this.progress(this.current, this.total); } /** * Should be called for the last update. Throws an error if total !== current after incrementing * current. */ done(): void { this.update(); if (this.current !== this.total) { throw new Error('Invoked done before current equals total.' + ` current: ${this.current}, total: ${this.total}`); } } } /** * Generates TWA Projects from a TWA Manifest */ export class TwaGenerator { private imageHelper = new ImageHelper(); // Ensures targetDir exists and copies a file from sourceDir to target dir. private async copyStaticFile( sourceDir: string, targetDir: string, filename: string): Promise<void> { const sourceFile = path.join(sourceDir, filename); const destFile = path.join(targetDir, filename); await fsMkDir(path.dirname(destFile), {recursive: true}); await fsCopyFile(sourceFile, destFile); } // Copies a list of file from sourceDir to targetDir. private copyStaticFiles( sourceDir: string, targetDir: string, fileList: string[]): Promise<void[]> { return Promise.all(fileList.map((file) => { return this.copyStaticFile(sourceDir, targetDir, file); })); } private async applyTemplate( sourceFile: string, destFile: string, args: object): Promise<void> { await fsMkDir(path.dirname(destFile), {recursive: true}); const templateFile = await fsReadFile(sourceFile, 'utf-8'); const output = template(templateFile)(args); await fsWriteFile(destFile, output); } private async applyTemplateList( sourceDir: string, targetDir: string, fileList: string[], args: object): Promise<void> { await Promise.all(fileList.map((filename) => { const sourceFile = path.join(sourceDir, filename); const destFile = path.join(targetDir, filename); this.applyTemplate(sourceFile, destFile, args); })); } private async applyJavaTemplate( sourceDir: string, targetDir: string, packageName: string, filename: string, args: object): Promise<void> { const sourceFile = path.join(sourceDir, JAVA_DIR, filename); const destFile = path.join(targetDir, JAVA_DIR, packageName.split('.').join('/'), filename); await fsMkDir(path.dirname(destFile), {recursive: true}); const templateFile = await fsReadFile(sourceFile, 'utf-8'); const output = template(templateFile)(args); await fsWriteFile(destFile, output); } private applyJavaTemplates( sourceDir: string, targetDir: string, packageName: string, fileList: string[], args: object): Promise<void[]> { return Promise.all(fileList.map((file) => { this.applyJavaTemplate(sourceDir, targetDir, packageName, file, args); })); } private async applyTemplateMap( sourceDir: string, targetDir: string, fileMap: Record<string, string>, args: object): Promise<void> { await Promise.all(Object.keys(fileMap).map((filename) => { const sourceFile = path.join(sourceDir, filename); const destFile = path.join(targetDir, fileMap[filename]); this.applyTemplate(sourceFile, destFile, args); })); } private async generateIcons(iconUrl: string, targetDir: string, iconList: IconDefinition[], backgroundColor?: Color): Promise<void> { const icon = await this.imageHelper.fetchIcon(iconUrl); await Promise.all(iconList.map((iconDef) => { return this.imageHelper.generateIcon(icon, targetDir, iconDef, backgroundColor); })); } private async writeWebManifest(twaManifest: TwaManifest, targetDirectory: string): Promise<void> { if (!twaManifest.webManifestUrl) { throw new Error( 'Unable to write the Web Manifest. The TWA Manifest does not have a webManifestUrl'); } const response = await fetchUtils.fetch(twaManifest.webManifestUrl.toString()); if (response.status !== 200) { throw new Error(`Failed to download Web Manifest ${twaManifest.webManifestUrl}.` + `Responded with status ${response.status}`); } // We're writing as a string, but attempt to convert to check if it's a well-formed JSON. const webManifestJson = await response.json(); // We want to ensure that "start_url" is the same used to launch the Trusted Web Activity. webManifestJson['start_url'] = twaManifest.startUrl; const webManifestLocation = path.join(targetDirectory, WEB_MANIFEST_LOCATION); // Ensures the target directory exists. await fs.promises.mkdir(webManifestLocation, {recursive: true}); const webManifestFileName = path.join(webManifestLocation, WEB_MANIFEST_FILE_NAME); await fs.promises.writeFile(webManifestFileName, JSON.stringify(webManifestJson)); } /** * Generates shortcut data for a new TWA Project. * * @param {String} targetDirectory the directory where the project will be created * @param {String} templateDirectory the directory where templates are located. * @param {Object} twaManifest configurations values for the project. */ private async generateShortcuts( targetDirectory: string, templateDirectory: string, twaManifest: TwaManifest): Promise<void> { await Promise.all(twaManifest.shortcuts.map(async (shortcut: ShortcutInfo, i: number) => { const assetName = shortcut.assetName(i); const monochromeAssetName = `${assetName}_monochrome`; const maskableAssetName = `${assetName}_maskable`; const templateArgs = {assetName, monochromeAssetName, maskableAssetName}; if (shortcut.chosenMonochromeIconUrl) { await this.applyTemplateMap( templateDirectory, targetDirectory, shortcutMonochromeTemplateFileMap(assetName), templateArgs); const monochromeImages = shortcutImages(monochromeAssetName); const baseMonochromeIcon = await this.imageHelper.fetchIcon(shortcut.chosenMonochromeIconUrl); const monochromeIcon = await this.imageHelper.monochromeFilter(baseMonochromeIcon, twaManifest.themeColor); return await Promise.all(monochromeImages.map((iconDef) => { return this.imageHelper.generateIcon(monochromeIcon, targetDirectory, iconDef); })); } if (!shortcut.chosenIconUrl) { throw new Error( `ShortcutInfo ${shortcut.name} is missing chosenIconUrl and chosenMonochromeIconUrl`); } if (shortcut.chosenMaskableIconUrl) { await this.applyTemplateMap( templateDirectory, targetDirectory, shortcutMaskableTemplateFileMap(assetName), templateArgs); const maskableImages = shortcutImages(maskableAssetName); await this.generateIcons(shortcut.chosenMaskableIconUrl, targetDirectory, maskableImages); } const images = shortcutImages(assetName); return this.generateIcons(shortcut.chosenIconUrl, targetDirectory, images); })); } private static generateShareTargetIntentFilter( twaManifest: TwaManifest): ShareTargetIntentFilter | undefined { if (!twaManifest.shareTarget) { return undefined; } const shareTargetIntentFilter: ShareTargetIntentFilter = { actions: ['android.intent.action.SEND'], mimeTypes: [], }; if (twaManifest.shareTarget?.params?.url || twaManifest.shareTarget?.params?.title || twaManifest.shareTarget?.params?.text) { shareTargetIntentFilter.mimeTypes.push('text/plain'); } if (twaManifest.shareTarget?.params?.files) { shareTargetIntentFilter.actions.push('android.intent.action.SEND_MULTIPLE'); for (const file of twaManifest.shareTarget.params.files) { file.accept.forEach((accept) => shareTargetIntentFilter.mimeTypes.push(accept)); } } return shareTargetIntentFilter; } /** * Creates a new TWA Project. * * @param {String} targetDirectory the directory where the project will be created * @param {Object} twaManifest configurations values for the project. */ async createTwaProject(targetDirectory: string, twaManifest: TwaManifest, log: Log, reportProgress: twaGeneratorProgress = noOpProgress): Promise<void> { const features = new FeatureManager(twaManifest, log); const progress = new Progress(9, reportProgress); const error = twaManifest.validate(); if (error !== null) { throw new Error(`Invalid TWA Manifest: ${error}`); } const templateDirectory = path.join(__dirname, '../../template_project'); const copyFileList = new Set(COPY_FILE_LIST); if (!twaManifest.maskableIconUrl) { DELETE_FILE_LIST.forEach((file) => copyFileList.delete(file)); } progress.update(); // Copy Project Files await this.copyStaticFiles(templateDirectory, targetDirectory, Array.from(copyFileList)); // Apply proper permissions to gradlew. See https://nodejs.org/api/fs.html#fs_file_modes await fs.promises.chmod(path.join(targetDirectory, 'gradlew'), '755'); progress.update(); // Those are the arguments passed when applying templates. Functions are not automatically // copied from objects, so we explicitly copy generateShortcuts. const args = { ...twaManifest, ...features, shareTargetIntentFilter: TwaGenerator.generateShareTargetIntentFilter(twaManifest), generateShortcuts: twaManifest.generateShortcuts, escapeJsonString: escapeJsonString, escapeGradleString: escapeGradleString, toAndroidScreenOrientation: toAndroidScreenOrientation, }; // Generate templated files await this.applyTemplateList( templateDirectory, targetDirectory, TEMPLATE_FILE_LIST, args); progress.update(); // Generate java files await this.applyJavaTemplates( templateDirectory, targetDirectory, twaManifest.packageId, JAVA_FILE_LIST, args); progress.update(); // Generate images if (twaManifest.iconUrl) { await this.generateIcons(twaManifest.iconUrl, targetDirectory, IMAGES); await this.generateIcons( twaManifest.iconUrl, targetDirectory, SPLASH_IMAGES, twaManifest.backgroundColor); } progress.update(); await this.generateShortcuts(targetDirectory, templateDirectory, twaManifest); progress.update(); // Generate adaptive images if (twaManifest.maskableIconUrl) { await this.generateIcons(twaManifest.maskableIconUrl, targetDirectory, ADAPTIVE_IMAGES); } progress.update(); // Generate notification images const iconOrMonochromeIconUrl = twaManifest.monochromeIconUrl || twaManifest.iconUrl; if (twaManifest.enableNotifications && iconOrMonochromeIconUrl) { await this.generateIcons(iconOrMonochromeIconUrl, targetDirectory, NOTIFICATION_IMAGES); } progress.update(); if (twaManifest.webManifestUrl) { // Save the Web Manifest into the project await this.writeWebManifest(twaManifest, targetDirectory); } progress.done(); } /** * Removes all files generated by crateTwaProject. * @param targetDirectory the directory where the project was created. */ async removeTwaProject(targetDirectory: string): Promise<void> { await Promise.all( DELETE_PROJECT_FILE_LIST.map((entry) => rmdir(path.join(targetDirectory, entry)))); } }
the_stack
import assert from "assert"; import { ReadableStream, ReadableStreamBYOBReadResult } from "stream/web"; import { ArrayBufferViewConstructor, FixedLengthStream, Request, Response, } from "@miniflare/core"; import { utf8Encode } from "@miniflare/shared-test"; import test, { ThrowsExpectation } from "ava"; function chunkedStream(chunks: number[][]): ReadableStream<Uint8Array> { return new ReadableStream({ type: "bytes", pull(controller) { const chunk = chunks.shift(); assert(chunk); controller.enqueue(new Uint8Array(chunk)); if (chunks.length === 0) controller.close(); }, }); } async function* byobReadAtLeast<Ctor extends ArrayBufferViewConstructor>( stream: ReadableStream<Uint8Array>, readAtLeastBytes: number, bufferLength: number, ctor: Ctor ): AsyncGenerator<ReadableStreamBYOBReadResult<InstanceType<Ctor>>> { let buffer = new ArrayBuffer(bufferLength); let offset = 0; const reader = stream.getReader({ mode: "byob" }); // @ts-expect-error ctor.BYTES_PER_ELEMENT will just be undefined for DataView const bytesPerElement = ctor.BYTES_PER_ELEMENT ?? 1; while (true /*offset < buffer.byteLength*/) { const view = new ctor( buffer, offset, (buffer.byteLength - offset) / bytesPerElement ) as InstanceType<Ctor>; const result = await reader.readAtLeast(readAtLeastBytes, view); yield result; if (result.value) { buffer = result.value.buffer; offset += result.value.byteLength; } // if (result.done) break; } } test("ReadableStreamBYOBReader: readAtLeast: reads at least n bytes", async (t) => { const stream = chunkedStream([[1, 2, 3], [4], [5, 6]]); const reads = byobReadAtLeast(stream, 4, 8, Uint8Array); const { value } = await reads.next(); assert(value); t.false(value.done); t.deepEqual(value.value, new Uint8Array([1, 2, 3, 4])); }); test("ReadableStreamBYOBReader: readAtLeast: reads more than n bytes if available", async (t) => { const stream = chunkedStream([[1, 2, 3], [4, 5], [7]]); const reads = byobReadAtLeast(stream, 4, 8, Uint8Array); const { value } = await reads.next(); assert(value); t.false(value.done); t.deepEqual(value.value, new Uint8Array([1, 2, 3, 4, 5])); }); test("ReadableStreamBYOBReader: readAtLeast: reads less than n bytes if EOF reached", async (t) => { const stream = chunkedStream([[1], [2, 3], [4, 5]]); const reads = byobReadAtLeast(stream, 3, 8, Uint8Array); let value = (await reads.next()).value; assert(value); t.false(value.done); t.deepEqual(value.value, new Uint8Array([1, 2, 3])); value = (await reads.next()).value; assert(value); t.false(value.done); // final readAtLeast() call needed to get done = true t.deepEqual(value.value, new Uint8Array([4, 5])); value = (await reads.next()).value; assert(value); t.true(value.done); t.deepEqual(value.value, new Uint8Array([])); }); test("ReadableStreamBYOBReader: readAtLeast: reads with Uint32Arrays", async (t) => { const stream = chunkedStream([ [0x01, 0x02, 0x03], [0x04, 0x05], [0x06, 0x07, 0x08], [0x09, 0x10, 0x11, 0x12], ]); const reads = byobReadAtLeast(stream, 5, 20, Uint32Array); let value = (await reads.next()).value; assert(value); t.false(value.done); // Reading at least 5 bytes, but 4 required for each uint32, so 2 read t.deepEqual(value.value, new Uint32Array([0x04030201, 0x08070605])); value = (await reads.next()).value; assert(value); t.false(value.done); t.deepEqual(value.value, new Uint32Array([0x12111009])); value = (await reads.next()).value; assert(value); t.true(value.done); t.deepEqual(value.value, new Uint32Array([])); }); test("ReadableStreamBYOBReader: readAtLeast: throws with Uint32Arrays on partial read", async (t) => { const stream = chunkedStream([ [0x01, 0x02, 0x03, 0x04], [0x05, 0x06, 0x07], ]); const reads = byobReadAtLeast(stream, 5, 20, Uint32Array); await t.throwsAsync(reads.next(), { instanceOf: TypeError, message: "Invalid state: Partial read", }); }); // See https://github.com/nodejs/node/issues/40612 // test("ReadableStreamBYOBReader: readAtLeast: reads with DataViews", async (t) => { // const stream = chunkedStream([[1, 2, 3], [4], [5, 6]]); // const reads = byobReadAtLeast(stream, 4, 8, DataView); // // const { value } = await reads.next(); // assert(value); // t.false(value.done); // const buffer = new ArrayBuffer(4); // const array = new Uint8Array(buffer); // array[0] = 1; // array[1] = 2; // array[2] = 3; // array[3] = 4; // t.deepEqual(value.value, new DataView(buffer)); // }); test("ReadableStreamBYOBReader: readAtLeast: throws with invalid minimum number of bytes", async (t) => { let stream = chunkedStream([]); let reads = byobReadAtLeast(stream, -3, 8, Uint8Array); await t.throwsAsync(reads.next(), { instanceOf: TypeError, message: `Requested invalid minimum number of bytes to read (-3).`, }); stream = chunkedStream([]); reads = byobReadAtLeast(stream, 0, 8, Uint8Array); await t.throwsAsync(reads.next(), { instanceOf: TypeError, message: `Requested invalid minimum number of bytes to read (0).`, }); stream = chunkedStream([]); // @ts-expect-error testing error with invalid type reads = byobReadAtLeast(stream, "not a number", 8, Uint8Array); await t.throwsAsync(reads.next(), { instanceOf: TypeError, message: `Requested invalid minimum number of bytes to read (not a number).`, }); }); test("ReadableStreamBYOBReader: readAtLeast: throws with non-positive-sized TypedArray", async (t) => { const stream = chunkedStream([]); const buffer = new ArrayBuffer(8); const reader = stream.getReader({ mode: "byob" }); await t.throwsAsync(reader.readAtLeast(3, new Uint8Array(buffer, 0, 0)), { instanceOf: TypeError, message: 'You must call read() on a "byob" reader with a positive-sized TypedArray object.', }); }); test("ReadableStreamBYOBReader: readAtLeast: throws if minimum number of bytes exceeds buffer size", async (t) => { const stream = chunkedStream([]); const buffer = new ArrayBuffer(8); const reader = stream.getReader({ mode: "byob" }); await t.throwsAsync(reader.readAtLeast(4, new Uint8Array(buffer, 0, 3)), { instanceOf: TypeError, message: "Minimum bytes to read (4) exceeds size of buffer (3).", }); }); test("FixedLengthStream: requires non-negative integer expected length", (t) => { const expectations: ThrowsExpectation = { instanceOf: TypeError, message: "FixedLengthStream requires a non-negative integer expected length.", }; // @ts-expect-error intentionally testing incorrect types t.throws(() => new FixedLengthStream(), expectations); t.throws(() => new FixedLengthStream(-42), expectations); new FixedLengthStream(0); }); test("FixedLengthStream: throws if too many bytes written", async (t) => { const { readable, writable } = new FixedLengthStream(3); const writer = writable.getWriter(); // noinspection ES6MissingAwait void writer.write(new Uint8Array([1, 2])); // noinspection ES6MissingAwait void writer.write(new Uint8Array([3, 4])); const reader = readable.getReader(); t.deepEqual((await reader.read()).value, new Uint8Array([1, 2])); await t.throwsAsync(reader.read(), { instanceOf: TypeError, message: "Attempt to write too many bytes through a FixedLengthStream.", }); }); test("FixedLengthStream: throws if too few bytes written", async (t) => { const { readable, writable } = new FixedLengthStream(3); const writer = writable.getWriter(); // noinspection ES6MissingAwait void writer.write(new Uint8Array([1, 2])); // noinspection ES6MissingAwait const closePromise = writer.close(); const reader = readable.getReader(); t.deepEqual((await reader.read()).value, new Uint8Array([1, 2])); await t.throwsAsync(closePromise, { instanceOf: TypeError, message: "FixedLengthStream did not see all expected bytes before close().", }); }); test("FixedLengthStream: behaves as identity transform if just right number of bytes written", async (t) => { const { readable, writable } = new FixedLengthStream(3); const writer = writable.getWriter(); // noinspection ES6MissingAwait void writer.write(new Uint8Array([1, 2])); // noinspection ES6MissingAwait void writer.write(new Uint8Array([3])); // noinspection ES6MissingAwait void writer.close(); const reader = readable.getReader(); t.deepEqual((await reader.read()).value, new Uint8Array([1, 2])); t.deepEqual((await reader.read()).value, new Uint8Array([3])); t.true((await reader.read()).done); }); test("FixedLengthStream: throws on string chunks", async (t) => { const { readable, writable } = new FixedLengthStream(5); const writer = writable.getWriter(); // noinspection ES6MissingAwait void writer.write( // @ts-expect-error intentionally testing incorrect types "how much chunk would a chunk-chuck chuck if a chunk-chuck could chuck chunk?" ); const reader = readable.getReader(); await t.throwsAsync(reader.read(), { instanceOf: TypeError, message: "This TransformStream is being used as a byte stream, " + "but received a string on its writable side. " + "If you wish to write a string, you'll probably want to " + "explicitly UTF-8-encode it with TextEncoder.", }); }); test("FixedLengthStream: throws on non-ArrayBuffer/ArrayBufferView chunks", async (t) => { const { readable, writable } = new FixedLengthStream(5); const writer = writable.getWriter(); // @ts-expect-error intentionally testing incorrect types // noinspection ES6MissingAwait void writer.write(42); const reader = readable.getReader(); await t.throwsAsync(reader.read(), { instanceOf: TypeError, message: "This TransformStream is being used as a byte stream, " + "but received an object of non-ArrayBuffer/ArrayBufferView " + "type on its writable side.", }); }); function buildFixedLengthReadableStream(length: number) { const { readable, writable } = new FixedLengthStream(length); const writer = writable.getWriter(); if (length > 0) void writer.write(utf8Encode("".padStart(length, "x"))); void writer.close(); return readable; } test("FixedLengthStream: sets Content-Length header on Request", async (t) => { let body = buildFixedLengthReadableStream(3); let req = new Request("http://localhost", { method: "POST", body }); t.is(req.headers.get("Content-Length"), "3"); t.is(await req.text(), "xxx"); // Check overrides existing Content-Length header body = buildFixedLengthReadableStream(3); req = new Request("http://localhost", { method: "POST", body, headers: { "Content-Length": "2" }, }); t.is(req.headers.get("Content-Length"), "3"); t.is(await req.text(), "xxx"); // Check still includes header with 0 expected length body = buildFixedLengthReadableStream(0); req = new Request("http://localhost", { method: "POST", body }); t.is(req.headers.get("Content-Length"), "0"); t.is(await req.text(), ""); }); test("FixedLengthStream: sets Content-Length header on Response", async (t) => { let body = buildFixedLengthReadableStream(3); let res = new Response(body); t.is(res.headers.get("Content-Length"), "3"); t.is(await res.text(), "xxx"); // Check overrides existing Content-Length header body = buildFixedLengthReadableStream(3); res = new Response(body, { headers: { "Content-Length": "2" } }); t.is(res.headers.get("Content-Length"), "3"); t.is(await res.text(), "xxx"); // Check still includes header with 0 expected length body = buildFixedLengthReadableStream(0); res = new Response(body); t.is(res.headers.get("Content-Length"), "0"); t.is(await res.text(), ""); });
the_stack
import { h, JSX, Component, createRef, ComponentType } from 'preact'; import b from 'bem-react-helper'; import { getHandleClickProps } from 'common/accessibility'; import { COMMENT_NODE_CLASSNAME_PREFIX } from 'common/constants'; import { StaticStore } from 'common/static-store'; import { debounce } from 'utils/debounce'; import { copy } from 'common/copy'; import { Theme, BlockTTL, Comment as CommentType, PostInfo, User, CommentMode, Profile } from 'common/types'; import { extractErrorMessageFromResponse, FetcherError } from 'utils/errorUtils'; import { isUserAnonymous } from 'utils/isUserAnonymous'; import { CommentFormProps } from 'components/comment-form'; import { Avatar } from 'components/avatar'; import { Button } from 'components/button'; import { Countdown } from 'components/countdown'; import { getPreview, uploadImage } from 'common/api'; import { postMessageToParent } from 'utils/post-message'; import { FormattedMessage, IntlShape, defineMessages } from 'react-intl'; import { getVoteMessage, VoteMessagesTypes } from './getVoteMessage'; import { getBlockingDurations } from './getBlockingDurations'; import { boundActions } from './connected-comment'; import './styles'; export type CommentProps = { user: User | null; CommentForm?: ComponentType<CommentFormProps>; data: CommentType; repliesCount?: number; post_info?: PostInfo; /** whether comment's user is banned */ isUserBanned?: boolean; isCommentsDisabled: boolean; /** edit mode: is comment should have reply, or edit Input */ editMode?: CommentMode; /** * "main" view used in main case, * "pinned" view used in pinned block, * "user" is for user comments widget, * "preview" is for last comments page */ view: 'main' | 'pinned' | 'user' | 'preview'; /** defines whether comment should have reply/edit actions */ disabled?: boolean; collapsed?: boolean; theme: Theme; inView?: boolean; level?: number; mix?: string; getPreview?: typeof getPreview; uploadImage?: typeof uploadImage; intl: IntlShape; } & Partial<typeof boundActions>; export interface State { renderDummy: boolean; isCopied: boolean; editDeadline: Date | null; voteErrorMessage: string | null; /** * delta of the score: * default is 0. * if user upvoted delta will be incremented * if downvoted delta will be decremented */ scoreDelta: number; /** * score copied from props, that updates instantly, * without server response */ cachedScore: number; initial: boolean; } export class Comment extends Component<CommentProps, State> { votingPromise: Promise<unknown> = Promise.resolve(); /** comment text node. Used in comment text copying */ textNode = createRef<HTMLDivElement>(); updateState = (props: CommentProps) => { const newState: Partial<State> = { scoreDelta: props.data.vote, cachedScore: props.data.score, }; if (props.inView) { newState.renderDummy = false; } // set comment edit timer if (props.user && props.user.id === props.data.user.id) { const editDuration = StaticStore.config.edit_duration; const timeDiff = StaticStore.serverClientTimeDiff || 0; const editDeadline = new Date(new Date(props.data.time).getTime() + timeDiff + editDuration * 1000); if (editDeadline < new Date()) { newState.editDeadline = null; } else { newState.editDeadline = editDeadline; } } return newState; }; state = { renderDummy: typeof this.props.inView === 'boolean' ? !this.props.inView : false, isCopied: false, editDeadline: null, voteErrorMessage: null, scoreDelta: 0, cachedScore: this.props.data.score, initial: true, ...this.updateState(this.props), }; // getHandleClickProps = (handler?: (e: KeyboardEvent | MouseEvent) => void) => { // if (this.state.initial) return null; // if (this.props.inView === false) return null; // return getHandleClickProps(handler); // }; componentWillReceiveProps(nextProps: CommentProps) { this.setState(this.updateState(nextProps)); } componentDidMount() { // eslint-disable-next-line react/no-did-mount-set-state this.setState({ initial: false }); } toggleReplying = () => { const { editMode, setReplyEditState, data } = this.props; setReplyEditState?.({ id: data.id, state: editMode === CommentMode.Reply ? CommentMode.None : CommentMode.Reply }); }; toggleEditing = () => { const { editMode, setReplyEditState, data } = this.props; setReplyEditState?.({ id: data.id, state: editMode === CommentMode.Edit ? CommentMode.None : CommentMode.Edit }); }; toggleUserInfoVisibility = () => { const profile: Profile = { ...this.props.data.user }; if (this.props.user?.id === profile.id) { profile.current = '1'; } postMessageToParent({ profile }); }; togglePin = () => { const value = !this.props.data.pin; const intl = this.props.intl; const promptMessage = value ? intl.formatMessage(messages.pinComment) : intl.formatMessage(messages.unpinComment); if (window.confirm(promptMessage)) { this.props.setPinState!(this.props.data.id, value); } }; toggleVerify = () => { const value = !this.props.data.user.verified; const userId = this.props.data.user.id; const intl = this.props.intl; const userName = this.props.data.user.name; const promptMessage = value ? intl.formatMessage(messages.verifyUser, { userName }) : intl.formatMessage(messages.unverifyUser, { userName }); if (window.confirm(promptMessage)) { this.props.setVerifiedStatus!(userId, value); } }; onBlockUserClick = (e: Event) => { const target = e.target as HTMLOptionElement; // blur event will be triggered by the confirm pop-up which will start // infinite loop of blur -> confirm -> blur -> ... // so we trigger the blur event manually and have debounce mechanism to prevent it if (e.type === 'change') { target.blur(); } // we have to debounce the blockUser function calls otherwise it will be // called 2 times (by change event and by blur event) this.blockUser(target.value as BlockTTL); }; blockUser = debounce((ttl: BlockTTL): void => { const { user } = this.props.data; const blockingDurations = getBlockingDurations(this.props.intl); const blockDuration = blockingDurations.find((el) => el.value === ttl); // blocking duration may be undefined if user hasn't selected anything // and ttl equals "Blocking period" if (!blockDuration) return; const duration = blockDuration.label; const blockUser = this.props.intl.formatMessage(messages.blockUser, { userName: user.name, duration: duration.toLowerCase(), }); if (window.confirm(blockUser)) { this.props.blockUser!(user.id, user.name, ttl); } }, 100); onUnblockUserClick = () => { const { user } = this.props.data; const unblockUser = this.props.intl.formatMessage(messages.unblockUser); if (window.confirm(unblockUser)) { this.props.unblockUser!(user.id); } }; deleteComment = () => { const deleteComment = this.props.intl.formatMessage(messages.deleteMessage); if (window.confirm(deleteComment)) { this.props.setReplyEditState!({ id: this.props.data.id, state: CommentMode.None }); this.props.removeComment!(this.props.data.id); } }; hideUser = () => { const hideUserComment = this.props.intl.formatMessage(messages.hideUserComments, { userName: this.props.data.user.name, }); if (!window.confirm(hideUserComment)) return; this.props.hideUser!(this.props.data.user); }; handleVoteError = (e: FetcherError, originalScore: number, originalDelta: number) => { this.setState({ scoreDelta: originalDelta, cachedScore: originalScore, voteErrorMessage: extractErrorMessageFromResponse(e, this.props.intl), }); }; sendVotingRequest = (votingValue: number, originalScore: number, originalDelta: number) => { this.votingPromise = this.votingPromise .then(() => this.props.putCommentVote!(this.props.data.id, votingValue)) .catch((e) => this.handleVoteError(e, originalScore, originalDelta)); }; increaseScore = () => { const { cachedScore, scoreDelta } = this.state; if (scoreDelta === 1) return; this.setState({ scoreDelta: scoreDelta + 1, cachedScore: cachedScore + 1, voteErrorMessage: null, }); this.sendVotingRequest(1, cachedScore, scoreDelta); }; decreaseScore = () => { const { cachedScore, scoreDelta } = this.state; if (scoreDelta === -1) return; this.setState({ scoreDelta: scoreDelta - 1, cachedScore: cachedScore - 1, voteErrorMessage: null, }); this.sendVotingRequest(-1, cachedScore, scoreDelta); }; addComment = async (text: string, title: string, pid?: CommentType['id']) => { await this.props.addComment!(text, title, pid); this.props.setReplyEditState!({ id: this.props.data.id, state: CommentMode.None }); }; updateComment = async (id: CommentType['id'], text: string) => { await this.props.updateComment!(id, text); this.props.setReplyEditState!({ id: this.props.data.id, state: CommentMode.None }); }; scrollToParent = (evt: Event) => { const { pid } = this.props.data; const parentCommentNode = document.getElementById(`${COMMENT_NODE_CLASSNAME_PREFIX}${pid}`); evt.preventDefault(); if (!parentCommentNode) { return; } const top = parentCommentNode.getBoundingClientRect().top; if (postMessageToParent({ scrollTo: top })) { return; } parentCommentNode.scrollIntoView(); }; copyComment = () => { const username = this.props.data.user.name; const time = getLocalDatetime(this.props.intl, new Date(this.props.data.time)); const text = this.textNode.current?.textContent || ''; copy(`<b>${username}</b>&nbsp;${time}<br>${text.replace(/\n+/g, '<br>')}`); this.setState({ isCopied: true }, () => { setTimeout(() => this.setState({ isCopied: false }), 3000); }); }; /** * Defines whether current client is admin */ isAdmin = (): boolean => { return !!this.props.user && this.props.user.admin; }; /** * Defines whether current client is not logged in */ isGuest = (): boolean => { return !this.props.user; }; /** * Defines whether current client is logged in via `Anonymous provider` */ isAnonymous = (): boolean => { return isUserAnonymous(this.props.user); }; /** * Defines whether comment made by logged in user */ isCurrentUser = (): boolean => { if (this.isGuest()) return false; return this.props.data.user.id === this.props.user!.id; }; /** * returns reason for disabled downvoting */ getDownvoteDisabledReason = (): string | null => { const intl = this.props.intl; if (!(this.props.view === 'main' || this.props.view === 'pinned')) return getVoteMessage(VoteMessagesTypes.ONLY_POST_PAGE, intl); if (this.props.post_info?.read_only) return getVoteMessage(VoteMessagesTypes.READONLY, intl); if (this.props.data.delete) return getVoteMessage(VoteMessagesTypes.DELETED, intl); if (this.isCurrentUser()) return getVoteMessage(VoteMessagesTypes.OWN_COMMENT, intl); if (StaticStore.config.positive_score && this.props.data.score < 1) return getVoteMessage(VoteMessagesTypes.ONLY_POSITIVE, intl); if (this.isGuest()) return getVoteMessage(VoteMessagesTypes.GUEST, intl); if (this.isAnonymous() && !StaticStore.config.anon_vote) return getVoteMessage(VoteMessagesTypes.ANONYMOUS, intl); return null; }; /** * returns reason for disabled upvoting */ getUpvoteDisabledReason = (): string | null => { const intl = this.props.intl; if (!(this.props.view === 'main' || this.props.view === 'pinned')) return getVoteMessage(VoteMessagesTypes.ONLY_POST_PAGE, intl); if (this.props.post_info?.read_only) return getVoteMessage(VoteMessagesTypes.READONLY, intl); if (this.props.data.delete) return getVoteMessage(VoteMessagesTypes.DELETED, intl); if (this.isCurrentUser()) return getVoteMessage(VoteMessagesTypes.OWN_COMMENT, intl); if (this.isGuest()) return getVoteMessage(VoteMessagesTypes.GUEST, intl); if (this.isAnonymous() && !StaticStore.config.anon_vote) return getVoteMessage(VoteMessagesTypes.ANONYMOUS, intl); return null; }; getCommentControls = (): JSX.Element[] => { const isAdmin = this.isAdmin(); const isCurrentUser = this.isCurrentUser(); const controls: JSX.Element[] = []; if (this.props.data.delete) { return controls; } if (!(this.props.view === 'main' || this.props.view === 'pinned')) { return controls; } if (isAdmin) { controls.push( this.state.isCopied ? ( <span className="comment__control comment__control_view_inactive"> <FormattedMessage id="comment.copied" defaultMessage="Copied!" /> </span> ) : ( <Button kind="link" onClick={this.copyComment} mix="comment__control"> <FormattedMessage id="comment.copy" defaultMessage="Copy" /> </Button> ) ); controls.push( <Button kind="link" onClick={this.togglePin} mix="comment__control"> {this.props.data.pin ? ( <FormattedMessage id="comment.unpin" defaultMessage="Unpin" /> ) : ( <FormattedMessage id="comment.pin" defaultMessage="Pin" /> )} </Button> ); } if (!isCurrentUser) { controls.push( <Button kind="link" onClick={this.hideUser} mix="comment__control"> <FormattedMessage id="comment.hide" defaultMessage="Hide" /> </Button> ); } if (isAdmin) { if (this.props.isUserBanned) { controls.push( <Button kind="link" onClick={this.onUnblockUserClick} mix="comment__control"> <FormattedMessage id="comment.unblock" defaultMessage="Unblock" /> </Button> ); } const blockingDurations = getBlockingDurations(this.props.intl); if (this.props.user!.id !== this.props.data.user.id && !this.props.isUserBanned) { controls.push( <span className="comment__control comment__control_select-label"> <FormattedMessage id="comment.block" defaultMessage="Block" /> <select className="comment__control_select" onBlur={this.onBlockUserClick} onChange={this.onBlockUserClick}> <option disabled selected value={undefined}> <FormattedMessage id="comment.blocking-period" defaultMessage="Blocking period" /> </option> {blockingDurations.map((block) => ( <option key={block.value} value={block.value}> {block.label} </option> ))} </select> </span> ); } if (!this.props.data.delete) { controls.push( <Button kind="link" onClick={this.deleteComment} mix="comment__control"> <FormattedMessage id="comment.delete" defaultMessage="Delete" /> </Button> ); } } return controls; }; render(props: CommentProps, state: State) { const isAdmin = this.isAdmin(); const isGuest = this.isGuest(); const isCurrentUser = this.isCurrentUser(); const isReplying = props.editMode === CommentMode.Reply; const isEditing = props.editMode === CommentMode.Edit; const lowCommentScore = StaticStore.config.low_score; const downvotingDisabledReason = this.getDownvoteDisabledReason(); const isDownvotingDisabled = downvotingDisabledReason !== null; const upvotingDisabledReason = this.getUpvoteDisabledReason(); const isUpvotingDisabled = upvotingDisabledReason !== null; const editable = props.repliesCount === 0 && state.editDeadline; const scoreSignEnabled = !StaticStore.config.positive_score; const uploadImageHandler = this.isAnonymous() ? undefined : this.props.uploadImage; const commentControls = this.getCommentControls(); const intl = props.intl; const CommentForm = this.props.CommentForm || null; /** * CommentType adapted for rendering */ const o = { ...props.data, controversyText: intl.formatMessage(messages.controversy, { value: (props.data.controversy || 0).toFixed(2), }), text: props.view === 'preview' ? getTextSnippet(props.data.text) : props.data.delete ? intl.formatMessage(messages.deletedComment) : props.data.text, time: new Date(props.data.time), orig: isEditing ? props.data.orig && props.data.orig.replace(/&[#A-Za-z0-9]+;/gi, (entity) => { const span = document.createElement('span'); span.innerHTML = entity; return span.innerText; }) : props.data.orig, score: { value: Math.abs(state.cachedScore), sign: !scoreSignEnabled ? '' : state.cachedScore > 0 ? '+' : state.cachedScore < 0 ? '−' : null, view: state.cachedScore > 0 ? 'positive' : state.cachedScore < 0 ? 'negative' : undefined, }, user: props.data.user, }; const defaultMods = { disabled: props.disabled, pinned: props.data.pin, // TODO: we also have critical_score, so we need to collapse comments with it in future useless: !!props.isUserBanned || !!props.data.delete || (props.view !== 'preview' && props.data.score < lowCommentScore && !props.data.pin && !props.disabled), // TODO: add default view mod or don't? guest: isGuest, view: props.view === 'main' || props.view === 'pinned' ? props.data.user.admin && 'admin' : props.view, replying: props.view === 'main' && isReplying, editing: props.view === 'main' && isEditing, theme: props.view === 'preview' ? undefined : props.theme, level: props.level, collapsed: props.collapsed, }; if (props.view === 'preview') { return ( <article className={b('comment', { mix: props.mix }, defaultMods)}> <div className="comment__body"> {!!o.title && ( <div className="comment__title"> <a className="comment__title-link" href={`${o.locator.url}#${COMMENT_NODE_CLASSNAME_PREFIX}${o.id}`}> {o.title} </a> </div> )} <div className="comment__info"> {!!o.title && o.user.name} {!o.title && ( <a href={`${o.locator.url}#${COMMENT_NODE_CLASSNAME_PREFIX}${o.id}`} className="comment__username"> {o.user.name} </a> )} </div>{' '} <div className={b('comment__text', { mix: b('raw-content', {}, { theme: props.theme }) })} // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: o.text }} /> </div> </article> ); } if (this.state.renderDummy && !props.editMode) { const [width, height] = this.base ? [(this.base as Element).scrollWidth, (this.base as Element).scrollHeight] : [100, 100]; return ( <article id={props.disabled ? undefined : `${COMMENT_NODE_CLASSNAME_PREFIX}${o.id}`} style={{ width: `${width}px`, height: `${height}px`, }} /> ); } const goToParentMessage = intl.formatMessage(messages.goToParent); return ( <article className={b('comment', { mix: this.props.mix }, defaultMods)} id={props.disabled ? undefined : `${COMMENT_NODE_CLASSNAME_PREFIX}${o.id}`} > {props.view === 'user' && o.title && ( <div className="comment__title"> <a className="comment__title-link" href={`${o.locator.url}#${COMMENT_NODE_CLASSNAME_PREFIX}${o.id}`}> {o.title} </a> </div> )} <div className="comment__info"> {props.view !== 'user' && !props.collapsed && ( <div className="comment__avatar"> <Avatar url={o.user.picture} /> </div> )} {props.view !== 'user' && ( <button onClick={() => this.toggleUserInfoVisibility()} className="comment__username"> {o.user.name} </button> )} {isAdmin && props.view !== 'user' && ( <span {...getHandleClickProps(this.toggleVerify)} aria-label={intl.formatMessage(messages.toggleVerification)} title={intl.formatMessage(o.user.verified ? messages.verifiedUser : messages.unverifiedUser)} className={b('comment__verification', {}, { active: o.user.verified, clickable: true })} /> )} {!isAdmin && !!o.user.verified && props.view !== 'user' && ( <span title={intl.formatMessage(messages.verifiedUser)} className={b('comment__verification', {}, { active: true })} /> )} <a href={`${o.locator.url}#${COMMENT_NODE_CLASSNAME_PREFIX}${o.id}`} className="comment__time"> {getLocalDatetime(this.props.intl, o.time)} </a> {!!props.level && props.level > 0 && props.view === 'main' && ( <a className="comment__link-to-parent" href={`${o.locator.url}#${COMMENT_NODE_CLASSNAME_PREFIX}${o.pid}`} aria-label={goToParentMessage} title={goToParentMessage} onClick={(e) => this.scrollToParent(e)} > {' '} </a> )} {props.isUserBanned && props.view !== 'user' && ( <span className="comment__status"> <FormattedMessage id="comment.blocked-user" defaultMessage="Blocked" /> </span> )} {isAdmin && !props.isUserBanned && props.data.delete && ( <span className="comment__status"> <FormattedMessage id="comment.deleted-user" defaultMessage="Deleted" /> </span> )} <span className={b('comment__score', {}, { view: o.score.view })}> <span className={b( 'comment__vote', {}, { type: 'up', selected: state.scoreDelta === 1, disabled: isUpvotingDisabled } )} aria-disabled={state.scoreDelta === 1 || isUpvotingDisabled ? 'true' : 'false'} {...getHandleClickProps(isUpvotingDisabled ? undefined : this.increaseScore)} title={upvotingDisabledReason || undefined} > Vote up </span> <span className="comment__score-value" title={o.controversyText}> {o.score.sign} {o.score.value} </span> <span className={b( 'comment__vote', {}, { type: 'down', selected: state.scoreDelta === -1, disabled: isDownvotingDisabled } )} aria-disabled={state.scoreDelta === -1 || isUpvotingDisabled ? 'true' : 'false'} {...getHandleClickProps(isDownvotingDisabled ? undefined : this.decreaseScore)} title={downvotingDisabledReason || undefined} > Vote down </span> </span> </div> <div className="comment__body"> {!!state.voteErrorMessage && ( <div className="voting__error" role="alert"> <FormattedMessage id="comment.vote-error" defaultMessage="Voting error: {voteErrorMessage}" values={{ voteErrorMessage: state.voteErrorMessage }} /> </div> )} {(!props.collapsed || props.view === 'pinned') && ( <div className={b('comment__text', { mix: b('raw-content', {}, { theme: props.theme }) })} ref={this.textNode} // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: o.text }} /> )} {(!props.collapsed || props.view === 'pinned') && ( <div className="comment__actions"> {!props.data.delete && !props.isCommentsDisabled && !props.disabled && props.view === 'main' && ( <Button kind="link" onClick={this.toggleReplying} mix="comment__action"> {isReplying ? ( <FormattedMessage id="comment.cancel" defaultMessage="Cancel" /> ) : ( <FormattedMessage id="comment.reply" defaultMessage="Reply" /> )} </Button> )} {!props.data.delete && !props.disabled && !!o.orig && isCurrentUser && (editable || isEditing) && props.view === 'main' && [ <Button key="edit-button" kind="link" {...getHandleClickProps(this.toggleEditing)} mix={['comment__action', 'comment__action_type_edit']} > {isEditing ? ( <FormattedMessage id="comment.cancel" defaultMessage="Cancel" /> ) : ( <FormattedMessage id="comment.edit" defaultMessage="Edit" /> )} </Button>, !isAdmin && ( <Button key="delete-button" kind="link" {...getHandleClickProps(this.deleteComment)} mix={['comment__action', 'comment__action_type_delete']} > <FormattedMessage id="comment.delete" defaultMessage="Delete" /> </Button> ), state.editDeadline && ( <Countdown key="countdown" className="comment__edit-timer" time={state.editDeadline} onTimePassed={() => this.setState({ editDeadline: null, }) } /> ), ]} {commentControls.length > 0 && <span className="comment__controls">{commentControls}</span>} </div> )} </div> {CommentForm && isReplying && props.view === 'main' && ( <CommentForm id={o.id} intl={this.props.intl} user={props.user} theme={props.theme} mode="reply" mix="comment__input" onSubmit={(text: string, title: string) => this.addComment(text, title, o.id)} onCancel={this.toggleReplying} getPreview={this.props.getPreview!} autofocus={true} uploadImage={uploadImageHandler} simpleView={StaticStore.config.simple_view} /> )} {CommentForm && isEditing && props.view === 'main' && ( <CommentForm id={o.id} intl={this.props.intl} user={props.user} theme={props.theme} value={o.orig} mode="edit" mix="comment__input" onSubmit={(text: string) => this.updateComment(props.data.id, text)} onCancel={this.toggleEditing} getPreview={this.props.getPreview!} errorMessage={state.editDeadline === null ? intl.formatMessage(messages.expiredTime) : undefined} autofocus={true} uploadImage={uploadImageHandler} simpleView={StaticStore.config.simple_view} /> )} </article> ); } } function getTextSnippet(html: string) { const LENGTH = 100; const tmp = document.createElement('div'); tmp.innerHTML = html.replace('</p><p>', ' '); const result = tmp.innerText || ''; const snippet = result.substr(0, LENGTH); return snippet.length === LENGTH && result.length !== LENGTH ? `${snippet}...` : snippet; } function getLocalDatetime(intl: IntlShape, date: Date) { return intl.formatMessage(messages.commentTime, { day: intl.formatDate(date), time: intl.formatTime(date), }); } const messages = defineMessages({ deleteMessage: { id: 'comment.delete-message', defaultMessage: 'Do you want to delete this comment?', }, hideUserComments: { id: 'comment.hide-user-comment', defaultMessage: 'Do you want to hide comments of {userName}?', }, pinComment: { id: 'comment.pin-comment', defaultMessage: 'Do you want to pin this comment?', }, unpinComment: { id: 'comment.unpin-comment', defaultMessage: 'Do you want to unpin this comment?', }, verifyUser: { id: 'comment.verify-user', defaultMessage: 'Do you want to verify {userName}?', }, unverifyUser: { id: 'comment.unverify-user', defaultMessage: 'Do you want to unverify {userName}?', }, blockUser: { id: 'comment.block-user', defaultMessage: 'Do you want to block {userName} {duration}?', }, unblockUser: { id: 'comment.unblock-user', defaultMessage: 'Do you want to unblock this user?', }, deletedComment: { id: 'comment.deleted-comment', defaultMessage: 'This comment was deleted', }, controversy: { id: 'comment.controversy', defaultMessage: 'Controversy: {value}', }, toggleVerification: { id: 'comment.toggle-verification', defaultMessage: 'Toggle verification', }, verifiedUser: { id: 'comment.verified-user', defaultMessage: 'Verified user', }, unverifiedUser: { id: 'comment.unverified-user', defaultMessage: 'Unverified user', }, goToParent: { id: 'comment.go-to-parent', defaultMessage: 'Go to parent comment', }, expiredTime: { id: 'comment.expired-time', defaultMessage: 'Editing time has expired.', }, commentTime: { id: 'comment.time', defaultMessage: '{day} at {time}', }, });
the_stack
import { Injectable } from '@angular/core'; import { Plugin, Cordova, AwesomeCordovaNativePlugin } from '@awesome-cordova-plugins/core'; import { Observable } from 'rxjs'; /** * @deprecated use ATTRIBUTION_NETWORK instead * * Enum for attribution networks * @readonly * @enum {number} */ export enum ATTRIBUTION_NETWORKS { APPLE_SEARCH_ADS = 0, ADJUST = 1, APPSFLYER = 2, BRANCH = 3, TENJIN = 4, FACEBOOK = 5, } export enum ATTRIBUTION_NETWORK { APPLE_SEARCH_ADS = 0, ADJUST = 1, APPSFLYER = 2, BRANCH = 3, TENJIN = 4, FACEBOOK = 5, } export enum PURCHASE_TYPE { /** * A type of SKU for in-app products. */ INAPP = 'inapp', /** * A type of SKU for subscriptions. */ SUBS = 'subs', } /** * Enum for billing features. * Currently, these are only relevant for Google Play Android users: * https://developer.android.com/reference/com/android/billingclient/api/BillingClient.FeatureType */ export enum BILLING_FEATURE { /** * Purchase/query for subscriptions. */ SUBSCRIPTIONS, /** * Subscriptions update/replace. */ SUBSCRIPTIONS_UPDATE, /** * Purchase/query for in-app items on VR. */ IN_APP_ITEMS_ON_VR, /** * Purchase/query for subscriptions on VR. */ SUBSCRIPTIONS_ON_VR, /** * Launch a price change confirmation flow. */ PRICE_CHANGE_CONFIRMATION, } /** * @deprecated use PURCHASE_TYPE instead * * Enum for attribution networks * @readonly * @enum {string} */ export enum ProductType { SUBS = 'subs', INAPP = 'inapp', } export enum PRORATION_MODE { UNKNOWN_SUBSCRIPTION_UPGRADE_DOWNGRADE_POLICY = 0, /** * Replacement takes effect immediately, and the remaining time will be * prorated and credited to the user. This is the current default behavior. */ IMMEDIATE_WITH_TIME_PRORATION = 1, /** * Replacement takes effect immediately, and the billing cycle remains the * same. The price for the remaining period will be charged. This option is * only available for subscription upgrade. */ IMMEDIATE_AND_CHARGE_PRORATED_PRICE = 2, /** * Replacement takes effect immediately, and the new price will be charged on * next recurrence time. The billing cycle stays the same. */ IMMEDIATE_WITHOUT_PRORATION = 3, /** * Replacement takes effect when the old plan expires, and the new price will * be charged at the same time. */ DEFERRED = 4, } export enum PACKAGE_TYPE { /** * A package that was defined with a custom identifier. */ UNKNOWN = 'UNKNOWN', /** * A package that was defined with a custom identifier. */ CUSTOM = 'CUSTOM', /** * A package configured with the predefined lifetime identifier. */ LIFETIME = 'LIFETIME', /** * A package configured with the predefined annual identifier. */ ANNUAL = 'ANNUAL', /** * A package configured with the predefined six month identifier. */ SIX_MONTH = 'SIX_MONTH', /** * A package configured with the predefined three month identifier. */ THREE_MONTH = 'THREE_MONTH', /** * A package configured with the predefined two month identifier. */ TWO_MONTH = 'TWO_MONTH', /** * A package configured with the predefined monthly identifier. */ MONTHLY = 'MONTHLY', /** * A package configured with the predefined weekly identifier. */ WEEKLY = 'WEEKLY', } export enum INTRO_ELIGIBILITY_STATUS { /** * RevenueCat doesn't have enough information to determine eligibility. */ INTRO_ELIGIBILITY_STATUS_UNKNOWN = 0, /** * The user is not eligible for a free trial or intro pricing for this product. */ INTRO_ELIGIBILITY_STATUS_INELIGIBLE, /** * The user is eligible for a free trial or intro pricing for this product. */ INTRO_ELIGIBILITY_STATUS_ELIGIBLE, } /** * @name Purchases * @description * Purchases is a cross platform solution for managing in-app subscriptions. A backend is also provided via [RevenueCat](https://www.revenuecat.com) * * ## Features * | | RevenueCat | * | --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | * | ✅ | Server-side receipt validation | * | ➡️ | [Webhooks](https://docs.revenuecat.com/docs/webhooks) - enhanced server-to-server communication with events for purchases, renewals, cancellations, and more | * | 🎯 | Subscription status tracking - know whether a user is subscribed whether they're on iOS, Android or web | * | 📊 | Analytics - automatic calculation of metrics like conversion, mrr, and churn | * | 📝 | [Online documentation](https://docs.revenuecat.com/docs) up to date | * | 🔀 | [Integrations](https://www.revenuecat.com/integrations) - over a dozen integrations to easily send purchase data where you need it | * | 💯 | Well maintained - [frequent releases](https://github.com/RevenueCat/cordova-plugin-purchases/releases) | * | 📮 | Great support - [Help Center](https://revenuecat.zendesk.com) | * | 🤩 | Awesome [new features](https://trello.com/b/RZRnWRbI/revenuecat-product-roadmap) | * * ## Getting Started * * For more detailed information, you can view our complete documentation at [docs.revenuecat.com](https://docs.revenuecat.com/docs). * @usage * #### 1. Get a RevenueCat API key * * Log in to the [RevenueCat dashboard](https://app.revenuecat.com) and obtain a free API key for your application. * * #### 2. Initialize the SDK * * You should only configure _Purchases_ once (usually on app launch) as soon as your app has a unique user id for your user. This can be when a user logs in if you have accounts or on launch if you can generate a random user identifier. * * ```typescript * import { Platform } from "@ionic/angular"; * import { Purchases } from "@awesome-cordova-plugins/purchases/ngx"; * * constructor(public platform: Platform, private purchases: Purchases) { * platform.ready().then(() => { * this.purchases.setDebugLogsEnabled(true); // Enable to get debug logs * this.purchases.setup("my_api_key", "my_app_user_id"); * } * } * ``` * * #### 3. Quickstart * Please follow the [Quickstart Guide](https://docs.revenuecat.com/docs/) for more information on how to use the SDK * * ### Requirements * Requires XCode 11.0+ and minimum target iOS 9.0+ * This plugin has been tested with cordova-plugin-purchases@ * @interfaces * PurchasesError * IntroEligibility * UpgradeInfo * PurchasesOfferings * PurchasesOffering * PurchasesPackage * PurchasesProduct * PurchaserInfo * PurchasesEntitlementInfos * PurchasesEntitlementInfo * PurchasesTransaction */ @Plugin({ pluginName: 'Purchases', plugin: 'cordova-plugin-purchases@2.4.0', pluginRef: 'Purchases', // the variable reference to call the plugin, example: navigator.geolocation repo: 'https://github.com/RevenueCat/cordova-plugin-purchases', // the github repository URL for the plugin platforms: ['Android', 'iOS'], // Array of platforms supported, example: ['Android', 'iOS'] }) @Injectable({ providedIn: 'root', }) export class Purchases extends AwesomeCordovaNativePlugin { static ATTRIBUTION_NETWORKS = ATTRIBUTION_NETWORK; /** * Enum for attribution networks * * @readonly * @enum {number} */ static ATTRIBUTION_NETWORK = ATTRIBUTION_NETWORK; /** * Supported SKU types. * * @readonly * @enum {string} */ static PURCHASE_TYPE = PURCHASE_TYPE; /** * Enum for billing features. * Currently, these are only relevant for Google Play Android users: * https://developer.android.com/reference/com/android/billingclient/api/BillingClient.FeatureType */ static BILLING_FEATURE = BILLING_FEATURE; /** * Replace SKU's ProrationMode. * * @readonly * @enum {number} */ static PRORATION_MODE = PRORATION_MODE; /** * Enumeration of all possible Package types. * * @readonly * @enum {string} */ static PACKAGE_TYPE = PACKAGE_TYPE; /** * Enum of different possible states for intro price eligibility status. * * @readonly * @enum {number} */ static INTRO_ELIGIBILITY_STATUS = INTRO_ELIGIBILITY_STATUS; /** * Sets up Purchases with your API key and an app user id. * * @param {string} apiKey RevenueCat API Key. Needs to be a String * @param {string?} appUserID A unique id for identifying the user * @param {boolean} observerMode An optional boolean. Set this to TRUE if you have your own IAP implementation and * want to use only RevenueCat's backend. Default is FALSE. If you are on Android and setting this to ON, you will have * to acknowledge the purchases yourself. * @param {string?} userDefaultsSuiteName An optional string. iOS-only, will be ignored for Android. * Set this if you would like the RevenueCat SDK to store its preferences in a different NSUserDefaults * suite, otherwise it will use standardUserDefaults. Default is null, which will make the SDK use standardUserDefaults. */ @Cordova({ sync: true }) setup(apiKey: string, appUserID?: string | null, observerMode = false, userDefaultsSuiteName?: string): void {} /** * Set this to true if you are passing in an appUserID but it is anonymous, this is true by default if you didn't pass an appUserID * If a user tries to purchase a product that is active on the current app store account, we will treat it as a restore and alias * the new ID with the previous id. * * @param allowSharing {boolean} true if enabled, false to disabled */ @Cordova({ sync: true }) setAllowSharingStoreAccount(allowSharing: boolean): void {} /** * Add a dict of attribution information * * @deprecated Use the set<NetworkId> functions instead. * @param {object} data Attribution data from any of the attribution networks in Purchases.ATTRIBUTION_NETWORKS * @param {ATTRIBUTION_NETWORK} network Which network, see Purchases.ATTRIBUTION_NETWORK * @param {string?} networkUserId An optional unique id for identifying the user. Needs to be a string. */ @Cordova({ sync: true }) addAttributionData(data: { [key: string]: any }, network: ATTRIBUTION_NETWORK, networkUserId?: string): void {} /** * Gets the Offerings configured in the dashboard * * @returns {Promise<PurchasesOfferings>} Will return a [PurchasesError] if the offerings are not properly configured in RevenueCat or if there is another error retrieving them. */ @Cordova() getOfferings(): Promise<PurchasesOfferings> { return; } /** * Fetch the product info * * @param {string[]} productIdentifiers Array of product identifiers * @param {PURCHASE_TYPE} type Optional type of products to fetch, can be inapp or subs. Subs by default * @returns {Promise<PurchasesProduct[]>} Will return a [PurchasesError] if the products are not properly configured in RevenueCat or if there is another error retrieving them. */ @Cordova({ successIndex: 1, errorIndex: 2, }) getProducts(productIdentifiers: string[], type: PURCHASE_TYPE = PURCHASE_TYPE.SUBS): Promise<PurchasesProduct[]> { return; } /** * @typedef {Object} MakePurchaseResponse * @property {string} productIdentifier - The product identifier that has been purchased * @property {PurchaserInfo} purchaserInfo - The new PurchaserInfo after the successful purchase */ /** * Make a purchase * * @param {string} productIdentifier The product identifier of the product you want to purchase. * @param {UpgradeInfo} upgradeInfo Android only. Optional UpgradeInfo you wish to upgrade from containing the oldSKU * and the optional prorationMode. * @param {PURCHASE_TYPE} type Optional type of product, can be inapp or subs. Subs by default * @returns {Promise<MakePurchaseResponse>} A [PurchasesError] is triggered after an error or when the user cancels the purchase. * If user cancelled, userCancelled will be true */ @Cordova({ successIndex: 1, errorIndex: 2, }) purchaseProduct( productIdentifier: string, upgradeInfo?: UpgradeInfo | null, type: PURCHASE_TYPE = PURCHASE_TYPE.SUBS ): Promise<{ productIdentifier: string; purchaserInfo: PurchaserInfo }> { return; } /** * Make a purchase * * @param {PurchasesPackage} aPackage The Package you wish to purchase. You can get the Packages by calling getOfferings * @param {UpgradeInfo} upgradeInfo Android only. Optional UpgradeInfo you wish to upgrade from containing the oldSKU * and the optional prorationMode. * @returns {Promise<MakePurchaseResponse>} A [PurchasesError] is triggered after an error or when the user cancels the purchase. * If user cancelled, userCancelled will be true */ @Cordova({ successIndex: 1, errorIndex: 2, }) purchasePackage( aPackage: PurchasesPackage, upgradeInfo?: UpgradeInfo | null ): Promise<{ productIdentifier: string; purchaserInfo: PurchaserInfo }> { return; } /** * Restores a user's previous purchases and links their appUserIDs to any user's also using those purchases. * * @returns {Promise<PurchaserInfo>} Errors are of type [PurchasesError] */ @Cordova() restoreTransactions(): Promise<PurchaserInfo> { return; } /** * Get the appUserID that is currently in placed in the SDK * * @returns {string} */ @Cordova({ sync: true }) getAppUserID(): string { return; } /** * This function will logIn the current user with an appUserID. Typically this would be used after a log in * to identify a user without calling configure. * * @param {string} appUserID The appUserID that should be linked to the currently user * @returns {Promise<LogInResult>} an object that contains the purchaserInfo after logging in, as well as a boolean indicating * whether the user has just been created for the first time in the RevenueCat backend. */ @Cordova() logIn(appUserID: string): Promise<LogInResult> { return; } /** * Logs out the Purchases client clearing the saved appUserID. This will generate a random user id and save it in the cache. * If the current user is already anonymous, this will produce a PurchasesError. * * @returns {Promise<PurchaserInfo>} new purchaser info after resetting. */ @Cordova() logOut(): Promise<PurchaserInfo> { return; } /** * @deprecated, use logIn instead. * This function will alias two appUserIDs together. * @param newAppUserID {String} The new appUserID that should be linked to the currently identified appUserID. Needs to be a string. * @returns {Promise<PurchaserInfo>} Errors are of type [PurchasesError] and get normally triggered if there * is an error retrieving the new purchaser info for the new user or if there is an error creating the alias. */ @Cordova() createAlias(newAppUserID: string): Promise<PurchaserInfo> { return; } /** * @deprecated, use logIn instead. * This function will identify the current user with an appUserID. Typically this would be used after a logout to identify a new user without calling configure * @param newAppUserID {String} The new appUserID that should be linked to the currently identified appUserID. Needs to be a string. * @returns {Promise<PurchaserInfo>} Errors are of type [PurchasesError] and get normally triggered if there * is an error retrieving the new purchaser info for the new user. */ @Cordova() identify(newAppUserID: string): Promise<PurchaserInfo> { return; } /** * @deprecated, use logOut instead. * Resets the Purchases client clearing the saved appUserID. This will generate a random user id and save it in the cache. * @returns {Promise<PurchaserInfo>} Errors are of type [PurchasesError] and get normally triggered if there * is an error retrieving the new purchaser info for the new user. */ @Cordova() reset(): Promise<PurchaserInfo> { return; } /** * Gets the current purchaser info. This call will return the cached purchaser info unless the cache is stale, in which case, * it will make a network call to retrieve it from the servers. * * @returns {Promise<PurchaserInfo>} Errors are of type [PurchasesError] and get normally triggered if there * is an error retrieving the purchaser info. */ @Cordova() getPurchaserInfo(): Promise<PurchaserInfo> { return; } /** * Returns an observable that can be used to receive updates on the purchaser info * * @returns {Observable<PurchaserInfo>} */ @Cordova({ eventObservable: true, event: 'onPurchaserInfoUpdated', element: 'window', }) onPurchaserInfoUpdated(): Observable<PurchaserInfo> { return; } /** * Enables/Disables debugs logs * * @param {boolean} enabled true to enable debug logs, false to disable */ @Cordova({ sync: true }) setDebugLogsEnabled(enabled: boolean): void {} /** * This method will send all the purchases to the RevenueCat backend. Call this when using your own implementation * for subscriptions anytime a sync is needed, like after a successful purchase. * * @warning This function should only be called if you're not calling purchaseProduct. */ @Cordova({ sync: true }) syncPurchases(): void {} /** * iOS only. * * @param {boolean} enabled Set this property to true *only* when testing the ask-to-buy / SCA purchases flow. * More information: http://errors.rev.cat/ask-to-buy */ @Cordova({ sync: true }) setSimulatesAskToBuyInSandbox(enabled: boolean): void {} /** * Enable automatic collection of Apple Search Ads attribution. Disabled by default. * * @param {boolean} enabled Enable or not automatic collection */ @Cordova({ sync: true }) setAutomaticAppleSearchAdsAttributionCollection(enabled: boolean): void {} /** * @returns {Promise<boolean>} A boolean indicating if the `appUserID` has been generated * by RevenueCat or not. */ @Cordova({ sync: true }) isAnonymous(): boolean { return; } /** * iOS only. Computes whether or not a user is eligible for the introductory pricing period of a given product. * You should use this method to determine whether or not you show the user the normal product price or the * introductory price. This also applies to trials (trials are considered a type of introductory pricing). * * @note Subscription groups are automatically collected for determining eligibility. If RevenueCat can't * definitively compute the eligibility, most likely because of missing group information, it will return * `INTRO_ELIGIBILITY_STATUS_UNKNOWN`. The best course of action on unknown status is to display the non-intro * pricing, to not create a misleading situation. To avoid this, make sure you are testing with the latest version of * iOS so that the subscription group can be collected by the SDK. Android always returns INTRO_ELIGIBILITY_STATUS_UNKNOWN. * @param productIdentifiers Array of product identifiers for which you want to compute eligibility * @returns { Promise<Object.<string, IntroEligibility>> } Map of IntroEligibility per productId */ @Cordova() checkTrialOrIntroductoryPriceEligibility( productIdentifiers: string[] ): Promise<{ [productId: string]: IntroEligibility }> { return; } /** * Sets a function to be called on purchases initiated on the Apple App Store. This is only used in iOS. * * @param {ShouldPurchasePromoProductListener} shouldPurchasePromoProductListener Called when a user initiates a * promotional in-app purchase from the App Store. If your app is able to handle a purchase at the current time, run * the deferredPurchase function. If the app is not in a state to make a purchase: cache the deferredPurchase, then * call the deferredPurchase when the app is ready to make the promotional purchase. * If the purchase should never be made, you don't need to ever call the deferredPurchase and the app will not * proceed with promotional purchases. */ @Cordova({ sync: true }) addShouldPurchasePromoProductListener(shouldPurchasePromoProductListener: ShouldPurchasePromoProductListener): void {} /** * Removes a given ShouldPurchasePromoProductListener * * @param {ShouldPurchasePromoProductListener} listenerToRemove ShouldPurchasePromoProductListener reference of the listener to remove * @returns {boolean} True if listener was removed, false otherwise */ @Cordova({ sync: true }) removeShouldPurchasePromoProductListener(listenerToRemove: ShouldPurchasePromoProductListener): boolean { return; } /** * Invalidates the cache for purchaser information. * * Most apps will not need to use this method; invalidating the cache can leave your app in an invalid state. * Refer to https://docs.revenuecat.com/docs/purchaserinfo#section-get-user-information for more information on * using the cache properly. * * This is useful for cases where purchaser information might have been updated outside of the * app, like if a promotional subscription is granted through the RevenueCat dashboard. */ @Cordova({ sync: true }) invalidatePurchaserInfoCache(): void {} /** * iOS only. Presents a code redemption sheet, useful for redeeming offer codes * Refer to https://docs.revenuecat.com/docs/ios-subscription-offers#offer-codes for more information on how * to configure and use offer codes. */ @Cordova({ sync: true }) presentCodeRedemptionSheet(): void {} /** * Subscriber attributes are useful for storing additional, structured information on a user. * Since attributes are writable using a public key they should not be used for * managing secure or sensitive information such as subscription status, coins, etc. * * Key names starting with "$" are reserved names used by RevenueCat. For a full list of key * restrictions refer to our guide: https://docs.revenuecat.com/docs/subscriber-attributes * * @param attributes Map of attributes by key. Set the value as an empty string to delete an attribute. */ @Cordova({ sync: true }) setAttributes(attributes: { [key: string]: string | null }): void {} /** * Subscriber attribute associated with the email address for the user * * @param email Empty String or null will delete the subscriber attribute. */ @Cordova({ sync: true }) setEmail(email: string | null): void {} /** * Subscriber attribute associated with the phone number for the user * * @param phoneNumber Empty String or null will delete the subscriber attribute. */ @Cordova({ sync: true }) setPhoneNumber(phoneNumber: string | null): void {} /** * Subscriber attribute associated with the display name for the user * * @param displayName Empty String or null will delete the subscriber attribute. */ @Cordova({ sync: true }) setDisplayName(displayName: string | null): void {} /** * Subscriber attribute associated with the push token for the user * * @param pushToken Empty String or null will delete the subscriber attribute. */ @Cordova({ sync: true }) setPushToken(pushToken: string | null): void {} /** * Subscriber attribute associated with the install media source for the user * * @param mediaSource Empty String or null will delete the subscriber attribute. */ @Cordova({ sync: true }) setMediaSource(mediaSource: string | null): void {} /** * Subscriber attribute associated with the install campaign for the user * * @param campaign Empty String or null will delete the subscriber attribute. */ @Cordova({ sync: true }) setCampaign(campaign: string | null): void {} /** * Subscriber attribute associated with the install ad group for the user * * @param adGroup Empty String or null will delete the subscriber attribute. */ @Cordova({ sync: true }) setAdGroup(adGroup: string | null): void {} /** * Subscriber attribute associated with the install ad for the user * * @param ad Empty String or null will delete the subscriber attribute. */ @Cordova({ sync: true }) setAd(ad: string | null): void {} /** * Subscriber attribute associated with the install keyword for the user * * @param keyword Empty String or null will delete the subscriber attribute. */ @Cordova({ sync: true }) setKeyword(keyword: string | null): void {} /** * Subscriber attribute associated with the install ad creative for the user * * @param creative Empty String or null will delete the subscriber attribute. */ @Cordova({ sync: true }) setCreative(creative: string | null): void {} /** * Subscriber attribute associated with the Adjust Id for the user * Required for the RevenueCat Adjust integration * * @param adjustID Empty String or null will delete the subscriber attribute. */ @Cordova({ sync: true }) setAdjustID(adjustID: string | null): void {} /** * Subscriber attribute associated with the AppsFlyer Id for the user * Required for the RevenueCat AppsFlyer integration * * @param appsflyerID Empty String or null will delete the subscriber attribute. */ @Cordova({ sync: true }) setAppsflyerID(appsflyerID: string | null): void {} /** * Subscriber attribute associated with the Facebook SDK Anonymous Id for the user * Recommended for the RevenueCat Facebook integration * * @param fbAnonymousID Empty String or null will delete the subscriber attribute. */ @Cordova({ sync: true }) setFBAnonymousID(fbAnonymousID: string | null): void {} /** * Subscriber attribute associated with the mParticle Id for the user * Recommended for the RevenueCat mParticle integration * * @param mparticleID Empty String or null will delete the subscriber attribute. */ @Cordova({ sync: true }) setMparticleID(mparticleID: string | null): void {} /** * Subscriber attribute associated with the OneSignal Player Id for the user * Required for the RevenueCat OneSignal integration * * @param onesignalID Empty String or null will delete the subscriber attribute. */ @Cordova({ sync: true }) setOnesignalID(onesignalID: string | null): void {} /** * Subscriber attribute associated with the Airship Channel Id for the user * Required for the RevenueCat Airship integration * * @param airshipChannelID Empty String or null will delete the subscriber attribute. */ @Cordova({ sync: true }) setAirshipChannelID(airshipChannelID: string | null): void {} /** * Automatically collect subscriber attributes associated with the device identifiers. * $idfa, $idfv, $ip on iOS * $gpsAdId, $androidId, $ip on Android */ @Cordova({ sync: true }) collectDeviceIdentifiers(): void {} /** * Check if billing is supported for the current user (meaning IN-APP purchases are supported) * and optionally, whether a list of specified feature types are supported. * * Note: Billing features are only relevant to Google Play Android users. * For other stores and platforms, billing features won't be checked. * * @param feature An array of feature types to check for support. Feature types must be one of * [BILLING_FEATURE]. By default, is an empty list and no specific feature support will be checked. * @param features * @returns {Promise<boolean>} Or [PurchasesError] if there is an error. */ @Cordova() canMakePayments(features: BILLING_FEATURE[] = []): Promise<boolean> { return; } /** * Set this property to your proxy URL before configuring Purchases *only* if you've received a proxy key value from your RevenueCat contact. * * @param url Proxy URL as a string. */ @Cordova({ sync: true }) setProxyURL(url: string): void {} } /** * @deprecated use PurchasesProduct instead */ export interface RCProduct {} /** * @deprecated use PurchaserInfo instead */ export interface RCPurchaserInfo {} /** * @deprecated use PurchasesError instead */ export interface RCError {} /** * The EntitlementInfo object gives you access to all of the information about the status of a user entitlement. */ export interface PurchasesEntitlementInfo { /** * The entitlement identifier configured in the RevenueCat dashboard */ readonly identifier: string; /** * True if the user has access to this entitlement */ readonly isActive: boolean; /** * True if the underlying subscription is set to renew at the end of the billing period (expirationDate). * Will always be True if entitlement is for lifetime access. */ readonly willRenew: boolean; /** * The last period type this entitlement was in. Either: NORMAL, INTRO, TRIAL. */ readonly periodType: string; /** * The latest purchase or renewal date for the entitlement. */ readonly latestPurchaseDate: string; /** * The first date this entitlement was purchased. */ readonly originalPurchaseDate: string; /** * The expiration date for the entitlement, can be `null` for lifetime access. If the `periodType` is `trial`, * this is the trial expiration date. */ readonly expirationDate: string | null; /** * The store where this entitlement was unlocked from. Either: appStore, macAppStore, playStore, stripe, * promotional, unknownStore */ readonly store: string; /** * The product identifier that unlocked this entitlement */ readonly productIdentifier: string; /** * False if this entitlement is unlocked via a production purchase */ readonly isSandbox: boolean; /** * The date an unsubscribe was detected. Can be `null`. * * @note: Entitlement may still be active even if user has unsubscribed. Check the `isActive` property. */ readonly unsubscribeDetectedAt: string | null; /** * The date a billing issue was detected. Can be `null` if there is no billing issue or an issue has been resolved * * @note: Entitlement may still be active even if there is a billing issue. Check the `isActive` property. */ readonly billingIssueDetectedAt: string | null; } /** * Contains all the entitlements associated to the user. */ export interface PurchasesEntitlementInfos { /** * Map of all EntitlementInfo (`PurchasesEntitlementInfo`) objects (active and inactive) keyed by entitlement identifier. */ readonly all: { [key: string]: PurchasesEntitlementInfo }; /** * Map of active EntitlementInfo (`PurchasesEntitlementInfo`) objects keyed by entitlement identifier. */ readonly active: { [key: string]: PurchasesEntitlementInfo }; } export interface PurchaserInfo { /** * Entitlements attached to this purchaser info */ readonly entitlements: PurchasesEntitlementInfos; /** * Set of active subscription skus */ readonly activeSubscriptions: [string]; /** * Set of purchased skus, active and inactive */ readonly allPurchasedProductIdentifiers: [string]; /** * Returns all the non-subscription purchases a user has made. * The purchases are ordered by purchase date in ascending order. */ readonly nonSubscriptionTransactions: PurchasesTransaction[]; /** * The latest expiration date of all purchased skus */ readonly latestExpirationDate: string | null; /** * The date this user was first seen in RevenueCat. */ readonly firstSeen: string; /** * The original App User Id recorded for this user. */ readonly originalAppUserId: string; /** * Date when this info was requested */ readonly requestDate: string; /** * Map of skus to expiration dates */ readonly allExpirationDates: { [key: string]: string | null }; /** * Map of skus to purchase dates */ readonly allPurchaseDates: { [key: string]: string | null }; /** * Returns the version number for the version of the application when the * user bought the app. Use this for grandfathering users when migrating * to subscriptions. * * This corresponds to the value of CFBundleVersion (in iOS) in the * Info.plist file when the purchase was originally made. This is always null * in Android */ readonly originalApplicationVersion: string | null; /** * Returns the purchase date for the version of the application when the user bought the app. * Use this for grandfathering users when migrating to subscriptions. */ readonly originalPurchaseDate: string | null; /** * URL to manage the active subscription of the user. If this user has an active iOS * subscription, this will point to the App Store, if the user has an active Play Store subscription * it will point there. If there are no active subscriptions it will be null. * If there are multiple for different platforms, it will point to the device store. */ readonly managementURL: string | null; } export interface PurchasesTransaction { /** * RevenueCat Id associated to the transaction. */ readonly revenueCatId: string; /** * Product Id associated with the transaction. */ readonly productId: string; /** * Purchase date of the transaction in ISO 8601 format. */ readonly purchaseDate: string; } export interface PurchasesProduct { /** * Product Id. */ readonly identifier: string; /** * Description of the product. */ readonly description: string; /** * Title of the product. */ readonly title: string; /** * Price of the product in the local currency. */ readonly price: number; /** * Formatted price of the item, including its currency sign, such as €3.99. */ readonly price_string: string; /** * Currency code for price and original price. */ readonly currency_code: string; /** * Introductory price of a subscription in the local currency. */ readonly intro_price: number | null; /** * Formatted introductory price of a subscription, including its currency sign, such as €3.99. */ readonly intro_price_string: string | null; /** * Billing period of the introductory price, specified in ISO 8601 format. */ readonly intro_price_period: string | null; /** * Number of subscription billing periods for which the user will be given the introductory price, such as 3. */ readonly intro_price_cycles: number | null; /** * Unit for the billing period of the introductory price, can be DAY, WEEK, MONTH or YEAR. */ readonly intro_price_period_unit: string | null; /** * Number of units for the billing period of the introductory price. */ readonly intro_price_period_number_of_units: number | null; } /** * Contains information about the product available for the user to purchase. * For more info see https://docs.revenuecat.com/docs/entitlements */ export interface PurchasesPackage { /** * Unique identifier for this package. Can be one a predefined package type or a custom one. */ readonly identifier: string; /** * Package type for the product. Will be one of [PACKAGE_TYPE]. */ readonly packageType: PACKAGE_TYPE; /** * Product assigned to this package. */ readonly product: PurchasesProduct; /** * Offering this package belongs to. */ readonly offeringIdentifier: string; } /** * An offering is a collection of Packages (`PurchasesPackage`) available for the user to purchase. * For more info see https://docs.revenuecat.com/docs/entitlements */ export interface PurchasesOffering { /** * Unique identifier defined in RevenueCat dashboard. */ readonly identifier: string; /** * Offering description defined in RevenueCat dashboard. */ readonly serverDescription: string; /** * Array of `Package` objects available for purchase. */ readonly availablePackages: PurchasesPackage[]; /** * Lifetime package type configured in the RevenueCat dashboard, if available. */ readonly lifetime: PurchasesPackage | null; /** * Annual package type configured in the RevenueCat dashboard, if available. */ readonly annual: PurchasesPackage | null; /** * Six month package type configured in the RevenueCat dashboard, if available. */ readonly sixMonth: PurchasesPackage | null; /** * Three month package type configured in the RevenueCat dashboard, if available. */ readonly threeMonth: PurchasesPackage | null; /** * Two month package type configured in the RevenueCat dashboard, if available. */ readonly twoMonth: PurchasesPackage | null; /** * Monthly package type configured in the RevenueCat dashboard, if available. */ readonly monthly: PurchasesPackage | null; /** * Weekly package type configured in the RevenueCat dashboard, if available. */ readonly weekly: PurchasesPackage | null; } /** * Contains all the offerings configured in RevenueCat dashboard. * For more info see https://docs.revenuecat.com/docs/entitlements */ export interface PurchasesOfferings { /** * Map of all Offerings [PurchasesOffering] objects keyed by their identifier. */ readonly all: { [key: string]: PurchasesOffering }; /** * Current offering configured in the RevenueCat dashboard. */ readonly current: PurchasesOffering | null; } export interface PurchasesError { code: number; message: string; readableErrorCode: string; underlyingErrorMessage?: string; } /** * Holds the information used when upgrading from another sku. For Android use only. */ export interface UpgradeInfo { /** * The oldSKU to upgrade from. */ readonly oldSKU: string; /** * The [PRORATION_MODE] to use when upgrading the given oldSKU. */ readonly prorationMode?: PRORATION_MODE; } /** * Holds the introductory price status */ export interface IntroEligibility { /** * The introductory price eligibility status */ readonly status: INTRO_ELIGIBILITY_STATUS; /** * Description of the status */ readonly description: string; } /** * Holds the logIn result */ export interface LogInResult { /** * The Purchaser Info for the user. */ readonly purchaserInfo: PurchaserInfo; /** * True if the call resulted in a new user getting created in the RevenueCat backend. */ readonly created: boolean; } export type ShouldPurchasePromoProductListener = (deferredPurchase: () => void) => void;
the_stack
export interface Account { /** Gets or sets the identifier. */ id?: string; /** Identity Info on the tracked resource */ identity?: Identity; /** Gets or sets the location. */ location?: string; /** Gets or sets the name. */ name?: string; /** Gets or sets the properties. */ properties?: AccountProperties; /** Gets or sets the Sku. */ sku?: AccountSku; /** Metadata pertaining to creation and last modification of the resource. */ systemData?: AccountSystemData; /** Tags on the azure resource. */ tags?: Record<string, string>; /** Gets or sets the type. */ type?: string; } export interface Identity { /** Service principal object Id */ principalId?: string; /** Tenant Id */ tenantId?: string; /** Identity Type */ type?: "SystemAssigned"; } export interface AccountProperties { /** * Cloud connectors. * External cloud identifier used as part of scanning configuration. */ cloudConnectors?: CloudConnectors; /** Gets the time at which the entity was created. */ createdAt?: Date; /** Gets the creator of the entity. */ createdBy?: string; /** Gets the creators of the entity's object id. */ createdByObjectId?: string; /** The URIs that are the public endpoints of the account. */ endpoints?: AccountPropertiesEndpoints; /** Gets or sets the friendly name. */ friendlyName?: string; /** Gets or sets the managed resource group name */ managedResourceGroupName?: string; /** Gets the resource identifiers of the managed resources. */ managedResources?: AccountPropertiesManagedResources; /** Gets the private endpoint connections information. */ privateEndpointConnections?: Array<PrivateEndpointConnection>; /** Gets or sets the state of the provisioning. */ provisioningState?: | "Unknown" | "Creating" | "Moving" | "Deleting" | "SoftDeleting" | "SoftDeleted" | "Failed" | "Succeeded" | "Canceled"; /** Gets or sets the public network access. */ publicNetworkAccess?: "NotSpecified" | "Enabled" | "Disabled"; } export interface CloudConnectors { /** * AWS external identifier. * Configured in AWS to allow use of the role arn used for scanning */ awsExternalId?: string; } export interface AccountEndpoints { /** Gets the catalog endpoint. */ catalog?: string; /** Gets the guardian endpoint. */ guardian?: string; /** Gets the scan endpoint. */ scan?: string; } export interface AccountPropertiesEndpoints extends AccountEndpoints {} export interface ManagedResources { /** Gets the managed event hub namespace resource identifier. */ eventHubNamespace?: string; /** Gets the managed resource group resource identifier. This resource group will host resource dependencies for the account. */ resourceGroup?: string; /** Gets the managed storage account resource identifier. */ storageAccount?: string; } export interface AccountPropertiesManagedResources extends ManagedResources {} export interface PrivateEndpointConnection { /** Gets or sets the identifier. */ id?: string; /** Gets or sets the name. */ name?: string; /** The connection identifier. */ properties?: PrivateEndpointConnectionProperties; /** Gets or sets the type. */ type?: string; } export interface PrivateEndpointConnectionProperties { /** The private endpoint information. */ privateEndpoint?: PrivateEndpoint; /** The private link service connection state. */ privateLinkServiceConnectionState?: PrivateLinkServiceConnectionState; /** The provisioning state. */ provisioningState?: string; } export interface PrivateEndpoint { /** The private endpoint identifier. */ id?: string; } export interface PrivateLinkServiceConnectionState { /** The required actions. */ actionsRequired?: string; /** The description. */ description?: string; /** The status. */ status?: "Unknown" | "Pending" | "Approved" | "Rejected" | "Disconnected"; } export interface AccountSku { /** Gets or sets the sku capacity. Possible values include: 4, 16 */ capacity?: number; /** Gets or sets the sku name. */ name?: "Standard"; } export interface SystemData { /** The timestamp of resource creation (UTC). */ createdAt?: Date; /** The identity that created the resource. */ createdBy?: string; /** The type of identity that created the resource. */ createdByType?: "User" | "Application" | "ManagedIdentity" | "Key"; /** The timestamp of the last modification the resource (UTC). */ lastModifiedAt?: Date; /** The identity that last modified the resource. */ lastModifiedBy?: string; /** The type of identity that last modified the resource. */ lastModifiedByType?: "User" | "Application" | "ManagedIdentity" | "Key"; } export interface AccountSystemData extends SystemData {} export interface ErrorResponseModel { /** Gets or sets the error. */ error?: ErrorResponseModelError; } export interface ErrorModel { /** Gets or sets the code. */ code?: string; /** Gets or sets the details. */ details?: Array<ErrorModel>; /** Gets or sets the messages. */ message?: string; /** Gets or sets the target. */ target?: string; } export interface ErrorResponseModelError extends ErrorModel {} export interface DataPlaneAccountUpdateParameters { /** The friendly name for the azure resource. */ friendlyName?: string; } export interface AccessKeys { /** Gets or sets the primary connection string. */ atlasKafkaPrimaryEndpoint?: string; /** Gets or sets the secondary connection string. */ atlasKafkaSecondaryEndpoint?: string; } export interface AccessKeyOptions { /** The access key type. */ keyType?: "PrimaryAtlasKafkaKey" | "SecondaryAtlasKafkaKey"; } export interface Collection { /** Gets the state of the provisioning. */ collectionProvisioningState?: | "Unknown" | "Creating" | "Moving" | "Deleting" | "Failed" | "Succeeded"; /** Gets or sets the description. */ description?: string; /** Gets or sets the friendly name of the collection. */ friendlyName?: string; /** Gets the name. */ name?: string; /** Gets or sets the parent collection reference. */ parentCollection?: CollectionReference; /** Metadata pertaining to creation and last modification of the resource. */ systemData?: CollectionSystemData; } export interface CollectionReference { /** Gets or sets the reference name. */ referenceName?: string; /** Gets or sets the reference type property. */ type?: string; } export interface CollectionSystemData extends SystemData {} export interface CollectionList { /** Total item count. */ count?: number; /** The Url of next result page. */ nextLink?: string; /** Collection of items of type results. */ value: Array<Collection>; } export interface CollectionNameResponseList { /** Total item count. */ count?: number; /** The Url of next result page. */ nextLink?: string; /** Collection of items of type results. */ value: Array<CollectionNameResponse>; } export interface CollectionNameResponse { /** Gets or sets the friendly name of the collection. */ friendlyName?: string; /** Gets the name. */ name?: string; } export interface CollectionPathResponse { /** The friendly names of ancestors starting from the default (root) collection and ending with the immediate parent. */ parentFriendlyNameChain?: Array<string>; /** The names of ancestors starting from the default (root) collection and ending with the immediate parent. */ parentNameChain?: Array<string>; } export interface ResourceSetRuleConfig { /** Gets or sets the advanced resource set property of the account. */ advancedResourceSet?: AdvancedResourceSet; /** The name of the rule */ name?: string; /** The configuration rules for path pattern extraction. */ pathPatternConfig?: PathPatternExtractorConfig; } export interface AdvancedResourceSet { /** Date at which ResourceSetProcessing property of the account is updated. */ modifiedAt?: Date; /** The advanced resource property of the account. */ resourceSetProcessing?: "Default" | "Advanced"; } export interface PathPatternExtractorConfig { acceptedPatterns?: Array<Filter>; complexReplacers?: Array<ComplexReplacerConfig>; createdBy: string; enableDefaultPatterns: boolean; lastUpdatedTimestamp?: number; modifiedBy?: string; normalizationRules?: Array<NormalizationRule>; regexReplacers?: Array<RegexReplacer>; rejectedPatterns?: Array<Filter>; scopedRules?: Array<ScopedRule>; version?: number; } export interface Filter { createdBy?: string; filterType?: "Pattern" | "Regex"; lastUpdatedTimestamp?: number; modifiedBy?: string; name: string; path: string; } export interface ComplexReplacerConfig { createdBy?: string; description?: string; disabled?: boolean; disableRecursiveReplacerApplication?: boolean; lastUpdatedTimestamp?: number; modifiedBy?: string; name?: string; typeName?: string; } export interface NormalizationRule { description?: string; disabled?: boolean; dynamicReplacement?: boolean; entityTypes?: Array<string>; lastUpdatedTimestamp?: number; name?: string; regex?: FastRegex; replaceWith?: string; version?: number; } export interface FastRegex { maxDigits?: number; maxLetters?: number; minDashes?: number; minDigits?: number; minDigitsOrLetters?: number; minDots?: number; minHex?: number; minLetters?: number; minUnderscores?: number; options?: number; regexStr?: string; } export interface RegexReplacer { condition?: string; createdBy?: string; description?: string; disabled: boolean; disableRecursiveReplacerApplication?: boolean; doNotReplaceRegex?: FastRegex; lastUpdatedTimestamp?: number; modifiedBy?: string; name: string; regex?: FastRegex; replaceWith?: string; } export interface ScopedRule { bindingUrl: string; rules?: Array<Rule>; storeType: string; } export interface Rule { displayName?: string; isResourceSet?: boolean; lastUpdatedTimestamp?: number; name?: string; qualifiedName: string; } export interface ResourceSetRuleConfigList { /** Total item count. */ count?: number; /** The Url of next result page. */ nextLink?: string; /** Collection of items of type results. */ value: Array<ResourceSetRuleConfig>; }
the_stack
import { Button, Row, Select, Space, Tabs, Transfer, Tree } from 'antd'; import { FilterConditionType } from 'app/constants'; import useI18NPrefix, { I18NComponentProps } from 'app/hooks/useI18NPrefix'; import useMount from 'app/hooks/useMount'; import ChartFilterCondition, { ConditionBuilder, } from 'app/models/ChartFilterCondition'; import { RelationFilterValue } from 'app/types/ChartConfig'; import ChartDataView from 'app/types/ChartDataView'; import { getDistinctFields } from 'app/utils/fetch'; import { FilterSqlOperator } from 'globalConstants'; import { forwardRef, ForwardRefRenderFunction, useCallback, useImperativeHandle, useState, } from 'react'; import styled from 'styled-components/macro'; import { SPACE_TIMES, SPACE_XS } from 'styles/StyleConstants'; import { isEmpty, isEmptyArray, IsKeyIn, isTreeModel } from 'utils/object'; import { FilterOptionForwardRef } from '.'; import CategoryConditionEditableTable from './CategoryConditionEditableTable'; import CategoryConditionRelationSelector from './CategoryConditionRelationSelector'; const CategoryConditionConfiguration: ForwardRefRenderFunction< FilterOptionForwardRef, { colName: string; dataView?: ChartDataView; condition?: ChartFilterCondition; onChange: (condition: ChartFilterCondition) => void; fetchDataByField?: (fieldId) => Promise<string[]>; } & I18NComponentProps > = ( { colName, i18nPrefix, condition, dataView, onChange: onConditionChange, fetchDataByField, }, ref, ) => { const t = useI18NPrefix(i18nPrefix); const [curTab, setCurTab] = useState<FilterConditionType>(() => { if ( [ FilterConditionType.List, FilterConditionType.Condition, FilterConditionType.Customize, ].includes(condition?.type!) ) { return condition?.type!; } return FilterConditionType.List; }); const [targetKeys, setTargetKeys] = useState<string[]>(() => { let values; if (condition?.operator === FilterSqlOperator.In) { values = condition?.value; if (Array.isArray(condition?.value)) { const firstValues = (condition?.value as [])?.filter(n => { if (IsKeyIn(n as RelationFilterValue, 'key')) { return (n as RelationFilterValue).isSelected; } return false; }) || []; values = firstValues?.map((n: RelationFilterValue) => n.key); } } return values || []; }); const [selectedKeys, setSelectedKeys] = useState<string[]>([]); const [isTree, setIsTree] = useState(isTreeModel(condition?.value)); const [treeOptions, setTreeOptions] = useState<string[]>([]); const [listDatas, setListDatas] = useState<RelationFilterValue[]>([]); const [treeDatas, setTreeDatas] = useState<RelationFilterValue[]>([]); useImperativeHandle(ref, () => ({ onValidate: (args: ChartFilterCondition) => { if (isEmpty(args?.operator)) { return false; } if (args?.operator === FilterSqlOperator.In) { return !isEmptyArray(args?.value); } else if ( [ FilterSqlOperator.Contain, FilterSqlOperator.PrefixContain, FilterSqlOperator.SuffixContain, FilterSqlOperator.Equal, FilterSqlOperator.NotContain, FilterSqlOperator.NotPrefixContain, FilterSqlOperator.NotSuffixContain, FilterSqlOperator.NotEqual, ].includes(args?.operator as FilterSqlOperator) ) { return !isEmpty(args?.value); } else if ( [FilterSqlOperator.Null, FilterSqlOperator.NotNull].includes( args?.operator as FilterSqlOperator, ) ) { return true; } return false; }, })); useMount(() => { if (curTab === FilterConditionType.List) { handleFetchData(); } }); const getDataOptionFields = () => { return dataView?.meta || []; }; const isChecked = (selectedKeys, eventKey) => selectedKeys.indexOf(eventKey) !== -1; const fetchNewDataset = async (viewId, colName: string) => { const fieldDataset = await getDistinctFields( viewId, [colName], undefined, undefined, ); return fieldDataset; }; const setListSelectedState = ( list?: RelationFilterValue[], keys?: string[], ) => { return (list || []).map(c => Object.assign(c, { isSelected: isChecked(keys, c.key) }), ); }; const setTreeCheckableState = ( treeList?: RelationFilterValue[], keys?: string[], ) => { return (treeList || []).map(c => { c.isSelected = isChecked(keys, c.key); c.children = setTreeCheckableState(c.children, keys); return c; }); }; const handleGeneralListChange = async selectedKeys => { const items = setListSelectedState(listDatas, selectedKeys); setTargetKeys(selectedKeys); setListDatas(items); const generalTypeItems = items?.filter(i => i.isSelected); const filter = new ConditionBuilder(condition) .setOperator(FilterSqlOperator.In) .setValue(generalTypeItems) .asGeneral(); onConditionChange(filter); }; const filterGeneralListOptions = useCallback( (inputValue, option) => option.label?.includes(inputValue) || false, [], ); const handleGeneralTreeChange = async treeSelectedKeys => { const selectedKeys = treeSelectedKeys.checked; const treeItems = setTreeCheckableState(treeDatas, selectedKeys); setTargetKeys(selectedKeys); setTreeDatas(treeItems); const filter = new ConditionBuilder(condition) .setOperator(FilterSqlOperator.In) .setValue(treeItems) .asTree(); onConditionChange(filter); }; const onSelectChange = ( sourceSelectedKeys: string[], targetSelectedKeys: string[], ) => { const newSelectedKeys = [...sourceSelectedKeys, ...targetSelectedKeys]; setSelectedKeys(newSelectedKeys); }; const handleTreeOptionChange = ( associateField: string, labelField: string, ) => { setTreeOptions([associateField, labelField]); }; const handleFetchData = () => { fetchNewDataset?.(dataView?.id, colName).then(dataset => { if (isTree) { // setTreeDatas(convertToTree(dataset?.columns, selectedKeys)); // setListDatas(convertToList(dataset?.columns, selectedKeys)); } else { setListDatas(convertToList(dataset?.rows, selectedKeys)); } }); }; const convertToList = (collection, selectedKeys) => { const items: string[] = (collection || []).flatMap(c => c); const uniqueKeys = Array.from(new Set(items)); return uniqueKeys.map(item => ({ key: item, label: item, isSelected: selectedKeys.includes(item), })); }; const convertToTree = (collection, selectedKeys) => { const associateField = treeOptions?.[0]; const labelField = treeOptions?.[1]; if (!associateField || !labelField) { return []; } const associateKeys = Array.from( new Set(collection?.map(c => c[associateField])), ); const treeNodes = associateKeys .map(key => { const associateItem = collection?.find(c => c[colName] === key); if (!associateItem) { return null; } const associateChildren = collection .filter(c => c[associateField] === key) .map(c => { const itemKey = c[labelField]; return { key: itemKey, label: itemKey, isSelected: isChecked(selectedKeys, itemKey), }; }); const itemKey = associateItem?.[colName]; return { key: itemKey, label: itemKey, isSelected: isChecked(selectedKeys, itemKey), children: associateChildren, }; }) .filter(i => Boolean(i)) as RelationFilterValue[]; return treeNodes; }; const handleTabChange = (activeKey: string) => { const conditionType = +activeKey; setCurTab(conditionType); const filter = new ConditionBuilder(condition) .setOperator(null!) .setValue(null) .asFilter(conditionType); setTreeDatas([]); setTargetKeys([]); setListDatas([]); onConditionChange(filter); }; return ( <StyledTabs activeKey={curTab.toString()} onChange={handleTabChange}> <Tabs.TabPane tab={t('general')} key={FilterConditionType.List.toString()} > <Row> <Space> <Button type="primary" onClick={handleFetchData}> {t('load')} </Button> {/* <Checkbox checked={isTree} disabled onChange={e => setIsTree(e.target.checked)} > {t('useTree')} </Checkbox> */} </Space> </Row> <Row> <Space> {isTree && ( <> {t('associateField')} <Select value={treeOptions?.[0]} options={getDataOptionFields()?.map(f => ({ label: f.name, value: f.id, }))} onChange={value => handleTreeOptionChange(value, treeOptions?.[1]) } /> {t('labelField')} <Select value={treeOptions?.[1]} options={getDataOptionFields()?.map(f => ({ label: f.name, value: f.id, }))} onChange={value => handleTreeOptionChange(treeOptions?.[0], value) } /> </> )} </Space> </Row> {isTree && ( <Tree blockNode checkable checkStrictly defaultExpandAll checkedKeys={targetKeys} treeData={treeDatas} onCheck={handleGeneralTreeChange} onSelect={handleGeneralTreeChange} /> )} {!isTree && ( <Transfer operations={[t('moveToRight'), t('moveToLeft')]} dataSource={listDatas} titles={[`${t('sourceList')}`, `${t('targetList')}`]} targetKeys={targetKeys} selectedKeys={selectedKeys} onChange={handleGeneralListChange} onSelectChange={onSelectChange} render={item => item.label} filterOption={filterGeneralListOptions} showSearch pagination /> )} </Tabs.TabPane> <Tabs.TabPane tab={t('customize')} key={FilterConditionType.Customize.toString()} > <CategoryConditionEditableTable dataView={dataView} i18nPrefix={i18nPrefix} condition={condition} onConditionChange={onConditionChange} fetchDataByField={fetchDataByField} /> </Tabs.TabPane> <Tabs.TabPane tab={t('condition')} key={FilterConditionType.Condition.toString()} > <CategoryConditionRelationSelector condition={condition} onConditionChange={onConditionChange} /> </Tabs.TabPane> </StyledTabs> ); }; export default forwardRef(CategoryConditionConfiguration); const StyledTabs = styled(Tabs)` & .ant-tabs-content-holder { max-height: 600px; margin-top: 10px; overflow-y: auto; } & .ant-form-item-explain { align-self: end; } .ant-transfer { margin: ${SPACE_XS} 0; /* * will be solved by upgrading antd to version a 4.17.x+ * https://github.com/ant-design/ant-design/pull/31809 */ .ant-transfer-list { width: ${SPACE_TIMES(56)}; height: ${SPACE_TIMES(80)}; .ant-pagination input { width: 48px; } } } .ant-select { width: 200px; } `;
the_stack
import * as chalk from "chalk"; import { UAState, UAStateVariable, UATransition, UATransition_Base, UATransitionVariable } from "node-opcua-nodeset-ua"; import { assert } from "node-opcua-assert"; import { ObjectTypeIds } from "node-opcua-constants"; import { coerceLocalizedText, LocalizedText, NodeClass } from "node-opcua-data-model"; import { AttributeIds } from "node-opcua-data-model"; import { NodeId } from "node-opcua-nodeid"; import { StatusCodes } from "node-opcua-status-code"; import { DataType } from "node-opcua-variant"; import { BaseNode, UAMethod, UAObject, UAObjectType, UAVariable } from "node-opcua-address-space-base"; import { registerNodePromoter } from "../../source/loader/register_node_promoter"; import { UAStateMachineEx, TransitionSelector } from "../../source/interfaces/state_machine/ua_state_machine_type"; import { UAObjectImpl } from "../ua_object_impl"; import { UATransitionEx } from "../../source/interfaces/state_machine/ua_transition_ex"; import { BaseNodeImpl } from "../base_node_impl"; const doDebug = false; export declare interface UATransitionImpl extends UATransition, UATransitionEx {} export class UATransitionImpl implements UATransition, UATransitionEx {} function getComponentFromTypeAndSubtype(typeDef: UAObjectType): UAObject[] { const components_parts: BaseNode[][] = []; components_parts.push(typeDef.getComponents()); while (typeDef.subtypeOfObj) { typeDef = typeDef.subtypeOfObj; components_parts.push(typeDef.getComponents()); } return Array.prototype.concat.apply([], components_parts).filter((x: BaseNode) => x.nodeClass === NodeClass.Object); } export interface UAStateMachineImpl { currentState: UAStateVariable<LocalizedText>; lastTransition?: UATransitionVariable<LocalizedText>; // Extra _currentStateNode: UAState | null; } const defaultPredicate = (transitions: UATransition[], fromState: UAState, toState: UAState) => { if (transitions.length === 0) { return null; } if (transitions.length === 1) { return transitions[0]; } // tslint:disable-next-line: no-console console.log(" FromState = ", fromState.browseName.toString()); // tslint:disable-next-line: no-console console.log(" ToState = ", toState.browseName.toString()); for (const transition of transitions) { // tslint:disable-next-line: no-console console.log(" possible transition : ", transition.browseName.toString(), " ", transition.nodeId.toString()); } // tslint:disable-next-line: no-console console.log( "warning: a duplicated FromState Reference to the same target has been found.\nPlease check your model or provide a predicate method to select which one to use" ); // tslint:disable-next-line: no-console console.log("fromStateNode: ", fromState.toString()); return transitions[0]; }; /* * * @class StateMachine * @constructor * @extends UAObject * * */ export class UAStateMachineImpl extends UAObjectImpl implements UAStateMachineEx { public getStates(): UAState[] { const addressSpace = this.addressSpace; const initialStateType = addressSpace.findObjectType("InitialStateType"); // istanbul ignore next if (!initialStateType) { throw new Error("cannot find InitialStateType"); } const stateType = addressSpace.findObjectType("StateType"); // istanbul ignore next if (!stateType) { throw new Error("cannot find StateType"); } assert(initialStateType.isSupertypeOf(stateType)); const typeDef = this.typeDefinitionObj; let comp = getComponentFromTypeAndSubtype(typeDef); comp = comp.filter((c) => { if (!c.typeDefinitionObj || c.typeDefinitionObj.nodeClass !== NodeClass.ObjectType) { return false; } return c.typeDefinitionObj.isSupertypeOf(stateType); }); return comp as UAState[]; } public get states(): UAState[] { return this.getStates(); } /** * @method getStateByName * @param name the name of the state to get * @return the state with the given name */ public getStateByName(name: string): UAState | null { let states = this.getStates(); states = states.filter((s: any) => { return s.browseName.name === name; }); assert(states.length <= 1); return states.length === 1 ? (states[0] as any as UAState) : null; } public getTransitions(): UATransitionEx[] { const addressSpace = this.addressSpace; const transitionType = addressSpace.findObjectType("TransitionType"); // istanbul ignore next if (!transitionType) { throw new Error("cannot find TransitionType"); } const typeDef = this.typeDefinitionObj; let comp = getComponentFromTypeAndSubtype(typeDef); comp = comp.filter((c) => { if (!c.typeDefinitionObj || c.typeDefinitionObj.nodeClass !== NodeClass.ObjectType) { return false; } return c.typeDefinitionObj.isSupertypeOf(transitionType); }); return comp as UATransitionEx[]; } public get transitions(): UATransitionEx[] { return this.getTransitions(); } /** * return the node InitialStateType * @property initialState */ get initialState(): UAState | null { const addressSpace = this.addressSpace; const initialStateType = addressSpace.findObjectType("InitialStateType"); const typeDef = this.typeDefinitionObj; let comp = getComponentFromTypeAndSubtype(typeDef); comp = comp.filter((c: any) => c.typeDefinitionObj === initialStateType); // istanbul ignore next if (comp.length > 1) { throw new Error(" More than 1 initial state in stateMachine"); } return comp.length === 0 ? null : (comp[0] as UAState); } /** * * @param node * @private */ public _coerceNode(node: UAState | BaseNode | null | string | NodeId): BaseNode | null { if (node === null) { return null; } const addressSpace = this.addressSpace; if (node instanceof BaseNodeImpl) { return node; } else if (node instanceof NodeId) { return addressSpace.findNode(node) as BaseNode; } else if (typeof node === "string") { return this.getStateByName(node) as any as BaseNode; } return null; } /** * @method isValidTransition * @param toStateNode * @return {boolean} */ public isValidTransition(toStateNode: UAState | string, predicate?: TransitionSelector): boolean { // is it legal to go from state currentState to toStateNode; if (!this.currentStateNode) { return true; } const n = this.currentState.readValue(); // to be executed there must be a transition from currentState to toState const transition = this.findTransitionNode(this.currentStateNode, toStateNode, predicate); if (!transition) { // istanbul ignore next if (doDebug) { // tslint:disable-next-line: no-console console.log(" No transition from ", this.currentStateNode.browseName.toString(), " to ", toStateNode.toString()); } return false; } return true; } /** */ public findTransitionNode( fromStateNode: NodeId | UAState | string | null, toStateNode: NodeId | UAState | string | null, predicate?: TransitionSelector ): UATransitionEx | null { const addressSpace = this.addressSpace; const _fromStateNode = this._coerceNode(fromStateNode) as UAObject; if (!_fromStateNode) { return null; } const _toStateNode = this._coerceNode(toStateNode) as UAObject; if (!_toStateNode) { return null; } if (_fromStateNode.nodeClass !== NodeClass.Object) { throw new Error("Internal Error"); } if (_toStateNode && _toStateNode.nodeClass !== NodeClass.Object) { throw new Error("Internal Error"); } const stateType = addressSpace.findObjectType("StateType"); if (!stateType) { throw new Error("Cannot find StateType"); } assert((_fromStateNode.typeDefinitionObj as any).isSupertypeOf(stateType)); assert((_toStateNode.typeDefinitionObj as any).isSupertypeOf(stateType)); let transitions = _fromStateNode.findReferencesAsObject("FromState", false) as UATransitionImpl[]; transitions = transitions.filter((transition: any) => { assert(transition.toStateNode.nodeClass === NodeClass.Object); return transition.toStateNode === _toStateNode; }); if (transitions.length === 0) { // cannot find a transition from fromState to toState return null; } // istanbul ignore next if (transitions.length > 1) { const selectedTransition = (predicate || defaultPredicate)( transitions, _fromStateNode as unknown as UAState, _toStateNode as unknown as UAState ); return selectedTransition as UATransitionEx; } return transitions[0]; } public get currentStateNode(): UAState | null { return this._currentStateNode; } /** * @property currentStateNode * @type BaseNode */ public set currentStateNode(value: UAState | null) { this._currentStateNode = value; } /** */ public getCurrentState(): string | null { // xx this.currentState.readValue().value.value.text // xx this.shelvingState.currentStateNode.browseName.toString() if (!this.currentStateNode) { return null; } return this.currentStateNode.browseName.toString(); } /** * @method setState */ public setState(toStateNode: string | UAState | null, predicate?: TransitionSelector): void { if (!toStateNode) { this.currentStateNode = null; this.currentState.setValueFromSource({ dataType: DataType.LocalizedText, value: null }, StatusCodes.BadStateNotActive); return; } if (typeof toStateNode === "string") { const state = this.getStateByName(toStateNode); // istanbul ignore next if (!state) { throw new Error("Cannot find state with name " + toStateNode); } assert(state.browseName.name!.toString() === toStateNode); toStateNode = state; } const fromStateNode = this.currentStateNode; toStateNode = this._coerceNode(toStateNode) as any as UAState; assert(toStateNode.nodeClass === NodeClass.Object); this.currentState.setValueFromSource( { dataType: DataType.LocalizedText, value: coerceLocalizedText(toStateNode.browseName.toString()) }, StatusCodes.Good ); this.currentStateNode = toStateNode; const transitionNode = this.findTransitionNode(fromStateNode, toStateNode, predicate) as UATransitionImpl; if (transitionNode) { // xx console.log("transitionNode ",transitionNode.toString()); // The inherited Property SourceNode shall be filled with the NodeId of the StateMachine instance where the // Transition occurs. If the Transition occurs in a SubStateMachine, then the NodeId of the SubStateMachine // has to be used. If the Transition occurs between a StateMachine and a SubStateMachine, then the NodeId of // the StateMachine has to be used, independent of the direction of the Transition. // Transition identifies the Transition that triggered the Event. // FromState identifies the State before the Transition. // ToState identifies the State after the Transition. this.raiseEvent("TransitionEventType", { // Base EventType // xx nodeId: this.nodeId, // TransitionEventType // TransitionVariableType transition: { dataType: "LocalizedText", value: (transitionNode as BaseNode).displayName[0] }, "transition.id": transitionNode.transitionNumber.readValue().value, fromState: { dataType: "LocalizedText", value: fromStateNode ? fromStateNode.displayName[0] : "" }, // StateVariableType "fromState.id": fromStateNode ? fromStateNode.stateNumber.readValue().value : { dataType: "Null" }, toState: { dataType: "LocalizedText", value: toStateNode.displayName[0] }, // StateVariableType "toState.id": toStateNode.stateNumber.readValue().value }); } else { if (fromStateNode && fromStateNode !== toStateNode) { // istanbul ignore next if (doDebug) { const f = fromStateNode.browseName.toString(); const t = toStateNode.browseName.toString(); // tslint:disable-next-line:no-console console.log(chalk.red("Warning"), " cannot raise event : transition " + f + " to " + t + " is missing"); } } } // also update executable flags on methods for (const method of this.getMethods()) { (method as any)._notifyAttributeChange(AttributeIds.Executable); } } /** * @internal * @private */ public _post_initialize(): void { const addressSpace = this.addressSpace; const finiteStateMachineType = addressSpace.findObjectType("FiniteStateMachineType"); if (!finiteStateMachineType) { throw new Error("cannot find FiniteStateMachineType"); } // xx assert(this.typeDefinitionObj && !this.subtypeOfObj); // xx assert(!this.typeDefinitionObj || this.typeDefinitionObj.isSupertypeOf(finiteStateMachineType)); // get current Status const d = this.currentState.readValue(); if (d.statusCode !== StatusCodes.Good) { this.setState(null); } else { const txt = d.value && d.value.value ? (d.value.value.text ? d.value.value.text.toString() : d.value.value.toString()) : ""; this.currentStateNode = this.getStateByName(txt); } } } export function promoteToStateMachine(node: UAObject): UAStateMachineEx { if (node instanceof UAStateMachineImpl) { return node; // already promoted } Object.setPrototypeOf(node, UAStateMachineImpl.prototype); assert(node instanceof UAStateMachineImpl, "should now be a State Machine"); const _node = node as unknown as UAStateMachineImpl; _node._post_initialize(); return _node; } registerNodePromoter(ObjectTypeIds.FiniteStateMachineType, promoteToStateMachine);
the_stack
import * as fs from "fs"; import * as glob from "glob"; import { join } from "path"; import * as readline from "readline"; import * as Yargs from "yargs"; import { CloudSqlite, EditableWorkspaceDb, IModelHost, IModelHostConfiguration, IModelJsFs, ITwinWorkspaceDb, WorkspaceContainerId, WorkspaceDbName, WorkspaceResourceName, } from "@itwin/core-backend"; import { DbResult, StopWatch } from "@itwin/core-bentley"; import { LocalDirName, LocalFileName } from "@itwin/core-common"; // cspell:ignore nodir /* eslint-disable id-blacklist,no-console */ /** Properties for accessing a blob storage account. */ interface BlobAccountProps { /** Token that provides required access (read/write/create/etc.) for blob store operation. */ sasToken: string; /** Name for blob store user account */ accountName: string; /** The string that identifies the storage type. Default = "azure?sas=1" */ storageType: string; } /** Allows overriding the location of WorkspaceDbs. If not present, defaults to `${homedir}/iTwin/Workspace` */ interface EditorOpts extends BlobAccountProps { /** Directory for WorkspaceDbs */ directory?: LocalDirName; containerId: WorkspaceContainerId; } /** Id of WorkspaceDb for operation */ interface WorkspaceDbOpt extends EditorOpts { dbName: WorkspaceDbName; } /** Resource type names */ type RscType = "blob" | "string" | "file"; /** Options for adding, updating, extracting, or deleting resources from a WorkspaceDb */ interface ResourceOption extends WorkspaceDbOpt { rscName?: WorkspaceResourceName; update: boolean; type: RscType; } /** Options for deleting resources from a WorkspaceDb */ interface RemoveResourceOpts extends ResourceOption { rscName: WorkspaceResourceName; } /** Options for extracting resources from a WorkspaceDb */ interface ExtractResourceOpts extends ResourceOption { rscName: WorkspaceResourceName; fileName: LocalFileName; } /** Options for adding or updating local files as resources into a WorkspaceDb */ interface AddFileOptions extends ResourceOption { files: LocalFileName; root?: LocalDirName; } /** Options for listing the resources in a WorkspaceDb */ interface ListOptions extends WorkspaceDbOpt { strings?: boolean; files?: boolean; blobs?: boolean; } interface TransferOptions extends BlobAccountProps, WorkspaceDbOpt { /** If present, name of local file for download. */ localFile?: string; } /** Options for uploading a WorkspaceDb to blob storage */ interface UploadOptions extends TransferOptions { initialize: boolean; replace: boolean; } /** Create a new empty WorkspaceDb */ async function createWorkspaceDb(args: WorkspaceDbOpt) { const wsFile = new EditableWorkspaceDb(args.dbName, IModelHost.appWorkspace.getContainer(args)); wsFile.create(); console.log(`created WorkspaceDb ${wsFile.sqliteDb.nativeDb.getFilePath()}`); wsFile.close(); } /** open, call a function to process, then close a WorkspaceDb */ function processWorkspace<W extends ITwinWorkspaceDb, T extends WorkspaceDbOpt>(args: T, ws: W, fn: (ws: W, args: T) => void) { ws.open(); console.log(`WorkspaceDb [${ws.sqliteDb.nativeDb.getFilePath()}]`); try { fn(ws, args); } finally { ws.close(); } } /** Open for write, call a function to process, then close a WorkspaceDb */ function editWorkspace<T extends WorkspaceDbOpt>(args: T, fn: (ws: EditableWorkspaceDb, args: T) => void) { processWorkspace(args, new EditableWorkspaceDb(args.dbName, IModelHost.appWorkspace.getContainer(args)), fn); } /** Open for read, call a function to process, then close a WorkspaceDb */ function readWorkspace<T extends WorkspaceDbOpt>(args: T, fn: (ws: ITwinWorkspaceDb, args: T) => void) { processWorkspace(args, new ITwinWorkspaceDb(args.dbName, IModelHost.appWorkspace.getContainer(args)), fn); } /** List the contents of a WorkspaceDb */ async function listWorkspaceDb(args: ListOptions) { readWorkspace(args, (file, args) => { if (!args.strings && !args.blobs && !args.files) args.blobs = args.files = args.strings = true; if (args.strings) { console.log(" strings:"); file.sqliteDb.withSqliteStatement("SELECT id,value FROM strings", (stmt) => { while (DbResult.BE_SQLITE_ROW === stmt.step()) console.log(` name=[${stmt.getValueString(0)}], size=${stmt.getValueString(1).length}`); }); } if (args.blobs) { console.log(" blobs:"); file.sqliteDb.withSqliteStatement("SELECT id,value FROM blobs", (stmt) => { while (DbResult.BE_SQLITE_ROW === stmt.step()) console.log(` name=[${stmt.getValueString(0)}], size=${stmt.getValueBlob(1).length}`); }); } if (args.files) { console.log(" files:"); file.sqliteDb.withSqliteStatement("SELECT name FROM be_EmbedFile", (stmt) => { while (DbResult.BE_SQLITE_ROW === stmt.step()) { const embed = file.queryFileResource(stmt.getValueString(0)); if (embed) { const info = embed.info; const date = new Date(info.date); console.log(` name=[${stmt.getValueString(0)}], size=${info.size}, ext="${info.fileExt}", date=${date.toString()}`); } } }); } }); } /** Add or Update files into a WorkspaceDb. */ async function addResource(args: AddFileOptions) { editWorkspace(args, (wsFile, args) => { glob.sync(args.files, { cwd: args.root ?? process.cwd(), nodir: true }).forEach((filePath) => { const file = args.root ? join(args.root, filePath) : filePath; if (!IModelJsFs.existsSync(file)) throw new Error(`file [${file}] does not exist`); const name = args.rscName ?? filePath; try { if (args.type === "string") { const val = fs.readFileSync(file, "utf-8"); wsFile[args.update ? "updateString" : "addString"](name, val); } else if (args.type === "blob") { const val = fs.readFileSync(file); wsFile[args.update ? "updateBlob" : "addBlob"](name, val); } else { wsFile[args.update ? "updateFile" : "addFile"](name, file); } console.log(` ${args.update ? "updated" : "added"} "${file}" as ${args.type} resource [${name}]`); } catch (e: any) { console.error(e.message); } }); }); } /** Extract a single resource from a WorkspaceDb into a local file */ async function extractResource(args: ExtractResourceOpts) { readWorkspace(args, (file, args) => { const verify = <T>(val: T | undefined): T => { if (val === undefined) throw new Error(` ${args.type} resource "${args.rscName}" does not exist`); return val; }; if (args.type === "string") { fs.writeFileSync(args.fileName, verify(file.getString(args.rscName))); } else if (args.type === "blob") { fs.writeFileSync(args.fileName, verify(file.getBlob(args.rscName))); } else { verify(file.getFile(args.rscName, args.fileName)); } console.log(` ${args.type} resource [${args.rscName}] extracted to "${args.fileName}"`); }); } /** Remove a single resource from a WorkspaceDb */ async function removeResource(args: RemoveResourceOpts) { editWorkspace(args, (wsFile, args) => { if (args.type === "string") wsFile.removeString(args.rscName); else if (args.type === "blob") wsFile.removeBlob(args.rscName); else wsFile.removeFile(args.rscName); console.log(` removed ${args.type} resource [${args.rscName}]`); }); } function getDbFileName(args: WorkspaceDbOpt): LocalFileName { return new ITwinWorkspaceDb(args.dbName, IModelHost.appWorkspace.getContainer(args)).localFile; } /** Vacuum a local WorkspaceDb file, usually immediately prior to uploading. */ async function vacuumWorkspaceDb(args: WorkspaceDbOpt) { const localFile = getDbFileName(args); IModelHost.platform.DgnDb.vacuum(localFile); console.log(`${localFile} vacuumed`); } /** Either upload or download a WorkspaceDb to/from a WorkspaceContainer. Shows progress % during transfer */ async function performTransfer(direction: CloudSqlite.TransferDirection, args: TransferOptions) { const localFile = args.localFile ?? getDbFileName(args); const info = `${direction} ${localFile}, containerId=${args.containerId}, WorkspaceDbName=${args.dbName} : `; let last = 0; const onProgress = (loaded: number, total: number) => { if (loaded > last) { last = loaded; const message = ` ${(loaded * 100 / total).toFixed(2)}%`; readline.cursorTo(process.stdout, info.length); process.stdout.write(message); } return 0; }; process.stdout.write(info); const timer = new StopWatch(direction, true); await CloudSqlite.transferDb(direction, { ...args, localFile, onProgress }); readline.cursorTo(process.stdout, info.length); process.stdout.write(`complete, ${timer.elapsedSeconds.toString()} seconds`); } /** Upload a WorkspaceDb to a WorkspaceContainer. */ async function uploadWorkspaceDb(args: UploadOptions) { if (args.initialize) await CloudSqlite.initializeContainer(args); return performTransfer("upload", args); } /** Download a WorkspaceDb from a WorkspaceContainer. */ async function downloadWorkspaceDb(args: TransferOptions) { return performTransfer("download", args); } /** Delete a WorkspaceDb from a WorkspaceContainer. */ async function deleteWorkspaceDb(args: BlobAccountProps & WorkspaceDbOpt) { await CloudSqlite.deleteDb(args); console.log(`deleted WorkspaceDb [${args.dbName}] from containerId: ${args.containerId}`); } /** Start `IModelHost`, then run a WorkspaceEditor command. Errors are logged to console. */ function runCommand<T extends EditorOpts>(cmd: (args: T) => Promise<void>) { return async (args: T) => { try { const config = new IModelHostConfiguration(); if (args.directory) config.workspace = { containerDir: args.directory }; await IModelHost.startup(config); await cmd(args); } catch (e: any) { console.error(e.message); } }; } /** Parse and execute WorkspaceEditor commands */ async function main() { const type = { alias: "t", describe: "the type of resource", choices: ["blob", "string", "file"], required: true }; const update = { alias: "u", describe: "update (i.e. replace) rather than add the files", boolean: true, default: false }; Yargs.usage("Edits or lists contents of a WorkspaceDb"); Yargs.wrap(Math.min(130, Yargs.terminalWidth())); Yargs.strict(); Yargs.config(); Yargs.default("config", "workspaceEditor.json"); Yargs.help(); Yargs.version("V2.0"); Yargs.options({ directory: { alias: "d", describe: "directory to use for WorkspaceContainers", string: true }, containerId: { alias: "c", describe: "WorkspaceContainerId for WorkspaceDb", string: true, required: true }, sasToken: { alias: "s", describe: "shared access signature token", string: true, default: "" }, accountName: { alias: "a", describe: "cloud storage account name for container", string: true, default: "" }, storageType: { describe: "storage module type", string: true, default: "azure?sas=1" }, }); Yargs.command({ command: "create <dbName>", describe: "create a new WorkspaceDb", handler: runCommand(createWorkspaceDb), }); Yargs.command({ command: "list <dbName>", describe: "list the contents of a WorkspaceDb", builder: { strings: { alias: "s", describe: "list string resources", boolean: true, default: false }, blobs: { alias: "b", describe: "list blob resources", boolean: true, default: false }, files: { alias: "f", describe: "list file resources", boolean: true, default: false }, }, handler: runCommand(listWorkspaceDb), }); Yargs.command({ command: "add <dbName> <files>", describe: "add or update files into a WorkspaceDb", builder: { name: { alias: "n", describe: "resource name for file", string: true }, root: { alias: "r", describe: "root directory. Path parts after this will be saved in resource name", string: true }, update, type, }, handler: runCommand(addResource), }); Yargs.command({ command: "extract <dbName> <rscName> <fileName>", describe: "extract a resource from a WorkspaceDb into a local file", builder: { type }, handler: runCommand(extractResource), }); Yargs.command({ command: "remove <dbName> <rscName>", describe: "remove a resource from a WorkspaceDb", builder: { type }, handler: runCommand(removeResource), }); Yargs.command({ command: "upload <dbName>", describe: "upload a WorkspaceDb to cloud storage", builder: { initialize: { alias: "i", describe: "initialize container", boolean: true, default: false }, localFile: { alias: "l", describe: "name of source local file", string: true, required: false }, }, handler: runCommand(uploadWorkspaceDb), }); Yargs.command({ command: "download <dbName>", describe: "download a WorkspaceDb from cloud storage to local file", builder: { localFile: { alias: "l", describe: "name of target local file", string: true, required: false }, }, handler: runCommand(downloadWorkspaceDb), }); Yargs.command({ command: "delete <dbName>", describe: "delete a WorkspaceDb from cloud storage", handler: runCommand(deleteWorkspaceDb), }); Yargs.command({ command: "vacuum <dbName>", describe: "vacuum a WorkspaceDb", handler: runCommand(vacuumWorkspaceDb), }); Yargs.demandCommand(); Yargs.argv; } void main();
the_stack
import * as React from 'react'; import styles from './AddJsCssReference.module.scss'; import { IAddJsCssReferenceProps } from './IAddJsCssReferenceProps'; import { escape } from '@microsoft/sp-lodash-subset'; import { TextField, MaskedTextField } from 'office-ui-fabric-react/lib/TextField'; import { ListView, IViewField, SelectionMode} from "@pnp/spfx-controls-react/lib/ListView"; import {MessageBarType,Link,Separator, CommandBarButton,IStackStyles,Text,MessageBar,PrimaryButton,DefaultButton,Dialog,DialogFooter,DialogType,Stack, IStackTokens, updateA, Icon, Spinner } from 'office-ui-fabric-react'; import { sp} from "@pnp/sp"; import "@pnp/sp/webs"; import "@pnp/sp/user-custom-actions"; import "@pnp/sp/presets/all"; import {TypedHash} from "@pnp/common"; import { IUserCustomActionAddResult,IUserCustomActionUpdateResult,IUserCustomAction } from '@pnp/sp/user-custom-actions'; import { createTheme, ITheme } from 'office-ui-fabric-react/lib/Styling'; import { mergeStyleSets } from 'office-ui-fabric-react/lib/Styling'; import { PermissionKind } from '@pnp/sp/presets/all'; const stackTokens: IStackTokens = { childrenGap: 40 }; const CustomActionTitle = 'JSCssAppCustomizer'; const ApplicationCustomizerComponentID = '38afa8d7-b498-4529-9f99-6279392f9309'; const description = 'This user action is of type application customizer to custom js and css file references via SFPx extension'; const theme: ITheme = createTheme({ fonts: { medium: { // fontFamily: 'Monaco, Menlo, Consolas', fontSize: '18px' } } }); const stackStyles: Partial<IStackStyles> = { root: { height: 30 } }; export interface IAddJsCssReferenceState { disableRegisterButton: boolean; disableRemoveButton: boolean; jsfiles:any[]; cssfiles:any[]; currentjsRef:string; currentcssRef:string; hideJSDailog:boolean; hideCSSDailog:boolean; currentCustomAction:any; isEdit:boolean; editIndex:number; showMesssage:boolean; successmessage:string; userHasPermission:boolean; showspinner:boolean; } export default class AddJsCssReference extends React.Component<IAddJsCssReferenceProps, IAddJsCssReferenceState> { private viewFields: any[] = [ { name: "Type", displayName: "Action", minWidth: 60, maxWidth:60, render: (item,index) =>{ console.log(item); return ( <React.Fragment> <Stack horizontal tokens={{childrenGap:20}}> <Icon iconName="Edit" className={"ms-IconExample" + styles.customicons} onClick={()=> this.editClicked(item,index)} /> <Icon iconName="Delete" className={"ms-IconExample" + styles.customicons} onClick={()=> this.deleteClicked(item,index)} /> {/* <i className={"ms-Icon ms-Icon--Edit " + styles.customicons} onClick={()=> this.editClicked(item,index)} aria-hidden="true"></i> <i className={"ms-Icon ms-Icon--Delete " + styles.customicons} onClick={()=> this.deleteClicked(item,index)} aria-hidden="true"></i> */} </Stack> </React.Fragment> ); }, className:"test" }, { name: "FilePath", displayName: "FilePath", minWidth:600, render: (item,index) =>{ console.log(item); return ( <React.Fragment> <span className={styles.filepath}> {item.FilePath} </span> </React.Fragment> ); } // maxWidth:800 } ]; constructor(props: IAddJsCssReferenceProps,state:IAddJsCssReferenceProps) { super(props); this.state = { disableRegisterButton:false, disableRemoveButton:false, jsfiles:[], cssfiles:[], currentjsRef:"", currentcssRef:"", hideJSDailog:true, hideCSSDailog:true, currentCustomAction:null, isEdit:false, editIndex:-1, showMesssage:false, successmessage:"", userHasPermission:false, showspinner:true }; sp.setup(this.props.context); } public render(): React.ReactElement<IAddJsCssReferenceProps> { return ( <React.Fragment> {this.state.showspinner && <Spinner label="Please wait..." ariaLive="assertive" labelPosition="top" /> } {this.state.userHasPermission && <div className={styles.addJsCssReference}> <div className={ styles.container }> <div className={ styles.row }> <div className={ styles.column }> <span className={ styles.title }>SPFx JS CSS References WebPart</span> <p className={ styles.subTitle }>This webpart can be used to add reference to custom js files and css files via SPFx extension application customizer.</p> </div> <div className={ styles.row }> <div className={ styles.column }> {this.state.showMesssage && <MessageBar dismissButtonAriaLabel="Close" onDismiss={()=>{ this.setState({showMesssage:false});}} messageBarType={MessageBarType.success}> {this.state.successmessage} </MessageBar> } {this.state.currentCustomAction && this.state.showMesssage != true && <MessageBar > We found you already have some custom js and css files references added via this customizer. Feel free to Edit or Remove references. </MessageBar> } <div id="jsfiles"> <Separator></Separator> <Stack horizontal styles={stackStyles} tokens={stackTokens}> <Text theme={theme}>Javascript Files</Text> <CommandBarButton iconProps={{iconName: 'Add'}} text="Add JS Link" onClick={()=>this.openAddJSDailog()} /> </Stack> <Separator></Separator> {/* <PrimaryButton text="Add New Item" } /> */} {this.state.jsfiles.length === 0 && <React.Fragment> <MessageBar> No References Found. <Link href="#" onClick={()=>this.openAddJSDailog()}> Click here </Link> <Text> to add new.</Text> </MessageBar> <br/> </React.Fragment> } {this.state.jsfiles.length >0 && <ListView items={this.state.jsfiles} viewFields={this.viewFields} /> } <Dialog minWidth={600} maxWidth={900} hidden={this.state.hideJSDailog} onDismiss={this._closeJSDialog} dialogContentProps={{ type: DialogType.normal, title: 'Add JS Reference', // subText: 'Enter a valid JS file link.' }} modalProps={{ isBlocking: false, // styles: { main: { maxWidth: 450 } } }} > <TextField required onChange={evt => this.updateJSValue(evt)} value={this.state.currentjsRef} label="URL" resizable={false} /> <DialogFooter> <PrimaryButton onClick={()=>this._addJsReference()} text="Add" /> <DefaultButton onClick={this._closeJSDialog} text="Cancel" /> </DialogFooter> </Dialog> </div> <div id="cssfiles"> <br/> <Stack horizontal styles={stackStyles} tokens={stackTokens}> <Text theme={theme}>CSS Files</Text> <CommandBarButton iconProps={{iconName: 'Add'}} text="Add CSS Link" onClick={()=>this.openAddCSSDailog()} /> </Stack> {/* <PrimaryButton text="Add New Item" onClick={()=>this.openAddCSSDailog()} /> */} <Separator></Separator> {this.state.cssfiles.length === 0 && <React.Fragment> <MessageBar> No References Found. <Link href="#" onClick={()=>this.openAddCSSDailog()}> Click here </Link> <Text> to add new.</Text> </MessageBar> <br/> </React.Fragment> } {this.state.cssfiles.length > 0 && <ListView items={this.state.cssfiles} viewFields={this.viewFields} // iconFieldName="ServerRelativeUrl" // selectionMode={SelectionMode.multiple} // selection={this._getSelection} /> } <Dialog minWidth={600} maxWidth={900} hidden={this.state.hideCSSDailog} onDismiss={this._closeCSSDialog} dialogContentProps={{ type: DialogType.normal, title: 'Add CSS Reference', // subText: 'Enter a valid CSS file link.' }} modalProps={{ isBlocking: false, // styles: { main: { minWidth: 500 !important ,width:500} } }} > <TextField required onChange={evt => this.updateCSSValue(evt)} value={this.state.currentcssRef} label="URL" /> <DialogFooter> <PrimaryButton onClick={()=>this._addCSSReference()} text="Add" /> <DefaultButton onClick={this._closeCSSDialog} text="Cancel" /> </DialogFooter> </Dialog> </div> <br/> <Stack horizontal tokens={stackTokens}> <PrimaryButton text="Activate" onClick={()=>this._registerClicked()} disabled={(this.state.jsfiles.length>0 || this.state.cssfiles.length>0 )?false:true} /> <DefaultButton text="Deactivate" onClick={()=> this._removeClicked()} disabled={this.state.currentCustomAction==null?true:false} /> </Stack> </div> </div> </div> </div> <div> </div> </div> } {!this.state.userHasPermission && !this.state.showspinner && <MessageBar messageBarType={MessageBarType.severeWarning}> Access denied, you do not have permission to access this section. Please connect with your site admins. </MessageBar> } </React.Fragment> ); } public componentDidMount() { this.checkPermisson(); } private async checkPermisson(){ const perms2 = await sp.web.currentUserHasPermissions(PermissionKind.ManageWeb); this.setState({userHasPermission:perms2}); console.log(perms2); var temp = true; this.setState({showspinner:false}); if(perms2){ this.getCustomAction(); } } private _registerClicked(): void { this.setCustomAction(); } private _removeClicked(): void { const uca = sp.web.userCustomActions.getById(this.state.currentCustomAction.Id); const response = uca.delete(); console.log("removed custom action"); console.log(response); this.setState({currentCustomAction:null,jsfiles:[],cssfiles:[], showMesssage:true,successmessage:"Application Customizer deactivated sucessfully."}); } private updateJSValue(evt) { this.setState({ currentjsRef: evt.target.value }); } private updateCSSValue(evt) { this.setState({ currentcssRef: evt.target.value }); } private editClicked (item,index){ if(item.Type == "js") { this.setState({hideJSDailog:false, currentjsRef:item.FilePath, isEdit:true, editIndex:index }); } if(item.Type == "css") { this.setState({hideCSSDailog:false, currentcssRef:item.FilePath, isEdit:true, editIndex:index }); } } private deleteClicked (item,index){ if(item.Type == "css") { let currentitems = this.state.cssfiles.map((x) => x); currentitems.splice(index,1); this.setState({cssfiles:currentitems}); } else if(item.Type == "js"){ let currentitems = this.state.jsfiles.map((x) => x); currentitems.splice(index,1); this.setState({jsfiles:currentitems}); } } private openAddJSDailog (){ this.setState({hideJSDailog:false}); } private openAddCSSDailog (){ this.setState({hideCSSDailog:false}); } private _addJsReference (){ if(!this.state.isEdit){ var item = { FilePath:this.state.currentjsRef, Type: "js" }; let currentitems = this.state.jsfiles.map((x) => x); currentitems.push(item); currentitems[this.state.jsfiles.length] = item; this.setState({jsfiles:currentitems, hideJSDailog:true,currentjsRef:""}); } else{ item = { FilePath:this.state.currentjsRef, Type: "js" }; let currentitems = this.state.jsfiles.map((x) => x); currentitems[this.state.editIndex] = item; this.setState({jsfiles:currentitems, hideJSDailog:true,currentjsRef:"", isEdit:false,editIndex:-1}); } } private _addCSSReference (){ if(!this.state.isEdit){ console.log("add item to grid"); var item = { FilePath:this.state.currentcssRef, Type:"css" }; let currentitems = this.state.cssfiles.map((x) => x); currentitems.push(item); currentitems[this.state.cssfiles.length] = item; this.setState({cssfiles:currentitems, hideCSSDailog:true, currentcssRef:""}); } else{ console.log("add item to grid"); item = { FilePath:this.state.currentcssRef, Type:"css" }; let currentitems = this.state.cssfiles.map((x) => x); currentitems[this.state.editIndex] = item; this.setState({cssfiles:currentitems, hideCSSDailog:true, currentcssRef:"", editIndex:-1,isEdit:false}); } } private _closeJSDialog = (): void => { this.setState({ hideJSDailog: true }); } private _closeCSSDialog = (): void => { this.setState({ hideCSSDailog: true }); } private async getCustomAction(){ var web = await sp.web.get(); console.log(web); var customactions:any = await sp.web.userCustomActions.get(); console.log(customactions); var found = customactions.filter(item => item.Title == CustomActionTitle); if (found.length > 0) { this.setState({currentCustomAction:found[0]}); var jsonproperties = found[0].ClientSideComponentProperties; var jsfileArray = JSON.parse(jsonproperties).jsfiles; var cssfileArray = JSON.parse(jsonproperties).cssfiles; console.log(jsfileArray); console.log(cssfileArray); this.setState({jsfiles:jsfileArray,cssfiles:cssfileArray}); } } protected async setCustomAction() { try { const payload: TypedHash<string> = { "Title": CustomActionTitle, "Description": description, "Location": 'ClientSideExtension.ApplicationCustomizer', ClientSideComponentId:ApplicationCustomizerComponentID, ClientSideComponentProperties: JSON.stringify({jsfiles:this.state.jsfiles,cssfiles:this.state.cssfiles }), }; if(this.state.currentCustomAction == null) { const response : IUserCustomActionAddResult = await sp.web.userCustomActions.add(payload); console.log(response); const uca = await sp.web.userCustomActions.getById(response.data.Id); this.setState({currentCustomAction: uca,showMesssage:true,successmessage:"Application customizer activated sucessfully."}); } else{ const uca = sp.web.userCustomActions.getById(this.state.currentCustomAction.Id); const response: IUserCustomActionUpdateResult =await uca.update(payload); const ucaupdated = await sp.web.userCustomActions.getById(response.data.Id); this.setState({currentCustomAction: ucaupdated,showMesssage:true,successmessage:"Application customizer updated sucessfully."}); } } catch (error) { console.error(error); } } }
the_stack
import React, { useState, useRef, useEffect, useContext, useMemo, useCallback, MutableRefObject, RefObject, } from 'react' import { encode, decode } from '@kunigi/string-compression' import cn from 'classnames' import copy from 'copy-to-clipboard' import { BN } from 'ethereumjs-util' import { useRouter } from 'next/router' import Select, { OnChangeValue } from 'react-select' import SCEditor from 'react-simple-code-editor' import { EthereumContext } from 'context/ethereumContext' import { SettingsContext, Setting } from 'context/settingsContext' import { getAbsoluteURL } from 'util/browser' import { getTargetEvmVersion, compilerSemVer, getBytecodeFromMnemonic, } from 'util/compiler' import { codeHighlight, isEmpty, isFullHex, isHex, objToQueryString, } from 'util/string' import examples from 'components/Editor/examples' import InstructionList from 'components/Editor/Instructions' import { Button, Input, Icon } from 'components/ui' import Console from './Console' import ExecutionState from './ExecutionState' import ExecutionStatus from './ExecutionStatus' import Header from './Header' import { IConsoleOutput, CodeType, ValueUnit } from './types' type Props = { readOnly?: boolean } type SCEditorRef = { _input: HTMLTextAreaElement } & RefObject<React.FC> const editorHeight = 350 const consoleHeight = 350 const instructionsListHeight = editorHeight + 52 // RunBar const unitOptions = Object.keys(ValueUnit).map((value) => ({ value, label: value, })) const Editor = ({ readOnly = false }: Props) => { const { settingsLoaded, getSetting, setSetting } = useContext(SettingsContext) const router = useRouter() const { transactionData, loadInstructions, startExecution, startTransaction, deployedContractAddress, vmError, selectedFork, opcodes, } = useContext(EthereumContext) const [code, setCode] = useState('') const [compiling, setIsCompiling] = useState(false) const [codeType, setCodeType] = useState<string | undefined>() const [codeModified, setCodeModified] = useState(false) const [output, setOutput] = useState<IConsoleOutput[]>([ { type: 'info', message: `Loading Solidity compiler ${compilerSemVer}...`, }, ]) const solcWorkerRef = useRef<null | Worker>(null) const instructionsRef = useRef() as MutableRefObject<HTMLDivElement> const editorRef = useRef<SCEditorRef>() const [callData, setCallData] = useState('') const [callValue, setCallValue] = useState('') const [unit, setUnit] = useState(ValueUnit.Wei as string) const log = useCallback( (line: string, type = 'info') => { // See https://blog.logrocket.com/a-guide-to-usestate-in-react-ecb9952e406c/ setOutput((previous) => { const cloned = previous.map((x) => ({ ...x })) cloned.push({ type, message: line }) return cloned }) }, [setOutput], ) const getCallValue = useCallback(() => { const _callValue = new BN(callValue) if (unit === ValueUnit.Gwei) { _callValue.imul(new BN('1000000000')) } else if (unit === ValueUnit.Finney) { _callValue.imul(new BN('1000000000000000')) } else if (unit === ValueUnit.Ether) { _callValue.imul(new BN('1000000000000000000')) } return _callValue }, [callValue, unit]) const handleWorkerMessage = useCallback( (event: MessageEvent) => { const { code: byteCode, warning, error } = event.data if (error) { log(error, 'error') setIsCompiling(false) return } if (warning) { log(warning, 'warn') } log('Compilation successful') try { const _callValue = getCallValue() transactionData(byteCode, _callValue).then((tx) => { loadInstructions(byteCode) setIsCompiling(false) startTransaction(tx) }) } catch (error) { log((error as Error).message, 'error') setIsCompiling(false) } }, [ log, setIsCompiling, transactionData, loadInstructions, startTransaction, getCallValue, ], ) useEffect(() => { const query = router.query if ('callValue' in query && 'unit' in query) { setCallValue(query.callValue as string) setUnit(query.unit as string) } if ('callData' in query) { setCallData(query.callData as string) } if ('codeType' in query && 'code' in query) { setCodeType(query.codeType as string) setCode(JSON.parse('{"a":' + decode(query.code as string) + '}').a) } else { const initialCodeType: CodeType = getSetting(Setting.EditorCodeType) || CodeType.Yul setCodeType(initialCodeType) setCode(examples[initialCodeType][0]) } // eslint-disable-next-line react-hooks/exhaustive-deps }, [settingsLoaded && router.isReady]) useEffect(() => { solcWorkerRef.current = new Worker( new URL('../../lib/solcWorker.js', import.meta.url), ) solcWorkerRef.current.onmessage = handleWorkerMessage log('Solidity compiler loaded') return () => { if (solcWorkerRef?.current) { solcWorkerRef.current.terminate() } } // eslint-disable-next-line react-hooks/exhaustive-deps }, []) useEffect(() => { if (deployedContractAddress) { log(`Contract deployed at address: ${deployedContractAddress}`) } // eslint-disable-next-line react-hooks/exhaustive-deps }, [deployedContractAddress]) useEffect(() => { if (vmError) { log(vmError, 'error') } // eslint-disable-next-line react-hooks/exhaustive-deps }, [vmError]) const handleCodeChange = (value: string) => { setCode(value) setCodeModified(true) } const highlightCode = (value: string) => { if (!codeType) { return value } return codeHighlight(value, codeType) .value.split('\n') .map((line, i) => `<span class='line-number'>${i + 1}</span>${line}`) .join('\n') } const highlightBytecode = (value: string) => { return value } const handleCodeTypeChange = (option: OnChangeValue<any, any>) => { const { value } = option setCodeType(value) setSetting(Setting.EditorCodeType, value) if (!codeModified && codeType) { setCode(examples[value as CodeType][0]) } // NOTE: SCEditor does not expose input ref as public /shrug if (editorRef?.current?._input) { const input = editorRef?.current?._input input.focus() input.select() } } const handleRun = useCallback(() => { if (!isEmpty(callValue) && !/^[0-9]+$/.test(callValue)) { log('Callvalue should be a positive integer', 'error') return } if (!isEmpty(callData) && !isFullHex(callData)) { log( 'Calldata should be a hexadecimal string with 2 digits per byte', 'error', ) return } try { const _callData = callData.substr(2) const _callValue = getCallValue() if (codeType === CodeType.Mnemonic) { const bytecode = getBytecodeFromMnemonic(code, opcodes) loadInstructions(bytecode) startExecution(bytecode, _callValue, _callData) } else if (codeType === CodeType.Bytecode) { if (code.length % 2 !== 0) { log('There should be at least 2 characters per byte', 'error') return } if (!isHex(code)) { log('Only hexadecimal characters are allowed', 'error') return } loadInstructions(code) startExecution(code, _callValue, _callData) } else { setIsCompiling(true) log('Starting compilation...') if (solcWorkerRef?.current) { solcWorkerRef.current.postMessage({ language: codeType, evmVersion: getTargetEvmVersion(selectedFork?.name), source: code, }) } } } catch (error) { log((error as Error).message, 'error') } }, [ code, codeType, opcodes, selectedFork, callData, callValue, loadInstructions, log, startExecution, getCallValue, ]) const handleCopyPermalink = useCallback(() => { const params = { callValue, unit, callData, codeType, code: encodeURIComponent(encode(JSON.stringify(code))), } copy(`${getAbsoluteURL('/playground')}?${objToQueryString(params)}`) log('Link to current code, calldata and value copied to clipboard') }, [callValue, unit, callData, codeType, code, log]) const isRunDisabled = useMemo(() => { return compiling || isEmpty(code) }, [compiling, code]) const isBytecode = useMemo(() => codeType === CodeType.Bytecode, [codeType]) const isCallDataActive = useMemo( () => codeType === CodeType.Mnemonic || codeType === CodeType.Bytecode, [codeType], ) const unitValue = useMemo( () => ({ value: unit, label: unit, }), [unit], ) return ( <div className="bg-gray-100 dark:bg-black-700 rounded-lg"> <div className="flex flex-col md:flex-row"> <div className="w-full md:w-1/2"> <div className="border-b border-gray-200 dark:border-black-500 flex items-center pl-6 pr-2 h-14 md:border-r"> <Header onCodeTypeChange={handleCodeTypeChange} codeType={codeType} /> </div> <div> <div className="relative pane pane-light overflow-auto md:border-r bg-gray-50 dark:bg-black-600 border-gray-200 dark:border-black-500" style={{ height: editorHeight }} > <SCEditor // @ts-ignore: SCEditor is not TS-friendly ref={editorRef} value={code} readOnly={readOnly} onValueChange={handleCodeChange} highlight={isBytecode ? highlightBytecode : highlightCode} tabSize={4} className={cn('code-editor', { 'with-numbers': !isBytecode, })} /> </div> <div className="flex flex-col md:flex-row md:items-center md:justify-between px-4 py-4 md:py-2 md:border-r border-gray-200 dark:border-black-500"> <div className="flex flex-col md:flex-row md:gap-x-4 gap-y-2 md:gap-y-0 mb-4 md:mb-0"> {isCallDataActive && ( <Input placeholder="Calldata in HEX" className="bg-white dark:bg-black-500" value={callData} onChange={(e) => setCallData(e.target.value)} /> )} <Input type="number" step="1" placeholder="Value to send" className="bg-white dark:bg-black-500" value={callValue} onChange={(e) => setCallValue(e.target.value)} /> <Select onChange={(option: OnChangeValue<any, any>) => setUnit(option.value) } options={unitOptions} value={unitValue} isSearchable={false} classNamePrefix="select" menuPlacement="auto" /> <Button onClick={handleCopyPermalink} transparent padded={false} > <span className="inline-block mr-4 select-all" data-tip="Share permalink" > <Icon name="links-line" className="text-indigo-500 mr-2" /> </span> </Button> </div> <Button onClick={handleRun} disabled={isRunDisabled} size="sm" contentClassName="justify-center" > Run </Button> </div> </div> </div> <div className="w-full md:w-1/2"> <div className="border-t md:border-t-0 border-b border-gray-200 dark:border-black-500 flex items-center pl-4 pr-6 h-14"> <ExecutionStatus /> </div> <div className="pane pane-light overflow-auto bg-gray-50 dark:bg-black-600 h-full" ref={instructionsRef} style={{ height: instructionsListHeight }} > <InstructionList containerRef={instructionsRef} /> </div> </div> </div> <div className="flex flex-col md:flex-row-reverse"> <div className="w-full md:w-1/2"> <div className="pane pane-dark overflow-auto border-t border-black-900 border-opacity-25 bg-gray-800 dark:bg-black-700 text-white px-4 py-3" style={{ height: consoleHeight }} > <ExecutionState /> </div> </div> <div className="w-full md:w-1/2"> <div className="pane pane-dark overflow-auto bg-gray-800 dark:bg-black-700 text-white border-t border-black-900 border-opacity-25 md:border-r" style={{ height: consoleHeight }} > <Console output={output} /> </div> </div> </div> <div className="rounded-b-lg py-2 px-4 border-t bg-gray-800 dark:bg-black-700 border-black-900 border-opacity-25 text-gray-400 dark:text-gray-600 text-xs"> Solidity Compiler {compilerSemVer} </div> </div> ) } export default Editor
the_stack
export as namespace Reselect; export type Selector<S, R> = (state: S) => R; export type OutputSelector<S, R, C> = Selector<S, R> & { resultFunc: C; recomputations: () => number; resetRecomputations: () => number; } export type ParametricSelector<S, P, R> = (state: S, props: P, ...args: any[]) => R; export type OutputParametricSelector<S, P, R, C> = ParametricSelector<S, P, R> & { resultFunc: C; recomputations: () => number; resetRecomputations: () => number; } /* one selector */ export function createSelector<S, R1, T>( selector: Selector<S, R1>, combiner: (res: R1) => T, ): OutputSelector<S, T, (res: R1) => T>; export function createSelector<S, P, R1, T>( selector: ParametricSelector<S, P, R1>, combiner: (res: R1) => T, ): OutputParametricSelector<S, P, T, (res: R1) => T>; /* two selectors */ export function createSelector<S, R1, R2, T>( selector1: Selector<S, R1>, selector2: Selector<S, R2>, combiner: (res1: R1, res2: R2) => T, ): OutputSelector<S, T, (res1: R1, res2: R2) => T>; export function createSelector<S, P, R1, R2, T>( selector1: ParametricSelector<S, P, R1>, selector2: ParametricSelector<S, P, R2>, combiner: (res1: R1, res2: R2) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2) => T>; /* three selectors */ export function createSelector<S, R1, R2, R3, T>( selector1: Selector<S, R1>, selector2: Selector<S, R2>, selector3: Selector<S, R3>, combiner: (res1: R1, res2: R2, res3: R3) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3) => T>; export function createSelector<S, P, R1, R2, R3, T>( selector1: ParametricSelector<S, P, R1>, selector2: ParametricSelector<S, P, R2>, selector3: ParametricSelector<S, P, R3>, combiner: (res1: R1, res2: R2, res3: R3) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3) => T>; /* four selectors */ export function createSelector<S, R1, R2, R3, R4, T>( selector1: Selector<S, R1>, selector2: Selector<S, R2>, selector3: Selector<S, R3>, selector4: Selector<S, R4>, combiner: (res1: R1, res2: R2, res3: R3, res4: R4) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3, res4: R4) => T>; export function createSelector<S, P, R1, R2, R3, R4, T>( selector1: ParametricSelector<S, P, R1>, selector2: ParametricSelector<S, P, R2>, selector3: ParametricSelector<S, P, R3>, selector4: ParametricSelector<S, P, R4>, combiner: (res1: R1, res2: R2, res3: R3, res4: R4) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3, res4: R4) => T>; /* five selectors */ export function createSelector<S, R1, R2, R3, R4, R5, T>( selector1: Selector<S, R1>, selector2: Selector<S, R2>, selector3: Selector<S, R3>, selector4: Selector<S, R4>, selector5: Selector<S, R5>, combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5) => T>; export function createSelector<S, P, R1, R2, R3, R4, R5, T>( selector1: ParametricSelector<S, P, R1>, selector2: ParametricSelector<S, P, R2>, selector3: ParametricSelector<S, P, R3>, selector4: ParametricSelector<S, P, R4>, selector5: ParametricSelector<S, P, R5>, combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5) => T>; /* six selectors */ export function createSelector<S, R1, R2, R3, R4, R5, R6, T>( selector1: Selector<S, R1>, selector2: Selector<S, R2>, selector3: Selector<S, R3>, selector4: Selector<S, R4>, selector5: Selector<S, R5>, selector6: Selector<S, R6>, combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6) => T>; export function createSelector<S, P, R1, R2, R3, R4, R5, R6, T>( selector1: ParametricSelector<S, P, R1>, selector2: ParametricSelector<S, P, R2>, selector3: ParametricSelector<S, P, R3>, selector4: ParametricSelector<S, P, R4>, selector5: ParametricSelector<S, P, R5>, selector6: ParametricSelector<S, P, R6>, combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6) => T>; /* seven selectors */ export function createSelector<S, R1, R2, R3, R4, R5, R6, R7, T>( selector1: Selector<S, R1>, selector2: Selector<S, R2>, selector3: Selector<S, R3>, selector4: Selector<S, R4>, selector5: Selector<S, R5>, selector6: Selector<S, R6>, selector7: Selector<S, R7>, combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7) => T>; export function createSelector<S, P, R1, R2, R3, R4, R5, R6, R7, T>( selector1: ParametricSelector<S, P, R1>, selector2: ParametricSelector<S, P, R2>, selector3: ParametricSelector<S, P, R3>, selector4: ParametricSelector<S, P, R4>, selector5: ParametricSelector<S, P, R5>, selector6: ParametricSelector<S, P, R6>, selector7: ParametricSelector<S, P, R7>, combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7) => T>; /* eight selectors */ export function createSelector<S, R1, R2, R3, R4, R5, R6, R7, R8, T>( selector1: Selector<S, R1>, selector2: Selector<S, R2>, selector3: Selector<S, R3>, selector4: Selector<S, R4>, selector5: Selector<S, R5>, selector6: Selector<S, R6>, selector7: Selector<S, R7>, selector8: Selector<S, R8>, combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8) => T>; export function createSelector<S, P, R1, R2, R3, R4, R5, R6, R7, R8, T>( selector1: ParametricSelector<S, P, R1>, selector2: ParametricSelector<S, P, R2>, selector3: ParametricSelector<S, P, R3>, selector4: ParametricSelector<S, P, R4>, selector5: ParametricSelector<S, P, R5>, selector6: ParametricSelector<S, P, R6>, selector7: ParametricSelector<S, P, R7>, selector8: ParametricSelector<S, P, R8>, combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8) => T>; /* nine selectors */ export function createSelector<S, R1, R2, R3, R4, R5, R6, R7, R8, R9, T>( selector1: Selector<S, R1>, selector2: Selector<S, R2>, selector3: Selector<S, R3>, selector4: Selector<S, R4>, selector5: Selector<S, R5>, selector6: Selector<S, R6>, selector7: Selector<S, R7>, selector8: Selector<S, R8>, selector9: Selector<S, R9>, combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9) => T>; export function createSelector<S, P, R1, R2, R3, R4, R5, R6, R7, R8, R9, T>( selector1: ParametricSelector<S, P, R1>, selector2: ParametricSelector<S, P, R2>, selector3: ParametricSelector<S, P, R3>, selector4: ParametricSelector<S, P, R4>, selector5: ParametricSelector<S, P, R5>, selector6: ParametricSelector<S, P, R6>, selector7: ParametricSelector<S, P, R7>, selector8: ParametricSelector<S, P, R8>, selector9: ParametricSelector<S, P, R9>, combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9) => T>; /* ten selectors */ export function createSelector<S, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, T>( selector1: Selector<S, R1>, selector2: Selector<S, R2>, selector3: Selector<S, R3>, selector4: Selector<S, R4>, selector5: Selector<S, R5>, selector6: Selector<S, R6>, selector7: Selector<S, R7>, selector8: Selector<S, R8>, selector9: Selector<S, R9>, selector10: Selector<S, R10>, combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10) => T>; export function createSelector<S, P, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, T>( selector1: ParametricSelector<S, P, R1>, selector2: ParametricSelector<S, P, R2>, selector3: ParametricSelector<S, P, R3>, selector4: ParametricSelector<S, P, R4>, selector5: ParametricSelector<S, P, R5>, selector6: ParametricSelector<S, P, R6>, selector7: ParametricSelector<S, P, R7>, selector8: ParametricSelector<S, P, R8>, selector9: ParametricSelector<S, P, R9>, selector10: ParametricSelector<S, P, R10>, combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10) => T>; /* eleven selectors */ export function createSelector<S, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, T>( selector1: Selector<S, R1>, selector2: Selector<S, R2>, selector3: Selector<S, R3>, selector4: Selector<S, R4>, selector5: Selector<S, R5>, selector6: Selector<S, R6>, selector7: Selector<S, R7>, selector8: Selector<S, R8>, selector9: Selector<S, R9>, selector10: Selector<S, R10>, selector11: Selector<S, R11>, combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10, res11: R11) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10, res11: R11) => T>; export function createSelector<S, P, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, T>( selector1: ParametricSelector<S, P, R1>, selector2: ParametricSelector<S, P, R2>, selector3: ParametricSelector<S, P, R3>, selector4: ParametricSelector<S, P, R4>, selector5: ParametricSelector<S, P, R5>, selector6: ParametricSelector<S, P, R6>, selector7: ParametricSelector<S, P, R7>, selector8: ParametricSelector<S, P, R8>, selector9: ParametricSelector<S, P, R9>, selector10: ParametricSelector<S, P, R10>, selector11: ParametricSelector<S, P, R11>, combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10, res11: R11) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10, res11: R11) => T>; /* twelve selectors */ export function createSelector<S, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, R12, T>( selector1: Selector<S, R1>, selector2: Selector<S, R2>, selector3: Selector<S, R3>, selector4: Selector<S, R4>, selector5: Selector<S, R5>, selector6: Selector<S, R6>, selector7: Selector<S, R7>, selector8: Selector<S, R8>, selector9: Selector<S, R9>, selector10: Selector<S, R10>, selector11: Selector<S, R11>, selector12: Selector<S, R12>, combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10, res11: R11, res12: R12) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10, res11: R11, res12: R12) => T>; export function createSelector<S, P, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, R12, T>( selector1: ParametricSelector<S, P, R1>, selector2: ParametricSelector<S, P, R2>, selector3: ParametricSelector<S, P, R3>, selector4: ParametricSelector<S, P, R4>, selector5: ParametricSelector<S, P, R5>, selector6: ParametricSelector<S, P, R6>, selector7: ParametricSelector<S, P, R7>, selector8: ParametricSelector<S, P, R8>, selector9: ParametricSelector<S, P, R9>, selector10: ParametricSelector<S, P, R10>, selector11: ParametricSelector<S, P, R11>, selector12: ParametricSelector<S, P, R12>, combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10, res11: R11, res12: R12) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10, res11: R11, res12: R12) => T>; /* array argument */ /* one selector */ export function createSelector<S, R1, T>( selectors: [Selector<S, R1>], combiner: (res: R1) => T, ): OutputSelector<S, T, (res: R1) => T>; export function createSelector<S, P, R1, T>( selectors: [ParametricSelector<S, P, R1>], combiner: (res: R1) => T, ): OutputParametricSelector<S, P, T, (res: R1) => T>; /* two selectors */ export function createSelector<S, R1, R2, T>( selectors: [Selector<S, R1>, Selector<S, R2>], combiner: (res1: R1, res2: R2) => T, ): OutputSelector<S, T, (res1: R1, res2: R2) => T>; export function createSelector<S, P, R1, R2, T>( selectors: [ParametricSelector<S, P, R1>, ParametricSelector<S, P, R2>], combiner: (res1: R1, res2: R2) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2) => T>; /* three selectors */ export function createSelector<S, R1, R2, R3, T>( selectors: [Selector<S, R1>, Selector<S, R2>, Selector<S, R3>], combiner: (res1: R1, res2: R2, res3: R3) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3) => T>; export function createSelector<S, P, R1, R2, R3, T>( selectors: [ParametricSelector<S, P, R1>, ParametricSelector<S, P, R2>, ParametricSelector<S, P, R3>], combiner: (res1: R1, res2: R2, res3: R3) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3) => T>; /* four selectors */ export function createSelector<S, R1, R2, R3, R4, T>( selectors: [Selector<S, R1>, Selector<S, R2>, Selector<S, R3>, Selector<S, R4>], combiner: (res1: R1, res2: R2, res3: R3, res4: R4) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3, res4: R4) => T>; export function createSelector<S, P, R1, R2, R3, R4, T>( selectors: [ParametricSelector<S, P, R1>, ParametricSelector<S, P, R2>, ParametricSelector<S, P, R3>, ParametricSelector<S, P, R4>], combiner: (res1: R1, res2: R2, res3: R3, res4: R4) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3, res4: R4) => T>; /* five selectors */ export function createSelector<S, R1, R2, R3, R4, R5, T>( selectors: [Selector<S, R1>, Selector<S, R2>, Selector<S, R3>, Selector<S, R4>, Selector<S, R5>], combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5) => T>; export function createSelector<S, P, R1, R2, R3, R4, R5, T>( selectors: [ParametricSelector<S, P, R1>, ParametricSelector<S, P, R2>, ParametricSelector<S, P, R3>, ParametricSelector<S, P, R4>, ParametricSelector<S, P, R5>], combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5) => T>; /* six selectors */ export function createSelector<S, R1, R2, R3, R4, R5, R6, T>( selectors: [Selector<S, R1>, Selector<S, R2>, Selector<S, R3>, Selector<S, R4>, Selector<S, R5>, Selector<S, R6>], combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6) => T>; export function createSelector<S, P, R1, R2, R3, R4, R5, R6, T>( selectors: [ParametricSelector<S, P, R1>, ParametricSelector<S, P, R2>, ParametricSelector<S, P, R3>, ParametricSelector<S, P, R4>, ParametricSelector<S, P, R5>, ParametricSelector<S, P, R6>], combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6) => T>; /* seven selectors */ export function createSelector<S, R1, R2, R3, R4, R5, R6, R7, T>( selectors: [Selector<S, R1>, Selector<S, R2>, Selector<S, R3>, Selector<S, R4>, Selector<S, R5>, Selector<S, R6>, Selector<S, R7>], combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7) => T>; export function createSelector<S, P, R1, R2, R3, R4, R5, R6, R7, T>( selectors: [ParametricSelector<S, P, R1>, ParametricSelector<S, P, R2>, ParametricSelector<S, P, R3>, ParametricSelector<S, P, R4>, ParametricSelector<S, P, R5>, ParametricSelector<S, P, R6>, ParametricSelector<S, P, R7>], combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7) => T>; /* eight selectors */ export function createSelector<S, R1, R2, R3, R4, R5, R6, R7, R8, T>( selectors: [Selector<S, R1>, Selector<S, R2>, Selector<S, R3>, Selector<S, R4>, Selector<S, R5>, Selector<S, R6>, Selector<S, R7>, Selector<S, R8>], combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8) => T>; export function createSelector<S, P, R1, R2, R3, R4, R5, R6, R7, R8, T>( selectors: [ParametricSelector<S, P, R1>, ParametricSelector<S, P, R2>, ParametricSelector<S, P, R3>, ParametricSelector<S, P, R4>, ParametricSelector<S, P, R5>, ParametricSelector<S, P, R6>, ParametricSelector<S, P, R7>, ParametricSelector<S, P, R8>], combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8) => T>; /* nine selectors */ export function createSelector<S, R1, R2, R3, R4, R5, R6, R7, R8, R9, T>( selectors: [Selector<S, R1>, Selector<S, R2>, Selector<S, R3>, Selector<S, R4>, Selector<S, R5>, Selector<S, R6>, Selector<S, R7>, Selector<S, R8>, Selector<S, R9>], combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9) => T>; export function createSelector<S, P, R1, R2, R3, R4, R5, R6, R7, R8, R9, T>( selectors: [ParametricSelector<S, P, R1>, ParametricSelector<S, P, R2>, ParametricSelector<S, P, R3>, ParametricSelector<S, P, R4>, ParametricSelector<S, P, R5>, ParametricSelector<S, P, R6>, ParametricSelector<S, P, R7>, ParametricSelector<S, P, R8>, ParametricSelector<S, P, R9>], combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9) => T>; /* ten selectors */ export function createSelector<S, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, T>( selectors: [Selector<S, R1>, Selector<S, R2>, Selector<S, R3>, Selector<S, R4>, Selector<S, R5>, Selector<S, R6>, Selector<S, R7>, Selector<S, R8>, Selector<S, R9>, Selector<S, R10>], combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10) => T>; export function createSelector<S, P, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, T>( selectors: [ParametricSelector<S, P, R1>, ParametricSelector<S, P, R2>, ParametricSelector<S, P, R3>, ParametricSelector<S, P, R4>, ParametricSelector<S, P, R5>, ParametricSelector<S, P, R6>, ParametricSelector<S, P, R7>, ParametricSelector<S, P, R8>, ParametricSelector<S, P, R9>, ParametricSelector<S, P, R10>], combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10) => T>; /* eleven selectors */ export function createSelector<S, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, T>( selectors: [Selector<S, R1>, Selector<S, R2>, Selector<S, R3>, Selector<S, R4>, Selector<S, R5>, Selector<S, R6>, Selector<S, R7>, Selector<S, R8>, Selector<S, R9>, Selector<S, R10>, Selector<S, R11>], combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10, res11: R11) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10, res11: R11) => T>; export function createSelector<S, P, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, T>( selectors: [ParametricSelector<S, P, R1>, ParametricSelector<S, P, R2>, ParametricSelector<S, P, R3>, ParametricSelector<S, P, R4>, ParametricSelector<S, P, R5>, ParametricSelector<S, P, R6>, ParametricSelector<S, P, R7>, ParametricSelector<S, P, R8>, ParametricSelector<S, P, R9>, ParametricSelector<S, P, R10>, ParametricSelector<S, P, R11>], combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10, res11: R11) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10, res11: R11) => T>; /* twelve selectors */ export function createSelector<S, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, R12, T>( selectors: [Selector<S, R1>, Selector<S, R2>, Selector<S, R3>, Selector<S, R4>, Selector<S, R5>, Selector<S, R6>, Selector<S, R7>, Selector<S, R8>, Selector<S, R9>, Selector<S, R10>, Selector<S, R11>, Selector<S, R12>], combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10, res11: R11, res12: R12) => T, ): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10, res11: R11, res12: R12) => T>; export function createSelector<S, P, R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, R12, T>( selectors: [ParametricSelector<S, P, R1>, ParametricSelector<S, P, R2>, ParametricSelector<S, P, R3>, ParametricSelector<S, P, R4>, ParametricSelector<S, P, R5>, ParametricSelector<S, P, R6>, ParametricSelector<S, P, R7>, ParametricSelector<S, P, R8>, ParametricSelector<S, P, R9>, ParametricSelector<S, P, R10>, ParametricSelector<S, P, R11>, ParametricSelector<S, P, R12>], combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10, res11: R11, res12: R12) => T, ): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7, res8: R8, res9: R9, res10: R10, res11: R11, res12: R12) => T>; export function defaultMemoize<F extends Function>( func: F, equalityCheck?: <T>(a: T, b: T, index: number) => boolean, ): F; export function createSelectorCreator( memoize: <F extends Function>(func: F) => F, ): typeof createSelector; export function createSelectorCreator<O1>( memoize: <F extends Function>(func: F, option1: O1) => F, option1: O1, ): typeof createSelector; export function createSelectorCreator<O1, O2>( memoize: <F extends Function>(func: F, option1: O1, option2: O2) => F, option1: O1, option2: O2, ): typeof createSelector; export function createSelectorCreator<O1, O2, O3>( memoize: <F extends Function>(func: F, option1: O1, option2: O2, option3: O3, ...rest: any[]) => F, option1: O1, option2: O2, option3: O3, ...rest: any[], ): typeof createSelector; export function createStructuredSelector<S, T>( selectors: {[K in keyof T]: Selector<S, T[K]>}, selectorCreator?: typeof createSelector, ): Selector<S, T>; export function createStructuredSelector<S, P, T>( selectors: {[K in keyof T]: ParametricSelector<S, P, T[K]>}, selectorCreator?: typeof createSelector, ): ParametricSelector<S, P, T>;
the_stack
import { calculatePosition, OffsetPosition,calculateRelativeBasedPosition } from '../../src/common/position'; import {createElement} from '@syncfusion/ej2-base'; describe('Position Module Specs', () => { let element: HTMLElement; let offset: OffsetPosition = { left: 228, top: 220 }; function updateoffset(): void { offset = { left: getTargetElement().getBoundingClientRect().left, top: getTargetElement().getBoundingClientRect().top }; } beforeAll(() => { //document.body.appendChild() if (getTargetElement()) { getTargetElement().remove(); } element = createElement('div', { id: 'dialogSample' }); element.innerHTML = '<div id="block"><div style="margin: 220px;"><button id="targetElement">TargetElement</button> </div></div>'; document.body.appendChild(element); updateoffset(); }); describe('Position calculation', () => { it('Params -left,bottom', () => { //Expected -Get the Element Position ~ Left--Bottom //ToEqual - Get the Element getBoundingClientRect ~ Top--Left and add the height with top expect(calculatePosition(getTargetElement(), 'left', 'bottom')) .toEqual({ left: offset.left, top: offset.top + (getTargetElement().getBoundingClientRect().height) }); }); it('Params -center,bottom', () => { //Expected -Get the Element Position ~ center--Bottom //ToEqual - Get the Element getBoundingClientRect ~ Top--Left and add the height with top and add width/2 with the left. expect(calculatePosition(getTargetElement(), 'center', 'bottom')) .toEqual({ left: offset.left + (getTargetElement().getBoundingClientRect().width / 2), top: offset.top + (getTargetElement().getBoundingClientRect().height) }); }); it('Params -right,bottom', () => { //Expected -Get the Element Position ~ right--Bottom //ToEqual - Get the Element getBoundingClientRect ~ Top--Left and add the height with top and add width with the left. expect(calculatePosition(getTargetElement(), 'right', 'bottom')) .toEqual({ left: offset.left + (getTargetElement().getBoundingClientRect().width), top: offset.top + (getTargetElement().getBoundingClientRect().height) }); }); it('Params -left,center', () => { //Expected -Get the Element Position ~ left--center //ToEqual - Get the Element getBoundingClientRect ~ Top--Left and add the height/2 with top. expect(calculatePosition(getTargetElement(), 'left', 'center')) .toEqual({ left: offset.left, top: offset.top + (getTargetElement().getBoundingClientRect().height / 2) }); }); it('Params -right,center', () => { //Expected -Get the Element Position ~ right--center //ToEqual - Get the Element getBoundingClientRect ~ Top--Left and add the height/2 with top and add the width with left. expect(calculatePosition(getTargetElement(), 'right', 'center')) .toEqual({ left: offset.left + (getTargetElement().getBoundingClientRect().width), top: offset.top + (getTargetElement().getBoundingClientRect().height / 2) }); }); it('Params -center,center', () => { //Expected - Get the Element Position ~ center--center //ToEqual - Get the Element getBoundingClientRect ~ Top--Left and add the height/2 with top and add width/2 with left. expect(calculatePosition(getTargetElement(), 'center', 'center')) .toEqual({ left: offset.left + (getTargetElement().getBoundingClientRect().width / 2), top: offset.top + (getTargetElement().getBoundingClientRect().height / 2) }); }); it('Params -left,top', () => { //Expected - Get the Element Position ~ left--top. //ToEqual - Get the Element getBoundingClientRect ~ Top--Left . expect(calculatePosition(getTargetElement(), 'left', 'top')).toEqual(offset); }); it('Params -center,top', () => { //Expected -Get the Element Position ~ center--top. //ToEqual -Get the Element getBoundingClientRect ~ Top--Left and add height/2. expect(calculatePosition(getTargetElement(), 'center', 'top')) .toEqual({ left: offset.left + (getTargetElement().getBoundingClientRect().width / 2), top: offset.top }); }); it('Params -right,top', () => { //Expected -Get the Element Position ~ right--center //ToEqual -Get the Element getBoundingClientRect ~ Top--Left and add width. expect(calculatePosition(getTargetElement(), 'right', 'top')) .toEqual({ left: offset.left + (getTargetElement().getBoundingClientRect().width), top: offset.top }); }); }); describe('with different Position css Values', () => { it('With Abosolute Element.', () => { (getTargetElement() as HTMLElement).style.position = 'absolute'; (getTargetElement() as HTMLElement).style.left = '10px'; (getTargetElement() as HTMLElement).style.top = '10px'; updateoffset(); //Expected - Get the Element Position ~ left--top with absolute parent. //ToEqual - Get the Element getBoundingClientRect ~ Top--Left expect(calculatePosition(getTargetElement(), 'left', 'top')).toEqual({ left: offset.left , top: offset.top }); }); it('With relative body element.', () => { document.body.style.position = 'relative'; updateoffset(); //Expected - Get the Element Position ~ left--top with relative parent. //ToEqual -Get the Element getBoundingClientRect ~ Top--Left expect(calculatePosition(getTargetElement(), 'left', 'top')).toEqual({ left: offset.left , top: offset.top }); }); it('With relative parent with abosolute child.', () => { document.body.style.position = ''; getTargetElement().parentElement.style.position = 'relative'; (getTargetElement() as HTMLElement).style.position = 'abosolute'; (getTargetElement() as HTMLElement).style.left = '10px'; (getTargetElement() as HTMLElement).style.top = '10px'; //Expected - Get the Element Position ~ left--top with relative parent element and element position abosolute. //ToEqual -Get the Element getBoundingClientRect ~ Top--Left updateoffset(); expect(calculatePosition(getTargetElement(), 'left', 'top')).toEqual({ left: offset.left, top: offset.top }); }); it('inside the scroller content', () => { getTargetElement().parentElement.style.position = 'relative'; (getTargetElement() as HTMLElement).style.position = 'abosolute'; (document.body.querySelector('#block') as HTMLElement).style.height = '150px'; (document.body.querySelector('#block') as HTMLElement).style.overflow = 'scroll'; updateoffset(); //Expected - Get the Element Position ~ left--top with relative parent element, element position abosolute with content parent. //ToEqual - Get the Element getBoundingClientRect ~ Top -- Left expect(calculatePosition(getTargetElement(), 'left', 'top')).toEqual({ left: offset.left , top: offset.top }); }); }); describe('improper function Params scenario-', () => { it('API Call with null parameter', () => { // API CheckUps with null element //Expected - left:0,top:0. //ToEqual - left:0,top:0 expect(calculatePosition(null, 'left', 'top')).toEqual({ left: 0 , top: 0 }); }); it('API Call with un attached element', () => { // API CheckUps with un attached document element. //Expected - left:0,top:0. //ToEqual - left:0,top:0 expect(calculatePosition(createElement('div', { id: 'sample' }), 'left', 'top')).toEqual({ left: 0 , top: 0 }); }); it('API Call with with improper positionX, positionY', () => { //API CheckUps with improper positionX, positionY. //Expected - Get the Element Position ~ left--top. //ToEqual - Get the Element getBoundingClientRect ~ Top--Left . expect(calculatePosition(getTargetElement(), null, undefined)) .toEqual({ left: offset.left, top: offset.top}); }); }); afterAll(() => { element.remove(); }); }); describe('position calculation for popup-', () => { let element: HTMLElement; let offset: OffsetPosition; function updateoffset(): void { offset = { left: getTargetElement().getBoundingClientRect().left, top: getTargetElement().getBoundingClientRect().top }; } beforeAll(() => { //document.body.appendChild() if (getTargetElement()) { getTargetElement().remove(); } element = createElement('div', { id: 'dialogSample' }); element.innerHTML = '<div id="block"><div style="margin: 713px;"><button id="targetElement">TargetElement</button> </div></div>'; document.body.appendChild(element); updateoffset(); }); afterAll(() => { element.remove(); }); it('if bottom and right collison occurs', () => { expect(calculatePosition(getTargetElement(), 'right', 'top')) .toEqual({ left: document.querySelector("#targetElement").getBoundingClientRect().right, top: document.querySelector("#targetElement").getBoundingClientRect().top }); }); }); describe('Position calculation - calculateRelativeBasedPosition -', () => { let element: HTMLElement; let offset: OffsetPosition; let popup: HTMLElement; function updateoffset(): void { offset = { left: getTargetElement().getBoundingClientRect().left, top: getTargetElement().getBoundingClientRect().top }; } beforeAll(() => { //document.body.appendChild() if (getTargetElement()) { getTargetElement().remove(); } element = createElement('div', { id: 'dialogSample', styles:'position:absolute; margin:100px' }); element.innerHTML = '<div id="block" style="position: absolute;margin: 203px;"><div style="margin: 220px;overflow: scroll;height: 77px;width: 182px;position: absolute;"><button id="targetElement" style="margin: 48px;">TargetElement</button> </div></div>'; document.body.appendChild(element); element.appendChild(createElement('div', { id: 'sampleElement',innerHTML:'Related Element', styles:'margin:"100px"'})); updateoffset(); }); it('Position Calculation with the different offset parent.', () => { //Expected - Relative Element Positions check ups. //ToEqual - {left: 471, top: 471} expect(calculateRelativeBasedPosition(<HTMLElement>getTargetElement(),<HTMLElement>document.querySelector("#sampleElement")) ).toEqual({left: 471, top: 471}); }); it('Invalid parametter checkups', () => { //Expected - Relative Element Positions check ups. //ToEqual - {left: 471, top: 471} expect(calculateRelativeBasedPosition(null,null) ).toEqual({left: 0, top: 0}); }); }); function getTargetElement(): Element { return document.body.querySelector('#targetElement'); }
the_stack
import Stream = require("stream"); import File = require("fs"); // Note: The 'import * as Foo from "./Foo' syntax avoids the "compiler re-write problem" that breaks debugger hover inspection import * as IC from "./ICProcess"; import * as Configuration from "./Configuration"; import * as StringEncoding from "./StringEncoding"; import * as Utils from "./Utils/Utils-Index"; import * as Messages from "./Messages"; import * as Root from "./AmbrosiaRoot"; export type BasicEventHandler = () => void; /** Type of a handler for OutgoingMessageStream errors. */ export type ErrorHandler = (error: Error) => void; /** Type of the object returned by a CheckpointProducer method. When the checkpoint has been sent (to the IC), onFinished will be called. */ export type OutgoingCheckpoint = { /** The outgoing [to the IC] stream of checkpoint data (serialized application state). */ dataStream: Stream.Readable, /** The length (in bytes) of the dataStream. */ length: number, /** * Callback invoked when the send is complete, or an error has occurred.\ * Note: Setting this to null is reserved for future use. */ onFinished: ((error?: Error) => void) | null }; /** Type of the object returned by a CheckpointConsumer method. */ export type IncomingCheckpoint = { /** The incoming [from the IC] stream of checkpoint data (serialized application state). */ dataStream: Stream.Writable, /** Callback invoked when the receive is complete, or an error has occurred. */ onFinished: (error?: Error) => void }; /** Type of a method that generates (writes) serialized application state. */ export type CheckpointProducer = () => OutgoingCheckpoint; /** Type of a method that loads (reads) serialized application state. */ export type CheckpointConsumer = () => IncomingCheckpoint; /** * A utility method that returns a simple in-memory, outgoing [to IC] checkpoint from the supplied application state. * After the checkpoint has been sent (to the IC), onFinished will be called.\ * Use in conjunction with simpleCheckpointConsumer(). */ export function simpleCheckpointProducer(appState: Root.AmbrosiaAppState, onFinished: ((error?: Error) => void) | null): OutgoingCheckpoint { // Verify that the appState we're about to save [as a checkpoint] is the same appState that Ambrosia has been using to persist its internal state. // If this throws, it indicates that the user has [illegally] reassigned the appState since it was returned by the IC.initializeAmbrosiaState() call. IC.checkAmbrosiaState(appState); let stream: MemoryStream = new MemoryStream(); let jsonAppState: string = Utils.jsonStringify(appState); let serializedState: Uint8Array = StringEncoding.toUTF8Bytes(jsonAppState); stream.end(serializedState); return ({ dataStream: stream, length: serializedState.length, onFinished: onFinished }); } /** * A utility method that returns a simple in-memory, incoming [from IC] checkpoint consumer. * After the checkpoint has been received (from the IC), 'onFinished' will be called with the checkpoint deserialized to the * application state (as instantiated by 'appStateConstructor', the application state class name).\ * Use in conjunction with simpleCheckpointProducer(). */ export function simpleCheckpointConsumer<T extends Root.AmbrosiaAppState>(appStateConstructor: new (restoredAppState?: T) => T, onFinished: (appState?: T, error?: Error) => void): IncomingCheckpoint { Root.checkAppStateConstructor(appStateConstructor); let receiverStream: MemoryStream = new MemoryStream(); function onCheckpointReceived(error?: Error) { let appState: T | undefined = undefined; if (!error) { appState = Utils.jsonParse(StringEncoding.fromUTF8Bytes(receiverStream.readAll())); // This deserializes the data appState = IC.initializeAmbrosiaState<T>(appStateConstructor, appState); // This rehydrates the class instance from the data } onFinished(appState, error); } return ({ dataStream: receiverStream, onFinished: onCheckpointReceived }); } /** * A class respresenting a stream for outgoing messages [to the IC].\ * Add messages to the stream using either addBytes() or addStreamedBytes(), or queueBytes() followed by flushQueue().\ * Note: This "wrapper" (over _lbSendSocket) enables us to implement control over the batching of outgoing messages (using RPCBatch). */ export class OutgoingMessageStream extends Stream.Readable { private _allowRPCBatching: boolean; private _pendingMessages: Uint8Array[] = []; private _maxQueuedBytes: number = 1024 * 1024 * 256; // 256 MB, but optionally re-initialized in constructor private _queuedByteCount: number = 0; private _destinationStream: Stream.Writable; // Initialized in constructor private _onErrorHandler: ErrorHandler; // Initialized in constructor private _isProcessingByteStream: boolean = false; private _loggingPrefix = "READER"; private _isClosing: boolean = false; private _flushPending = false; /** * [ReadOnly] Whether a byte stream is currently in the process of being added [via addStreamedBytes()]. * If true, wait until the onFinished callback of the current stream is invoked before attempting to add another stream. */ get isProcessingByteStream(): boolean { return (this._isProcessingByteStream); } /** [ReadOnly] The current length of the message queue (in messages). */ get queueLength(): number { return (this._pendingMessages.length); } /** [ReadOnly] The maximum number of bytes that the stream can queue (or internally buffer). Defaults to 256 MB. Cannot be smaller than 32 MB. */ get maxQueuedBytes(): number { return (this._maxQueuedBytes); } constructor(destinationStream: Stream.Writable, onError: ErrorHandler, allowRPCBatching: boolean = true, maxQueueSizeInBytes?: number, options?: Stream.ReadableOptions) { super(options) this._destinationStream = destinationStream; this._onErrorHandler = onError; this._allowRPCBatching = allowRPCBatching; if (maxQueueSizeInBytes) { this._maxQueuedBytes = Math.max(1024 * 1024 * 32, maxQueueSizeInBytes); // Enforce a 32 MB minimum } this.addEventHandlers(); this.pipe(this._destinationStream); // pipe() sets up a pipeline orchestration between 2 streams, so this call does not block } private addEventHandlers(): void { // An error in the destination (writable) stream // Note: This [external] stream may already have its own on("error") handler; multiple event handlers will fire in the order they were added this._destinationStream.on("error", (error: Error) => { this.handleError(error, "WRITER"); }); // An error in our (readable) stream this.on("error", (error: Error) => { this.handleError(error, this._loggingPrefix); }); // End-of-stream reached, eg. push(null) this.on("end", () => { Utils.log("End event", this._loggingPrefix, Utils.LoggingLevel.Debug); if (!this._isClosing && !this.destroyed) { this.handleError(new Error("Stream unexpectedly ended"), this._loggingPrefix); } }); // Stream closed (ie. destroyed). After this event, no more events will be emitted by the stream. this.on("close", () => { Utils.log("Close event", this._loggingPrefix, Utils.LoggingLevel.Debug); }); } private handleError(error: Error, source: string) { // We do this to avoid duplicate logging. The assumption is that if the user provided their own error handler, they will also take responsibility for logging. if (!this._onErrorHandler) { Utils.log("Error: " + error.message, source); } try { this.unpipe(this._destinationStream); if (!this._destinationStream.destroyed) { this._destinationStream.end(); // This will make _destinationStream [synchronously] emit a 'finish' event this._destinationStream.destroy(); // This will make _destinationStream [asynchronously] emit a 'close' event } if (!this.destroyed) { this.destroy(); } if (this._onErrorHandler) { // We use setImmediate() here to allow any [asynchronous] events (like 'close') to fire setImmediate(() => this._onErrorHandler(error)); } } catch (error: unknown) { Utils.log(Utils.makeError(error)); } } // Called when a consumer (in our case 'pipe()') wants to read data from the stream. // Note: We MUST provide an implementation for this method, even if it's a no-op. // Note: When we push() to the stream this method will end up being called, even if the stream isn't being piped. _read(size: number): void { try { // No-op } catch (error: unknown) { // This is the ONLY supported way to report an error [to the on("error") handler] from _read // The stream will emit 'error' (synchronously) then 'close' (asynchronously) events this.destroy(Utils.makeError(error)); } } /** Returns true if the stream can be closed using close(). */ canClose(): boolean { return (!this.destroyed && !this._isClosing); } /** Closes the stream. The stream cannot be used again after this has been called. */ close(onClosed?: BasicEventHandler): void { this.checkDestroyed(); if (this._isClosing) { return; } this._isClosing = true; // Push null to cause the destination stream to emit the 'finish' event [after it flushes its last write] this.push(null); // EOF [push() will return false indicating that no more data can be pushed] // Wait for the destination stream to finish this._destinationStream.once("finish", () => { this.unpipe(this._destinationStream); this.destroy(); this._destinationStream.destroy(); if (onClosed) { // We use setImmediate() here to allow our 'end'/'close' events, and _destinationStream's 'close' event, to fire setImmediate(onClosed); } }); } /** Checks if the stream has been destroyed and, if so, throws. */ private checkDestroyed(): void { if (this.destroyed) { throw new Error("Invalid operation: The stream has already been destroyed"); } } /** Checks if the stream's internal buffer has exceeded the size limit (_maxQueuedBytes) and, if so, throws. */ private checkInternalBuffer(): void { if (this.readableLength > this._maxQueuedBytes) { // Throwing here is more deterministic than failing at some unpredictable location with OOM (if we let the internal buffer grow unchecked). // This exception indicates that the stream is not emptying (likely due to I/O starvation). throw new Error(`The stream buffer size limit (${this._maxQueuedBytes} bytes) has been exceeded (${this.readableLength} bytes))`); } } /** * Asynchronously adds bytes to the stream from another stream. * Only one byte stream at-a-time can be added, and messages added with addBytes() will queue until the byte stream ends. * Useful, for example, to send a large checkpoint (binary blob). * * This method will flush any queued messages before streaming begins, and after streaming ends. */ addStreamedBytes(byteStream: Stream.Readable, expectedStreamLength: number = -1, onFinished?: (error?: Error) => void): void { let startTime: number = Date.now(); let bytesSentCount: number = 0; this.checkDestroyed(); this.checkInternalBuffer(); if (this._isProcessingByteStream) { throw new Error("Another byte stream is currently being being added; try again later (after the onFinished callback for that stream has been invoked)"); } const pendingMessageCount: number = this.flushQueue(); if (pendingMessageCount > 0) { Utils.log(`Flushed ${pendingMessageCount} messages from the outgoing queue (before streaming)`, null, Utils.LoggingLevel.Minimal); } this._isProcessingByteStream = true; // Must be set AFTER calling flushQueue() const onAddStreamedBytesFinished: (error?: Error) => void = (error?: Error) => { if (!this._isProcessingByteStream) { return; } this._isProcessingByteStream = false; const elapsedMs: number = Date.now() - startTime; if (error) { Utils.log(`Byte stream read failed (in ${elapsedMs}ms): ${Utils.makeError(error).message}`, this._loggingPrefix, Utils.LoggingLevel.Minimal); } else { Utils.log(`Byte stream read ended (in ${elapsedMs}ms)`, this._loggingPrefix, Utils.LoggingLevel.Debug); if ((expectedStreamLength >= 0) && (bytesSentCount !== expectedStreamLength)) { // For example, if we're sending checkpoint data to the IC but the length we sent to it (in a Checkpoint // message) has a length that doesn't match the length of the data stream we sent, then we should error throw new Error(`The stream contained ${bytesSentCount} bytes when ${expectedStreamLength} were expected`); } } if (onFinished) { onFinished(error); } // Flush anything that accumulated in the queue while we were processing byteStream [typically, there should be nothing to flush] const pendingMessageCount: number = this.flushQueue(); if (pendingMessageCount > 0) { Utils.log(`Flushed ${pendingMessageCount} messages from the outgoing queue (after streaming)`, null, Utils.LoggingLevel.Minimal); } // Remove handlers byteStream.removeListener("data", onByteStreamData); byteStream.removeListener("end", onAddStreamedBytesFinished); byteStream.removeListener("error", onAddStreamedBytesFinished); }; const onByteStreamData: (data: Buffer) => void = (data: Buffer) => { this.push(data); // If this returns false, it will just buffer bytesSentCount += data.length; }; byteStream.on("data", onByteStreamData); byteStream.on("end", onAddStreamedBytesFinished); // 'end' will be raise when there is no more data to consume from byteStream (ie. end-of-stream is reached) byteStream.on("error", onAddStreamedBytesFinished); } /** * Adds byte data to the stream. * The data ('bytes') should always represent a complete message (to enable batching).\ * To avoid excessive memory usage, for very large data (ie. 10's of MB) consider using addStreamedBytes(). */ addBytes(bytes: Uint8Array, immediateFlush: boolean = false): void { this.queueBytes(bytes); if (this._isProcessingByteStream) { // We must not push() to the stream while we're in the process of adding a byte stream [using addStreamedBytes()], // so instead we just accumulate the messages in the queue (ignoring the immediateFlush value) which will be // automatically flushed when the byte stream completes. return; } if (immediateFlush) { this.flushQueue(); } else { if (!this._flushPending) { // We use setImmediate() here so that addBytes() can be called repeatedly (eg. in a loop) without // flushing on each call (the flush will happen AFTER the function containing the loop finishes). // This is "implicit" batching ("explicit" batching is using queueBytes() and calling flushQueue() explicitly). // Note: This will result in messages accumulating in _pendingMessages. setImmediate(() => this.flushQueue()); this._flushPending = true; } } } /** * Queues byte data to be flushed to the stream later using flushQueue(). * The data ('bytes') should always represent a complete message (to enable batching).\ * To avoid excessive memory usage, for very large data (ie. 10's of MB) consider using addStreamedBytes(). */ queueBytes(bytes: Uint8Array): void { this.checkDestroyed(); this.checkInternalBuffer(); /* ** WARNING: This is untested code! ** 9/8/21: It's not clear if this added complexity is required, so leaving commented out for now. // If recovery is running and there's no room for 'bytes' in the queue, then try to make room by flushing. // This can [theoretically] happen if a received log page (containing multiple messages) is larger than _maxQueuedBytes. // In practice, the IC seems to avoid sending "oversize" log pages (eg. bundling 2+ "large" messages into a single log page) // which means that flushQueue() already gets called "naturally" [via setImmediate()] between received log pages. if (Messages.isRecoveryRunning() && ((this._queuedByteCount + bytes.length) > this._maxQueuedBytes)) { this.flushQueue(); } */ if ((this._queuedByteCount + bytes.length) <= this._maxQueuedBytes) { this._pendingMessages.push(bytes); this._queuedByteCount += bytes.length; } else { // Note: This could also be the result of the user not calling IC.flushQueue() frequently enough throw new Error(`Cannot add the supplied ${bytes.length} bytes (reason: The stream queue size limit (${this._maxQueuedBytes} bytes) would be exceeded; consider increasing the 'lbOptions.maxMessageQueueSizeInMB' configuration setting)`); } } /** * Flushes the message queue to the stream.\ * Returns the number of messages (not bytes) that were queued (and flushed). * A returned negative number indicates that the queue was not flushed and still contains that number of messages.\ * Note: Calling flushQueue() [synchronously] while reading from the IC will NOT result in interleaved I/O, so OutgoingMessageStream will just buffer. */ flushQueue(): number { let bytes: Uint8Array; let messageCount: number = this._pendingMessages.length; let logLevel: Utils.LoggingLevel = Utils.LoggingLevel.Debug; if (this._isProcessingByteStream) { // When addStreamedBytes() completes it will flush any messages that accumulated in the queue while it was was processing the stream. // Aside: If a message is accidentally flushed AFTER a Checkpoint message has been sent but BEFORE the checkpoint stream starts, then // the IC will fail with "FATAL ERROR 0: Illegal leading byte in local message". return (-messageCount); } this._flushPending = false; if (messageCount === 0) { return (0); } if (messageCount === 1) { // No need to batch when we only have one message bytes = this._pendingMessages[0]; } else { // Concatenate into a "batch", optionally using an RPCBatch [which has an optimized processing path in the IC]. // Note: It's valid to re-batch outgoing messages [with RPCBatch] during recovery. if (this._allowRPCBatching && Messages.canUseRPCBatch(this._pendingMessages)) { // Rather than pre-pending the RPCBatch header to _pendingMessages, we just push it directly [thereby avoiding a potentially costly memory copy] let rpcBatchHeader: Uint8Array = Messages.makeRPCBatchMessageHeader(messageCount, this._queuedByteCount); let readableLength: number = this.readableLength; // The number of bytes in the queue ready to be read let wasBuffered: boolean = !this.push(rpcBatchHeader); // If this returns false, it will just buffer let headerBytesPushed: number = wasBuffered ? (this.readableLength - readableLength) : rpcBatchHeader.length; if (headerBytesPushed !== rpcBatchHeader.length) { throw new Error(`Only ${headerBytesPushed} of ${rpcBatchHeader.length} RPCBatch-header bytes were pushed`); } if (Utils.canLog(logLevel)) { Utils.log(`${messageCount} RPC messages batched: Pushed ${headerBytesPushed} RPCBatch-header bytes ${wasBuffered ? "[buffered] " : ""}`, null, logLevel); } if (Utils.canLog(Utils.LoggingLevel.Verbose)) { // An RPCBatch only contains outgoing RPC messages, each of which specifies a destination, so the batch can ONLY be sent to the local IC Utils.log(`Sending 'RPCBatch' (of ${messageCount} messages) to local IC (${rpcBatchHeader.length + this._queuedByteCount} bytes)`, null, Utils.LoggingLevel.Verbose); } } bytes = Buffer.concat(this._pendingMessages, this._queuedByteCount); } let readableFlowing: boolean | null = this.readableFlowing; // If readableFlowing is null it means that "no mechanism for consuming the stream's data is provided" let readableLength: number = this.readableLength; // The number of bytes in the queue ready to be read let bytesPushed: number = 0; let warning: string = ""; if (Utils.canLog(logLevel)) { Utils.log(`Pushing ${bytes.length} bytes, ${messageCount} messages`, this._loggingPrefix, logLevel); } // Note: The writable being piped to will respond immediately to push(), NOT at the next tick of the event loop. if (this.push(bytes)) // If this returns false, it will just buffer { bytesPushed = bytes.length; } else { // The number of pushed bytes (or this.readableLength + pushed bytes) exceeded this.readableHighWaterMark. // Note: The stream's internal buffer will accumulate the bytes, but seems to grow indefinitely (presumably // until Node.js fails with OOM; which is why we have checkInternalBuffer()). bytesPushed = this.readableLength - readableLength; // This *should* be the same as bytes.length warning = `(Warning: the stream is full [${this.readableLength} bytes buffered / ${this.readableHighWaterMark} bytes highWaterMark])`; } if (bytesPushed === bytes.length) { let logLevel: Utils.LoggingLevel = warning ? Utils.LoggingLevel.Verbose : Utils.LoggingLevel.Debug; if (Utils.canLog(logLevel)) { Utils.log(`Pushed ${bytesPushed} bytes ${warning}`, this._loggingPrefix, logLevel); } this._pendingMessages = []; this._queuedByteCount = 0; } else { throw new Error(`Only ${bytesPushed} of ${bytes.length} bytes were pushed, so the pending message queue could not be cleared (messageCount: ${messageCount}, readableLength: ${this.readableLength}, readableFlowing: ${readableFlowing}, destroyed: ${this.destroyed})`); } return (messageCount); } } /** * Provides a basic in-memory stream, which can be both written to and read from. * Read the entire stream at once with readAll(), or read the entire stream in chunks (in a loop) using readUpTo(). * The lastReadSize/lastWriteSize properties track the result of the last read/write operation. * The maximum size of the MemoryStream can be set by specifying a maxSize value in the constructor. */ export class MemoryStream extends Stream.Duplex { private _maxSize: number; private _lastReadSize: number = 0; private _lastWriteSize: number = 0; private _totalBytesWritten: number = 0; /** [ReadOnly] The maximum size (in bytes) of the MemoryStream (-1 means no limit). */ get maxSize(): number { return (this._maxSize); } /** [ReadOnly] The number of bytes read with the last read/readAll/readUpTo operation. */ get lastReadSize(): number { return (this._lastReadSize); } /** [ReadOnly] The number of bytes written with the last write operation. */ get lastWriteSize(): number { return (this._lastWriteSize); } /** [ReadOnly] The total number of bytes written (so far). */ get totalBytesWritten(): number { return (this._totalBytesWritten); } /** [ReadOnly] Whether writing to the stream has ended. Note: This will only become true if MemoryStream.end() is called. */ get writingEnded(): boolean { return (this.writableEnded); } constructor(maxSize: number = -1) { super(); this._maxSize = Math.max(-1, maxSize); } _write(chunk: Buffer, encoding: string, callback: (error?: Error) => void): void { if ((this._maxSize !== -1) && (this.readableLength + chunk.length > this._maxSize)) { callback(new Error(`Writing ${chunk.length} bytes would exceed the MemoryStream maxSize (${this._maxSize} bytes) by ${ this.readableLength + chunk.length - this._maxSize} bytes`)); } else { if (chunk.length > 0) { this.push(chunk); // If this returns false, it will just buffer this._lastWriteSize = chunk.length; this._totalBytesWritten += chunk.length; } // Utils.log(`DEBUG: MemoryStream wrote ${this._lastWriteSize} bytes`); callback(); } } // Called before the stream closes (ie. [some time] after Duplex.end() is called) _final(callback: (error?: Error) => void): void { // Push null to cause the destination stream [when piping] to emit the 'finish' event [after it flushes its last write] this.push(null); // EOF [push() will return false indicating that no more data can be pushed] callback(); } _read(size: number): void { } /** Reads all available data in the MemoryStream. Returns null if no data is available. */ readAll(): Buffer { let isEmptyStream: boolean = this.writableEnded && (this._totalBytesWritten === 0); let chunk: Buffer = isEmptyStream ? Buffer.alloc(0) : this.read(this.readableLength); // Note: read() returns null if no data is available this._lastReadSize = (chunk === null) ? 0 : chunk.length; // Utils.log(`DEBUG: MemoryStream read ${this._lastReadSize} bytes`); return (chunk); } /** Reads - at most - size bytes, but may read less if fewer bytes are available. Returns null if no data is available. */ readUpTo(size: number): Buffer { let isEmptyStream: boolean = this.writableEnded && (this._totalBytesWritten === 0); let chunk: Buffer = isEmptyStream ? Buffer.alloc(0) : this.read(Math.min(size, this.readableLength)); this._lastReadSize = (chunk === null) ? 0 : chunk.length; return (chunk); } } /** * A simple stream processor that asynchronously counts the bytes in a stream, calling the supplied onFinished handler when the count is complete.\ * Example usage: fs.createReadStream("./lib/Demo.js").pipe(new StreamByteCounter((count: number) => Utils.log(count))); */ class StreamByteCounter extends Stream.Transform { private _onFinished: ((finalByteCount: number) => void) | undefined; private _finalByteCount: number = -1; private _currentByteCount: number = 0; private _bufferingCount: number = 0; // Used for debugging only private _chunkCount: number = 0; // Used for debugging only /** The length of the stream in bytes. Will be -1 until writing to the stream has finished. */ public get byteCount(): number { return (this._finalByteCount); } constructor(onFinished?: (finalByteCount: number) => void, options?: Stream.WritableOptions) { super(options); this._onFinished = onFinished; } // Called when there's no more written data to be consumed (ie. StreamByteCounter.end() is [implicitly] called, // which typically happens when the stream that's being piped into StreamByteCounter has it's end() called). // Consequently, it's possible that _flush() may never be called (but which would indicate a coding error in // the stream being piped into StreamByteCounter). _flush(callback: (error?: Error) => void): void { this._finalByteCount = this._currentByteCount; // Utils.log(`StreamByteCounter: Number of times buffering occurred: ${this._bufferingCount} (${((this._bufferingCount / this._chunkCount) * 100).toFixed(2)}%)`); if (this._onFinished) { this._onFinished(this._finalByteCount); } callback(); } _transform(chunk: Buffer, encoding: string, callback: (error?: Error) => void): void { try { if (!this.push(chunk)) // If this returns false, it will just buffer { this._bufferingCount++; } this._chunkCount++; this._currentByteCount += chunk.length; callback(); // Signal [to the caller of 'write'] that the write completed } catch (error: unknown) { callback(Utils.makeError(error)); // Signal [to the caller of 'write'] that the write failed } } } /** * Asynchronously counts the bytes in a stream, calling the supplied onDone handler when the count is complete. * Note: The supplied stream will not be re-readable (unless it has persistent storage, like a file). */ export function getStreamLength(stream: Stream.Readable, onDone: (length: number) => void): void { stream.pipe(new StreamByteCounter((count: number) => onDone(count))); } export function inMemStreamTest(): void { let memStream: MemoryStream = new MemoryStream(); let iterations: number = 3; let writeChunkSize: number = 64; for (let i = 0; i < iterations; i++) { memStream.write(new Uint8Array(writeChunkSize + i).fill(99)); Utils.log(`lastWriteSize: ${memStream.lastWriteSize}`); } let data: Uint8Array; while (data = memStream.readUpTo(61)) // Math.min(61, memStream.readableLength))) { Utils.log(`lastReadSize: ${memStream.lastReadSize}, writingEnded: ${memStream.writingEnded}`); } memStream.end(new Uint8Array(123).fill(88)); data = memStream.readAll(); Utils.log(`lastReadSize: ${memStream.lastReadSize}, writingEnded: ${memStream.writingEnded}`); } /** Tests OutgoingMessageStream [without using the IC]. */ export function startStreamTest(): void { // Check that we'll see OutgoingMessageStream output in the console if (!Utils.canLog(Utils.LoggingLevel.Debug) || !Utils.canLogToConsole()) { Utils.log(`Incorrect configuration for test: 'outputLoggingLevel' must be '${Utils.LoggingLevel[Utils.LoggingLevel.Debug]}', and 'outputLogDestination' must include '${Configuration.OutputLogDestination[Configuration.OutputLogDestination.Console]}'`); return; } let stopStreamTest: BasicEventHandler = () => { Utils.consoleInputStop(); }; Utils.log("startStreamTest() running: Press 'x' or 'Enter' to stop"); // Send the [readable] inStream to the [writable] outStream, ie. this is how to consume a "flowing" readable stream using a // writable stream [the writable stream here serves as a stream processor, it doesn't actually need to "write" the stream]. // When using pipe() we don't need to worry about responding to stream events ('drain', 'readable, 'data', etc.) because pipe() // handles them internally. It is recommended to avoid mixing the pipe end event-driven approaches. let outStream: ConsoleOutStream = new ConsoleOutStream({}, 64); let inStream: OutgoingMessageStream = new OutgoingMessageStream(outStream, (error: Error) => stopStreamTest(), false); // Note: We disable RPC batching // Add to the inStream each time a key is pressed Utils.consoleInputStart((char: string) => { let message: string = ""; switch (char) { case "x": case Utils.ENTER_KEY: inStream.close(() => { Utils.log("startStreamTest() stopping"); stopStreamTest(); }); break; case "b": // Add a "big" message message = char.repeat(127112 * 64); inStream.addBytes(StringEncoding.toUTF8Bytes(message)); break; case "s": // Add from a stream inStream.addStreamedBytes(File.createReadStream("./lib/Demo.js")); return; case "l": // Add in a loop for (let i = 0; i < 12; i++) { inStream.addBytes(StringEncoding.toUTF8Bytes(char)); } return; case "f": // Flush test inStream.addBytes(StringEncoding.toUTF8Bytes("Hello")); inStream.addBytes(StringEncoding.toUTF8Bytes("World")); inStream.addStreamedBytes(File.createReadStream("./lib/Demo.js")); // This will automatically flush the 2 items in the queue break; default: message = `Key pressed! ('${char}')`; inStream.addBytes(StringEncoding.toUTF8Bytes(message)); } }); } /** [For testing only] A writable stream that reports (to the console) how much data it was sent. */ class ConsoleOutStream extends Stream.Writable { _maxBytesToDisplay: number = 0; _loggingPrefix: string = "WRITER"; constructor(options?: Stream.WritableOptions, maxBytesToDisplay: number = 128) { super(options); this._maxBytesToDisplay = maxBytesToDisplay; this.addEventHandlers(); } // Called when a consumer wants to write data to the stream _write(chunk: Buffer, encoding: string, callback: (error?: Error) => void): void { try { if (encoding !== "buffer") { throw new Error(`his stream can only write Buffer/Uint8Array data, not '${encoding}' data`); } if (chunk.length > 0) { // Write the data to its destination (in our case, to the console) let displayBytes: string = (chunk.length <= this._maxBytesToDisplay) ? Utils.makeDisplayBytes(chunk) : "..."; Utils.log(`Writing ${chunk.length} bytes (${displayBytes})`, this._loggingPrefix); } callback(); // Signal [to the caller of 'write'] that the write completed } catch (error: unknown) { // This is the ONLY supported way to report an error [to the on("error") handler] from _write() callback(Utils.makeError(error)); } } private addEventHandlers(): void { this.on("error", (error: Error) => { Utils.log("Error: " + error.message, this._loggingPrefix); }); // All writes are complete and flushed this.on("finish", (...args: any[]) => { Utils.log("Finish event", this._loggingPrefix); }); // Stream closed (ie. destroyed). After this event, no more events will be emitted by the stream. this.on("close", () => { Utils.log("Close event", this._loggingPrefix); }); // The stream has drained all data from the internal buffer this.on("drain", () => { Utils.log("Drained event", this._loggingPrefix); }) } }
the_stack
import * as sinon from "sinon"; import { ClientContextMock, ContextMock, EntityMock, EventContextMock, FormItemMock, FormSelectorMock, ItemCollectionMock, ProcessManagerMock, ProcessMock, StageMock, StepMock, StringAttributeMock, UiMock, UserSettingsMock } from "../../src/xrm-mock"; import { XrmMockGenerator } from "../../src/xrm-mock-generator"; import FormContext from "../../src/xrm-mock-generator/formcontext"; describe("XrmMockGenerator Builder", () => { let tab: Xrm.Controls.Tab; let section: Xrm.Controls.Section; let control: Xrm.Controls.StringControl; let attribute: Xrm.Attributes.Attribute; let context: Xrm.GlobalContext; let navigation: Xrm.Navigation; let process: Xrm.ProcessFlow.ProcessManager; const contact = { firstname: "Joe", id: "123", lastname: "Bloggs", }; let tempValue: string; beforeAll(() => { // attributes const nameAttribute = new StringAttributeMock({ name: "name", requiredLevel: "required", }); nameAttribute.addOnChange(() => tempValue = "Test OnChange!"); // entity const entity = new EntityMock({ attributes: new ItemCollectionMock<Xrm.Attributes.Attribute>([nameAttribute]), entityName: "account", id: "{00000000-0000-0000-0000-000000000000}", }); // ui const ui = new UiMock({ formSelector: new FormSelectorMock(new ItemCollectionMock<FormItemMock>( [ new FormItemMock({ currentItem: true, formType: 2, id: "5", label: "Main", }), ])), }); // context const globalContext = new ContextMock( { clientContext: new ClientContextMock("Web", "Online"), clientUrl: "https://org.crm.dynamics.com/", currentTheme: "default", isAutoSaveEnabled: false, orgLcid: 1031, orgUniqueName: "Contoso", timeZoneOffset: 0, userId: "{B05EC7CE-5D51-DF11-97E0-00155DB232D0}", userLcid: 1033, userName: "Joe Bloggs", userRoles: ["cf4cc7ce-5d51-df11-97e0-00155db232d0"], userSettings: new UserSettingsMock( { isGuidedHelpEnabled: false, isHighContrastEnabled: false, isRTL: false, languageId: 1033, securityRoles: ["cf4cc7ce-5d51-df11-97e0-00155db232d0"], userId: "{00000000-0000-0000-0000-000000000000}", userName: "jdoe", }), version: "8.2.1.185", }); // bpf /// steps const firstNameStep = new StepMock("First Name", "firstname", false); const lastNameStep = new StepMock("Last Name", "lastname", false); const firstStage = new StageMock("6001", "Start", "active", null, [firstNameStep]); const secondStage = new StageMock("6002", "Finish", "inactive", null, [lastNameStep]); /// process const process1 = new ProcessMock({ id: "4444", name: "Sales Process", rendered: true, stages: new ItemCollectionMock<Xrm.ProcessFlow.Stage>([firstStage, secondStage]), }); const process2 = new ProcessMock({ id: "5555", name: "Service Process", rendered: false, stages: new ItemCollectionMock<Xrm.ProcessFlow.Stage>([firstStage, secondStage]), }); const processManager = new ProcessManagerMock([process1, process2]); XrmMockGenerator.initialise({ context: globalContext, entity, process: processManager, ui, }); // form structure XrmMockGenerator.Tab.createTab("testTab", "Test Tab", false, "collapsed", null, new ItemCollectionMock<Xrm.Controls.Section>( [ XrmMockGenerator.Section.createSection("testSection", "Test Section", false, null, new ItemCollectionMock<Xrm.Controls.Control>( [ XrmMockGenerator.Control.createString({ attribute: nameAttribute, disabled: true, label: "Name", name: "name", visible: false, }), XrmMockGenerator.Control.createGrid({ entityName: "account", name: "accounts", }), ])), ])); // event context (OnLoad, OnChange ... etc.) const eventContext = new EventContextMock( { context: globalContext, formContext: FormContext.createFormContext(entity, ui), }); // web api const recordId = "123"; const stub = sinon.stub(Xrm.WebApi, "retrieveRecord"); stub.withArgs("contact", recordId, "?$select=fullname").resolves(contact); // extract sample doc from here and test.ts }); describe("Tab", () => { it("should create a tab", () => { tab = Xrm.Page.ui.tabs.get("testTab"); expect(tab).toBeDefined(); expect(tab).not.toBeNull(); }); it("should have a name", () => { expect(tab.getName()).toBe("testTab"); }); it("should have a label", () => { expect(tab.getLabel()).toBe("Test Tab"); }); it("should have a parent", () => { expect(tab.getParent()).toEqual(Xrm.Page.ui); }); it("should be invisible", () => { expect(tab.getVisible()).toBeFalsy(); }); it("should be collapsed", () => { expect(tab.getDisplayState()).toBe("collapsed"); }); }); describe("Section", () => { it("should create a section", () => { const sections = Xrm.Page.ui.tabs.get("testTab").sections; expect(sections).toBeDefined(); expect(sections).not.toBeNull(); section = sections.get("testSection"); expect(section).toBeDefined(); expect(section).not.toBeNull(); }); it("should have a name", () => { expect(section.getName()).toBe("testSection"); }); it("should have a label", () => { expect(section.getLabel()).toBe("Test Section"); }); it("should have a parent", () => { expect(section.getParent()).toEqual(tab); }); it("should be invisible", () => { expect(section.getVisible()).toBeFalsy(); }); }); describe("Control", () => { it("should create a control", () => { const sections = Xrm.Page.ui.tabs.get("testTab").sections; expect(sections).toBeDefined(); expect(sections).not.toBeNull(); section = sections.get("testSection"); expect(section).toBeDefined(); expect(section).not.toBeNull(); const controls = section.controls; expect(controls).toBeDefined(); expect(controls).not.toBeNull(); control = controls.get("name") as Xrm.Controls.StringControl; expect(control).toBeDefined(); expect(control).not.toBeNull(); control = Xrm.Page.getControl("name"); expect(control).toBeDefined(); expect(control).not.toBeNull(); }); it("should have a name", () => { expect(control.getName()).toBe("name"); }); it("should have a label", () => { expect(control.getLabel()).toBe("Name"); }); it("should have a parent", () => { expect(control.getParent()).toEqual(section); }); it("should be invisible", () => { expect(control.getVisible()).toBeFalsy(); }); it("should be disabled", () => { expect(control.getDisabled()).toBeTruthy(); }); }); describe("Attribute", () => { it("should create an attribute", () => { attribute = Xrm.Page.getAttribute("name"); expect(attribute).toBeDefined(); expect(attribute).not.toBeNull(); }); it("should have a name", () => { expect(attribute.getName()).toBe("name"); }); it("should be required", () => { expect(attribute.getRequiredLevel()).toBe("required"); }); it("should be dirty", () => { attribute.setValue("TEST!"); expect(attribute.getIsDirty()).toBeTruthy(); }); it("should be have value 'TEST!'", () => { attribute.setValue("TEST!"); expect(attribute.getValue()).toBe("TEST!"); }); it("should fire OnChange", () => { tempValue = ""; attribute.fireOnChange(); expect(tempValue).toBe("Test OnChange!"); }); it("should fire OnChange with eventContext", () => { let contextArg: Xrm.Events.EventContext; attribute.addOnChange((c: Xrm.Events.EventContext) => {contextArg = c}); attribute.fireOnChange(); expect(contextArg.getContext()).toBe(XrmMockGenerator.getEventContext().getContext()); expect(contextArg.getEventSource()).toBe(attribute); }); }); describe("Entity", () => { it("should be an account", () => { expect(Xrm.Page.data.entity.getEntityName()).toBe("account"); }); it("should have an ID", () => { expect(Xrm.Page.data.entity.getId()).toBe("{00000000-0000-0000-0000-000000000000}"); }); }); describe("Form", () => { it("should have an ID", () => { expect(Xrm.Page.ui.formSelector.getCurrentItem().getId()).toBe("5"); }); it("should have a label", () => { expect(Xrm.Page.ui.formSelector.getCurrentItem().getLabel()).toBe("Main"); }); }); describe("Navigation", () => { it("should be defined", () => { navigation = Xrm.Navigation; expect(navigation).toBeDefined(); }); it("should have openUrl stubed", () => { expect(Xrm.Navigation.openUrl).toBeDefined(); }); }); describe("Context", () => { it("should have a context", () => { context = Xrm.Page.context; expect(context).toBeDefined(); expect(context).not.toBeNull(); }); it("should have a user language", () => { expect(context.getUserLcid()).toBe(1033); }); }); describe("Process", () => { it("should have a process manager", () => { process = Xrm.Page.data.process; expect(process).toBeDefined(); expect(process).not.toBeNull(); }); it("should have an active stage", () => { const activeStage = process.getActiveStage(); expect(activeStage).toBeDefined(); expect(activeStage).not.toBeNull(); expect(activeStage.getId()).toBe("6001"); }); }); describe("Web API", () => { it("should return a contact with ID '123'", () => { Xrm.WebApi .retrieveRecord("contact", contact.id, "?$select=fullname") .then((result: any) => { expect(result.id).toBe(contact.id); }); }); }); });
the_stack
import { CancellationToken } from 'vscode-languageserver'; import { Declaration, DeclarationType, isAliasDeclaration } from '../analyzer/declaration'; import * as ParseTreeUtils from '../analyzer/parseTreeUtils'; import { SourceMapper } from '../analyzer/sourceMapper'; import { Symbol } from '../analyzer/symbol'; import { TypeEvaluator } from '../analyzer/typeEvaluatorTypes'; import { maxTypeRecursionCount } from '../analyzer/types'; import { throwIfCancellationRequested } from '../common/cancellationUtils'; import { appendArray } from '../common/collectionUtils'; import { assertNever } from '../common/debug'; import { convertOffsetToPosition, convertPositionToOffset } from '../common/positionUtils'; import { DocumentRange, Position } from '../common/textRange'; import { TextRange } from '../common/textRange'; import { NameNode, ParseNode, ParseNodeType } from '../parser/parseNodes'; import { ParseResults } from '../parser/parser'; import { DocumentSymbolCollector } from './documentSymbolCollector'; export type ReferenceCallback = (locations: DocumentRange[]) => void; export class ReferencesResult { private readonly _locations: DocumentRange[] = []; readonly nonImportDeclarations: Declaration[]; constructor( readonly requiresGlobalSearch: boolean, readonly nodeAtOffset: ParseNode, readonly symbolName: string, readonly declarations: Declaration[], private readonly _reporter?: ReferenceCallback ) { // Filter out any import decls. but leave one with alias. this.nonImportDeclarations = declarations.filter((d) => { if (!isAliasDeclaration(d)) { return true; } // We must have alias and decl node that point to import statement. if (!d.usesLocalName || !d.node) { return false; } // d.node can't be ImportFrom if usesLocalName is true. // but we are doing this for type checker. if (d.node.nodeType === ParseNodeType.ImportFrom) { return false; } // Check alias and what we are renaming is same thing. if (d.node.alias?.value !== symbolName) { return false; } return true; }); } get containsOnlyImportDecls(): boolean { return this.declarations.length > 0 && this.nonImportDeclarations.length === 0; } get locations(): readonly DocumentRange[] { return this._locations; } addLocations(...locs: DocumentRange[]) { if (locs.length === 0) { return; } if (this._reporter) { this._reporter(locs); } appendArray(this._locations, locs); } } export class FindReferencesTreeWalker { constructor( private _parseResults: ParseResults, private _filePath: string, private _referencesResult: ReferencesResult, private _includeDeclaration: boolean, private _evaluator: TypeEvaluator, private _cancellationToken: CancellationToken ) {} findReferences(rootNode = this._parseResults.parseTree) { const collector = new DocumentSymbolCollector( this._referencesResult.symbolName, this._referencesResult.declarations, this._evaluator, this._cancellationToken, rootNode, /* treatModuleInImportAndFromImportSame */ true, /* skipUnreachableCode */ false ); const results: DocumentRange[] = []; for (const result of collector.collect()) { // Is it the same symbol? if (this._includeDeclaration || result.node !== this._referencesResult.nodeAtOffset) { results.push({ path: this._filePath, range: { start: convertOffsetToPosition(result.range.start, this._parseResults.tokenizerOutput.lines), end: convertOffsetToPosition( TextRange.getEnd(result.range), this._parseResults.tokenizerOutput.lines ), }, }); } } return results; } } export class ReferencesProvider { static getDeclarationForNode( sourceMapper: SourceMapper, filePath: string, node: NameNode, evaluator: TypeEvaluator, reporter: ReferenceCallback | undefined, token: CancellationToken ) { throwIfCancellationRequested(token); const declarations = DocumentSymbolCollector.getDeclarationsForNode( node, evaluator, /* resolveLocalNames */ false, token, sourceMapper ); if (declarations.length === 0) { return undefined; } const requiresGlobalSearch = isVisibleOutside(evaluator, filePath, node, declarations); return new ReferencesResult(requiresGlobalSearch, node, node.value, declarations, reporter); } static getDeclarationForPosition( sourceMapper: SourceMapper, parseResults: ParseResults, filePath: string, position: Position, evaluator: TypeEvaluator, reporter: ReferenceCallback | undefined, token: CancellationToken ): ReferencesResult | undefined { throwIfCancellationRequested(token); const offset = convertPositionToOffset(position, parseResults.tokenizerOutput.lines); if (offset === undefined) { return undefined; } const node = ParseTreeUtils.findNodeByOffset(parseResults.parseTree, offset); if (node === undefined) { return undefined; } // If this isn't a name node, there are no references to be found. if (node.nodeType !== ParseNodeType.Name) { return undefined; } return this.getDeclarationForNode(sourceMapper, filePath, node, evaluator, reporter, token); } static addReferences( parseResults: ParseResults, filePath: string, referencesResult: ReferencesResult, includeDeclaration: boolean, evaluator: TypeEvaluator, token: CancellationToken ): void { const refTreeWalker = new FindReferencesTreeWalker( parseResults, filePath, referencesResult, includeDeclaration, evaluator, token ); referencesResult.addLocations(...refTreeWalker.findReferences()); } } function isVisibleOutside( evaluator: TypeEvaluator, currentFilePath: string, node: NameNode, declarations: Declaration[] ) { const result = evaluator.lookUpSymbolRecursive(node, node.value, /* honorCodeFlow */ false); if (result && !isExternallyVisible(result.symbol)) { return false; } // A symbol's effective external visibility check is not enough to determine whether // the symbol is visible to the outside. Something like the local variable inside // a function will still say it is externally visible even if it can't be accessed from another module. // So, we also need to determine whether the symbol is declared within an evaluation scope // that is within the current file and cannot be imported directly from other modules. return declarations.some((decl) => { // If the declaration is outside of this file, a global search is needed. if (decl.path !== currentFilePath) { return true; } const evalScope = ParseTreeUtils.getEvaluationScopeNode(decl.node); // If the declaration is at the module level or a class level, it can be seen // outside of the current module, so a global search is needed. if (evalScope.nodeType === ParseNodeType.Module || evalScope.nodeType === ParseNodeType.Class) { return true; } // If the name node is a member variable, we need to do a global search. if (decl.node?.parent?.nodeType === ParseNodeType.MemberAccess && decl.node === decl.node.parent.memberName) { return true; } return false; }); // Return true if the symbol is visible outside of current module, false if not. function isExternallyVisible(symbol: Symbol, recursionCount = 0): boolean { if (recursionCount > maxTypeRecursionCount) { return false; } recursionCount++; if (symbol.isExternallyHidden()) { return false; } return symbol.getDeclarations().reduce<boolean>((isVisible, decl) => { if (!isVisible) { return false; } switch (decl.type) { case DeclarationType.Alias: case DeclarationType.Intrinsic: case DeclarationType.SpecialBuiltInClass: return isVisible; case DeclarationType.Class: case DeclarationType.Function: return isVisible && isContainerExternallyVisible(decl.node.name, recursionCount); case DeclarationType.Parameter: return isVisible && isContainerExternallyVisible(decl.node.name!, recursionCount); case DeclarationType.Variable: { if (decl.node.nodeType === ParseNodeType.Name) { return isVisible && isContainerExternallyVisible(decl.node, recursionCount); } // Symbol without name is not visible outside. return false; } default: assertNever(decl); } }, /* visible */ true); } // Return true if the scope that contains the specified node is visible // outside of the current module, false if not. function isContainerExternallyVisible(node: NameNode, recursionCount: number) { const scopingNode = ParseTreeUtils.getEvaluationScopeNode(node); switch (scopingNode.nodeType) { case ParseNodeType.Class: case ParseNodeType.Function: { const name = scopingNode.name; const result = evaluator.lookUpSymbolRecursive(name, name.value, /* honorCodeFlow */ false); return result ? isExternallyVisible(result.symbol, recursionCount) : true; } case ParseNodeType.Lambda: case ParseNodeType.ListComprehension: // Symbols in this scope can't be visible outside. return false; case ParseNodeType.Module: return true; default: assertNever(scopingNode); } } }
the_stack
import { EventEmitter } from '@angular/core'; import { cloneArray, cloneValue, IBaseEventArgs, resolveNestedPath, yieldingLoop } from '../../core/utils'; import { GridColumnDataType, DataUtil } from '../../data-operations/data-util'; import { ExportUtilities } from './export-utilities'; import { IgxExporterOptionsBase } from './exporter-options-base'; import { ITreeGridRecord } from '../../grids/tree-grid/tree-grid.interfaces'; import { TreeGridFilteringStrategy } from '../../grids/tree-grid/tree-grid.filtering.strategy'; import { IGroupingState } from '../../data-operations/groupby-state.interface'; import { getHierarchy, isHierarchyMatch } from '../../data-operations/operations'; import { IGroupByExpandState } from '../../data-operations/groupby-expand-state.interface'; import { IFilteringState } from '../../data-operations/filtering-state.interface'; import { IgxColumnComponent, IgxGridBaseDirective } from '../../grids/public_api'; import { IgxTreeGridComponent } from '../../grids/tree-grid/public_api'; import { IgxGridComponent } from '../../grids/grid/public_api'; import { DatePipe } from '@angular/common'; import { IGroupByRecord } from '../../data-operations/groupby-record.interface'; import { IgxHierarchicalGridComponent } from '../../grids/hierarchical-grid/hierarchical-grid.component'; import { IgxRowIslandComponent } from '../../grids/hierarchical-grid/row-island.component'; import { IPathSegment } from './../../grids/hierarchical-grid/hierarchical-grid-base.directive'; import { IgxColumnGroupComponent } from './../../grids/columns/column-group.component'; export enum ExportRecordType { GroupedRecord = 'GroupedRecord', TreeGridRecord = 'TreeGridRecord', DataRecord = 'DataRecord', HierarchicalGridRecord = 'HierarchicalGridRecord', HeaderRecord = 'HeaderRecord', } export enum HeaderType { ColumnHeader = 'ColumnHeader', MultiColumnHeader = 'MultiColumnHeader' } export interface IExportRecord { data: any; level: number; type: ExportRecordType; owner?: string | IgxGridBaseDirective; hidden?: boolean; } export interface IColumnList { columns: IColumnInfo[]; columnWidths: number[]; indexOfLastPinnedColumn: number; maxLevel?: number; } export interface IColumnInfo { header: string; field: string; skip: boolean; dataType?: GridColumnDataType; skipFormatter?: boolean; formatter?: any; headerType?: HeaderType; startIndex?: number; columnSpan?: number; level?: number; exportIndex?: number; pinnedIndex?: number; } /** * rowExporting event arguments * this.exporterService.rowExporting.subscribe((args: IRowExportingEventArgs) => { * // set args properties here * }) */ export interface IRowExportingEventArgs extends IBaseEventArgs { /** * Contains the exporting row data */ rowData: any; /** * Contains the exporting row index */ rowIndex: number; /** * Skip the exporting row when set to true */ cancel: boolean; } /** * columnExporting event arguments * ```typescript * this.exporterService.columnExporting.subscribe((args: IColumnExportingEventArgs) => { * // set args properties here * }); * ``` */ export interface IColumnExportingEventArgs extends IBaseEventArgs { /** * Contains the exporting column header */ header: string; /** * Contains the exporting column field name */ field: string; /** * Contains the exporting column index */ columnIndex: number; /** * Skip the exporting column when set to true */ cancel: boolean; /** * Export the column's data without applying its formatter, when set to true */ skipFormatter: boolean; /** * A reference to the grid owner. */ grid?: IgxGridBaseDirective; } /**hidden * A helper class used to identify whether the user has set a specific columnIndex * during columnExporting, so we can honor it at the exported file. */ class IgxColumnExportingEventArgs implements IColumnExportingEventArgs { public header: string; public field: string; public cancel: boolean; public skipFormatter: boolean; public grid?: IgxGridBaseDirective; public owner?: any; public userSetIndex? = false; private _columnIndex?: number; public get columnIndex(): number { return this._columnIndex; } public set columnIndex(value: number) { this._columnIndex = value; this.userSetIndex = true; } constructor(original: IColumnExportingEventArgs) { this.header = original.header; this.field = original.field; this.cancel = original.cancel; this.skipFormatter = original.skipFormatter; this.grid = original.grid; this.owner = original.owner; this._columnIndex = original.columnIndex; } } export const DEFAULT_OWNER = 'default'; const DEFAULT_COLUMN_WIDTH = 8.43; export abstract class IgxBaseExporter { public exportEnded = new EventEmitter<IBaseEventArgs>(); /** * This event is emitted when a row is exported. * ```typescript * this.exporterService.rowExporting.subscribe((args: IRowExportingEventArgs) => { * // put event handler code here * }); * ``` * * @memberof IgxBaseExporter */ public rowExporting = new EventEmitter<IRowExportingEventArgs>(); /** * This event is emitted when a column is exported. * ```typescript * this.exporterService.columnExporting.subscribe((args: IColumnExportingEventArgs) => { * // put event handler code here * }); * ``` * * @memberof IgxBaseExporter */ public columnExporting = new EventEmitter<IColumnExportingEventArgs>(); protected _sort = null; protected _ownersMap: Map<any, IColumnList> = new Map<any, IColumnList>(); private flatRecords: IExportRecord[] = []; private options: IgxExporterOptionsBase; /** * Method for exporting IgxGrid component's data. * ```typescript * this.exporterService.export(this.igxGridForExport, this.exportOptions); * ``` * * @memberof IgxBaseExporter */ public export(grid: any, options: IgxExporterOptionsBase): void { if (options === undefined || options === null) { throw Error('No options provided!'); } this.options = options; let columns = grid.columnList.toArray(); if (this.options.ignoreMultiColumnHeaders) { columns = columns.filter(col => col.children === undefined); } const columnList = this.getColumns(columns); const tagName = grid.nativeElement.tagName.toLowerCase(); if (tagName === 'igx-hierarchical-grid') { this._ownersMap.set(grid, columnList); const childLayoutList = (grid as IgxHierarchicalGridComponent).childLayoutList; for (const island of childLayoutList) { this.mapHierarchicalGridColumns(island, grid.data[0]); } } else { this._ownersMap.set(DEFAULT_OWNER, columnList); } this.prepareData(grid); this.exportGridRecordsData(this.flatRecords, grid); } /** * Method for exporting any kind of array data. * ```typescript * this.exporterService.exportData(this.arrayForExport, this.exportOptions); * ``` * * @memberof IgxBaseExporter */ public exportData(data: any[], options: IgxExporterOptionsBase): void { if (options === undefined || options === null) { throw Error('No options provided!'); } this.options = options; const records = data.map(d => { const record: IExportRecord = { data: d, type: ExportRecordType.DataRecord, level: 0 }; return record; }); this.exportGridRecordsData(records); } private exportGridRecordsData(records: IExportRecord[], grid?: IgxGridBaseDirective) { if (this._ownersMap.size === 0) { const recordsData = records.map(r => r.data); const keys = ExportUtilities.getKeysFromData(recordsData); const columns = keys.map((k) => ({ header: k, field: k, skip: false, headerType: HeaderType.ColumnHeader, level: 0, columnSpan: 1 })); const columnWidths = new Array<number>(keys.length).fill(DEFAULT_COLUMN_WIDTH); const mapRecord: IColumnList = { columns, columnWidths, indexOfLastPinnedColumn: -1, maxLevel: 0 }; this._ownersMap.set(DEFAULT_OWNER, mapRecord); } let shouldReorderColumns = false; for (const [key, mapRecord] of this._ownersMap) { let skippedPinnedColumnsCount = 0; let columnsWithoutHeaderCount = 1; let indexOfLastPinnedColumn = mapRecord.indexOfLastPinnedColumn; mapRecord.columns.forEach((column, index) => { if (!column.skip) { const columnExportArgs: IColumnExportingEventArgs = { header: !ExportUtilities.isNullOrWhitespaces(column.header) ? column.header : 'Column' + columnsWithoutHeaderCount++, field: column.field, columnIndex: index, cancel: false, skipFormatter: false, grid: key === DEFAULT_OWNER ? grid : key }; const newColumnExportArgs = new IgxColumnExportingEventArgs(columnExportArgs); this.columnExporting.emit(newColumnExportArgs); column.header = newColumnExportArgs.header; column.skip = newColumnExportArgs.cancel; column.skipFormatter = newColumnExportArgs.skipFormatter; if (newColumnExportArgs.userSetIndex) { column.exportIndex = newColumnExportArgs.columnIndex; shouldReorderColumns = true; } if (column.skip && index <= indexOfLastPinnedColumn) { skippedPinnedColumnsCount++; } if (this._sort && this._sort.fieldName === column.field) { if (column.skip) { this._sort = null; } else { this._sort.fieldName = column.header; } } } }); indexOfLastPinnedColumn -= skippedPinnedColumnsCount; // Reorder columns only if a column has been assigned a specific columnIndex during columnExporting event if (shouldReorderColumns) { mapRecord.columns = this.reorderColumns(mapRecord.columns); } } const dataToExport = new Array<IExportRecord>(); const actualData = records[0]?.data; const isSpecialData = ExportUtilities.isSpecialData(actualData); yieldingLoop(records.length, 100, (i) => { const row = records[i]; this.exportRow(dataToExport, row, i, isSpecialData); }, () => { this.exportDataImplementation(dataToExport, this.options, () => { this.resetDefaults(); }); }); } private exportRow(data: IExportRecord[], record: IExportRecord, index: number, isSpecialData: boolean) { if (!isSpecialData && record.type !== ExportRecordType.HeaderRecord) { const owner = record.owner === undefined ? DEFAULT_OWNER : record.owner; const columns = this._ownersMap.get(owner).columns .filter(c => c.headerType !== HeaderType.MultiColumnHeader) .sort((a, b) => a.startIndex - b.startIndex) .sort((a, b) => a.pinnedIndex - b.pinnedIndex); record.data = columns.reduce((a, e) => { if (!e.skip) { let rawValue = resolveNestedPath(record.data, e.field); const shouldApplyFormatter = e.formatter && !e.skipFormatter && record.type !== ExportRecordType.GroupedRecord; if (e.dataType === 'date' && !(rawValue instanceof Date) && !shouldApplyFormatter && rawValue !== undefined && rawValue !== null) { rawValue = new Date(rawValue); } else if (e.dataType === 'string' && rawValue instanceof Date) { rawValue = rawValue.toString(); } a[e.field] = shouldApplyFormatter ? e.formatter(rawValue) : rawValue; } return a; }, {}); } const rowArgs = { rowData: record.data, rowIndex: index, cancel: false }; this.rowExporting.emit(rowArgs); if (!rowArgs.cancel) { data.push(record); } } private reorderColumns(columns: IColumnInfo[]): IColumnInfo[] { const filteredColumns = columns.filter(c => !c.skip); const length = filteredColumns.length; const specificIndicesColumns = filteredColumns.filter((col) => !isNaN(col.exportIndex)) .sort((a,b) => a.exportIndex - b.exportIndex); const indices = specificIndicesColumns.map(col => col.exportIndex); specificIndicesColumns.forEach(col => { filteredColumns.splice(filteredColumns.indexOf(col), 1); }); const reorderedColumns = new Array(length); if (specificIndicesColumns.length > Math.max(...indices)) { return specificIndicesColumns.concat(filteredColumns); } else { indices.forEach((i, index) => { if (i < 0 || i >= length) { filteredColumns.push(specificIndicesColumns[index]); } else { let k = i; while (k < length && reorderedColumns[k] !== undefined) { ++k; } reorderedColumns[k] = specificIndicesColumns[index]; } }); for (let i = 0; i < length; i++) { if (reorderedColumns[i] === undefined) { reorderedColumns[i] = filteredColumns.splice(0, 1)[0]; } } } return reorderedColumns; } private prepareData(grid: IgxGridBaseDirective) { this.flatRecords = []; const tagName = grid.nativeElement.tagName.toLowerCase(); const hasFiltering = (grid.filteringExpressionsTree && grid.filteringExpressionsTree.filteringOperands.length > 0) || (grid.advancedFilteringExpressionsTree && grid.advancedFilteringExpressionsTree.filteringOperands.length > 0); const hasSorting = grid.sortingExpressions && grid.sortingExpressions.length > 0; switch (tagName) { case 'igx-hierarchical-grid': { this.prepareHierarchicalGridData(grid as IgxHierarchicalGridComponent, hasFiltering, hasSorting); break; } case 'igx-tree-grid': { this.prepareTreeGridData(grid as IgxTreeGridComponent, hasFiltering, hasSorting); break; } default: { this.prepareGridData(grid as IgxGridComponent, hasFiltering, hasSorting); break; } } } private prepareHierarchicalGridData(grid: IgxHierarchicalGridComponent, hasFiltering: boolean, hasSorting: boolean) { const skipOperations = (!hasFiltering || !this.options.ignoreFiltering) && (!hasSorting || !this.options.ignoreSorting); if (skipOperations) { const data = grid.filteredSortedData; this.addHierarchicalGridData(grid, data); } else { let data = grid.data; if (hasFiltering && !this.options.ignoreFiltering) { const filteringState: IFilteringState = { expressionsTree: grid.filteringExpressionsTree, advancedExpressionsTree: grid.advancedFilteringExpressionsTree, strategy: grid.filterStrategy }; data = DataUtil.filter(data, filteringState, grid); } if (hasSorting && !this.options.ignoreSorting) { this._sort = cloneValue(grid.sortingExpressions[0]); data = DataUtil.sort(data, grid.sortingExpressions, grid.sortStrategy, grid); } this.addHierarchicalGridData(grid, data); } } private addHierarchicalGridData(grid: IgxHierarchicalGridComponent, records: any[]) { const childLayoutList = grid.childLayoutList; const columnFields = this._ownersMap.get(grid).columns.map(col => col.field); for (const entry of records) { const expansionStateVal = grid.expansionStates.has(entry) ? grid.expansionStates.get(entry) : false; const dataWithoutChildren = Object.keys(entry) .filter(k => columnFields.includes(k)) .reduce((obj, key) => { obj[key] = entry[key]; return obj; }, {}); const hierarchicalGridRecord: IExportRecord = { data: dataWithoutChildren, level: 0, type: ExportRecordType.HierarchicalGridRecord, owner: grid, }; this.flatRecords.push(hierarchicalGridRecord); for (const island of childLayoutList) { const path: IPathSegment = { rowID: island.primaryKey ? entry[island.primaryKey] : entry, rowIslandKey: island.key }; const islandGrid = grid?.hgridAPI.getChildGrid([path]); const keyRecordData = this.prepareIslandData(island, islandGrid, entry[island.key]) || []; this.getAllChildColumnsAndData(island, keyRecordData, expansionStateVal, islandGrid); } } } private prepareIslandData(island: IgxRowIslandComponent, islandGrid: IgxHierarchicalGridComponent, data: any[]): any[] { if (islandGrid !== undefined) { const hasFiltering = (islandGrid.filteringExpressionsTree && islandGrid.filteringExpressionsTree.filteringOperands.length > 0) || (islandGrid.advancedFilteringExpressionsTree && islandGrid.advancedFilteringExpressionsTree.filteringOperands.length > 0); const hasSorting = islandGrid.sortingExpressions && islandGrid.sortingExpressions.length > 0; const skipOperations = (!hasFiltering || !this.options.ignoreFiltering) && (!hasSorting || !this.options.ignoreSorting); if (skipOperations) { data = islandGrid.filteredSortedData; } else { if (hasFiltering && !this.options.ignoreFiltering) { const filteringState: IFilteringState = { expressionsTree: islandGrid.filteringExpressionsTree, advancedExpressionsTree: islandGrid.advancedFilteringExpressionsTree, strategy: islandGrid.filterStrategy }; data = DataUtil.filter(data, filteringState, islandGrid); } if (hasSorting && !this.options.ignoreSorting) { this._sort = cloneValue(islandGrid.sortingExpressions[0]); data = DataUtil.sort(data, islandGrid.sortingExpressions, islandGrid.sortStrategy, islandGrid); } } } else { const hasFiltering = (island.filteringExpressionsTree && island.filteringExpressionsTree.filteringOperands.length > 0) || (island.advancedFilteringExpressionsTree && island.advancedFilteringExpressionsTree.filteringOperands.length > 0); const hasSorting = island.sortingExpressions && island.sortingExpressions.length > 0; const skipOperations = (!hasFiltering || this.options.ignoreFiltering) && (!hasSorting || this.options.ignoreSorting); if (!skipOperations) { if (hasFiltering && !this.options.ignoreFiltering) { const filteringState: IFilteringState = { expressionsTree: island.filteringExpressionsTree, advancedExpressionsTree: island.advancedFilteringExpressionsTree, strategy: island.filterStrategy }; data = DataUtil.filter(data, filteringState, island); } if (hasSorting && !this.options.ignoreSorting) { this._sort = cloneValue(island.sortingExpressions[0]); data = DataUtil.sort(data, island.sortingExpressions, island.sortStrategy, island); } } } return data; } private getAllChildColumnsAndData(island: IgxRowIslandComponent, childData: any[], expansionStateVal: boolean, grid: IgxHierarchicalGridComponent) { const columnList = this._ownersMap.get(island).columns; const columnHeader = columnList .filter(col => col.headerType === HeaderType.ColumnHeader) .map(col => col.header ? col.header : col.field); const headerRecord: IExportRecord = { data: columnHeader, level: island.level, type: ExportRecordType.HeaderRecord, owner: island, hidden: !expansionStateVal }; if (childData && childData.length > 0) { this.flatRecords.push(headerRecord); for (const rec of childData) { const exportRecord: IExportRecord = { data: rec, level: island.level, type: ExportRecordType.HierarchicalGridRecord, owner: island, hidden: !expansionStateVal }; this.flatRecords.push(exportRecord); if (island.children.length > 0) { const islandExpansionStateVal = grid === undefined ? false : grid.expansionStates.has(rec) ? grid.expansionStates.get(rec) : false; for (const childIsland of island.children) { const path: IPathSegment = { rowID: childIsland.primaryKey ? rec[childIsland.primaryKey] : rec, rowIslandKey: childIsland.key }; const childIslandGrid = grid?.hgridAPI.getChildGrid([path]); const keyRecordData = this.prepareIslandData(island, childIslandGrid, rec[childIsland.key]) || []; this.getAllChildColumnsAndData(childIsland, keyRecordData, islandExpansionStateVal, childIslandGrid); } } } } } private prepareGridData(grid: IgxGridComponent, hasFiltering: boolean, hasSorting: boolean) { const groupedGridGroupingState: IGroupingState = { expressions: grid.groupingExpressions, expansion: grid.groupingExpansionState, defaultExpanded: grid.groupsExpanded, }; const hasGrouping = grid.groupingExpressions && grid.groupingExpressions.length > 0; const skipOperations = (!hasFiltering || !this.options.ignoreFiltering) && (!hasSorting || !this.options.ignoreSorting) && (!hasGrouping || !this.options.ignoreGrouping); if (skipOperations) { if (hasGrouping) { this.addGroupedData(grid, grid.groupsRecords, groupedGridGroupingState); } else { this.addFlatData(grid.filteredSortedData); } } else { let gridData = grid.data; if (hasFiltering && !this.options.ignoreFiltering) { const filteringState: IFilteringState = { expressionsTree: grid.filteringExpressionsTree, advancedExpressionsTree: grid.advancedFilteringExpressionsTree, strategy: grid.filterStrategy }; gridData = DataUtil.filter(gridData, filteringState, grid); } if (hasSorting && !this.options.ignoreSorting) { // TODO: We should drop support for this since in a grouped grid it doesn't make sense // this._sort = !isGroupedGrid ? // cloneValue(grid.sortingExpressions[0]) : // grid.sortingExpressions.length > 1 ? // cloneValue(grid.sortingExpressions[1]) : // cloneValue(grid.sortingExpressions[0]); gridData = DataUtil.sort(gridData, grid.sortingExpressions, grid.sortStrategy, grid); } if (hasGrouping && !this.options.ignoreGrouping) { const groupsRecords = []; DataUtil.group(cloneArray(gridData), groupedGridGroupingState, grid, groupsRecords); gridData = groupsRecords; } if (hasGrouping && !this.options.ignoreGrouping) { this.addGroupedData(grid, gridData, groupedGridGroupingState); } else { this.addFlatData(gridData); } } } private prepareTreeGridData(grid: IgxTreeGridComponent, hasFiltering: boolean, hasSorting: boolean) { const skipOperations = (!hasFiltering || !this.options.ignoreFiltering) && (!hasSorting || !this.options.ignoreSorting); if (skipOperations) { this.addTreeGridData(grid.processedRootRecords); } else { let gridData = grid.rootRecords; if (hasFiltering && !this.options.ignoreFiltering) { const filteringState: IFilteringState = { expressionsTree: grid.filteringExpressionsTree, advancedExpressionsTree: grid.advancedFilteringExpressionsTree, strategy: (grid.filterStrategy) ? grid.filterStrategy : new TreeGridFilteringStrategy() }; gridData = filteringState.strategy .filter(gridData, filteringState.expressionsTree, filteringState.advancedExpressionsTree); } if (hasSorting && !this.options.ignoreSorting) { this._sort = cloneValue(grid.sortingExpressions[0]); gridData = DataUtil.treeGridSort(gridData, grid.sortingExpressions, grid.sortStrategy); } this.addTreeGridData(gridData); } } private addTreeGridData(records: ITreeGridRecord[], parentExpanded: boolean = true) { if (!records) { return; } for (const record of records) { const hierarchicalRecord: IExportRecord = { data: record.data, level: record.level, hidden: !parentExpanded, type: ExportRecordType.TreeGridRecord }; this.flatRecords.push(hierarchicalRecord); this.addTreeGridData(record.children, parentExpanded && record.expanded); } } private addFlatData(records: any) { if (!records) { return; } for (const record of records) { const data: IExportRecord = { data: record, type: ExportRecordType.DataRecord, level: 0 }; this.flatRecords.push(data); } } private addGroupedData(grid: IgxGridComponent, records: IGroupByRecord[], groupingState: IGroupingState, parentExpanded: boolean = true) { if (!records) { return; } const firstCol = this._ownersMap.get(DEFAULT_OWNER).columns[0].field; for (const record of records) { let recordVal = record.value; const hierarchy = getHierarchy(record); const expandState: IGroupByExpandState = groupingState.expansion.find((s) => isHierarchyMatch(s.hierarchy || [{ fieldName: record.expression.fieldName, value: recordVal }], hierarchy)); const expanded = expandState ? expandState.expanded : groupingState.defaultExpanded; const isDate = recordVal instanceof Date; if (isDate) { const timeZoneOffset = recordVal.getTimezoneOffset() * 60000; const isoString = (new Date(recordVal - timeZoneOffset)).toISOString(); const pipe = new DatePipe(grid.locale); recordVal = pipe.transform(isoString); } const groupExpressionName = record.column && record.column.header ? record.column.header : record.expression.fieldName; recordVal = recordVal !== null ? recordVal : ''; const groupExpression: IExportRecord = { data: { [firstCol]: `${groupExpressionName}: ${recordVal} (${record.records.length})` }, level: record.level, hidden: !parentExpanded, type: ExportRecordType.GroupedRecord, }; this.flatRecords.push(groupExpression); if (record.groups.length > 0) { this.addGroupedData(grid, record.groups, groupingState, expanded && parentExpanded); } else { const rowRecords = record.records; for (const rowRecord of rowRecords) { const currentRecord: IExportRecord = { data: rowRecord, level: record.level + 1, hidden: !(expanded && parentExpanded), type: ExportRecordType.DataRecord, }; this.flatRecords.push(currentRecord); } } } } private getColumns(columns: IgxColumnComponent[]): IColumnList { const colList = []; const colWidthList = []; const hiddenColumns = []; let indexOfLastPinnedColumn = -1; let lastVisibleColumnIndex = -1; let maxLevel = 0; columns.forEach((column) => { const columnHeader = !ExportUtilities.isNullOrWhitespaces(column.header) ? column.header : column.field; const exportColumn = !column.hidden || this.options.ignoreColumnsVisibility; const index = this.options.ignoreColumnsOrder || this.options.ignoreColumnsVisibility ? column.index : column.visibleIndex; const columnWidth = Number(column.width?.slice(0, -2)) || DEFAULT_COLUMN_WIDTH; const columnLevel = !this.options.ignoreMultiColumnHeaders ? column.level : 0; const isMultiColHeader = column instanceof IgxColumnGroupComponent; const colSpan = isMultiColHeader ? column.allChildren .filter(ch => !(ch instanceof IgxColumnGroupComponent) && (!this.options.ignoreColumnsVisibility ? !ch.hidden : true)) .length : 1; const columnInfo: IColumnInfo = { header: columnHeader, dataType: column.dataType, field: column.field, skip: !exportColumn, formatter: column.formatter, skipFormatter: false, headerType: isMultiColHeader ? HeaderType.MultiColumnHeader : HeaderType.ColumnHeader, columnSpan: colSpan, level: columnLevel, startIndex: index, pinnedIndex: !column.pinned ? Number.MAX_VALUE : !column.hidden ? column.grid.pinnedColumns.indexOf(column) : NaN }; if (this.options.ignoreColumnsOrder) { if (columnInfo.startIndex !== columnInfo.pinnedIndex) { columnInfo.pinnedIndex = Number.MAX_VALUE; } } if (column.level > maxLevel && !this.options.ignoreMultiColumnHeaders) { maxLevel = column.level; } if (index !== -1) { colList.push(columnInfo); colWidthList.push(columnWidth); lastVisibleColumnIndex = Math.max(lastVisibleColumnIndex, colList.indexOf(columnInfo)); } else { hiddenColumns.push(columnInfo); } if (column.pinned && exportColumn && columnInfo.headerType === HeaderType.ColumnHeader) { indexOfLastPinnedColumn++; } }); //Append the hidden columns to the end of the list hiddenColumns.forEach((hiddenColumn) => { colList[++lastVisibleColumnIndex] = hiddenColumn; }); const result: IColumnList = { columns: colList, columnWidths: colWidthList, indexOfLastPinnedColumn, maxLevel }; return result; } private mapHierarchicalGridColumns(island: IgxRowIslandComponent, gridData: any) { let columnList: IColumnList; let keyData; if (island.autoGenerate) { keyData = gridData[island.key]; const islandKeys = island.children.map(i => i.key); const islandData = keyData.map(i => { const newItem = {}; Object.keys(i).map(k => { if (!islandKeys.includes(k)) { newItem[k] = i[k]; } }); return newItem; }); columnList = this.getAutoGeneratedColumns(islandData); } else { const islandColumnList = island.childColumns.toArray(); columnList = this.getColumns(islandColumnList); } this._ownersMap.set(island, columnList); if (island.children.length > 0) { for (const childIsland of island.children) { const islandKeyData = keyData !== undefined ? keyData[0] : {}; this.mapHierarchicalGridColumns(childIsland, islandKeyData); } } } private getAutoGeneratedColumns(data: any[]) { const colList = []; const colWidthList = []; const keys = Object.keys(data[0]); keys.forEach((colKey, i) => { const columnInfo: IColumnInfo = { header: colKey, field: colKey, dataType: 'string', skip: false, headerType: HeaderType.ColumnHeader, columnSpan: 1, level: 0, startIndex: i, pinnedIndex: Number.MAX_VALUE }; colList.push(columnInfo); colWidthList.push(DEFAULT_COLUMN_WIDTH); }); const result: IColumnList = { columns: colList, columnWidths: colWidthList, indexOfLastPinnedColumn: -1, maxLevel: 0, }; return result; } private resetDefaults() { this._sort = null; this.flatRecords = []; this.options = {} as IgxExporterOptionsBase; this._ownersMap.clear(); } protected abstract exportDataImplementation(data: any[], options: IgxExporterOptionsBase, done: () => void): void; }
the_stack
import { convertToGraph, stripInsertInputClientFields, convertToInsertInput } from "."; /* * */ test("convertToGraph - object should return as expected", () => { const foo = { id: 1, bar: { id: 2, name: "foo bar" } }; const fragment = convertToGraph({ input: foo, fieldMap: { typenames: { bar: "Bar" } } }); expect(fragment).toMatchObject({ id: 1, bar: { id: 2, name: "foo bar", __typename: "Bar" } }); }); test("convertToGraph - object with root typename should return as expected", () => { const foo = { id: 1, bar: { id: 2, name: "foo bar" } }; const fragment = convertToGraph({ input: foo, fieldMap: { typenames: { bar: "Bar" } }, typename: "Foo" }); expect(fragment).toMatchObject({ id: 1, __typename: "Foo", bar: { id: 2, name: "foo bar", __typename: "Bar" } }); }); test("convertToGraph - updated_at and created_at fields should populated as expected", () => { const foo = { id: 1, updated_at: null, bar: { id: 2, name: "foo bar", created_at: null } }; const fragment = convertToGraph({ input: foo, fieldMap: { typenames: { bar: "Bar" } }, typename: "Foo" }); expect(fragment).toMatchObject({ id: 1, __typename: "Foo", bar: { id: 2, name: "foo bar", __typename: "Bar" } }); expect(fragment.updated_at).toBeTruthy(); expect(fragment.bar.created_at).toBeTruthy(); }); test("convertToGraph - object with root typename but no Id should return as expected", () => { const foo = { bar: { id: 2, name: "foo bar" } }; const fragment = convertToGraph({ input: foo, fieldMap: { typenames: { bar: "Bar" } }, typename: "Foo" }); expect(fragment).toMatchObject({ __typename: "Foo", bar: { id: 2, name: "foo bar", __typename: "Bar" } }); }); test("convertToGraph - object with client fields should return as expected", () => { const foo = { id: 1, ___bar: { id: 2, name: "foo bar" } }; const fragment = convertToGraph({ input: foo, fieldMap: { typenames: { bar: "Bar" } } }); expect(fragment).toMatchObject({ id: 1, bar: { id: 2, name: "foo bar", __typename: "Bar" } }); }); /* * */ test("convertToGraph - plain array should return as expected (no typename)", () => { const foo = { id: 1, bar: [{ id: 2 }, { id: 3 }] }; const fragment = convertToGraph({ input: foo }); expect(fragment).toMatchObject({ id: 1, bar: [{ id: 2 }, { id: 3 }], }); expect(fragment.bar[0]._typename).toBeUndefined(); }); /* * */ test("convertToGraph - plain array should return as expected (with typename)", () => { const foo = { id: 1, bar: [{ id: 2 }, { id: 3 }] }; const fragment = convertToGraph({ input: foo, fieldMap: { typenames: { bar: "Bar" } } }); expect(fragment).toMatchObject({ id: 1, bar: [ { id: 2, __typename: "Bar" }, { id: 3, __typename: "Bar" }, ], }); }); test("convertToGraph - plain array should be omitted", () => { const foo = { id: 1, bar: [{ id: 2 }, { id: 3 }] }; const fragment = convertToGraph({ input: foo, fieldMap: { ignore: { bar: true } } }); expect(fragment).toMatchObject({ id: 1 }); expect(fragment.bar).toBeUndefined(); }); /* * */ test("convertToGraph - insertInput object should return as expected", () => { const foo = { id: 1, bar: { data: { id: 2 } } }; const fragment = convertToGraph({ input: foo, fieldMap: { typenames: { bar: "Bar" } } }); expect(fragment).toMatchObject({ id: 1, bar: { id: 2, __typename: "Bar" } }); }); /* * */ test("convertToGraph - insertInput array should return as expected", () => { const foo = { id: 1, bar: { data: [{ id: 2 }, { id: 3 }] } }; const fragment = convertToGraph({ input: foo, fieldMap: { typenames: { bar: "Bar" } } }); expect(fragment).toMatchObject({ id: 1, bar: [ { id: 2, __typename: "Bar" }, { id: 3, __typename: "Bar" }, ], }); }); /* * */ test("convertToGraph - insertInput recursive array should return as expected", () => { const foo = { id: 1, bar: { data: [ { id: 2, name: "foo bar 2" }, { id: 3, name: "foo bar 3", baz: { data: [{ id: 4, name: "foo bar baz 4" }] } }, ], }, }; const expected = { id: 1, bar: [ { id: 2, name: "foo bar 2", __typename: "Bar" }, { id: 3, name: "foo bar 3", __typename: "Bar", baz: [{ id: 4, name: "foo bar baz 4", __typename: "Baz" }] }, ], }; const fragmentRecursive = convertToGraph({ input: foo, fieldMap: { typenames: { bar: "Bar", baz: "Baz" } } }); expect(fragmentRecursive).toMatchObject(expected); }); test("convertToGraph - insertInput recursive (deeper definition copied as-is) should return as expected", () => { const foo = { id: 1, bar: { data: [ { id: 2, name: "foo bar 2" }, { id: 3, name: "foo bar 3", baz: { data: [{ id: 4, name: "foo bar baz 4" }] } }, ], }, }; const expected = { id: 1, bar: [ { id: 2, name: "foo bar 2", __typename: "Bar" }, { id: 3, name: "foo bar 3", __typename: "Bar" }, ], }; const fragmentRecursive = convertToGraph({ input: foo, fieldMap: { typenames: { bar: "Bar" } } }); expect(fragmentRecursive).toMatchObject(expected); expect(fragmentRecursive.bar[1].baz).toBeDefined(); expect(fragmentRecursive.bar[1].baz.__typename).toBeUndefined(); }); test("convertToGraph - insertInput recursive (deeper definition missing) should return as expected", () => { const foo = { id: 1, bar: { data: [ { id: 2, name: "foo bar 2" }, { id: 3, name: "foo bar 3", baz: { data: [{ id: 4, name: "foo bar baz 4" }] } }, ], }, }; const expected = { id: 1, bar: [ { id: 2, name: "foo bar 2", __typename: "Bar" }, { id: 3, name: "foo bar 3", __typename: "Bar" }, ], }; const fragmentRecursive = convertToGraph({ input: foo, fieldMap: { typenames: { bar: "Bar" }, ignore: { baz: true } } }); expect(fragmentRecursive).toMatchObject(expected); expect(fragmentRecursive.bar[1].baz).toBeUndefined(); }); test("convertToGraph - deep nested realworld example", () => { const realWorldExample = { id: "00000000-0000-0000-0000-00000000", title: "Title", type: "Type", ___topLevelClientField: true, nested1: { data: [ { id: "10000000-0000-0000-0000-00000000", title: "Title", type: "Type", nested2: { data: { id: "20000000-0000-0000-0000-00000000", nested3A: { data: { id: "30000000-0000-0000-0000-00000000", nested4: { data: [ { id: "40000000-0000-0000-0000-00000000", title: "Test", index: 0, ___deepClientFieldInArray: true, }, ], }, }, }, nested3B: { data: { id: "50000000-0000-0000-0000-00000000", ___deepClientField: true, nested5: { data: [], }, }, }, }, }, }, ], }, related_id: "70000000-0000-0000-0000-00000000", relatedObject: { data: { id: "80000000-0000-0000-0000-00000000", }, }, }; const expected = { __typename: "root", id: "00000000-0000-0000-0000-00000000", title: "Title", type: "Type", topLevelClientField: true, nested1: [ { __typename: "nested1", id: "10000000-0000-0000-0000-00000000", title: "Title", type: "Type", nested2: { __typename: "nested2", id: "20000000-0000-0000-0000-00000000", nested3A: { __typename: "nested3", id: "30000000-0000-0000-0000-00000000", nested4: [ { __typename: "nested4", id: "40000000-0000-0000-0000-00000000", deepClientFieldInArray: true, title: "Test", index: 0, }, ], }, nested3B: { __typename: "nested3", id: "50000000-0000-0000-0000-00000000", deepClientField: true, nested5: [], }, }, }, ], related_id: "70000000-0000-0000-0000-00000000", relatedObject: { __typename: "relatedObject", id: "80000000-0000-0000-0000-00000000", }, }; const fragmentRecursive = convertToGraph({ input: realWorldExample, typename: "root", fieldMap: { typenames: { nested1: "nested1", nested2: "nested2", nested3A: "nested3", nested3B: "nested3", nested4: "nested4", nested5: "nested5", relatedObject: "relatedObject" }, }, }); expect(fragmentRecursive).toMatchObject(expected); }); test("stripInsertInputClientFields - object should return as expected", () => { const foo = { id: 1, ___clientField: true, bar: { id: 2, ___clientField: true }, baz: [ { id: 3, name: "foo baz 3", __typename: "Baz", ___clientField: true }, { id: 4, name: "foo baz 4", __typename: "Baz", ___clientField: true, stringArray: ["item1", "item2"] }, ], stringArray: ["item1"], }; const expected = { id: 1, bar: { id: 2 }, baz: [ { id: 3, name: "foo baz 3" }, { id: 4, name: "foo baz 4", stringArray: ["item1", "item2"] }, ], stringArray: ["item1"], }; const result = stripInsertInputClientFields({ input: foo }); expect(result).toMatchObject(expected); expect(result.___clientField).toBeUndefined(); expect(result.bar.___clientField).toBeUndefined(); expect(result.baz[0].___clientField).toBeUndefined(); expect(result.baz[0].__typename).toBeUndefined(); expect(result.baz[1].___clientField).toBeUndefined(); expect(result.baz[1].__typename).toBeUndefined(); }); test("convertToInsertInput - deep nested realworld example", () => { const realWorldExample = { __typename: "root", id: "00000000-0000-0000-0000-00000000", title: "Title", type: "Type", topLevelClientField: true, nested1: [ { __typename: "nested1", id: "10000000-0000-0000-0000-00000000", title: "Title", type: "Type", clientOnlyField: true, nested2: { __typename: "nested2", id: "20000000-0000-0000-0000-00000000", nested3A: { __typename: "nested3", id: "30000000-0000-0000-0000-00000000", nested4: [ { __typename: "nested4", id: "40000000-0000-0000-0000-00000000", deepClientFieldInArray: true, title: "Test", index: 0, }, ], }, nested3B: { __typename: "nested3", id: "50000000-0000-0000-0000-00000000", deepClientField: true, nested5: [], created_at: "2020-03-20T12:46:22.558695+00:00", updated_at: "2020-03-20T12:46:22.558695+00:00", }, }, }, ], related_id: "70000000-0000-0000-0000-00000000", relatedObject: { __typename: "relatedObject", id: "80000000-0000-0000-0000-00000000", }, }; const expected = { id: "00000000-0000-0000-0000-00000000B", title: "Title", type: "Type", topLevelClientField: true, nested1: { data: [ { id: "10000000-0000-0000-0000-00000000B", title: "Title", type: "Type", ___clientOnlyField: true, nested2: { data: { id: "20000000-0000-0000-0000-00000000B", nested3A: { data: { id: "30000000-0000-0000-0000-00000000B", nested4: { data: [ { id: "40000000-0000-0000-0000-00000000B", title: "Test", index: 0, deepClientFieldInArray: true, }, ], }, }, }, nested3B: { data: { id: "50000000-0000-0000-0000-00000000B", deepClientField: true, nested5: { data: [], }, }, }, }, }, }, ], }, relatedObject: { data: { id: "80000000-0000-0000-0000-00000000B", }, }, }; const insertInputRecursive = convertToInsertInput({ input: realWorldExample, fieldMap: { typenames: { nested1: "nested1", nested2: "nested2", nested3A: "nested3", nested3B: "nested3", nested4: "nested4", nested5: "nested5", relatedObject: "relatedObject" }, replace: { id: (fieldname: string, originalVal: string) => { return `${originalVal}B`; }, }, clientOnly: { clientOnlyField: true }, ignore: { related_id: true, }, }, }); // console.log(` ------> insertInputRecursive`, JSON.stringify(insertInputRecursive, null, 2)); // console.log(` ------> expected`, JSON.stringify(expected, null, 2)); expect(insertInputRecursive).toMatchObject(expected); expect(insertInputRecursive.__typename).toBeUndefined(); expect(insertInputRecursive.related_id).toBeUndefined(); expect(insertInputRecursive.nested1.data[0]).toBeDefined(); expect(insertInputRecursive.nested1.data[0].__typename).toBeUndefined(); expect(insertInputRecursive.nested1.data[0].nested2.data.nested3B.data).toBeDefined(); expect(insertInputRecursive.nested1.data[0].nested2.data.nested3B.data.created_at).toBeUndefined(); expect(insertInputRecursive.nested1.data[0].nested2.data.nested3B.data.updated_at).toBeUndefined(); });
the_stack
import type NodePath from "./index"; // This file contains Babels metainterpreter that can evaluate static code. const VALID_CALLEES = ["String", "Number", "Math"]; const INVALID_METHODS = ["random"]; /** * Walk the input `node` and statically evaluate if it's truthy. * * Returning `true` when we're sure that the expression will evaluate to a * truthy value, `false` if we're sure that it will evaluate to a falsy * value and `undefined` if we aren't sure. Because of this please do not * rely on coercion when using this method and check with === if it's false. * * For example do: * * if (t.evaluateTruthy(node) === false) falsyLogic(); * * **AND NOT** * * if (!t.evaluateTruthy(node)) falsyLogic(); * */ export function evaluateTruthy(this: NodePath): boolean { const res = this.evaluate(); if (res.confident) return !!res.value; } /** * Deopts the evaluation */ function deopt(path, state) { if (!state.confident) return; state.deoptPath = path; state.confident = false; } /** * We wrap the _evaluate method so we can track `seen` nodes, we push an item * to the map before we actually evaluate it so we can deopt on self recursive * nodes such as: * * var g = a ? 1 : 2, * a = g * this.foo */ function evaluateCached(path: NodePath, state) { const { node } = path; const { seen } = state; if (seen.has(node)) { const existing = seen.get(node); if (existing.resolved) { return existing.value; } else { deopt(path, state); return; } } else { // todo: create type annotation for state instead const item: { resolved: boolean; value?: any } = { resolved: false }; seen.set(node, item); const val = _evaluate(path, state); if (state.confident) { item.resolved = true; item.value = val; } return val; } } function _evaluate(path: NodePath, state) { if (!state.confident) return; if (path.isSequenceExpression()) { const exprs = path.get("expressions"); return evaluateCached(exprs[exprs.length - 1], state); } if ( path.isStringLiteral() || path.isNumericLiteral() || path.isBooleanLiteral() ) { return path.node.value; } if (path.isNullLiteral()) { return null; } if (path.isTemplateLiteral()) { return evaluateQuasis(path, path.node.quasis, state); } if ( path.isTaggedTemplateExpression() && path.get("tag").isMemberExpression() ) { const object = path.get("tag.object") as NodePath; const { // @ts-expect-error todo(flow->ts): possible bug, object is can be any expression and so name might be undefined node: { name }, } = object; const property = path.get("tag.property") as NodePath; if ( object.isIdentifier() && name === "String" && // todo(flow->ts): was changed from getBinding(name, true) // should this be hasBinding(name, true) as the binding is never used later? !path.scope.getBinding(name) && property.isIdentifier() && property.node.name === "raw" ) { return evaluateQuasis(path, path.node.quasi.quasis, state, true); } } if (path.isConditionalExpression()) { const testResult = evaluateCached(path.get("test"), state); if (!state.confident) return; if (testResult) { return evaluateCached(path.get("consequent"), state); } else { return evaluateCached(path.get("alternate"), state); } } if (path.isExpressionWrapper()) { // TypeCastExpression, ExpressionStatement etc return evaluateCached(path.get("expression"), state); } // "foo".length if ( path.isMemberExpression() && !path.parentPath.isCallExpression({ callee: path.node }) ) { const property = path.get("property"); const object = path.get("object"); if (object.isLiteral() && property.isIdentifier()) { // @ts-expect-error todo(flow->ts): instead of typeof - would it be better to check type of ast node? const value = object.node.value; const type = typeof value; if (type === "number" || type === "string") { return value[property.node.name]; } } } if (path.isReferencedIdentifier()) { const binding = path.scope.getBinding(path.node.name); if (binding && binding.constantViolations.length > 0) { return deopt(binding.path, state); } if (binding && path.node.start < binding.path.node.end) { return deopt(binding.path, state); } if (binding?.hasValue) { return binding.value; } else { if (path.node.name === "undefined") { return binding ? deopt(binding.path, state) : undefined; } else if (path.node.name === "Infinity") { return binding ? deopt(binding.path, state) : Infinity; } else if (path.node.name === "NaN") { return binding ? deopt(binding.path, state) : NaN; } const resolved = path.resolve(); if (resolved === path) { return deopt(path, state); } else { return evaluateCached(resolved, state); } } } if (path.isUnaryExpression({ prefix: true })) { if (path.node.operator === "void") { // we don't need to evaluate the argument to know what this will return return undefined; } const argument = path.get("argument"); if ( path.node.operator === "typeof" && (argument.isFunction() || argument.isClass()) ) { return "function"; } const arg = evaluateCached(argument, state); if (!state.confident) return; switch (path.node.operator) { case "!": return !arg; case "+": return +arg; case "-": return -arg; case "~": return ~arg; case "typeof": return typeof arg; } } if (path.isArrayExpression()) { const arr = []; const elems: Array<NodePath> = path.get("elements"); for (const elem of elems) { const elemValue = elem.evaluate(); if (elemValue.confident) { arr.push(elemValue.value); } else { return deopt(elemValue.deopt, state); } } return arr; } if (path.isObjectExpression()) { const obj = {}; const props = path.get("properties"); for (const prop of props) { if (prop.isObjectMethod() || prop.isSpreadElement()) { return deopt(prop, state); } const keyPath: any = prop.get("key"); let key = keyPath; // @ts-expect-error todo(flow->ts): type refinement issues ObjectMethod and SpreadElement somehow not excluded if (prop.node.computed) { key = key.evaluate(); if (!key.confident) { return deopt(key.deopt, state); } key = key.value; } else if (key.isIdentifier()) { key = key.node.name; } else { key = key.node.value; } // todo(flow->ts): remove typecast const valuePath = prop.get("value") as NodePath; let value = valuePath.evaluate(); if (!value.confident) { return deopt(value.deopt, state); } value = value.value; obj[key] = value; } return obj; } if (path.isLogicalExpression()) { // If we are confident that the left side of an && is false, or the left // side of an || is true, we can be confident about the entire expression const wasConfident = state.confident; const left = evaluateCached(path.get("left"), state); const leftConfident = state.confident; state.confident = wasConfident; const right = evaluateCached(path.get("right"), state); const rightConfident = state.confident; switch (path.node.operator) { case "||": // TODO consider having a "truthy type" that doesn't bail on // left uncertainty but can still evaluate to truthy. state.confident = leftConfident && (!!left || rightConfident); if (!state.confident) return; return left || right; case "&&": state.confident = leftConfident && (!left || rightConfident); if (!state.confident) return; return left && right; } } if (path.isBinaryExpression()) { const left = evaluateCached(path.get("left"), state); if (!state.confident) return; const right = evaluateCached(path.get("right"), state); if (!state.confident) return; switch (path.node.operator) { case "-": return left - right; case "+": return left + right; case "/": return left / right; case "*": return left * right; case "%": return left % right; case "**": return left ** right; case "<": return left < right; case ">": return left > right; case "<=": return left <= right; case ">=": return left >= right; case "==": return left == right; // eslint-disable-line eqeqeq case "!=": return left != right; case "===": return left === right; case "!==": return left !== right; case "|": return left | right; case "&": return left & right; case "^": return left ^ right; case "<<": return left << right; case ">>": return left >> right; case ">>>": return left >>> right; } } if (path.isCallExpression()) { const callee = path.get("callee"); let context; let func; // Number(1); if ( callee.isIdentifier() && !path.scope.getBinding(callee.node.name) && VALID_CALLEES.indexOf(callee.node.name) >= 0 ) { func = global[callee.node.name]; } if (callee.isMemberExpression()) { const object = callee.get("object"); const property = callee.get("property"); // Math.min(1, 2) if ( object.isIdentifier() && property.isIdentifier() && VALID_CALLEES.indexOf(object.node.name) >= 0 && INVALID_METHODS.indexOf(property.node.name) < 0 ) { context = global[object.node.name]; func = context[property.node.name]; } // "abc".charCodeAt(4) if (object.isLiteral() && property.isIdentifier()) { // @ts-expect-error todo(flow->ts): consider checking ast node type instead of value type (StringLiteral and NumberLiteral) const type = typeof object.node.value; if (type === "string" || type === "number") { // @ts-expect-error todo(flow->ts): consider checking ast node type instead of value type context = object.node.value; func = context[property.node.name]; } } } if (func) { const args = path.get("arguments").map(arg => evaluateCached(arg, state)); if (!state.confident) return; return func.apply(context, args); } } deopt(path, state); } function evaluateQuasis(path, quasis: Array<any>, state, raw = false) { let str = ""; let i = 0; const exprs = path.get("expressions"); for (const elem of quasis) { // not confident, evaluated an expression we don't like if (!state.confident) break; // add on element str += raw ? elem.value.raw : elem.value.cooked; // add on interpolated expression if it's present const expr = exprs[i++]; if (expr) str += String(evaluateCached(expr, state)); } if (!state.confident) return; return str; } /** * Walk the input `node` and statically evaluate it. * * Returns an object in the form `{ confident, value, deopt }`. `confident` * indicates whether or not we had to drop out of evaluating the expression * because of hitting an unknown node that we couldn't confidently find the * value of, in which case `deopt` is the path of said node. * * Example: * * t.evaluate(parse("5 + 5")) // { confident: true, value: 10 } * t.evaluate(parse("!true")) // { confident: true, value: false } * t.evaluate(parse("foo + foo")) // { confident: false, value: undefined, deopt: NodePath } * */ export function evaluate(this: NodePath): { confident: boolean; value: any; deopt?: NodePath; } { const state = { confident: true, deoptPath: null, seen: new Map(), }; let value = evaluateCached(this, state); if (!state.confident) value = undefined; return { confident: state.confident, deopt: state.deoptPath, value: value, }; }
the_stack
import { assert } from 'chai'; import { sort, inPlaceSort, createNewSortInstance, } from '../src/sort'; describe('sort', () => { let flatArray:number[]; let flatNaturalArray:string[]; let students:{ name:string, dob:Date, address:{ streetNumber?:number }, }[]; let multiPropArray:{ name:string, lastName:string, age:number, unit:string, }[]; beforeEach(() => { flatArray = [1, 5, 3, 2, 4, 5]; flatNaturalArray = ['A10', 'A2', 'B10', 'B2']; students = [{ name: 'Mate', dob: new Date(1987, 14, 11), address: { streetNumber: 3 }, }, { name: 'Ante', dob: new Date(1987, 14, 9), address: {}, }, { name: 'Dino', dob: new Date(1987, 14, 10), address: { streetNumber: 1 }, }]; multiPropArray = [{ name: 'aa', lastName: 'aa', age: 10, unit: 'A10', }, { name: 'aa', lastName: null, age: 9, unit: 'A01', }, { name: 'aa', lastName: 'bb', age: 11, unit: 'C2', }, { name: 'bb', lastName: 'aa', age: 6, unit: 'B3', }]; }); it('Should sort flat array in ascending order', () => { const sorted = sort(flatArray).asc(); assert.deepStrictEqual(sorted, [1, 2, 3, 4, 5, 5]); // flatArray should not be modified assert.deepStrictEqual(flatArray, [1, 5, 3, 2, 4, 5]); assert.notEqual(sorted, flatArray); }); it('Should in place sort flat array in ascending order', () => { const sorted = inPlaceSort(flatArray).asc(); assert.deepStrictEqual(sorted, [1, 2, 3, 4, 5, 5]); assert.deepStrictEqual(flatArray, [1, 2, 3, 4, 5, 5]); assert.equal(sorted, flatArray); }); it('Should sort flat array in descending order', () => { const sorted = sort(flatArray).desc(); assert.deepStrictEqual(sorted, [5, 5, 4, 3, 2, 1]); // Passed array is not mutated assert.deepStrictEqual(flatArray, [1, 5, 3, 2, 4, 5]); // Can do in place sorting const sorted2 = inPlaceSort(flatArray).desc(); assert.equal(sorted2, flatArray); assert.deepStrictEqual(flatArray, [5, 5, 4, 3, 2, 1]); }); it('Should sort flat array with by sorter', () => { const sorted = sort(flatArray).by({ asc: true }); assert.deepStrictEqual(sorted, [1, 2, 3, 4, 5, 5]); const sorted2 = sort(flatArray).by({ desc: true }); assert.deepStrictEqual(sorted2, [5, 5, 4, 3, 2, 1]); // Passed array is not mutated assert.deepStrictEqual(flatArray, [1, 5, 3, 2, 4, 5]); // Can do in place sorting const sorted3 = inPlaceSort(flatArray).by({ desc: true }); assert.equal(sorted3, flatArray); assert.deepStrictEqual(flatArray, [5, 5, 4, 3, 2, 1]); }); it('Should sort by student name in ascending order', () => { const sorted = sort(students).asc(p => p.name.toLowerCase()); assert.deepStrictEqual(['Ante', 'Dino', 'Mate'], sorted.map(p => p.name)); }); it('Should sort by student name in descending order', () => { const sorted = sort(students).desc((p) => p.name.toLowerCase()); assert.deepStrictEqual(['Mate', 'Dino', 'Ante'], sorted.map(p => p.name)); }); it('Should sort nil values to the bottom', () => { const sorted1 = sort(students).asc((p) => p.address.streetNumber); assert.deepStrictEqual([1, 3, undefined], sorted1.map(p => p.address.streetNumber)); const sorted2 = sort(students).desc((p) => p.address.streetNumber); assert.deepStrictEqual([3, 1, undefined], sorted2.map(p => p.address.streetNumber)); assert.deepStrictEqual( sort([1, undefined, 3, null, 2]).asc(), [1, 2, 3, null, undefined], ); assert.deepStrictEqual( sort([1, undefined, 3, null, 2]).desc(), [3, 2, 1, null, undefined], ); }); it('Should ignore values that are not sortable', () => { assert.equal(sort('string' as any).asc(), 'string' as any); assert.equal(sort(undefined).desc(), undefined); assert.equal(sort(null).desc(), null); assert.equal(sort(33 as any).asc(), 33 as any); assert.deepStrictEqual(sort({ name: 'test' } as any).desc(), { name: 'test' } as any); assert.equal((sort(33 as any) as any).by({ asc: true }), 33 as any); }); it('Should sort dates correctly', () => { const sorted = sort(students).asc('dob'); assert.deepStrictEqual(sorted.map(p => p.dob), [ new Date(1987, 14, 9), new Date(1987, 14, 10), new Date(1987, 14, 11), ]); }); it('Should sort on single property when passed as array', () => { const sorted = sort(students).asc(['name']); assert.deepStrictEqual(['Ante', 'Dino', 'Mate'], sorted.map(p => p.name)); }); it('Should sort on multiple properties', () => { const sorted = sort(multiPropArray).asc([ p => p.name, p => p.lastName, p => p.age, ]); const sortedArray = sorted.map(arr => ({ name: arr.name, lastName: arr.lastName, age: arr.age, })); assert.deepStrictEqual(sortedArray, [ { name: 'aa', lastName: 'aa', age: 10 }, { name: 'aa', lastName: 'bb', age: 11 }, { name: 'aa', lastName: null, age: 9 }, { name: 'bb', lastName: 'aa', age: 6 }, ]); }); it('Should sort on multiple properties by string sorter', () => { const sorted = sort(multiPropArray).asc(['name', 'age', 'lastName']); const sortedArray = sorted.map(arr => ({ name: arr.name, lastName: arr.lastName, age: arr.age, })); assert.deepStrictEqual(sortedArray, [ { name: 'aa', lastName: null, age: 9 }, { name: 'aa', lastName: 'aa', age: 10 }, { name: 'aa', lastName: 'bb', age: 11 }, { name: 'bb', lastName: 'aa', age: 6 }, ]); }); it('Should sort on multiple mixed properties', () => { const sorted = sort(multiPropArray).asc(['name', p => p.lastName, 'age']); const sortedArray = sorted.map(arr => ({ name: arr.name, lastName: arr.lastName, age: arr.age, })); assert.deepStrictEqual(sortedArray, [ { name: 'aa', lastName: 'aa', age: 10 }, { name: 'aa', lastName: 'bb', age: 11 }, { name: 'aa', lastName: null, age: 9 }, { name: 'bb', lastName: 'aa', age: 6 }, ]); }); it('Should sort with all equal values', () => { const same = [ { name: 'a', age: 1 }, { name: 'a', age: 1 }, ]; const sorted = sort(same).asc(['name', 'age']); assert.deepStrictEqual(sorted, [ { name: 'a', age: 1 }, { name: 'a', age: 1 }, ]); }); it('Should sort descending by name and ascending by lastName', () => { const sorted = sort(multiPropArray).by([ { desc: 'name' }, { asc: 'lastName' }, ]); const sortedArray = sorted.map(arr => ({ name: arr.name, lastName: arr.lastName, })); assert.deepStrictEqual(sortedArray, [ { name: 'bb', lastName: 'aa' }, { name: 'aa', lastName: 'aa' }, { name: 'aa', lastName: 'bb' }, { name: 'aa', lastName: null }, ]); }); it('Should sort ascending by name and descending by age', () => { const sorted = sort(multiPropArray).by([ { asc: 'name' }, { desc: 'age' }, ]); const sortedArray = sorted.map(arr => ({ name: arr.name, age: arr.age })); assert.deepStrictEqual(sortedArray, [ { name: 'aa', age: 11 }, { name: 'aa', age: 10 }, { name: 'aa', age: 9 }, { name: 'bb', age: 6 }, ]); }); it('Should sort ascending by lastName, descending by name and ascending by age', () => { const sorted = sort(multiPropArray).by([ { asc: p => p.lastName }, { desc: p => p.name }, { asc: p => p.age }, ]); const sortedArray = sorted.map(arr => ({ name: arr.name, lastName: arr.lastName, age: arr.age, })); assert.deepStrictEqual(sortedArray, [ { name: 'bb', lastName: 'aa', age: 6 }, { name: 'aa', lastName: 'aa', age: 10 }, { name: 'aa', lastName: 'bb', age: 11 }, { name: 'aa', lastName: null, age: 9 }, ]); }); it('Should throw error if asc or desc props not provided with object config', () => { const errorMessage = 'Invalid sort config: Expected `asc` or `desc` property'; assert.throws( () => sort(multiPropArray).by([{ asci: 'name' }] as any), Error, errorMessage, ); assert.throws( () => sort(multiPropArray).by([{ asc: 'lastName' }, { ass: 'name' }] as any), Error, errorMessage, ); assert.throws(() => sort([1, 2]).asc(null), Error, errorMessage); assert.throws(() => sort([1, 2]).desc([1, 2, 3] as any), Error, errorMessage); }); it('Should throw error if both asc and dsc props provided with object config', () => { const errorMessage = 'Invalid sort config: Ambiguous object with `asc` and `desc` config properties'; assert.throws( () => sort(multiPropArray).by([{ asc: 'name', desc: 'lastName' }] as any), Error, errorMessage, ); }); it('Should throw error if using nested property with string syntax', () => { assert.throw( () => sort(students).desc('address.streetNumber' as any), Error, 'Invalid sort config: String syntax not allowed for nested properties.', ); }); it('Should sort ascending on single property with by sorter', () => { const sorted = sort(multiPropArray).by([{ asc: p => p.age }]); assert.deepStrictEqual([6, 9, 10, 11], sorted.map(m => m.age)); }); it('Should sort descending on single property with by sorter', () => { const sorted = sort(multiPropArray).by([{ desc: 'age' }]); assert.deepStrictEqual([11, 10, 9, 6], sorted.map(m => m.age)); }); it('Should sort flat array in asc order using natural sort comparer', () => { const sorted = sort(flatNaturalArray).by([{ asc: true, comparer: new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }).compare, }]); assert.deepStrictEqual(sorted, ['A2', 'A10', 'B2', 'B10']); }); it('Should sort flat array in desc order using natural sort comparer', () => { const sorted = sort(flatNaturalArray).by([{ desc: true, comparer: new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }).compare, }]); assert.deepStrictEqual(sorted, ['B10', 'B2', 'A10', 'A2']); }); it('Should sort object in asc order using natural sort comparer', () => { const sorted = sort(multiPropArray).by([{ asc: p => p.unit, comparer: new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }).compare, }]); assert.deepStrictEqual(['A01', 'A10', 'B3', 'C2'], sorted.map(m => m.unit)); }); it('Should sort object in desc order using natural sort comparer', () => { const sorted = sort(multiPropArray).by([{ desc: p => p.unit, comparer: new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }).compare, }]); assert.deepStrictEqual(['C2', 'B3', 'A10', 'A01'], sorted.map(m => m.unit)); }); it('Should sort object on multiple props using both default and custom comparer', () => { const testArr = [ { a: 'A2', b: 'A2' }, { a: 'A2', b: 'A10' }, { a: 'A10', b: 'A2' }, ]; const sorted = sort(testArr).by([{ desc: p => p.a, }, { asc: 'b', comparer: new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }).compare, }]); assert.deepStrictEqual(sorted, [ { a: 'A2', b: 'A2' }, { a: 'A2', b: 'A10' }, // <= B is sorted using natural sort comparer { a: 'A10', b: 'A2' }, // <= A is sorted using default sort comparer ]); }); // BUG repo case: https://github.com/snovakovic/fast-sort/issues/18 it('Sort by comparer should not override default sort of other array property', () => { const rows = [ { status: 0, title: 'A' }, { status: 0, title: 'D' }, { status: 0, title: 'B' }, { status: 1, title: 'C' }, ]; const sorted = sort(rows).by([{ asc: row => row.status, comparer: (a, b) => a - b, }, { asc: row => row.title, }]); assert.deepStrictEqual(sorted, [ { status: 0, title: 'A' }, { status: 0, title: 'B' }, { status: 0, title: 'D' }, { status: 1, title: 'C' }, ]); }); it('Should create natural sort instance and handle sorting correctly', () => { const naturalSort = createNewSortInstance({ comparer: new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }).compare, }); const sorted1 = naturalSort(multiPropArray).desc('unit'); assert.deepStrictEqual(['C2', 'B3', 'A10', 'A01'], sorted1.map(m => m.unit)); const sorted2 = naturalSort(multiPropArray).by({ asc: 'unit' }); assert.deepStrictEqual(['A01', 'A10', 'B3', 'C2'], sorted2.map(m => m.unit)); const sorted3 = naturalSort(multiPropArray).asc('lastName'); assert.deepStrictEqual(['aa', 'aa', 'bb', null], sorted3.map(m => m.lastName)); const sorted4 = naturalSort(multiPropArray).desc(p => p.lastName); assert.deepStrictEqual([null, 'bb', 'aa', 'aa'], sorted4.map(m => m.lastName)); const sorted5 = naturalSort(flatArray).desc(); assert.deepStrictEqual(sorted5, [5, 5, 4, 3, 2, 1]); const sorted6 = naturalSort(flatNaturalArray).asc(); assert.deepStrictEqual(sorted6, ['A2', 'A10', 'B2', 'B10']); }); it('Should handle sorting on multiples props with custom sorter instance', () => { const naturalSort = createNewSortInstance({ comparer: new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }).compare, }); const arr = [ { a: 'a', b: 'A2' }, { a: 'a', b: 'A20' }, { a: 'a', b: null }, { a: 'a', b: 'A3' }, { a: 'a', b: undefined }, ]; const sort1 = naturalSort(arr).asc('b'); assert.deepStrictEqual(sort1.map(a => a.b), ['A2', 'A3', 'A20', null, undefined]); const sorted2 = naturalSort(arr).asc(['a', 'b']); assert.deepStrictEqual(sorted2.map(a => a.b), ['A2', 'A3', 'A20', null, undefined]); const sorted3 = naturalSort(arr).desc('b'); assert.deepStrictEqual(sorted3.map(a => a.b), [undefined, null, 'A20', 'A3', 'A2']); const sorted4 = naturalSort(arr).desc(['a', 'b']); assert.deepStrictEqual(sorted4.map(a => a.b), [undefined, null, 'A20', 'A3', 'A2']); }); it('Should create custom tag sorter instance', () => { const tagImportance = { vip: 3, influencer: 2, captain: 1 }; const customTagComparer = (a, b) => (tagImportance[a] || 0) - (tagImportance[b] || 0); const tags = ['influencer', 'unknown', 'vip', 'captain']; const tagSorter = createNewSortInstance({ comparer: customTagComparer }); assert.deepStrictEqual(tagSorter(tags).asc(), ['unknown', 'captain', 'influencer', 'vip']); assert.deepStrictEqual(tagSorter(tags).desc(), ['vip', 'influencer', 'captain', 'unknown']); assert.deepStrictEqual(sort(tags).asc(tag => tagImportance[tag] || 0), ['unknown', 'captain', 'influencer', 'vip']); }); it('Should be able to override natural sort comparer', () => { const naturalSort = createNewSortInstance({ comparer: new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }).compare, }); const sorted1 = naturalSort(multiPropArray).by([{ asc: 'name', }, { desc: 'unit', comparer(a, b) { // NOTE: override natural sort if (a === b) return 0; return a < b ? -1 : 1; }, }]); let sortedArray = sorted1.map(arr => ({ name: arr.name, unit: arr.unit })); assert.deepStrictEqual(sortedArray, [ { name: 'aa', unit: 'C2' }, { name: 'aa', unit: 'A10' }, { name: 'aa', unit: 'A01' }, { name: 'bb', unit: 'B3' }, ]); const sorted2 = naturalSort(multiPropArray).by([{ asc: 'name' }, { desc: 'unit' }]); sortedArray = sorted2.map(arr => ({ name: arr.name, unit: arr.unit })); assert.deepStrictEqual(sortedArray, [ { name: 'aa', unit: 'C2' }, { name: 'aa', unit: 'A10' }, { name: 'aa', unit: 'A01' }, { name: 'bb', unit: 'B3' }, ]); }); it('Should sort in asc order with by sorter if object config not provided', () => { const sorted = sort(multiPropArray).by(['name', 'unit'] as any); const sortedArray = sorted.map(arr => ({ name: arr.name, unit: arr.unit })); assert.deepStrictEqual(sortedArray, [ { name: 'aa', unit: 'A01' }, { name: 'aa', unit: 'A10' }, { name: 'aa', unit: 'C2' }, { name: 'bb', unit: 'B3' }, ]); }); it('Should ignore empty array as a sorting prop', () => { assert.deepStrictEqual(sort([2, 1, 4]).asc([]), [1, 2, 4]); }); it('Should sort by computed property', () => { const repos = [ { openIssues: 0, closedIssues: 5 }, { openIssues: 4, closedIssues: 4 }, { openIssues: 3, closedIssues: 3 }, ]; const sorted1 = sort(repos).asc(r => r.openIssues + r.closedIssues); assert.deepStrictEqual(sorted1, [ { openIssues: 0, closedIssues: 5 }, { openIssues: 3, closedIssues: 3 }, { openIssues: 4, closedIssues: 4 }, ]); const sorted2 = sort(repos).desc(r => r.openIssues + r.closedIssues); assert.deepStrictEqual(sorted2, [ { openIssues: 4, closedIssues: 4 }, { openIssues: 3, closedIssues: 3 }, { openIssues: 0, closedIssues: 5 }, ]); }); it('Should not mutate sort by array', () => { const sortBy = [{ asc: 'name' }, { asc: 'unit' }]; const sorted = sort(multiPropArray).by(sortBy as any); assert.deepStrictEqual(sortBy, [{ asc: 'name' }, { asc: 'unit' }]); const sortedArray = sorted.map(arr => ({ name: arr.name, unit: arr.unit })); assert.deepStrictEqual(sortedArray, [ { name: 'aa', unit: 'A01' }, { name: 'aa', unit: 'A10' }, { name: 'aa', unit: 'C2' }, { name: 'bb', unit: 'B3' }, ]); }); it('Should sort readme example for natural sort correctly', () => { const testArr = ['image-2.jpg', 'image-11.jpg', 'image-3.jpg']; // By default fast-sort is not doing natural sort const sorted1 = sort(testArr).desc(); // => assert.deepStrictEqual(sorted1, ['image-3.jpg', 'image-2.jpg', 'image-11.jpg']); const sorted2 = sort(testArr).by({ desc: true, comparer: new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }).compare, }); assert.deepStrictEqual(sorted2, ['image-11.jpg', 'image-3.jpg', 'image-2.jpg']); // If we want to reuse natural sort in multiple places we can create new sort instance const naturalSort = createNewSortInstance({ comparer: new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }).compare, }); const sorted3 = naturalSort(testArr).asc(); assert.deepStrictEqual(sorted3, ['image-2.jpg', 'image-3.jpg', 'image-11.jpg']); const sorted4 = naturalSort(testArr).desc(); assert.deepStrictEqual(sorted4, ['image-11.jpg', 'image-3.jpg', 'image-2.jpg']); assert.notEqual(sorted3, testArr); }); it('Should create sort instance that sorts nil value to the top in desc order', () => { const nilSort = createNewSortInstance({ comparer(a, b):number { if (a == null) return 1; if (b == null) return -1; if (a < b) return -1; if (a === b) return 0; return 1; }, }); const sorter1 = nilSort(multiPropArray).asc(p => p.lastName); assert.deepStrictEqual(['aa', 'aa', 'bb', null], sorter1.map(p => p.lastName)); const sorter2 = nilSort(multiPropArray).desc(p => p.lastName); assert.deepStrictEqual([null, 'bb', 'aa', 'aa'], sorter2.map(p => p.lastName)); // By default custom sorter should not mutate provided array assert.notEqual(sorter1, multiPropArray); assert.notEqual(sorter2, multiPropArray); }); it('Should mutate array with custom sorter if inPlaceSorting provided', () => { const customInPlaceSorting = createNewSortInstance({ comparer: new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }).compare, inPlaceSorting: true, // <= NOTE }); const sorted = customInPlaceSorting(flatArray).asc(); assert.equal(sorted, flatArray); assert.deepStrictEqual(flatArray, [1, 2, 3, 4, 5, 5]); }); it('Should be able to sort readonly arrays when not using inPlaceSorting', () => { const readOnlyArray = Object.freeze([2, 1, 4, 3]); const sorted = sort(readOnlyArray).asc(); assert.deepEqual(sorted, [1, 2, 3, 4]); // We can sort it with custom sorter if inPlaceSorting is false const custom = createNewSortInstance({ comparer: new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }).compare, inPlaceSorting: false, // <= NOTE }); const sorted2 = custom(readOnlyArray).asc(); assert.deepEqual(sorted2, [1, 2, 3, 4]); // NOTE: will throw error if trying to sort it in place assert.throws( () => inPlaceSort(readOnlyArray as any).asc(), Error, 'Cannot assign to read only property \'0\' of object \'[object Array]\'', ); }); });
the_stack
import { SwatchRGB } from "@fluentui/web-components"; import { parseColorHexRGB } from "@microsoft/fast-colors"; import { DesignToken, DesignTokenValue } from "@microsoft/fast-foundation"; import { AdditionalData, AppliedDesignToken, AppliedRecipe, PluginNodeData, ReadonlyAppliedDesignTokens, ReadonlyAppliedRecipes, RecipeEvaluation, } from "../model"; import { DesignTokenDefinition, DesignTokenRegistry, DesignTokenType, } from "./design-token-registry"; import { registerRecipes, registerTokens } from "./recipes"; /** * Represents a Node on the UI side. */ export interface PluginUINodeData extends PluginNodeData { /** * The ID of the node */ id: string; /** * The node type */ type: string; /** * The recipe types that the node supports */ supports: Array<DesignTokenType>; /** * For other transient data exchanged between the design tool and the plugin. */ additionalData: AdditionalData; /** * The design token values inherited by this node from layer hierarchy. */ inheritedDesignTokens: ReadonlyAppliedDesignTokens; /** * The design token values inherited by an instance node from the main component. */ componentDesignTokens?: ReadonlyAppliedDesignTokens; /** * Recipes inherited by an instance node from the main component. */ componentRecipes?: ReadonlyAppliedRecipes; /** * Children of this node that have design tokens or recipes applied. */ children: PluginUINodeData[]; } /** * Simple display information for representing design tokens applied to one or more Nodes. */ export interface UIDesignTokenValue { /** * The definition of the design token. */ definition: DesignTokenDefinition; /** * Represents the design token value if all selected nodes have the same value. */ value?: string; /** * If the selected nodes have multiple different values this will be a list for display. */ multipleValues?: string; } /** * The Controller for the UI side of the plugin, which encapsulates the business logic of * applying design tokens and recipes and evaluating the changes for the selected nodes. */ export class UIController { private readonly _updateStateCallback: ( selectedNodes: PluginUINodeData[] ) => void | undefined; // This is adapting the new token model to the previous plugin structure. Recipes are now just tokens, // but the separation is useful for now in that a token is where you set a value and a recipe you apply to some visual element. private readonly _designTokenRegistry: DesignTokenRegistry = new DesignTokenRegistry(); private readonly _recipeRegistry: DesignTokenRegistry = new DesignTokenRegistry(); /** * The container for the elements created for each node so we can resolve values from the Design Token infrastructure. * We don't need to set values for every design token because for we'll get the token's withDefault value. */ private readonly _rootElement: HTMLElement; private _selectedNodes: PluginUINodeData[] = []; /** * Create a new UI controller. * @param updateStateCallback Callback function to handle updated design token and recipe application and evaluation. */ constructor(updateStateCallback: (selectedNodes: PluginUINodeData[]) => void) { this._updateStateCallback = updateStateCallback; registerTokens(this._designTokenRegistry); registerRecipes(this._recipeRegistry); this._rootElement = document.createElement("div"); this._rootElement.id = "designTokenRoot"; document.body.appendChild(this._rootElement); } public get autoRefresh(): boolean { return !( this._selectedNodes.length === 1 && this._selectedNodes[0].type === "PAGE" ); } /** * Sets the selected nodes, which sets up the UI and immediately refreshes all recipe evaluations. * @param nodes The selected nodes. */ public setSelectedNodes(nodes: PluginUINodeData[]) { // console.log("--------------------------------"); // console.log("UIController.setSelectedNodes", nodes); this._selectedNodes = nodes; this._rootElement.childNodes.forEach(child => this._rootElement.removeChild(child) ); nodes.forEach(node => this.setupDesignTokenElement(this._rootElement, node)); if (this.autoRefresh) { this.refreshSelectedNodes("setSelectedNodes"); } } public refreshSelectedNodes(reason: string = "refreshSelectedNodes"): void { this.evaluateRecipes(this._selectedNodes); this.dispatchState(reason); } /** * Gets a display representation of design tokens applied to the selected nodes. * @returns Applied design tokens. */ public appliedDesignTokens(): UIDesignTokenValue[] { const tokenValues = new Map<string, Set<string>>(); const designTokens: UIDesignTokenValue[] = []; this._selectedNodes.forEach(node => node.designTokens.forEach((designToken, designTokenId) => { if (designToken.value) { const values = tokenValues.get(designTokenId) || new Set<string>(); values.add(designToken.value); tokenValues.set(designTokenId, values); } }) ); const allDesignTokens = this._designTokenRegistry.find( DesignTokenType.designToken ); allDesignTokens.forEach(designToken => { if (tokenValues.has(designToken.id)) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const set = tokenValues.get(designToken.id)!; designTokens.push({ definition: designToken, value: set.size === 1 ? set.values().next().value : undefined, multipleValues: set.size > 1 ? [...set].join(", ") : undefined, }); } }); return designTokens; } /** * Gets a display representation of recipes applied to the selected nodes. * @param type Recipe type. * @returns Applied recipes. */ public appliedRecipes(type: DesignTokenType): DesignTokenDefinition[] { const ids = new Set<string>(); const recipes: DesignTokenDefinition[] = []; this._selectedNodes.forEach(node => node.recipes.forEach((recipe, recipeId) => ids.add(recipeId)) ); const typeRecipes = this._recipeRegistry.find(type); typeRecipes.forEach(recipe => { if (ids.has(recipe.id)) { recipes.push(recipe); } }); return recipes.filter(recipe => recipe.type === type); } /** * Gets a list of recipes for the recipe type. * @param type Recipe type. * @returns List of available recipes. */ public recipeOptionsByType(type: DesignTokenType): DesignTokenDefinition[] { const val = this._recipeRegistry.find(type); return val; } /** * Returns the node IDs to which the recipe is assigned. * @param id - The recipe ID. */ public recipeIsAssigned(id: string): string[] { return this._selectedNodes .filter(node => { return Object.keys(node.recipes).includes(id); }) .map(node => node.id); } /** * Resets all design tokens and recipes for the selected nodes. */ public resetNodes(): void { this._selectedNodes.forEach(node => { // console.log("--------------------------------"); // console.log("reset", node); node.designTokens.clear(); node.recipes.clear(); node.recipeEvaluations.clear(); }); this.dispatchState("resetNodes"); } private evaluateRecipes(nodes: PluginUINodeData[]) { // console.log(" evaluateRecipes"); nodes.forEach(node => { const allRecipeIds = [ ...(node.componentRecipes ? node.componentRecipes.keys() : new Array<string>()), ...node.recipes.keys(), ]; allRecipeIds.reduceRight<Array<DesignTokenDefinition>>( (previousRecipes, currentId, index, array) => { // console.log(previousRecipes, currentId, index, array); const currentRecipe = this._recipeRegistry.get(currentId); if ( currentRecipe && !previousRecipes.find(value => value.type === currentRecipe.type) ) { // console.log("adding", currentRecipe); this.evaluateRecipe(currentRecipe, node); previousRecipes.push(currentRecipe); } return previousRecipes; }, [] ); this.evaluateRecipes(node.children); }); } private evaluateRecipe<T>( recipe: DesignTokenDefinition<T>, node: PluginUINodeData ): T { // console.log(" evaluateRecipe", recipe); let value: T = this.getDesignTokenValue<T>(node, recipe.token); if (typeof (value as any).toColorString === "function") { value = (value as any).toColorString(); } node.recipeEvaluations.set(recipe.id, [ new RecipeEvaluation(recipe.type, (value as unknown) as string), ]); // console.log(" evaluations", node.recipeEvaluations); if (recipe.type === DesignTokenType.layerFill) { // console.log(" Fill recipe, setting fillColor design token"); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const def = this._designTokenRegistry.get("fillColor")!; const element = this.getElementForNode(node); this.setDesignTokenForElement(element, def.token, value); this.evaluateRecipes(node.children); } return value; } public removeRecipe(recipe: DesignTokenDefinition): void { this._selectedNodes.forEach(node => { node.recipes.delete(recipe.id); node.recipeEvaluations.delete(recipe.id); // console.log("--------------------------------"); // console.log("removed recipe from node", recipe.id, node); }); this.evaluateRecipes(this._selectedNodes); this.dispatchState("removeRecipe"); } public assignRecipe(recipe: DesignTokenDefinition): void { this._selectedNodes.forEach(node => { // console.log("--------------------------------"); // console.log("assigning recipe to node", recipe); // There should only be able to be one recipe for a type, but maybe add safety check. let recipeToRemove: string | null = null; node.recipeEvaluations.forEach((evaluationAttrs, evaluationRecipeId) => { const found = evaluationAttrs.find( evaluation => evaluation.type === recipe.type ); if (found) { recipeToRemove = evaluationRecipeId; } }); if (recipeToRemove) { // console.log(" Removing recipe and evaluations for", recipeToRemove); node.recipes.delete(recipeToRemove); node.recipeEvaluations.delete(recipeToRemove); } node.recipes.set(recipe.id, new AppliedRecipe()); this.evaluateRecipe(recipe, node); // console.log(" node", node); }); this.dispatchState("assignRecipe"); } private setDesignTokenForElement<T>( nodeElement: HTMLElement, token: DesignToken<T>, value: T | null ) { try { if (value) { // TODO figure out a better way to handle storage data types const color = parseColorHexRGB((value as unknown) as string); if (color) { // console.log(" setting DesignToken value (color)", token.name, value); token.setValueFor( nodeElement, (SwatchRGB.from(color) as unknown) as DesignTokenValue<T> ); } else { const num = Number.parseFloat((value as unknown) as string); if (!Number.isNaN(num)) { // console.log(" setting DesignToken value (number)", token.name, value); token.setValueFor( nodeElement, (num as unknown) as DesignTokenValue<T> ); } else { // console.log(" setting DesignToken value (unconverted)", token.name, value); token.setValueFor(nodeElement, value as DesignTokenValue<T>); } } } else { token.deleteValueFor(nodeElement); } } catch (e) { // console.warn(" token error", e); // Ignore, token not found } } private getElementForNode(node: PluginUINodeData): HTMLElement { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const element = this._rootElement.querySelector( `#${CSS.escape(node.id)}` )! as HTMLElement; return element; } private appliedDesignTokensHandler( nodeElement: HTMLElement ): (value: AppliedDesignToken, key: string) => void { return (value: AppliedDesignToken, key: string): void => { const def = this._designTokenRegistry.get(key); if (def) { this.setDesignTokenForElement(nodeElement, def.token, value.value); } }; } private setupDesignTokenElement(element: HTMLElement, node: PluginUINodeData) { // console.log(" setupDesignTokenElement - node", node, "parent", element.id); // Create an element representing this node in our local dom. const nodeElement = document.createElement("div"); nodeElement.id = node.id; element.appendChild(nodeElement); // Set all the inherited design token values for the local element. // console.log(" setting inherited tokens"); node.inheritedDesignTokens.forEach( this.appliedDesignTokensHandler(nodeElement), this ); // Set all design token values from the main component for the local element (an instance component). // console.log(" setting main component tokens", node.componentDesignTokens); node.componentDesignTokens?.forEach( this.appliedDesignTokensHandler(nodeElement), this ); // Set all the design token override values for the local element. // console.log(" setting local tokens"); node.designTokens.forEach(this.appliedDesignTokensHandler(nodeElement), this); // Handle any additional data. Keys are provided as design token ids. node.additionalData.forEach((value, key) => { const def = this._designTokenRegistry.get(key); if (def) { // console.log(" setting token value on element", def, "value", value); this.setDesignTokenForElement(nodeElement, def.token, value); } }, this); node.children.forEach(child => this.setupDesignTokenElement(nodeElement, child)); } private valueToString(value: any): string { // TODO figure out a better way to handle storage data types if (typeof value.toColorString === "function") { return value.toColorString(); } else { return "" + value; } } public getDesignTokenDefinitions(): DesignTokenDefinition<any>[] { return this._designTokenRegistry.find(DesignTokenType.designToken); } public getDesignTokenDefinition<T>(id: string): DesignTokenDefinition<T> | null { return this._designTokenRegistry.get(id); } public getDefaultDesignTokenValue<T>(token: DesignToken<T>): string { const val = this.valueToString(token.getValueFor(this._rootElement)); // console.log("getDefaultDesignTokenValue", "token", token, "value", val); return val; } public getDesignTokenValue<T>(node: PluginUINodeData, token: DesignToken<T>): T { // Evaluate the token based on the tokens provided to the element. const element = this.getElementForNode(node); const val = token.getValueFor(element); // console.log(" getDesignTokenValue", node.id, node.type, token.name, "value", this.valueToString(val)); return val; } private setDesignTokenForNode<T>( node: PluginUINodeData, definition: DesignTokenDefinition<T>, value: T | null ): void { if (value) { const designToken = new AppliedDesignToken(); designToken.value = this.valueToString(value); node.designTokens.set(definition.id, designToken); } else { node.designTokens.delete(definition.id); } // console.log(" after set designTokens", node.id, node.type, node.designTokens); const element = this.getElementForNode(node); this.setDesignTokenForElement(element, definition.token, value); } public assignDesignToken<T>(definition: DesignTokenDefinition<T>, value: T): void { const nodes = this._selectedNodes.filter(node => node.supports.includes(DesignTokenType.designToken) ); // console.log("--------------------------------"); // console.log("UIController.assignDesignToken", definition, value, typeof value, nodes); nodes.forEach(node => this.setDesignTokenForNode(node, definition, value)); // console.log(" Evaluating all recipes for all selected nodes"); this.evaluateRecipes(this._selectedNodes); this.dispatchState("assignDesignToken " + definition.id); } public removeDesignToken(definition: DesignTokenDefinition): void { const nodes = this._selectedNodes.filter(node => node.supports.includes(DesignTokenType.designToken) ); // console.log("--------------------------------"); // console.log("UIController.removeDesignToken", definition.id, nodes); nodes.forEach(node => this.setDesignTokenForNode(node, definition, null)); // console.log(" Evaluating all recipes for all selected nodes"); this.evaluateRecipes(this._selectedNodes); this.dispatchState("removeDesignToken"); } private dispatchState(reason: string): void { // console.log("UIController.dispatchState", reason); this._updateStateCallback(this._selectedNodes); } }
the_stack
import PostNodeBuilder from 'mobiledoc-kit/models/post-node-builder' import Post from 'mobiledoc-kit/models/post' import { Dict, Maybe } from 'mobiledoc-kit/utils/types' import Atom from 'mobiledoc-kit/models/atom' import { keys } from 'mobiledoc-kit/utils/object-utils' import Markup from 'mobiledoc-kit/models/markup' import Markuperable from 'mobiledoc-kit/utils/markuperable' import Section from 'mobiledoc-kit/models/_section' import { unwrap } from 'mobiledoc-kit/utils/assert' import Position from 'mobiledoc-kit/utils/cursor/position' import Range from 'mobiledoc-kit/utils/cursor/range' import ListSection from 'mobiledoc-kit/models/list-section' import { isListItem } from 'mobiledoc-kit/models/list-item' import { Cloneable } from 'mobiledoc-kit/models/_cloneable' type ProxyMethod<T extends (...args: any) => any> = (...args: Parameters<T>) => ReturnType<T> export interface SimplePostBuilder { post: ProxyMethod<PostNodeBuilder['createPost']> markupSection: ProxyMethod<PostNodeBuilder['createMarkupSection']> markup: ProxyMethod<PostNodeBuilder['createMarkup']> marker: ProxyMethod<PostNodeBuilder['createMarker']> listSection: ProxyMethod<PostNodeBuilder['createListSection']> listItem: ProxyMethod<PostNodeBuilder['createListItem']> cardSection: ProxyMethod<PostNodeBuilder['createCardSection']> imageSection: ProxyMethod<PostNodeBuilder['createImageSection']> atom: ProxyMethod<PostNodeBuilder['createAtom']> } export type BuildCallback = (builder: SimplePostBuilder) => Post /* * usage: * Helpers.postAbstract.build(({post, section, marker, markup}) => * post([ * section('P', [ * marker('some text', [markup('B')]) * ]) * }) * ) */ function build(treeFn: BuildCallback) { let builder = new PostNodeBuilder() const simpleBuilder: SimplePostBuilder = { post: (...args) => builder.createPost(...args), markupSection: (...args) => builder.createMarkupSection(...args), markup: (...args) => builder.createMarkup(...args), marker: (...args) => builder.createMarker(...args), listSection: (...args) => builder.createListSection(...args), listItem: (...args) => builder.createListItem(...args), cardSection: (...args) => builder.createCardSection(...args), imageSection: (...args) => builder.createImageSection(...args), atom: (...args) => builder.createAtom(...args), } return treeFn(simpleBuilder) } let cardRegex = /\[(.*)\]/ let imageSectionRegex = /^\{(.*)\}/ let markupRegex = /\*/g let listStartRegex = /^\* / let cursorRegex = /<|>|\|/g function parsePositionOffsets(text: string) { let offsets: Dict<number> = {} if (cardRegex.test(text)) { ;[ ['|', 'solo'], ['<', 'start'], ['>', 'end'], ].forEach(([char, type]) => { if (text.indexOf(char) !== -1) { offsets[type] = text.indexOf(char) === 0 ? 0 : 1 } }) } else { if (listStartRegex.test(text)) { text = text.replace(listStartRegex, '') } text = text.replace(markupRegex, '') if (text.indexOf('|') !== -1) { offsets.solo = text.indexOf('|') } else if (text.indexOf('<') !== -1 || text.indexOf('>') !== -1) { let hasStart = text.indexOf('<') !== -1 let hasEnd = text.indexOf('>') !== -1 if (hasStart) { offsets.start = text.indexOf('<') text = text.replace(/</g, '') } if (hasEnd) { offsets.end = text.indexOf('>') } } } return offsets } const DEFAULT_ATOM_NAME = 'some-atom' const DEFAULT_ATOM_VALUE = '@atom' const MARKUP_CHARS = <const>{ '*': 'b', _: 'em', } function parseTextIntoAtom(text: string, builder: SimplePostBuilder) { let markers: Markuperable[] = [] let atomIndex = text.indexOf('@') let afterAtomIndex = atomIndex + 1 let atomName = DEFAULT_ATOM_NAME, atomValue = DEFAULT_ATOM_VALUE, atomPayload = {} // If "@" is followed by "( ... json ... )", parse the json data if (text[atomIndex + 1] === '(') { let jsonStartIndex = atomIndex + 1 let jsonEndIndex = text.indexOf(')', jsonStartIndex) afterAtomIndex = jsonEndIndex + 1 if (jsonEndIndex === -1) { throw new Error('Atom JSON data had unmatched "(": ' + text) } let jsonString = text.slice(jsonStartIndex + 1, jsonEndIndex) jsonString = '{' + jsonString + '}' try { let json = JSON.parse(jsonString) if (json.name) { atomName = json.name } if (json.value) { atomValue = json.value } if (json.payload) { atomPayload = json.payload } } catch (e) { throw new Error('Failed to parse atom JSON data string: ' + jsonString + ', ' + e) } } // create the atom let atom = builder.atom(atomName, atomValue, atomPayload) // recursively parse the remaining text pieces let pieces = [text.slice(0, atomIndex), atom, text.slice(afterAtomIndex)] // join the markers together pieces.forEach((piece, index) => { if (index === 1) { // atom markers.push(piece as Atom) } else if (piece.length) { markers = markers.concat(parseTextIntoMarkers(piece as string, builder)) } }) return markers } function parseTextWithMarkup(text: string, builder: SimplePostBuilder) { let markers: Markuperable[] = [] let markup!: Markup let char!: string keys(MARKUP_CHARS).forEach(key => { if (markup) { return } if (text.indexOf(key) !== -1) { markup = builder.markup(MARKUP_CHARS[key]) char = key } }) if (!markup) { throw new Error(`Failed to find markup in text: ${text}`) } let startIndex = text.indexOf(char) let endIndex = text.indexOf(char, startIndex + 1) if (endIndex === -1) { throw new Error(`Malformed text: char ${char} do not match`) } let pieces = [text.slice(0, startIndex), text.slice(startIndex + 1, endIndex), text.slice(endIndex + 1)] pieces.forEach((piece, index) => { if (index === 1) { // marked-up text markers.push(builder.marker(piece, [markup])) } else { markers = markers.concat(parseTextIntoMarkers(piece, builder)) } }) return markers } function parseTextIntoMarkers(text: string, builder: SimplePostBuilder) { text = text.replace(cursorRegex, '') let markers: Markuperable[] = [] let hasAtom = text.indexOf('@') !== -1 let hasMarkup = false Object.keys(MARKUP_CHARS).forEach(key => { if (text.indexOf(key) !== -1) { hasMarkup = true } }) if (hasAtom) { markers = markers.concat(parseTextIntoAtom(text, builder)) } else if (hasMarkup) { markers = markers.concat(parseTextWithMarkup(text, builder)) } else if (text.length) { markers.push(builder.marker(text)) } return markers } function parseSingleText(text: string, builder: SimplePostBuilder) { let section!: Cloneable<Section> let positions: Positions = {} let offsets = parsePositionOffsets(text) if (cardRegex.test(text)) { section = builder.cardSection(unwrap(cardRegex.exec(text))[1]) } else if (imageSectionRegex.test(text)) { section = builder.imageSection(unwrap(imageSectionRegex.exec(text))[1]) } else { let type = 'p' if (listStartRegex.test(text)) { text = text.replace(listStartRegex, '') type = 'ul' } let markers = parseTextIntoMarkers(text, builder) switch (type) { case 'p': section = builder.markupSection('p', markers) break case 'ul': section = builder.listItem(markers) break } } ;(<const>['start', 'end', 'solo']).forEach(type => { if (offsets[type] !== undefined) { positions[type] = section.toPosition(offsets[type]) } }) return { section, positions } } interface Positions { start?: Position end?: Position solo?: Position } /** * Shorthand to create a mobiledoc simply. * Pass a string or an array of strings. * * Returns { post, range }, a post built from the mobiledoc and a range. * * Use "|" to indicate the cursor position or "<" and ">" to indicate a range. * Use "[card-name]" to indicate a card * Use asterisks to indicate bold text: "abc *bold* def" * Use "@" to indicate an atom, default values for name,value,payload are DEFAULT_ATOM_NAME,DEFAULT_ATOM_VALUE,{} * Use "@(name, value, payload)" to specify name,value and/or payload for an atom. The string from `(` to `)` is parsed as * JSON, e.g.: '@("name": "my-atom", "value": "abc", "payload": {"foo": "bar"})' -> atom named "my-atom" with value 'abc', payload {foo: 'bar'} * Use "* " at the start of the string to indicate a list item ("ul") * * Examples: * buildFromText("abc") -> { post } with 1 markup section ("p") with text "abc" * buildFromText(["abc","def"]) -> { post } with 2 markups sections ("p") with texts "abc" and "def" * buildFromText("abc|def") -> { post, range } where range is collapsed at offset 3 (after the "c") * buildFromText(["abcdef","[some-card]","def"]) -> { post } with [MarkupSection, Card, MarkupSection] sections * buildFromText(["abc", "{def}", "def"]) -> { post } with [MarkupSection, ImageSection, MarkupSection] sections * buildFromText(["* item 1", "* item 2"]) -> { post } with a ListSection with 2 ListItems * buildFromText(["<abc", "def", "ghi>"]) -> { post, range } where range is the entire post (before the "a" to after the "i") */ function buildFromText(_texts: string | string[]) { const texts = Array.isArray(_texts) ? _texts : [_texts] const positions: Positions = {} let post = build(builder => { let sections: Cloneable<Section>[] = [] let curList: Maybe<ListSection> texts.forEach((text, index) => { let { section, positions: _positions } = parseSingleText(text, builder) let lastText = index === texts.length - 1 if (curList) { if (isListItem(section)) { curList.items.append(section) } else { sections.push(curList) sections.push(section) curList = null } } else if (isListItem(section)) { curList = builder.listSection('ul', [section]) } else { sections.push(section) } if (lastText && curList) { sections.push(curList) } if (_positions.start) { positions.start = _positions.start } if (_positions.end) { positions.end = _positions.end } if (_positions.solo) { positions.solo = _positions.solo } }) return builder.post(sections) }) let range!: Range if (positions.start) { if (!positions.end) { throw new Error(`startPos but no endPos ${texts.join('\n')}`) } range = positions.start.toRange(positions.end) } else if (positions.solo) { range = positions.solo.toRange() } return { post, range } } export default { build, buildFromText, DEFAULT_ATOM_NAME, }
the_stack
import { html, render } from 'lit-html'; import BXRadioButtonGroup, { RADIO_BUTTON_ORIENTATION } from '../../src/components/radio-button/radio-button-group'; import { RADIO_BUTTON_LABEL_POSITION } from '../../src/components/radio-button/radio-button'; import { Default } from '../../src/components/radio-button/radio-button-story'; /** * @param formData A `FormData` instance. * @returns The given `formData` converted to a classic key-value pair. */ const getValues = (formData: FormData) => { const values = {}; // eslint-disable-next-line no-restricted-syntax for (const [key, value] of formData.entries()) { values[key] = value; } return values; }; const template = (props?) => Default(props); describe('bx-radio-button', function() { describe('Rendering', function() { it('Should render with minimum attributes', async function() { render(template(), document.body); await Promise.resolve(); expect(document.body.querySelector('bx-radio-button[value="staging"]')).toMatchSnapshot({ mode: 'shadow' }); }); it('Should render with various attributes', async function() { render( template({ 'bx-radio-button-group': { disabled: true, labelPosition: RADIO_BUTTON_LABEL_POSITION.LEFT, name: 'name-foo', orientation: RADIO_BUTTON_ORIENTATION.VERTICAL, value: 'staging', }, 'bx-radio-button': { hideLabel: true, labelText: 'label-text-foo', }, }), document.body ); await Promise.resolve(); expect(document.body.querySelector('bx-radio-button[value="staging"]')).toMatchSnapshot({ mode: 'shadow' }); }); }); describe('Communication between <bx-radio-button-group> and <bx-radio-button>', function() { it('Should propagate disabled', async function() { render(template({ 'bx-radio-button-group': { disabled: true } }), document.body); await Promise.resolve(); expect(Array.prototype.every.call(document.body.querySelectorAll('bx-radio-button'), radio => radio.disabled)).toBe(true); }); it('Should propagate labelPosition', async function() { render( template({ 'bx-radio-button-group': { labelPosition: RADIO_BUTTON_LABEL_POSITION.LEFT }, }), document.body ); await Promise.resolve(); expect( Array.prototype.every.call( document.body.querySelectorAll('bx-radio-button'), radio => radio.labelPosition === RADIO_BUTTON_LABEL_POSITION.LEFT ) ).toBe(true); }); it('Should propagate orientation', async function() { render( template({ 'bx-radio-button-group': { orientation: RADIO_BUTTON_ORIENTATION.VERTICAL }, }), document.body ); await Promise.resolve(); expect( Array.prototype.every.call( document.body.querySelectorAll('bx-radio-button'), radio => radio.orientation === RADIO_BUTTON_ORIENTATION.VERTICAL ) ).toBe(true); }); it('Should propagate name', async function() { render( template({ 'bx-radio-button-group': { name: 'name-foo' }, }), document.body ); await Promise.resolve(); expect( Array.prototype.every.call(document.body.querySelectorAll('bx-radio-button'), radio => radio.name === 'name-foo') ).toBe(true); }); it('Should select <bx-radio-button> that matches the given value', async function() { render( template({ 'bx-radio-button-group': { value: 'staging' }, }), document.body ); await Promise.resolve(); expect(Array.prototype.map.call(document.body.querySelectorAll('bx-radio-button'), radio => radio.checked)).toEqual([ false, false, true, ]); }); it('Should update the value upon clicking <bx-radio-button>', async function() { render( template({ 'bx-radio-button-group': { name: 'name-foo' }, }), document.body ); await Promise.resolve(); (document.body.querySelector('bx-radio-button[value="staging"]') as HTMLElement).click(); expect((document.body.querySelector('bx-radio-button-group') as BXRadioButtonGroup).value).toBe('staging'); }); it('Should update the value upon space key on <bx-radio-button>', async function() { render( template({ 'bx-radio-button-group': { name: 'name-foo' }, }), document.body ); await Promise.resolve(); const event = new CustomEvent('keydown', { bubbles: true, composed: true }); const radioBaz = document.body.querySelector('bx-radio-button[value="staging"]'); (radioBaz as HTMLElement).dispatchEvent(Object.assign(event, { key: ' ' })); expect((document.body.querySelector('bx-radio-button-group') as BXRadioButtonGroup).value).toBe('staging'); }); it('Should update the value upon enter key on <bx-radio-button>', async function() { render( template({ 'bx-radio-button-group': { name: 'name-foo' }, }), document.body ); await Promise.resolve(); const event = new CustomEvent('keydown', { bubbles: true, composed: true }); const radioBaz = document.body.querySelector('bx-radio-button[value="staging"]'); (radioBaz as HTMLElement).dispatchEvent(Object.assign(event, { key: 'Enter' })); expect((document.body.querySelector('bx-radio-button-group') as BXRadioButtonGroup).value).toBe('staging'); }); }); describe('Keyboard navigation', function() { it('Should use left/right key for navigation in horizontal mode', async function() { render( template({ 'bx-radio-button-group': { orientation: RADIO_BUTTON_ORIENTATION.HORIZONTAL, name: 'name-foo' }, }), document.body ); await Promise.resolve(); const radioFoo = document.body.querySelector('bx-radio-button[value="all"]') as HTMLElement; radioFoo.focus(); const event = new CustomEvent('keydown', { bubbles: true, composed: true }); radioFoo.dispatchEvent(Object.assign(event, { key: 'ArrowRight' })); expect((document.body.querySelector('bx-radio-button-group') as BXRadioButtonGroup).value).toBe('cloudFoundry'); expect( Array.prototype.map.call( document.body.querySelectorAll('bx-radio-button'), radio => radio.shadowRoot.querySelector('input').tabIndex ) ).toEqual([-1, 0, -1]); const radioBar = document.body.querySelector('bx-radio-button[value="cloudFoundry"]') as HTMLElement; radioBar.dispatchEvent(Object.assign(event, { key: 'ArrowLeft' })); expect((document.body.querySelector('bx-radio-button-group') as BXRadioButtonGroup).value).toBe('all'); expect( Array.prototype.map.call( document.body.querySelectorAll('bx-radio-button'), radio => radio.shadowRoot.querySelector('input').tabIndex ) ).toEqual([0, -1, -1]); }); it('Should use up/down key for navigation in vertical mode', async function() { render( template({ 'bx-radio-button-group': { orientation: RADIO_BUTTON_ORIENTATION.VERTICAL, name: 'name-foo' }, }), document.body ); await Promise.resolve(); const radioFoo = document.body.querySelector('bx-radio-button[value="all"]') as HTMLElement; radioFoo.focus(); const event = new CustomEvent('keydown', { bubbles: true, composed: true }); radioFoo.dispatchEvent(Object.assign(event, { key: 'ArrowDown' })); expect((document.body.querySelector('bx-radio-button-group') as BXRadioButtonGroup).value).toBe('cloudFoundry'); expect( Array.prototype.map.call( document.body.querySelectorAll('bx-radio-button'), radio => radio.shadowRoot.querySelector('input').tabIndex ) ).toEqual([-1, 0, -1]); const radioBar = document.body.querySelector('bx-radio-button[value="cloudFoundry"]') as HTMLElement; radioBar.dispatchEvent(Object.assign(event, { key: 'ArrowUp' })); expect((document.body.querySelector('bx-radio-button-group') as BXRadioButtonGroup).value).toBe('all'); expect( Array.prototype.map.call( document.body.querySelectorAll('bx-radio-button'), radio => radio.shadowRoot.querySelector('input').tabIndex ) ).toEqual([0, -1, -1]); }); }); describe('Event-based form participation', function() { it('Should respond to `formdata` event', async function() { render( html` <form> ${template({ 'bx-radio-button-group': { name: 'name-foo', value: 'staging', }, })} </form> `, document.body ); await Promise.resolve(); const formData = new FormData(); const event = new CustomEvent('formdata', { bubbles: true, cancelable: false, composed: false }); (event as any).formData = formData; // TODO: Wait for `FormDataEvent` being available in `lib.dom.d.ts` const form = document.querySelector('form'); form!.dispatchEvent(event); expect(getValues(formData)).toEqual({ 'name-foo': 'staging' }); }); it('Should not respond to `formdata` event if form item name is not specified', async function() { render( html` <form> ${template({ 'bx-radio-button-group': { value: 'staging', }, })} </form> `, document.body ); await Promise.resolve(); const formData = new FormData(); const event = new CustomEvent('formdata', { bubbles: true, cancelable: false, composed: false }); (event as any).formData = formData; // TODO: Wait for `FormDataEvent` being available in `lib.dom.d.ts` const form = document.querySelector('form'); form!.dispatchEvent(event); expect(getValues(formData)).toEqual({}); }); it('Should not respond to `formdata` event if no item is selected', async function() { render( html` <form> ${template({ 'bx-radio-button-group': { name: 'name-foo', }, })} </form> `, document.body ); await Promise.resolve(); const formData = new FormData(); const event = new CustomEvent('formdata', { bubbles: true, cancelable: false, composed: false }); (event as any).formData = formData; // TODO: Wait for `FormDataEvent` being available in `lib.dom.d.ts` const form = document.querySelector('form'); form!.dispatchEvent(event); expect(getValues(formData)).toEqual({}); }); it('Should not respond to `formdata` event if disabled', async function() { render( html` <form> ${template({ 'bx-radio-button-group': { disabled: true, name: 'name-foo', }, })} </form> `, document.body ); await Promise.resolve(); const formData = new FormData(); const event = new CustomEvent('formdata', { bubbles: true, cancelable: false, composed: false }); (event as any).formData = formData; // TODO: Wait for `FormDataEvent` being available in `lib.dom.d.ts` const form = document.querySelector('form'); form!.dispatchEvent(event); expect(getValues(formData)).toEqual({}); }); }); afterEach(async function() { render(undefined!, document.body); await Promise.resolve(); }); });
the_stack
import { ContractTransaction, Signer, providers, constants, BigNumber } from 'ethers'; import { batchPaymentsArtifact } from '@requestnetwork/smart-contracts'; import { BatchPayments__factory } from '@requestnetwork/smart-contracts/types'; import { ClientTypes, PaymentTypes } from '@requestnetwork/types'; import { ITransactionOverrides } from './transaction-overrides'; import { comparePnTypeAndVersion, getAmountToPay, getPaymentNetworkExtension, getProvider, getRequestPaymentValues, getSigner, validateErc20FeeProxyRequest, } from './utils'; import { validateEthFeeProxyRequest } from './eth-fee-proxy'; import { IPreparedTransaction } from './prepared-transaction'; import { checkErc20Allowance, encodeApproveAnyErc20 } from './erc20'; /** * ERC20 Batch Proxy payment details: * batch of request with the same payment network type: ERC20 * batch of request with the same payment network version * 2 modes available: single token or multi tokens * It requires batch proxy's approval * * Eth Batch Proxy payment details: * batch of request with the same payment network type * batch of request with the same payment network version * -> Eth batch proxy accepts requests with 2 id: ethProxy and ethFeeProxy * but only call ethFeeProxy. It can impact payment detection */ /** * Processes a transaction to pay a batch of ETH Requests with fees. * Requests paymentType must be "ETH" or "ERC20" * @param requests List of requests * @param version version of the batch proxy, which can be different from request pn version * @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum. * @param batchFee Only for batch ETH: additional fee applied to a batch, between 0 and 1000, default value = 10 * @param overrides optionally, override default transaction values, like gas. */ export async function payBatchProxyRequest( requests: ClientTypes.IRequestData[], version: string, signerOrProvider: providers.Provider | Signer = getProvider(), batchFee: number, overrides?: ITransactionOverrides, ): Promise<ContractTransaction> { const { data, to, value } = prepareBatchPaymentTransaction(requests, version, batchFee); const signer = getSigner(signerOrProvider); return signer.sendTransaction({ data, to, value, ...overrides }); } /** * Prepate the transaction to pay a batch of requests through the batch proxy contract, can be used with a Multisig contract. * Requests paymentType must be "ETH" or "ERC20" * @param requests list of ETH requests to pay * @param version version of the batch proxy, which can be different from request pn version * @param batchFee additional fee applied to a batch */ export function prepareBatchPaymentTransaction( requests: ClientTypes.IRequestData[], version: string, batchFee: number, ): IPreparedTransaction { const encodedTx = encodePayBatchRequest(requests); const proxyAddress = getBatchProxyAddress(requests[0], version); let totalAmount = 0; if (requests[0].currencyInfo.type === 'ETH') { const { amountsToPay, feesToPay } = getBatchArgs(requests); const amountToPay = amountsToPay.reduce((sum, current) => sum.add(current), BigNumber.from(0)); const batchFeeToPay = BigNumber.from(amountToPay).mul(batchFee).div(1000); const feeToPay = feesToPay.reduce( (sum, current) => sum.add(current), BigNumber.from(batchFeeToPay), ); totalAmount = amountToPay.add(feeToPay).toNumber(); } return { data: encodedTx, to: proxyAddress, value: totalAmount, }; } /** * Encodes the call to pay a batch of requests through the ERC20Bacth or ETHBatch proxy contract, * can be used with a Multisig contract. * @param requests list of ECR20 requests to pay * @dev pn version of the requests is checked to avoid paying with two differents proxies (e.g: erc20proxy v1 and v2) */ export function encodePayBatchRequest(requests: ClientTypes.IRequestData[]): string { const { tokenAddresses, paymentAddresses, amountsToPay, paymentReferences, feesToPay, feeAddressUsed, } = getBatchArgs(requests); const proxyContract = BatchPayments__factory.createInterface(); if (requests[0].currencyInfo.type === 'ERC20') { let isMultiTokens = false; for (let i = 0; tokenAddresses.length; i++) { if (tokenAddresses[0] !== tokenAddresses[i]) { isMultiTokens = true; break; } } const pn = getPaymentNetworkExtension(requests[0]); for (let i = 0; i < requests.length; i++) { validateErc20FeeProxyRequest(requests[i]); if (!comparePnTypeAndVersion(pn, requests[i])) { throw new Error(`Every payment network type and version must be identical`); } } if (isMultiTokens) { return proxyContract.encodeFunctionData('batchERC20PaymentsMultiTokensWithReference', [ tokenAddresses, paymentAddresses, amountsToPay, paymentReferences, feesToPay, feeAddressUsed, ]); } else { return proxyContract.encodeFunctionData('batchERC20PaymentsWithReference', [ tokenAddresses[0], paymentAddresses, amountsToPay, paymentReferences, feesToPay, feeAddressUsed, ]); } } else { tokenAddresses; return proxyContract.encodeFunctionData('batchEthPaymentsWithReference', [ paymentAddresses, amountsToPay, paymentReferences, feesToPay, feeAddressUsed, ]); } } /** * Get batch arguments * @param requests List of requests * @returns List with the args required by batch Eth and Erc20 functions, * @dev tokenAddresses returned is for batch Erc20 functions */ function getBatchArgs(requests: ClientTypes.IRequestData[]): { tokenAddresses: Array<string>; paymentAddresses: Array<string>; amountsToPay: Array<BigNumber>; paymentReferences: Array<string>; feesToPay: Array<BigNumber>; feeAddressUsed: string; } { const tokenAddresses: Array<string> = []; const paymentAddresses: Array<string> = []; const amountsToPay: Array<BigNumber> = []; const paymentReferences: Array<string> = []; const feesToPay: Array<BigNumber> = []; let feeAddressUsed = constants.AddressZero; const paymentType = requests[0].currencyInfo.type; for (let i = 0; i < requests.length; i++) { if (paymentType === 'ETH') { validateEthFeeProxyRequest(requests[i]); } else if (paymentType === 'ERC20') { validateErc20FeeProxyRequest(requests[i]); } else { throw new Error(`paymentType ${paymentType} is not supported for batch payment`); } const tokenAddress = requests[i].currencyInfo.value; const { paymentReference, paymentAddress, feeAddress, feeAmount } = getRequestPaymentValues( requests[i], ); tokenAddresses.push(tokenAddress); paymentAddresses.push(paymentAddress); amountsToPay.push(getAmountToPay(requests[i])); paymentReferences.push(`0x${paymentReference}`); feesToPay.push(BigNumber.from(feeAmount || 0)); feeAddressUsed = feeAddress || constants.AddressZero; } return { tokenAddresses, paymentAddresses, amountsToPay, paymentReferences, feesToPay, feeAddressUsed, }; } /** * Get Batch contract Address * @param request * @param version version of the batch proxy, which can be different from request pn version */ export function getBatchProxyAddress(request: ClientTypes.IRequestData, version: string): string { const pn = getPaymentNetworkExtension(request); const pnId = pn?.id as unknown as PaymentTypes.PAYMENT_NETWORK_ID; if (!pnId) { throw new Error('No payment network Id'); } const proxyAddress = batchPaymentsArtifact.getAddress(request.currencyInfo.network!, version); if (!proxyAddress) { throw new Error(`No deployment found for network ${pn}, version ${pn?.version}`); } return proxyAddress; } /** * ERC20 Batch proxy approvals methods */ /** * Processes the approval transaction of the targeted ERC20 with batch proxy. * @param request request to pay * @param account account that will be used to pay the request * @param version version of the batch proxy, which can be different from request pn version * @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum. * @param overrides optionally, override default transaction values, like gas. */ export async function approveErc20BatchIfNeeded( request: ClientTypes.IRequestData, account: string, version: string, signerOrProvider: providers.Provider | Signer = getProvider(), overrides?: ITransactionOverrides, ): Promise<ContractTransaction | void> { if (!(await hasErc20BatchApproval(request, account, version, signerOrProvider))) { return approveErc20Batch(request, version, getSigner(signerOrProvider), overrides); } } /** * Checks if the batch proxy has the necessary allowance from a given account * to pay a given request with ERC20 batch * @param request request to pay * @param account account that will be used to pay the request * @param version version of the batch proxy, which can be different from request pn version * @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum. */ export async function hasErc20BatchApproval( request: ClientTypes.IRequestData, account: string, version: string, signerOrProvider: providers.Provider | Signer = getProvider(), ): Promise<boolean> { return checkErc20Allowance( account, getBatchProxyAddress(request, version), signerOrProvider, request.currencyInfo.value, request.expectedAmount, ); } /** * Processes the transaction to approve the batch proxy to spend signer's tokens to pay * the request in its payment currency. Can be used with a Multisig contract. * @param request request to pay * @param version version of the batch proxy, which can be different from request pn version * @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum. * @param overrides optionally, override default transaction values, like gas. */ export async function approveErc20Batch( request: ClientTypes.IRequestData, version: string, signerOrProvider: providers.Provider | Signer = getProvider(), overrides?: ITransactionOverrides, ): Promise<ContractTransaction> { const preparedTx = prepareApproveErc20Batch(request, version, signerOrProvider, overrides); const signer = getSigner(signerOrProvider); const tx = await signer.sendTransaction(preparedTx); return tx; } /** * Prepare the transaction to approve the proxy to spend signer's tokens to pay * the request in its payment currency. Can be used with a Multisig contract. * @param request request to pay * @param version version of the batch proxy, which can be different from request pn version * @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum. * @param overrides optionally, override default transaction values, like gas. */ export function prepareApproveErc20Batch( request: ClientTypes.IRequestData, version: string, signerOrProvider: providers.Provider | Signer = getProvider(), overrides?: ITransactionOverrides, ): IPreparedTransaction { const encodedTx = encodeApproveErc20Batch(request, version, signerOrProvider); const tokenAddress = request.currencyInfo.value; return { data: encodedTx, to: tokenAddress, value: 0, ...overrides, }; } /** * Encodes the transaction to approve the batch proxy to spend signer's tokens to pay * the request in its payment currency. Can be used with a Multisig contract. * @param request request to pay * @param version version of the batch proxy, which can be different from request pn version * @param signerOrProvider the Web3 provider, or signer. Defaults to window.ethereum. */ export function encodeApproveErc20Batch( request: ClientTypes.IRequestData, version: string, signerOrProvider: providers.Provider | Signer = getProvider(), ): string { const proxyAddress = getBatchProxyAddress(request, version); return encodeApproveAnyErc20( request.currencyInfo.value, proxyAddress, getSigner(signerOrProvider), ); }
the_stack
import chai, { expect } from 'chai'; import { BigNumber } from 'ethers'; import { solidity } from 'ethereum-waffle'; import { DRE, advanceBlockTo, advanceBlock, waitForTx, getImpersonatedSigner, evmSnapshot, evmRevert, } from '../helpers/misc-utils'; import { makeSuite, setupTestEnvironment, TestEnv } from './helpers/make-suite'; import { createBridgeTest1, createBridgeTest2, createBridgeTest3, createBridgeTest4, createBridgeTest5, createBridgeTest6, createBridgeTest7, createBridgeTest8, createBridgeTest9, createBridgeTest10, createBridgeTest11, createBridgeTest12, createBridgeTest13, createBridgeTest14, createBridgeTest15, createBridgeTest16, createArbitrumBridgeTest, } from './helpers/bridge-helpers'; import { expectProposalState, createProposal, triggerWhaleVotes, queueProposal, } from './helpers/governance-helpers'; import { PolygonBridgeExecutor__factory } from '../typechain'; import { ZERO_ADDRESS } from '../helpers/constants'; chai.use(solidity); const proposalStates = { PENDING: 0, CANCELED: 1, ACTIVE: 2, FAILED: 3, SUCCEEDED: 4, QUEUED: 5, EXPIRED: 6, EXECUTED: 7, }; makeSuite('Crosschain bridge tests', setupTestEnvironment, (testEnv: TestEnv) => { const proposals: any = []; const dummyAddress = '0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9'; const dummyUint = 10203040; const dummyString = 'Hello'; const overrides = { gasLimit: 5000000 }; let statePriorToCancellation; before(async () => { const { ethers } = DRE; const { BigNumber } = ethers; const { aaveWhale1, aaveWhale2, aaveWhale3, aaveGovContract, shortExecutor, customPolygonMapping, fxRoot, fxChild, polygonBridgeExecutor, } = testEnv; // Authorize new executor const authorizeExecutorTx = await aaveGovContract.authorizeExecutors([shortExecutor.address]); await expect(authorizeExecutorTx).to.emit(aaveGovContract, 'ExecutorAuthorized'); await customPolygonMapping.register(fxRoot.address, fxChild.address); await waitForTx(await fxRoot.setFxChild(fxChild.address)); // Fund Polygon Bridge await waitForTx( await polygonBridgeExecutor.connect(aaveWhale1.signer).receiveFunds({ value: DRE.ethers.BigNumber.from('100000000000000000010'), }) ); /** * Create Proposal Actions 1 * Successful Transactions on PolygonMarketUpdate * -> Action 1 PolygonMarketUpdate.execute(dummyInt) with value of 100 (non-delegate) * -> Action 2 PolygonMarketUpdate.executeWithDelegate(dummyString) with no value, as delegate */ const proposal1Actions = await createBridgeTest1(dummyUint, dummyString, testEnv); testEnv.proposalActions.push(proposal1Actions); /** * Create Proposal Actions 2 - * No signature or data - will fail on execution */ const proposal2Actions = await createBridgeTest2(testEnv); testEnv.proposalActions.push(proposal2Actions); /** * Create Proposal Actions 3 - * Not enough valued in delegate call */ const proposal3Actions = await createBridgeTest3(dummyUint, testEnv); testEnv.proposalActions.push(proposal3Actions); /** * Create Proposal Actions 4 - * Normal Contract Call - used for cancellation */ const proposal4Actions = await createBridgeTest4(dummyUint, testEnv); testEnv.proposalActions.push(proposal4Actions); /** * Create Proposal Actions 5 - * Normal Contract Call - used for expiration */ const proposal5Actions = await createBridgeTest5(dummyUint, testEnv); testEnv.proposalActions.push(proposal5Actions); /** * Create Proposal Actions 6 - * targets[].length = 0 */ const proposal6Actions = await createBridgeTest6(testEnv); testEnv.proposalActions.push(proposal6Actions); /** * Create Proposal Actions 7 - * targets[].length != values[].length */ const proposal7Actions = await createBridgeTest7(testEnv); testEnv.proposalActions.push(proposal7Actions); /** * Create Proposal Actions 8 - * duplicate actions */ const proposal8Actions = await createBridgeTest8(dummyUint, testEnv); testEnv.proposalActions.push(proposal8Actions); /** * Create Proposal Actions 9 - * Update RootSender - PolygonBridgeExecutor */ const proposal9Actions = await createBridgeTest9(aaveWhale2.address, testEnv); testEnv.proposalActions.push(proposal9Actions); /** * Create Proposal Actions 10 - * Update FxChild - PolygonBridgeExecutor */ const proposal10Actions = await createBridgeTest10(aaveWhale3.address, testEnv); testEnv.proposalActions.push(proposal10Actions); /** * Create Proposal Actions 11 - * Update MinimumDelay - PolygonBridgeExecutor */ const proposal11Actions = await createBridgeTest11(1, testEnv); testEnv.proposalActions.push(proposal11Actions); /** * Create Proposal Actions 12 - * Update MinimumDelay - PolygonBridgeExecutor */ const proposal12Actions = await createBridgeTest12(90000, testEnv); testEnv.proposalActions.push(proposal12Actions); /** * Create Proposal Actions 13 - * Update MinimumDelay - PolygonBridgeExecutor */ const proposal13Actions = await createBridgeTest13(2000, testEnv); testEnv.proposalActions.push(proposal13Actions); /** * Create Proposal Actions 14 - * Update MinimumDelay - PolygonBridgeExecutor */ const proposal14Actions = await createBridgeTest14(61, testEnv); testEnv.proposalActions.push(proposal14Actions); /** * Create Proposal Actions 15 - * Fail on Execution - Decode Error Message */ const proposal15Actions = await createBridgeTest15(testEnv); testEnv.proposalActions.push(proposal15Actions); /** * Create Proposal Actions 16 - * update guardian to dummy address */ const proposal16Actions = await createBridgeTest16(dummyAddress, testEnv); testEnv.proposalActions.push(proposal16Actions); /** * Arbitrum -- Create Proposal Actions 16 * Successful Transactions on PolygonMarketUpdate * Update Ethereum Governance Executor in the Arbitrum Governance contract */ const proposal17Actions = await createArbitrumBridgeTest(aaveWhale2.address, testEnv); testEnv.proposalActions.push(proposal17Actions); // Create Polygon Proposals for (let i = 0; i < 16; i++) { proposals[i] = await createProposal( aaveGovContract, aaveWhale1.signer, shortExecutor.address, [fxRoot.address], [BigNumber.from(0)], ['sendMessageToChild(address,bytes)'], [testEnv.proposalActions[i].encodedRootCalldata], [false], '0xf7a1f565fcd7684fba6fea5d77c5e699653e21cb6ae25fbf8c5dbc8d694c7949' ); await expectProposalState(aaveGovContract, proposals[i].id, proposalStates.PENDING); } // Vote on Proposals for (let i = 0; i < 16; i++) { await triggerWhaleVotes( aaveGovContract, [aaveWhale1.signer, aaveWhale2.signer, aaveWhale3.signer], proposals[i].id, true ); await expectProposalState(aaveGovContract, proposals[i].id, proposalStates.ACTIVE); } // Advance Block to End of Voting await advanceBlockTo(proposals[15].endBlock.add(1)); // Queue Proposals await queueProposal(aaveGovContract, proposals[0].id); await queueProposal(aaveGovContract, proposals[1].id); await queueProposal(aaveGovContract, proposals[2].id); await queueProposal(aaveGovContract, proposals[3].id); await queueProposal(aaveGovContract, proposals[4].id); await queueProposal(aaveGovContract, proposals[5].id); await queueProposal(aaveGovContract, proposals[6].id); await queueProposal(aaveGovContract, proposals[7].id); await queueProposal(aaveGovContract, proposals[8].id); await queueProposal(aaveGovContract, proposals[9].id); await queueProposal(aaveGovContract, proposals[10].id); await queueProposal(aaveGovContract, proposals[11].id); await queueProposal(aaveGovContract, proposals[12].id); await queueProposal(aaveGovContract, proposals[13].id); await queueProposal(aaveGovContract, proposals[14].id); const queuedProposal16 = await queueProposal(aaveGovContract, proposals[15].id); await expectProposalState(aaveGovContract, proposals[15].id, proposalStates.QUEUED); // advance to execution const currentBlock = await ethers.provider.getBlock(await ethers.provider.getBlockNumber()); const { timestamp } = currentBlock; const fastForwardTime = queuedProposal16.executionTime.sub(timestamp).toNumber(); await advanceBlock(timestamp + fastForwardTime + 10); }); describe('Executor - Check Deployed State', async function () { it('Check Grace Period', async () => { const { polygonBridgeExecutor } = testEnv; expect(await polygonBridgeExecutor.getGracePeriod()).to.be.equal(BigNumber.from(1000)); }); it('Check Minimum Delay', async () => { const { polygonBridgeExecutor } = testEnv; expect(await polygonBridgeExecutor.getMinimumDelay()).to.be.equal(BigNumber.from(15)); }); it('Check Maximum Delay', async () => { const { polygonBridgeExecutor } = testEnv; expect(await polygonBridgeExecutor.getMaximumDelay()).to.be.equal(BigNumber.from(500)); }); it('Check Guardian', async () => { const { polygonBridgeExecutor, aaveGovOwner } = testEnv; expect(await polygonBridgeExecutor.getGuardian()).to.be.equal(aaveGovOwner.address); }); it('Check ActionSet Count', async () => { const { polygonBridgeExecutor } = testEnv; expect(await polygonBridgeExecutor.getActionsSetCount()).to.be.equal(BigNumber.from(0)); }); it('Check Delay', async () => { const { polygonBridgeExecutor } = testEnv; expect(await polygonBridgeExecutor.getDelay()).to.be.equal(BigNumber.from(60)); }); it('Check isActionQueued', async () => { const { ethers } = DRE; const { polygonBridgeExecutor } = testEnv; const hash = ethers.utils.formatBytes32String('hello'); expect(await polygonBridgeExecutor.isActionQueued(hash)).to.be.false; }); it('Get State of Actions 0 - Actions Queued', async () => { const { polygonBridgeExecutor } = testEnv; await expect(polygonBridgeExecutor.getCurrentState(0)).to.be.revertedWith( 'INVALID_ACTION_ID' ); }); }); describe('Executor - Failed Deployments', async function () { it('Delay > Maximum Delay', async () => { const { shortExecutor, fxChild, aaveGovOwner } = testEnv; const bridgeExecutorFactory = new PolygonBridgeExecutor__factory(aaveGovOwner.signer); await expect( bridgeExecutorFactory.deploy( shortExecutor.address, fxChild.address, BigNumber.from(2000), BigNumber.from(1000), BigNumber.from(15), BigNumber.from(500), aaveGovOwner.address ) ).to.be.revertedWith('DELAY_LONGER_THAN_MAXIMUM'); }); it('Delay < Minimum Delay', async () => { const { shortExecutor, fxChild, aaveGovOwner } = testEnv; const bridgeExecutorFactory = new PolygonBridgeExecutor__factory(aaveGovOwner.signer); await expect( bridgeExecutorFactory.deploy( shortExecutor.address, fxChild.address, BigNumber.from(10), BigNumber.from(1000), BigNumber.from(15), BigNumber.from(500), aaveGovOwner.address ) ).to.be.revertedWith('DELAY_SHORTER_THAN_MINIMUM'); }); }); describe('PolygonBridgeExecutor Authorization', async function () { it('Unauthorized Transaction - Call Bridge Receiver From Non-FxChild Address', async () => { const { shortExecutor, polygonBridgeExecutor } = testEnv; const { encodedActions } = testEnv.proposalActions[0]; await expect( polygonBridgeExecutor.processMessageFromRoot(1, shortExecutor.address, encodedActions) ).to.be.revertedWith('UNAUTHORIZED_CHILD_ORIGIN'); }); it('Unauthorized Transaction - Call Root From Unauthorized Address', async () => { const { fxRoot, polygonBridgeExecutor } = testEnv; const { encodedActions } = testEnv.proposalActions[0]; await expect( fxRoot.sendMessageToChild(polygonBridgeExecutor.address, encodedActions) ).to.be.revertedWith('FAILED_ACTION_EXECUTION_CUSTOM_MAPPING'); }); it('Unauthorized FxRootSender Update - Revert', async () => { const { polygonBridgeExecutor, aaveWhale2 } = testEnv; await expect(polygonBridgeExecutor.updateFxRootSender(aaveWhale2.address)).to.be.revertedWith( 'UNAUTHORIZED_ORIGIN_ONLY_THIS' ); }); it('Unauthorized FxChild Update - Revert', async () => { const { polygonBridgeExecutor, aaveWhale2 } = testEnv; await expect(polygonBridgeExecutor.updateFxChild(aaveWhale2.address)).to.be.revertedWith( 'UNAUTHORIZED_ORIGIN_ONLY_THIS' ); }); it('Unauthorized Guardian Update - Revert', async () => { const { polygonBridgeExecutor } = testEnv; await expect(polygonBridgeExecutor.updateGuardian(ZERO_ADDRESS)).to.be.revertedWith( 'UNAUTHORIZED_ORIGIN_ONLY_THIS' ); }); it('Unauthorized Delay Update - Revert', async () => { const { polygonBridgeExecutor, aaveWhale1 } = testEnv; await expect( polygonBridgeExecutor.connect(aaveWhale1.signer).updateDelay(1000) ).to.be.revertedWith('UNAUTHORIZED_ORIGIN_ONLY_THIS'); }); it('Unauthorized GracePeriod Update - Revert', async () => { const { polygonBridgeExecutor } = testEnv; await expect(polygonBridgeExecutor.updateGracePeriod(1000)).to.be.revertedWith( 'UNAUTHORIZED_ORIGIN_ONLY_THIS' ); }); it('Unauthorized Minimum Delay Update - Revert', async () => { const { polygonBridgeExecutor } = testEnv; await expect(polygonBridgeExecutor.updateMinimumDelay(1)).to.be.revertedWith( 'UNAUTHORIZED_ORIGIN_ONLY_THIS' ); }); it('Unauthorized Maximum Delay Update - Revert', async () => { const { polygonBridgeExecutor } = testEnv; await expect(polygonBridgeExecutor.updateMaximumDelay(100000000)).to.be.revertedWith( 'UNAUTHORIZED_ORIGIN_ONLY_THIS' ); }); }); describe('ArbitrumBridgeExecutor Authorization', async function () { it('Unauthorized Transaction - Call Bridge Receiver From Non-FxChild Address', async () => { const { arbitrumBridgeExecutor } = testEnv; const { targets, values, signatures, calldatas, withDelegatecalls, } = testEnv.proposalActions[0]; await expect( arbitrumBridgeExecutor.queue(targets, values, signatures, calldatas, withDelegatecalls) ).to.be.revertedWith('UNAUTHORIZED_EXECUTOR'); }); it('Unauthorized Update Ethereum Governance Executor - revert', async () => { const { arbitrumBridgeExecutor, aaveWhale1 } = testEnv; await expect( arbitrumBridgeExecutor .connect(aaveWhale1.signer) .updateEthereumGovernanceExecutor(aaveWhale1.address) ).to.be.revertedWith('UNAUTHORIZED_ORIGIN_ONLY_THIS'); }); }); describe('Executor - Validate Delay Logic', async function () { it('Delay > Maximum Delay', async () => { const { polygonBridgeExecutor } = testEnv; const polygonBridgeExecutorSigner = await getImpersonatedSigner( polygonBridgeExecutor.address ); await expect( polygonBridgeExecutor.connect(polygonBridgeExecutorSigner).updateDelay(100000000) ).to.be.revertedWith('DELAY_LONGER_THAN_MAXIMUM'); }); it('Delay < Minimum Delay', async () => { const { polygonBridgeExecutor } = testEnv; const polygonBridgeExecutorSigner = await getImpersonatedSigner( polygonBridgeExecutor.address ); await expect( polygonBridgeExecutor.connect(polygonBridgeExecutorSigner).updateDelay(1) ).to.be.revertedWith('DELAY_SHORTER_THAN_MINIMUM'); }); }); describe('Queue - PolgygonBridgeExecutor through Ethereum Aave Governance', async function () { it('Execute Proposal 1 - successfully queue transaction - expected successful actions', async () => { const { ethers } = DRE; const { aaveGovContract, customPolygonMapping, fxChild, shortExecutor, polygonBridgeExecutor, } = testEnv; const { targets, values, signatures, calldatas, withDelegatecalls, encodedActions, } = testEnv.proposalActions[0]; const encodedSyncData = ethers.utils.defaultAbiCoder.encode( ['address', 'address', 'bytes'], [shortExecutor.address, polygonBridgeExecutor.address, encodedActions] ); const blockNumber = await ethers.provider.getBlockNumber(); const block = await await ethers.provider.getBlock(blockNumber); const blocktime = block.timestamp; const expectedExecutionTime = blocktime + 61; testEnv.proposalActions[0].executionTime = expectedExecutionTime; expect(await aaveGovContract.execute(proposals[0].id, overrides)) .to.emit(customPolygonMapping, 'StateSynced') .withArgs(1, fxChild.address, encodedSyncData) .to.emit(fxChild, 'NewFxMessage') .withArgs(shortExecutor.address, polygonBridgeExecutor.address, encodedActions) .to.emit(polygonBridgeExecutor, 'ActionsSetQueued') .withArgs( 0, targets, values, signatures, calldatas, withDelegatecalls, expectedExecutionTime ) .to.emit(shortExecutor, 'ExecutedAction') .to.emit(aaveGovContract, 'ProposalExecuted'); expect(await polygonBridgeExecutor.getActionsSetCount()).to.be.equal(BigNumber.from(1)); }); it('Execute Proposal 2 - successfully queue transaction - actions fail on execution (failed transaction)', async () => { const { ethers } = DRE; const { aaveGovContract, customPolygonMapping, fxChild, polygonBridgeExecutor, shortExecutor, } = testEnv; const { targets, values, signatures, calldatas, withDelegatecalls, } = testEnv.proposalActions[1]; const blockNumber = await ethers.provider.getBlockNumber(); const block = await await ethers.provider.getBlock(blockNumber); const blocktime = block.timestamp; const expectedExecutionTime = blocktime + 61; testEnv.proposalActions[1].executionTime = expectedExecutionTime; await expect(aaveGovContract.execute(proposals[1].id, overrides)) .to.emit(customPolygonMapping, 'StateSynced') .to.emit(fxChild, 'NewFxMessage') .to.emit(polygonBridgeExecutor, 'ActionsSetQueued') .withArgs( 1, targets, values, signatures, calldatas, withDelegatecalls, expectedExecutionTime ) .to.emit(shortExecutor, 'ExecutedAction') .to.emit(aaveGovContract, 'ProposalExecuted'); }); it('Execute Proposal 3 - successfully queue transaction - actions fail on execution (not enough value)', async () => { const { aaveGovContract, customPolygonMapping, fxChild, polygonBridgeExecutor, shortExecutor, } = testEnv; await expect(aaveGovContract.execute(proposals[2].id, overrides)) .to.emit(customPolygonMapping, 'StateSynced') .to.emit(fxChild, 'NewFxMessage') .to.emit(polygonBridgeExecutor, 'ActionsSetQueued') .to.emit(shortExecutor, 'ExecutedAction') .to.emit(aaveGovContract, 'ProposalExecuted'); }); it('Execute Proposal 4 - successfully queue transaction - actions used for cancellation', async () => { const { ethers } = DRE; const { aaveGovContract, customPolygonMapping, fxChild, polygonBridgeExecutor, shortExecutor, } = testEnv; const blockNumber = await ethers.provider.getBlockNumber(); const block = await await ethers.provider.getBlock(blockNumber); const blocktime = block.timestamp; const expectedExecutionTime = blocktime + 61; testEnv.proposalActions[3].executionTime = expectedExecutionTime; await expect(aaveGovContract.execute(proposals[3].id, overrides)) .to.emit(customPolygonMapping, 'StateSynced') .to.emit(fxChild, 'NewFxMessage') .to.emit(polygonBridgeExecutor, 'ActionsSetQueued') .to.emit(shortExecutor, 'ExecutedAction') .to.emit(aaveGovContract, 'ProposalExecuted'); }); it('Execute Proposal 5 - successfully queue transaction - actions used for expiration', async () => { const { aaveGovContract, customPolygonMapping, fxChild, polygonBridgeExecutor, shortExecutor, } = testEnv; await expect(aaveGovContract.execute(proposals[4].id, overrides)) .to.emit(customPolygonMapping, 'StateSynced') .to.emit(fxChild, 'NewFxMessage') .to.emit(polygonBridgeExecutor, 'ActionsSetQueued') .to.emit(shortExecutor, 'ExecutedAction') .to.emit(aaveGovContract, 'ProposalExecuted'); }); it('Execute Proposal 6 - polygon gov error - no targets in polygon actions', async () => { const { aaveGovContract } = testEnv; await expect(aaveGovContract.execute(proposals[5].id)).to.be.revertedWith( 'FAILED_ACTION_EXECUTION' ); }); it('Execute Proposal 7 - polygon gov error - targets[].length < values[].length in polygon actions', async () => { const { aaveGovContract } = testEnv; await expect(aaveGovContract.execute(proposals[6].id)).to.be.revertedWith( 'FAILED_ACTION_EXECUTION' ); }); it('Execute Proposal 8 - polygon gov error - duplicate polygon actions', async () => { const { aaveGovContract } = testEnv; await expect(aaveGovContract.execute(proposals[7].id)).to.be.revertedWith( 'FAILED_ACTION_EXECUTION' ); }); it('Execute Proposal 9 - successfully queue transaction - fx root sender update', async () => { const { aaveGovContract, customPolygonMapping, fxChild, polygonBridgeExecutor, shortExecutor, } = testEnv; await expect(aaveGovContract.execute(proposals[8].id, overrides)) .to.emit(customPolygonMapping, 'StateSynced') .to.emit(fxChild, 'NewFxMessage') .to.emit(polygonBridgeExecutor, 'ActionsSetQueued') .to.emit(shortExecutor, 'ExecutedAction') .to.emit(aaveGovContract, 'ProposalExecuted'); }); it('Execute Proposal 10 - successfully queue transaction - fx child update', async () => { const { aaveGovContract, customPolygonMapping, fxChild, polygonBridgeExecutor, shortExecutor, } = testEnv; await expect(aaveGovContract.execute(proposals[9].id, overrides)) .to.emit(customPolygonMapping, 'StateSynced') .to.emit(fxChild, 'NewFxMessage') .to.emit(polygonBridgeExecutor, 'ActionsSetQueued') .to.emit(shortExecutor, 'ExecutedAction') .to.emit(aaveGovContract, 'ProposalExecuted'); }); it('Execute Proposal 11 - successfully queue transaction - min delay update', async () => { const { aaveGovContract, customPolygonMapping, fxChild, polygonBridgeExecutor, shortExecutor, } = testEnv; await expect(aaveGovContract.execute(proposals[10].id, overrides)) .to.emit(customPolygonMapping, 'StateSynced') .to.emit(fxChild, 'NewFxMessage') .to.emit(polygonBridgeExecutor, 'ActionsSetQueued') .to.emit(shortExecutor, 'ExecutedAction') .to.emit(aaveGovContract, 'ProposalExecuted'); }); it('Execute Proposal 12 - successfully queue transaction - max delay update', async () => { const { aaveGovContract, customPolygonMapping, fxChild, polygonBridgeExecutor, shortExecutor, } = testEnv; await expect(aaveGovContract.execute(proposals[11].id, overrides)) .to.emit(customPolygonMapping, 'StateSynced') .to.emit(fxChild, 'NewFxMessage') .to.emit(polygonBridgeExecutor, 'ActionsSetQueued') .to.emit(shortExecutor, 'ExecutedAction') .to.emit(aaveGovContract, 'ProposalExecuted'); }); it('Execute Proposal 13 - successfully queue transaction - gracePeriod update', async () => { const { aaveGovContract, customPolygonMapping, fxChild, polygonBridgeExecutor, shortExecutor, } = testEnv; await expect(aaveGovContract.execute(proposals[12].id, overrides)) .to.emit(customPolygonMapping, 'StateSynced') .to.emit(fxChild, 'NewFxMessage') .to.emit(polygonBridgeExecutor, 'ActionsSetQueued') .to.emit(shortExecutor, 'ExecutedAction') .to.emit(aaveGovContract, 'ProposalExecuted'); }); it('Execute Proposal 14 - successfully queue transaction - delay update', async () => { const { aaveGovContract, customPolygonMapping, fxChild, polygonBridgeExecutor, shortExecutor, } = testEnv; await expect(aaveGovContract.execute(proposals[13].id, overrides)) .to.emit(customPolygonMapping, 'StateSynced') .to.emit(fxChild, 'NewFxMessage') .to.emit(polygonBridgeExecutor, 'ActionsSetQueued') .to.emit(shortExecutor, 'ExecutedAction') .to.emit(aaveGovContract, 'ProposalExecuted'); }); it('Execute Proposal 15 - successfully queue transaction - fail on execution with error', async () => { const { aaveGovContract, customPolygonMapping, fxChild, polygonBridgeExecutor, shortExecutor, } = testEnv; await expect(aaveGovContract.execute(proposals[14].id, overrides)) .to.emit(customPolygonMapping, 'StateSynced') .to.emit(fxChild, 'NewFxMessage') .to.emit(polygonBridgeExecutor, 'ActionsSetQueued') .to.emit(shortExecutor, 'ExecutedAction') .to.emit(aaveGovContract, 'ProposalExecuted'); }); it('Execute Proposal 16 - successfully queue transaction - update guardian', async () => { const { aaveGovContract, customPolygonMapping, fxChild, polygonBridgeExecutor, shortExecutor, } = testEnv; await expect(aaveGovContract.execute(proposals[15].id, overrides)) .to.emit(customPolygonMapping, 'StateSynced') .to.emit(fxChild, 'NewFxMessage') .to.emit(polygonBridgeExecutor, 'ActionsSetQueued') .to.emit(shortExecutor, 'ExecutedAction') .to.emit(aaveGovContract, 'ProposalExecuted'); }); }); describe('Queue - ArbitrumBridgeExecutor through Ethereum Aave Governance', async function () { it('Execute Proposal 17 - successfully queue Arbitrum transaction - duplicate polygon actions', async () => { const { ethers } = DRE; const { shortExecutor, arbitrumBridgeExecutor, aaveWhale1 } = testEnv; const { targets, values, signatures, calldatas, withDelegatecalls, } = testEnv.proposalActions[16]; const blockNumber = await ethers.provider.getBlockNumber(); const block = await await ethers.provider.getBlock(blockNumber); const blocktime = block.timestamp; const expectedExecutionTime = blocktime + 61; await aaveWhale1.signer.sendTransaction({ to: shortExecutor.address, value: BigNumber.from('1000000000000000000'), }); testEnv.proposalActions[16].executionTime = expectedExecutionTime; const shortExecutorSigner = await getImpersonatedSigner(shortExecutor.address); const tx = await arbitrumBridgeExecutor .connect(shortExecutorSigner) .queue(targets, values, signatures, calldatas, withDelegatecalls); const txReceipt = await tx.wait(); const parsedLog = arbitrumBridgeExecutor.interface.parseLog(txReceipt.logs[0]); expect(parsedLog.args.targets).to.be.eql(targets); expect(parsedLog.args[2]).to.be.eql(values); expect(parsedLog.args.signatures).to.be.eql(signatures); expect(parsedLog.args.calldatas).to.be.eql(calldatas); expect(parsedLog.args.withDelegatecalls).to.be.eql(withDelegatecalls); }); }); describe('Confirm ActionSet State - Bridge Executor', async function () { it('Confirm ActionsSet 0 State', async () => { const { polygonBridgeExecutor } = testEnv; const { targets, values, signatures, calldatas, withDelegatecalls, executionTime, } = testEnv.proposalActions[0]; const actionsSet = await polygonBridgeExecutor.getActionsSetById(0); expect(actionsSet.targets).to.be.eql(targets); // work around - actionsSet[1] == actionsSet.values expect(actionsSet[1]).to.be.eql(values); expect(actionsSet.signatures).to.be.eql(signatures); expect(actionsSet.calldatas).to.be.eql(calldatas); expect(actionsSet.withDelegatecalls).to.be.eql(withDelegatecalls); expect(actionsSet.executionTime).to.be.equal(executionTime); expect(actionsSet.executed).to.be.false; expect(actionsSet.canceled).to.be.false; }); it('Confirm ActionsSet 1 State', async () => { const { polygonBridgeExecutor } = testEnv; const { targets, values, signatures, calldatas, withDelegatecalls, executionTime, } = testEnv.proposalActions[1]; const actionsSet = await polygonBridgeExecutor.getActionsSetById(1); expect(actionsSet.targets).to.be.eql(targets); // work around - actionsSet[1] == actionsSet.values expect(actionsSet[1]).to.be.eql(values); expect(actionsSet.signatures).to.be.eql(signatures); expect(actionsSet.calldatas).to.be.eql(calldatas); expect(actionsSet.withDelegatecalls).to.be.eql(withDelegatecalls); expect(actionsSet.executionTime).to.be.equal(executionTime); expect(actionsSet.executed).to.be.false; expect(actionsSet.canceled).to.be.false; }); }); describe('Execute Action Sets - Aave Polygon Governance', async function () { it('Get State of Actions 0 - Actions Queued', async () => { const { polygonBridgeExecutor } = testEnv; await expect(await polygonBridgeExecutor.getCurrentState(0)).to.be.eq(0); }); it('Execute Action Set 0 - polygon gov error - timelock not finished', async () => { const { polygonBridgeExecutor } = testEnv; await expect(polygonBridgeExecutor.execute(0)).to.revertedWith('TIMELOCK_NOT_FINISHED'); }); it('Execute Action Set 0 - execution successful', async () => { const { ethers } = DRE; const { polygonBridgeExecutor, polygonMarketUpdate, aaveGovOwner } = testEnv; const { values } = testEnv.proposalActions[0]; const blocktime = (await ethers.provider.getBlock(await ethers.provider.getBlockNumber())) .timestamp; await advanceBlock(blocktime + 100); const encodedInteger = ethers.utils.defaultAbiCoder.encode(['uint256'], [dummyUint]); const tx = await polygonBridgeExecutor.execute(0); await expect(tx) .to.emit(polygonMarketUpdate, 'UpdateExecuted') .withArgs(1, dummyUint, dummyAddress, values[0]) .to.emit(polygonBridgeExecutor, 'ActionsSetExecuted') .withArgs(0, aaveGovOwner.address, [encodedInteger, '0x']); const transactionReceipt = await tx.wait(); const delegateLog = polygonMarketUpdate.interface.parseLog(transactionReceipt.logs[1]); expect(ethers.utils.parseBytes32String(delegateLog.args.testBytes)).to.equal(dummyString); expect(delegateLog.args.sender).to.equal(polygonBridgeExecutor.address); }); it('Get State of Action Set 0 - Actions Executed', async () => { const { polygonBridgeExecutor } = testEnv; await expect(await polygonBridgeExecutor.getCurrentState(0)).to.be.eq(1); }); it('Execute Action Set 100 - polygon gov error - invalid actions id', async () => { const { polygonBridgeExecutor } = testEnv; await expect(polygonBridgeExecutor.execute(100)).to.revertedWith('INVALID_ACTION_ID'); }); it('Execute Action Set 1 - polygon gov error - failing action', async () => { const { polygonBridgeExecutor } = testEnv; await expect(polygonBridgeExecutor.execute(1)).to.revertedWith('FAILED_ACTION_EXECUTION'); }); it('Execute Action Set 2 - polygon gov error - not enough msg value', async () => { const { polygonBridgeExecutor } = testEnv; await expect(polygonBridgeExecutor.execute(2)).to.revertedWith('NOT_ENOUGH_CONTRACT_BALANCE'); }); it('Execute Action Set 5 - updateFxRootSender', async () => { const { polygonBridgeExecutor, shortExecutor, aaveWhale2 } = testEnv; await expect(polygonBridgeExecutor.execute(5)) .to.emit(polygonBridgeExecutor, 'FxRootSenderUpdate') .withArgs( DRE.ethers.utils.getAddress(shortExecutor.address), DRE.ethers.utils.getAddress(aaveWhale2.address) ); }); it('Execute Action Set 6 - updateFxChild', async () => { const { polygonBridgeExecutor, fxChild, aaveWhale3 } = testEnv; await expect(polygonBridgeExecutor.execute(6)) .to.emit(polygonBridgeExecutor, 'FxChildUpdate') .withArgs( DRE.ethers.utils.getAddress(fxChild.address), DRE.ethers.utils.getAddress(aaveWhale3.address) ); }); it('Execute Action Set 7 - updateMinDelay', async () => { const { polygonBridgeExecutor } = testEnv; await expect(polygonBridgeExecutor.execute(7)) .to.emit(polygonBridgeExecutor, 'MinimumDelayUpdate') .withArgs(15, 1); }); it('Execute Action Set 8 - updateMaxDelay', async () => { const { polygonBridgeExecutor } = testEnv; await expect(polygonBridgeExecutor.execute(8)) .to.emit(polygonBridgeExecutor, 'MaximumDelayUpdate') .withArgs(500, 90000); }); it('Execute Action Set 9 - updateGracePeriod', async () => { const { polygonBridgeExecutor } = testEnv; await expect(polygonBridgeExecutor.execute(9)) .to.emit(polygonBridgeExecutor, 'GracePeriodUpdate') .withArgs(1000, 2000); }); it('Execute Action Set 10 - updateDelay', async () => { const { polygonBridgeExecutor } = testEnv; await expect(polygonBridgeExecutor.execute(10)) .to.emit(polygonBridgeExecutor, 'DelayUpdate') .withArgs(60, 61); }); it('Execute Action Set 11 - revert with error', async () => { const { polygonBridgeExecutor } = testEnv; await expect(polygonBridgeExecutor.execute(11)).to.be.revertedWith('THIS_ALWAYS_FAILS'); }); }); describe('Execute Action Sets - Aave Arbitrum Governance', async function () { it('Execute Action Set 0 - update ethereum governance executor', async () => { const { arbitrumBridgeExecutor, shortExecutor, aaveWhale2 } = testEnv; await expect(arbitrumBridgeExecutor.execute(0)) .to.emit(arbitrumBridgeExecutor, 'EthereumGovernanceExecutorUpdate') .withArgs( DRE.ethers.utils.getAddress(shortExecutor.address), DRE.ethers.utils.getAddress(aaveWhale2.address) ); }); }); describe('PolygonBridgeExecutor Getters - FxRootSender, FxChild', async function () { it('Get FxRootSender', async () => { const { polygonBridgeExecutor, aaveWhale2 } = testEnv; expect(await polygonBridgeExecutor.getFxRootSender()).to.be.equal( DRE.ethers.utils.getAddress(aaveWhale2.address) ); }); it('Get FxChild', async () => { const { polygonBridgeExecutor, aaveWhale3 } = testEnv; expect(await polygonBridgeExecutor.getFxChild()).to.be.equal( DRE.ethers.utils.getAddress(aaveWhale3.address) ); }); }); describe('ArbitrumBridgeExecutor Getters - EthereumGovernanceExecutor', async function () { it('Get EthereumGovernanceExecutor', async () => { const { arbitrumBridgeExecutor, aaveWhale2 } = testEnv; expect(await arbitrumBridgeExecutor.getEthereumGovernanceExecutor()).to.be.equal( DRE.ethers.utils.getAddress(aaveWhale2.address) ); }); }); describe('Cancel Actions - Aave Polygon Governance', async function () { it('Set Pre-Cancellation Snapshot', async () => { statePriorToCancellation = await evmSnapshot(); }); it('Get State of Action Set 2 - Action Set Queued', async () => { const { polygonBridgeExecutor } = testEnv; await expect(await polygonBridgeExecutor.getCurrentState(3)).to.be.eq(0); }); it('Cancel Action Set 2 - polygon gov error - only guardian', async () => { const { polygonBridgeExecutor, aaveWhale1 } = testEnv; await expect(polygonBridgeExecutor.connect(aaveWhale1.signer).cancel(3)).to.be.revertedWith( 'ONLY_BY_GUARDIAN' ); }); it('Cancel Action Set 0 - polygon gov error - only before executed', async () => { const { polygonBridgeExecutor } = testEnv; await expect(polygonBridgeExecutor.cancel(0)).to.be.revertedWith('ONLY_BEFORE_EXECUTED'); }); it('Cancel Action Set 2 - successful cancellation', async () => { const { polygonBridgeExecutor, aaveGovOwner } = testEnv; await expect(polygonBridgeExecutor.connect(aaveGovOwner.signer).cancel(3)) .to.emit(polygonBridgeExecutor, 'ActionsSetCanceled') .withArgs(3); }); it('Get State of Action Set 2 - Actions Canceled', async () => { const { polygonBridgeExecutor } = testEnv; await expect(await polygonBridgeExecutor.getCurrentState(3)).to.be.eq(2); }); }); describe('Update Guardian', async function () { it('Revert to Pre-Cancellation Snapshot', async () => { await evmRevert(statePriorToCancellation); }); it('Execute Action to Update Guardian', async () => { const { polygonBridgeExecutor, aaveGovOwner } = testEnv; await expect(polygonBridgeExecutor.execute(12)) .to.emit(polygonBridgeExecutor, 'GuardianUpdate') .withArgs(aaveGovOwner.address, dummyAddress); }); it('Check guardian getter', async () => { const { polygonBridgeExecutor } = testEnv; expect(await polygonBridgeExecutor.getGuardian()).to.be.equal(dummyAddress); }); it('Get State of Action Set 2 - Action Set Queued', async () => { const { polygonBridgeExecutor } = testEnv; await expect(await polygonBridgeExecutor.getCurrentState(3)).to.be.eq(0); }); it('Cancel Action Set 2 - polygon gov error - only guardian', async () => { const { polygonBridgeExecutor, aaveGovOwner } = testEnv; await expect(polygonBridgeExecutor.connect(aaveGovOwner.signer).cancel(3)).to.be.revertedWith( 'ONLY_BY_GUARDIAN' ); }); it('Cancel Action Set 2 - successful cancellation', async () => { const { polygonBridgeExecutor } = testEnv; const dummySigner = await getImpersonatedSigner(dummyAddress); await DRE.network.provider.send('hardhat_setBalance', [ dummyAddress, '0xFFFFFFFFFFFFFFFFFFFFF', ]); await expect(polygonBridgeExecutor.connect(dummySigner).cancel(3)) .to.emit(polygonBridgeExecutor, 'ActionsSetCanceled') .withArgs(3); }); }); describe('Expired Actions - Aave Polygon Governance', async function () { it('Get State of Action Set 3 - Actions Queued', async () => { const { polygonBridgeExecutor } = testEnv; await expect(await polygonBridgeExecutor.getCurrentState(4)).to.be.eq(0); }); it('Execute Actions 3 - polygon gov error - expired action', async () => { const { ethers } = DRE; const { polygonBridgeExecutor } = testEnv; const blocktime = (await ethers.provider.getBlock(await ethers.provider.getBlockNumber())) .timestamp; await advanceBlock(blocktime + 100000); await expect(polygonBridgeExecutor.execute(4)).to.revertedWith('ONLY_QUEUED_ACTIONS'); }); it('Get State of Actions 3 - Actions Expired', async () => { const { polygonBridgeExecutor } = testEnv; await expect(await polygonBridgeExecutor.getCurrentState(4)).to.be.eq(3); }); }); });
the_stack
import { useMutation, useQuery } from '@apollo/client'; import { FormControl, FormControlLabel, Radio, RadioGroup, Typography, } from '@material-ui/core'; import { ButtonFilled, ButtonOutlined, InputField, Modal } from 'litmus-ui'; import React, { useEffect, useState } from 'react'; import { useTranslation } from 'react-i18next'; import GithubInputFields from '../../../components/GitHubComponents/GithubInputFields/GithubInputFields'; import Loader from '../../../components/Loader'; import { DISABLE_GITOPS, ENABLE_GITOPS, GENERATE_SSH, UPDATE_GITOPS, } from '../../../graphql/mutations'; import { GET_GITOPS_DATA } from '../../../graphql/queries'; import { GitOpsDetail } from '../../../models/graphql/gitOps'; import { MyHubType, SSHKey, SSHKeys } from '../../../models/graphql/user'; import { getProjectID } from '../../../utils/getSearchParams'; import { validateStartEmptySpacing } from '../../../utils/validate'; import GitOpsInfo from './gitOpsInfo'; import SSHField from './sshField'; import useStyles from './styles'; interface GitHub { GitURL: string; GitBranch: string; } interface GitOpsResult { type: string; message: string; } const GitOpsTab = () => { const classes = useStyles(); const [value, setValue] = React.useState('disabled'); const projectID = getProjectID(); const { t } = useTranslation(); // Local State Variables for Github Data and GitOps result data const [gitHub, setGitHub] = useState<GitHub>({ GitURL: '', GitBranch: '', }); const [gitopsResult, setGitOpsResult] = useState<GitOpsResult>({ type: '', message: '', }); const [isOpen, setIsOpen] = useState(false); const [sshKey, setSshKey] = useState<SSHKey>({ privateKey: '', publicKey: '', }); const [accessToken, setAccessToken] = useState(''); const [confirmModal, setConfirmModal] = useState(false); // State Variable for AuthType Radio Buttons const [privateHub, setPrivateHub] = useState('token'); const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { setValue((event.target as HTMLInputElement).value); }; // Functions to handle the events const handleGitURL = ( event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement> ) => { setGitHub({ GitURL: event.target.value, GitBranch: gitHub.GitBranch, }); }; const handleGitBranch = ( event: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement> ) => { setGitHub({ GitURL: gitHub.GitURL, GitBranch: event.target.value, }); }; // Query to fetch GitOps Data const { data, refetch, loading } = useQuery<GitOpsDetail>(GET_GITOPS_DATA, { variables: { data: projectID }, fetchPolicy: 'cache-and-network', }); // Mutation to generate SSH key const [generateSSHKey, { loading: sshLoading }] = useMutation<SSHKeys>( GENERATE_SSH, { onCompleted: (data) => { setSshKey({ privateKey: data.generaterSSHKey.privateKey, publicKey: data.generaterSSHKey.publicKey, }); }, } ); const [copying, setCopying] = useState(false); // State variable to check if gitops is enable or not (required for edit gitops) const [isGitOpsEnabled, setIsGitOpsEnabled] = useState(false); // Function to copy the SSH key const copyTextToClipboard = (text: string) => { if (!navigator.clipboard) { console.error('Oops Could not copy text: '); return; } setCopying(true); navigator.clipboard .writeText(text) .catch((err) => console.error('Async: Could not copy text: ', err)); setTimeout(() => setCopying(false), 3000); }; // Mutation to enable GitOps const [enableGitOps, { loading: gitOpsLoader }] = useMutation(ENABLE_GITOPS, { onError: (data) => { setIsOpen(true); setGitOpsResult({ type: 'fail', message: data.message, }); }, onCompleted: () => { setIsOpen(true); setGitOpsResult({ type: 'success', message: 'Successfully enabled GitOps!', }); setIsGitOpsEnabled(true); }, }); // Mutation to enable GitOps const [updateGitOps, { loading: updateGitOpsLoader }] = useMutation( UPDATE_GITOPS, { onError: (data) => { setIsOpen(true); setGitOpsResult({ type: 'fail', message: data.message, }); }, onCompleted: () => { setIsOpen(true); setGitOpsResult({ type: 'success', message: 'Successfully updated GitOps!', }); setIsGitOpsEnabled(true); }, } ); // Mutation to disable GitOps const [disableGitOps, { loading: disableGitOpsLoader }] = useMutation( DISABLE_GITOPS, { onError: (data) => { setIsOpen(true); setGitOpsResult({ type: 'fail', message: data.message, }); }, onCompleted: () => { setIsOpen(true); setGitHub({ GitBranch: '', GitURL: '', }); setSshKey({ publicKey: '', privateKey: '', }); setGitOpsResult({ type: 'success', message: 'Successfully disabled GitOps!', }); }, } ); const handleClose = () => { setIsOpen(false); refetch(); }; const onEditClicked = () => { setConfirmModal(true); }; const onConfirmEdit = () => { setIsGitOpsEnabled(false); setGitHub({ GitURL: data?.getGitOpsDetails.RepoURL || '', GitBranch: data?.getGitOpsDetails.Branch || '', }); setPrivateHub(''); setAccessToken(''); setSshKey({ publicKey: '', privateKey: '', }); setConfirmModal(false); }; const onCancelEdit = () => { setConfirmModal(false); }; // UseEffect to set the initial state of radio-buttons useEffect(() => { if (data !== undefined) { if (data.getGitOpsDetails.Enabled) { setValue('enabled'); setIsGitOpsEnabled(true); } else { setValue('disabled'); setIsGitOpsEnabled(false); } } }, [data]); // Handle submit button to call the enableGitOps mutation const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => { event.preventDefault(); if (value === 'enabled') { if (data?.getGitOpsDetails.Enabled === false) { enableGitOps({ variables: { gitConfig: { ProjectID: projectID, RepoURL: gitHub.GitURL, Branch: gitHub.GitBranch, AuthType: privateHub === 'token' ? MyHubType.token : privateHub === 'ssh' ? MyHubType.ssh : MyHubType.none, Token: accessToken, UserName: 'user', Password: 'user', SSHPrivateKey: sshKey.privateKey, }, }, }); } if (data?.getGitOpsDetails.Enabled === true) { updateGitOps({ variables: { gitConfig: { ProjectID: projectID, RepoURL: gitHub.GitURL, Branch: gitHub.GitBranch, AuthType: privateHub === '' ? data?.getGitOpsDetails.AuthType : privateHub === 'token' ? MyHubType.token : privateHub === 'ssh' ? MyHubType.ssh : MyHubType.none, Token: privateHub === '' ? data?.getGitOpsDetails.Token : accessToken, UserName: 'user', Password: 'user', SSHPrivateKey: privateHub === '' ? data?.getGitOpsDetails.SSHPrivateKey : sshKey.privateKey, }, }, }); } } }; return ( <div className={classes.container}> {loading ? ( <Loader /> ) : ( <> <Typography className={classes.headerText}> <strong>{t('settings.gitopsTab.choose')} </strong> </Typography> <form id="login-form" autoComplete="on" onSubmit={handleSubmit}> <FormControl component="fieldset" style={{ width: '70%' }}> <RadioGroup name="gitops" value={value} onChange={handleChange}> <div className={classes.mainRadioDiv}> <FormControlLabel value="disabled" control={ <Radio classes={{ root: classes.radio, checked: classes.checked, }} /> } data-cy="localRadioButton" label={ <Typography className={classes.locallyText}> {t('settings.gitopsTab.locally')} </Typography> } /> {value === 'disabled' && data?.getGitOpsDetails.Enabled === true ? ( <div> <Typography className={classes.disconnectText}> {t('settings.gitopsTab.disconnect')} </Typography> <ButtonFilled data-cy="disableGitopsButton" disabled={disableGitOpsLoader} onClick={() => disableGitOps({ variables: { data: projectID, }, }) } > {t('settings.gitopsTab.save')} </ButtonFilled> </div> ) : null} </div> <div className={classes.enabledText}> <div> <FormControlLabel value="enabled" control={ <Radio classes={{ root: classes.radio, checked: classes.checked, }} /> } data-cy="gitopsRadioButton" label={ <Typography style={{ fontSize: '20px' }}> {t('settings.gitopsTab.repo')} </Typography> } /> {isGitOpsEnabled === false ? ( <div> <Typography className={classes.infoText}> {t('settings.gitopsTab.desc')} </Typography> {value === 'enabled' ? ( <div className={classes.mainPrivateRepo}> <div className={classes.privateToggleDiv}> <div className={classes.privateRepoDetails}> <GithubInputFields gitURL={gitHub.GitURL} gitBranch={gitHub.GitBranch} setGitURL={handleGitURL} setGitBranch={handleGitBranch} /> </div> <FormControl component="fieldset" className={classes.formControl} > <RadioGroup aria-label="privateHub" name="privateHub" value={privateHub} onChange={(e) => { if (e.target.value === 'ssh') { generateSSHKey(); } if (e.target.value === 'token') { setSshKey({ privateKey: '', publicKey: '', }); } setPrivateHub(e.target.value); }} > <FormControlLabel value="token" control={ <Radio classes={{ root: classes.radio, checked: classes.checked, }} /> } data-cy="accessTokenRadioButton" label={ <Typography> {t('myhub.connectHubPage.accessToken')} </Typography> } /> {privateHub === 'token' ? ( <InputField data-cy="accessTokenInput" label="Access Token" value={accessToken} helperText={ validateStartEmptySpacing(accessToken) ? t('myhub.validationEmptySpace') : '' } variant={ validateStartEmptySpacing(accessToken) ? 'error' : 'primary' } onChange={(e) => setAccessToken(e.target.value) } /> ) : null} <FormControlLabel className={classes.sshRadioBtn} data-cy="sshKeyRadioButton" value="ssh" control={ <Radio classes={{ root: classes.radio, checked: classes.checked, }} /> } label={ <Typography> {t('myhub.connectHubPage.ssh')} </Typography> } /> {privateHub === 'ssh' ? ( <SSHField sshLoading={sshLoading} copying={copying} publicKey={sshKey.publicKey} copyPublicKey={copyTextToClipboard} /> ) : null} <div className={classes.submitBtnDiv} data-cy="connectButton" > <ButtonFilled type="submit" disabled={ gitOpsLoader || updateGitOpsLoader } > {updateGitOpsLoader || gitOpsLoader ? ( <Loader size={20} /> ) : ( <Typography> {data?.getGitOpsDetails.Enabled ? 'Update' : t('settings.gitopsTab.connect')} </Typography> )} </ButtonFilled> </div> </RadioGroup> </FormControl> </div> </div> ) : null} </div> ) : isGitOpsEnabled === true ? ( <GitOpsInfo data={data} onEditClicked={onEditClicked} modalState={confirmModal} onModalClick={onConfirmEdit} onModalCancel={onCancelEdit} /> ) : null} </div> <img src="./icons/gitops-image.svg" alt="Gitops" style={{ marginLeft: 'auto', paddingLeft: 20 }} /> </div> </RadioGroup> </FormControl> </form> <Modal data-cy="gitopsModal" open={isOpen} onClose={handleClose} modalActions={ <ButtonOutlined onClick={handleClose}>&#x2715;</ButtonOutlined> } > <div className={classes.modalDiv}> <div> {gitopsResult.type === 'fail' ? ( <div> <img src="./icons/red-cross.svg" alt="checkmark" className={classes.checkImg} /> <Typography gutterBottom className={classes.modalHeading}> <strong>Error: {gitopsResult.message}</strong> </Typography> <ButtonFilled onClick={handleClose} data-cy="closeButton"> {t('settings.gitopsTab.setting')} </ButtonFilled> </div> ) : null} <div> {gitopsResult.type === 'success' ? ( <> <img src="./icons/checkmark.svg" alt="checkmark" className={classes.checkImg} /> <Typography gutterBottom className={classes.modalHeading}> {gitopsResult.message} </Typography> <ButtonFilled onClick={handleClose} data-cy="closeButton"> {t('settings.gitopsTab.setting')} </ButtonFilled> </> ) : null} </div> </div> </div> </Modal> </> )} </div> ); }; export default GitOpsTab;
the_stack
import * as vscode from "vscode"; import assert from "assert"; import { EmacsEmulator } from "../../../emulator"; import { assertTextEqual, cleanUpWorkspace, setEmptyCursors, assertCursorsEqual, setupWorkspace, assertSelectionsEqual, } from "../utils"; import { KillRing } from "../../../kill-yank/kill-ring"; import { Minibuffer } from "src/minibuffer"; suite("Kill, copy, and yank rectangle", () => { let activeTextEditor: vscode.TextEditor; let emulator: EmacsEmulator; const initialText = `0123456789 abcdefghij ABCDEFGHIJ klmnopqrst KLMNOPQRST`; setup(async () => { activeTextEditor = await setupWorkspace(initialText); emulator = new EmacsEmulator(activeTextEditor); }); teardown(cleanUpWorkspace); test("nothing happens when the selection is empty", async () => { setEmptyCursors(activeTextEditor, [1, 5]); await emulator.runCommand("killRectangle"); assertTextEqual(activeTextEditor, initialText); assertCursorsEqual(activeTextEditor, [1, 5]); }); test("nothing happens when the selections are empty", async () => { setEmptyCursors(activeTextEditor, [1, 5], [2, 7]); await emulator.runCommand("killRectangle"); assertTextEqual(activeTextEditor, initialText); assertCursorsEqual(activeTextEditor, [1, 5], [2, 7]); }); test("killing and yanking a rectangle", async () => { activeTextEditor.selections = [new vscode.Selection(0, 3, 2, 7)]; await emulator.runCommand("killRectangle"); assertTextEqual( activeTextEditor, `012789 abchij ABCHIJ klmnopqrst KLMNOPQRST` ); assertCursorsEqual(activeTextEditor, [2, 3]); setEmptyCursors(activeTextEditor, [0, 0]); await emulator.runCommand("yankRectangle"); assertTextEqual( activeTextEditor, `3456012789 defgabchij DEFGABCHIJ klmnopqrst KLMNOPQRST` ); // Yank on an out-of-range area setEmptyCursors(activeTextEditor, [4, 5]); await emulator.runCommand("yankRectangle"); assertTextEqual( activeTextEditor, `3456012789 defgabchij DEFGABCHIJ klmnopqrst KLMNO3456PQRST defg DEFG` ); setEmptyCursors(activeTextEditor, [4, 10]); await emulator.runCommand("yankRectangle"); assertTextEqual( activeTextEditor, `3456012789 defgabchij DEFGABCHIJ klmnopqrst KLMNO3456P3456QRST defg defg DEFG DEFG` ); }); test("deleting a rectangle", async () => { activeTextEditor.selections = [new vscode.Selection(0, 3, 2, 7)]; await emulator.runCommand("deleteRectangle"); assertTextEqual( activeTextEditor, `012789 abchij ABCHIJ klmnopqrst KLMNOPQRST` ); assertCursorsEqual(activeTextEditor, [2, 3]); setEmptyCursors(activeTextEditor, [0, 0]); await emulator.runCommand("yankRectangle"); // Nothing yanked as there is no killed rectangle. assertTextEqual( activeTextEditor, `012789 abchij ABCHIJ klmnopqrst KLMNOPQRST` ); }); test("kill and yank with reversed range", async () => { activeTextEditor.selections = [new vscode.Selection(2, 7, 0, 3)]; // Rigth bottom to top left await emulator.runCommand("killRectangle"); assertTextEqual( activeTextEditor, `012789 abchij ABCHIJ klmnopqrst KLMNOPQRST` ); assertCursorsEqual(activeTextEditor, [0, 3]); setEmptyCursors(activeTextEditor, [0, 0]); await emulator.runCommand("yankRectangle"); assertTextEqual( activeTextEditor, `3456012789 defgabchij DEFGABCHIJ klmnopqrst KLMNOPQRST` ); }); test("copy and yank a rectangle", async () => { activeTextEditor.selections = [new vscode.Selection(0, 3, 2, 7)]; await emulator.runCommand("copyRectangleAsKill"); assertTextEqual(activeTextEditor, initialText); assert.deepStrictEqual(activeTextEditor.selections, [new vscode.Selection(0, 3, 2, 7)]); // The selection is not changed setEmptyCursors(activeTextEditor, [0, 0]); await emulator.runCommand("yankRectangle"); assertTextEqual( activeTextEditor, `34560123456789 defgabcdefghij DEFGABCDEFGHIJ klmnopqrst KLMNOPQRST` ); }); }); suite("clear rectangle", () => { let activeTextEditor: vscode.TextEditor; let emulator: EmacsEmulator; const initialText = `0123456789 abcdefghij ABCDEFGHIJ klmnopqrst KLMNOPQRST`; setup(async () => { activeTextEditor = await setupWorkspace(initialText); emulator = new EmacsEmulator(activeTextEditor); }); teardown(cleanUpWorkspace); test("nothing happens when the selection is empty", async () => { setEmptyCursors(activeTextEditor, [1, 5]); await emulator.runCommand("clearRectangle"); assertTextEqual(activeTextEditor, initialText); assertCursorsEqual(activeTextEditor, [1, 5]); }); test("nothing happens when the selections are empty", async () => { setEmptyCursors(activeTextEditor, [1, 5], [2, 7]); await emulator.runCommand("clearRectangle"); assertTextEqual(activeTextEditor, initialText); assertCursorsEqual(activeTextEditor, [1, 5], [2, 7]); }); test("clearing a rectangle", async () => { activeTextEditor.selections = [new vscode.Selection(0, 3, 2, 7)]; await emulator.runCommand("clearRectangle"); assertTextEqual( activeTextEditor, `012 789 abc hij ABC HIJ klmnopqrst KLMNOPQRST` ); assertCursorsEqual(activeTextEditor, [2, 7]); }); test("clearing rectangles", async () => { activeTextEditor.selections = [new vscode.Selection(0, 3, 2, 5), new vscode.Selection(2, 7, 3, 9)]; await emulator.runCommand("clearRectangle"); assertTextEqual( activeTextEditor, `012 56789 abc fghij ABC FG J klmnopq t KLMNOPQRST` ); assertCursorsEqual(activeTextEditor, [2, 5], [3, 9]); }); }); suite("string-rectangle", () => { let activeTextEditor: vscode.TextEditor; let emulator: EmacsEmulator; class MockMinibuffer implements Minibuffer { returnValue: string | undefined; constructor(returnValue: string | undefined) { this.returnValue = returnValue; } public get isReading(): boolean { return true; } public paste(): void { return; } public readFromMinibuffer(): Promise<string | undefined> { return Promise.resolve(this.returnValue); } } const initialText = `0123456789 abcdefghij ABCDEFGHIJ klmnopqrst KLMNOPQRST`; setup(async () => { activeTextEditor = await setupWorkspace(initialText); emulator = new EmacsEmulator(activeTextEditor, null, new MockMinibuffer("foo")); }); teardown(cleanUpWorkspace); // XXX: The behavior is different from the original Emacs when the selections are empty. test("nothing happens when the selection is empty", async () => { setEmptyCursors(activeTextEditor, [1, 5]); await emulator.runCommand("stringRectangle"); assertTextEqual(activeTextEditor, initialText); assertCursorsEqual(activeTextEditor, [1, 5]); }); // XXX: The behavior is different from the original Emacs when the selections are empty. test("nothing happens when the selections are empty", async () => { setEmptyCursors(activeTextEditor, [1, 5], [2, 7]); await emulator.runCommand("stringRectangle"); assertTextEqual(activeTextEditor, initialText); assertCursorsEqual(activeTextEditor, [1, 5], [2, 7]); }); test("replacing the rectangle with a text input from minibuffer", async () => { activeTextEditor.selections = [new vscode.Selection(0, 3, 2, 7)]; await emulator.runCommand("stringRectangle"); assertTextEqual( activeTextEditor, `012foo789 abcfoohij ABCfooHIJ klmnopqrst KLMNOPQRST` ); assertCursorsEqual(activeTextEditor, [2, 6]); }); test("replacing the rectangles with a text input from minibuffer", async () => { activeTextEditor.selections = [new vscode.Selection(0, 3, 2, 5), new vscode.Selection(2, 7, 3, 9)]; await emulator.runCommand("stringRectangle"); assertTextEqual( activeTextEditor, `012foo56789 abcfoofghij ABCfooFGfooJ klmnopqfoot KLMNOPQRST` ); assertCursorsEqual(activeTextEditor, [2, 6], [3, 10]); }); }); suite("open-rectangle", () => { let activeTextEditor: vscode.TextEditor; let emulator: EmacsEmulator; const initialText = `0123456789 abcdefghij ABCDEFGHIJ klmnopqrst KLMNOPQRST`; setup(async () => { activeTextEditor = await setupWorkspace(initialText); emulator = new EmacsEmulator(activeTextEditor); }); teardown(cleanUpWorkspace); test("nothing happens when the selection is empty", async () => { setEmptyCursors(activeTextEditor, [1, 5]); await emulator.runCommand("openRectangle"); assertTextEqual(activeTextEditor, initialText); assertCursorsEqual(activeTextEditor, [1, 5]); }); test("nothing happens when the selections are empty", async () => { setEmptyCursors(activeTextEditor, [1, 5], [2, 7]); await emulator.runCommand("openRectangle"); assertTextEqual(activeTextEditor, initialText); assertCursorsEqual(activeTextEditor, [1, 5], [2, 7]); }); test("opening a rectangle", async () => { activeTextEditor.selections = [new vscode.Selection(0, 3, 2, 7)]; await emulator.runCommand("openRectangle"); assertTextEqual( activeTextEditor, `012 3456789 abc defghij ABC DEFGHIJ klmnopqrst KLMNOPQRST` ); assertCursorsEqual(activeTextEditor, [0, 3]); }); test("opening rectangles", async () => { activeTextEditor.selections = [new vscode.Selection(0, 3, 2, 5), new vscode.Selection(2, 7, 3, 9)]; await emulator.runCommand("openRectangle"); assertTextEqual( activeTextEditor, `012 3456789 abc defghij ABC DEFG HIJ klmnopq rst KLMNOPQRST` ); assertCursorsEqual(activeTextEditor, [0, 3], [2, 7]); }); }); suite("replace-killring-to-rectangle", () => { let activeTextEditor: vscode.TextEditor; let killring: KillRing; let emulator_no_killring: EmacsEmulator; let emulator_has_killring: EmacsEmulator; const initialText = `0123456789 abcdefghij ABCDEFGHIJ abc klmnopqrst KLMNOPQRST <r>`; setup(async () => { activeTextEditor = await setupWorkspace(initialText); emulator_no_killring = new EmacsEmulator(activeTextEditor, null); killring = new KillRing(3); emulator_has_killring = new EmacsEmulator(activeTextEditor, killring); }); teardown(cleanUpWorkspace); test("nothing happens if no killring", async () => { const selection = new vscode.Selection(0, 4, 4, 4); activeTextEditor.selections = [selection]; await emulator_no_killring.runCommand("replaceKillRingToRectangle"); assertTextEqual(activeTextEditor, initialText); assertSelectionsEqual(activeTextEditor, selection); }); test("nothing happens if killring is empty", async () => { const selection = new vscode.Selection(0, 4, 4, 4); activeTextEditor.selections = [selection]; await emulator_has_killring.runCommand("replaceKillRingToRectangle"); assertTextEqual(activeTextEditor, initialText); assertSelectionsEqual(activeTextEditor, selection); }); test("nothing happens if killring has newline", async () => { const wholeFirstLine = `0123456789 `; const copySelection = new vscode.Selection(0, 0, 1, 0); activeTextEditor.selections = [copySelection]; await emulator_has_killring.runCommand("copyRegion"); assert.strictEqual(killring.getTop()?.asString(), wholeFirstLine); const selection = new vscode.Selection(0, 4, 4, 4); activeTextEditor.selections = [selection]; await emulator_has_killring.runCommand("replaceKillRingToRectangle"); assertTextEqual(activeTextEditor, initialText); assertSelectionsEqual(activeTextEditor, selection); assert.strictEqual(killring.getTop()?.asString(), wholeFirstLine); }); test("nothing happens if selection is empty", async () => { const copySelection = new vscode.Selection(6, 0, 6, 3); activeTextEditor.selections = [copySelection]; await emulator_has_killring.runCommand("copyRegion"); assert.strictEqual(killring.getTop()?.asString(), "<r>"); setEmptyCursors(activeTextEditor, [1, 5]); await emulator_has_killring.runCommand("replaceKillRingToRectangle"); assertTextEqual(activeTextEditor, initialText); assertCursorsEqual(activeTextEditor, [1, 5]); assert.strictEqual(killring.getTop()?.asString(), "<r>"); }); test("nothing happens if selections are empty", async () => { const copySelection = new vscode.Selection(6, 0, 6, 3); activeTextEditor.selections = [copySelection]; await emulator_has_killring.runCommand("copyRegion"); assert.strictEqual(killring.getTop()?.asString(), "<r>"); setEmptyCursors(activeTextEditor, [1, 5], [2, 7]); await emulator_has_killring.runCommand("replaceKillRingToRectangle"); assertTextEqual(activeTextEditor, initialText); assertCursorsEqual(activeTextEditor, [1, 5], [2, 7]); assert.strictEqual(killring.getTop()?.asString(), "<r>"); }); test("multi selection are not supported", async () => { const copySelection = new vscode.Selection(6, 0, 6, 3); activeTextEditor.selections = [copySelection]; await emulator_has_killring.runCommand("copyRegion"); assert.strictEqual(killring.getTop()?.asString(), "<r>"); const selection1 = new vscode.Selection(0, 4, 1, 4); const selection2 = new vscode.Selection(4, 4, 5, 4); activeTextEditor.selections = [selection1, selection2]; await emulator_has_killring.runCommand("replaceKillRingToRectangle"); assertTextEqual(activeTextEditor, initialText); assertSelectionsEqual(activeTextEditor, selection1, selection2); }); test("replace-killring-to-rectangle, cursor bottom-right", async () => { const copySelection = new vscode.Selection(6, 0, 6, 3); activeTextEditor.selections = [copySelection]; await emulator_has_killring.runCommand("copyRegion"); assert.strictEqual(killring.getTop()?.asString(), "<r>"); const selection = new vscode.Selection(0, 4, 4, 5); activeTextEditor.selections = [selection]; await emulator_has_killring.runCommand("replaceKillRingToRectangle"); assertTextEqual( activeTextEditor, `0123<r>56789 abcd<r>fghij ABCD<r>FGHIJ abc <r> klmn<r>pqrst KLMNOPQRST <r>` ); assertCursorsEqual(activeTextEditor, [4, 7]); assert.strictEqual(killring.getTop()?.asString(), "<r>"); }); test("replace-killring-to-rectangle, cursor bottom-left", async () => { const copySelection = new vscode.Selection(6, 0, 6, 3); activeTextEditor.selections = [copySelection]; await emulator_has_killring.runCommand("copyRegion"); assert.strictEqual(killring.getTop()?.asString(), "<r>"); const selection = new vscode.Selection(0, 5, 4, 4); activeTextEditor.selections = [selection]; await emulator_has_killring.runCommand("replaceKillRingToRectangle"); assertTextEqual( activeTextEditor, `0123<r>56789 abcd<r>fghij ABCD<r>FGHIJ abc <r> klmn<r>pqrst KLMNOPQRST <r>` ); assertCursorsEqual(activeTextEditor, [4, 4]); assert.strictEqual(killring.getTop()?.asString(), "<r>"); }); test("replace-killring-to-rectangle, cursor upper-right", async () => { const copySelection = new vscode.Selection(6, 0, 6, 3); activeTextEditor.selections = [copySelection]; await emulator_has_killring.runCommand("copyRegion"); assert.strictEqual(killring.getTop()?.asString(), "<r>"); const selection = new vscode.Selection(4, 4, 0, 5); activeTextEditor.selections = [selection]; await emulator_has_killring.runCommand("replaceKillRingToRectangle"); assertTextEqual( activeTextEditor, `0123<r>56789 abcd<r>fghij ABCD<r>FGHIJ abc <r> klmn<r>pqrst KLMNOPQRST <r>` ); assertCursorsEqual(activeTextEditor, [0, 7]); assert.strictEqual(killring.getTop()?.asString(), "<r>"); }); test("replace-killring-to-rectangle, cursor upper-left", async () => { const copySelection = new vscode.Selection(6, 0, 6, 3); activeTextEditor.selections = [copySelection]; await emulator_has_killring.runCommand("copyRegion"); assert.strictEqual(killring.getTop()?.asString(), "<r>"); const selection = new vscode.Selection(4, 5, 0, 4); activeTextEditor.selections = [selection]; await emulator_has_killring.runCommand("replaceKillRingToRectangle"); assertTextEqual( activeTextEditor, `0123<r>56789 abcd<r>fghij ABCD<r>FGHIJ abc <r> klmn<r>pqrst KLMNOPQRST <r>` ); assertCursorsEqual(activeTextEditor, [0, 4]); assert.strictEqual(killring.getTop()?.asString(), "<r>"); }); test("replace-killring-to-0-width-rectangle, cursor upper-left", async () => { const copySelection = new vscode.Selection(6, 0, 6, 3); activeTextEditor.selections = [copySelection]; await emulator_has_killring.runCommand("copyRegion"); assert.strictEqual(killring.getTop()?.asString(), "<r>"); const selection = new vscode.Selection(4, 4, 0, 4); activeTextEditor.selections = [selection]; await emulator_has_killring.runCommand("replaceKillRingToRectangle"); assertTextEqual( activeTextEditor, `0123<r>456789 abcd<r>efghij ABCD<r>EFGHIJ abc <r> klmn<r>opqrst KLMNOPQRST <r>` ); assertCursorsEqual(activeTextEditor, [0, 7]); assert.strictEqual(killring.getTop()?.asString(), "<r>"); }); test("replace-killring-to-0-width-rectangle, cursor bottom-right", async () => { const copySelection = new vscode.Selection(6, 0, 6, 3); activeTextEditor.selections = [copySelection]; await emulator_has_killring.runCommand("copyRegion"); assert.strictEqual(killring.getTop()?.asString(), "<r>"); const selection = new vscode.Selection(0, 4, 4, 4); activeTextEditor.selections = [selection]; await emulator_has_killring.runCommand("replaceKillRingToRectangle"); assertTextEqual( activeTextEditor, `0123<r>456789 abcd<r>efghij ABCD<r>EFGHIJ abc <r> klmn<r>opqrst KLMNOPQRST <r>` ); assertCursorsEqual(activeTextEditor, [4, 7]); assert.strictEqual(killring.getTop()?.asString(), "<r>"); }); });
the_stack
import {fromEvent, Unsubscribable} from 'rxjs'; import {auditTime} from 'rxjs/operators'; import {defaultsDeep, divide, add} from 'lodash-es'; let doc: Document = document; type Grid = boolean | number | { width: number, height: number } | { x?: number, y?: number }[] interface setting { [propName: string]: any; grid?: Grid } // 默认参数项 const DEFAULTS: setting = { container: doc,//监听鼠标移动的元素 range: doc, // 移动元素所在容器 主要用于限制移动范围 item: '[data-query="item"]',//需要定位的成员选择器 moveItem: '[data-select="multi"]',//多选移动 auto: 15, // 自动吸附功能 距离多少px范围内自行吸附 cache: {}, auditTime: 5, // ms moue 移动时抖动 数值截越小越平滑性能开销越高 zIndex: 0,//参考线层级 drag: true,//是否开启拖放, vLine: true,//是否开启垂直参考线 hLine: true,//是否开启水平参考线 grid: false, //是否开启对齐到网格 lineColor: '#07f7f9',//参考线颜色 offset: 20,//参考线头尾的延伸距离 lineWidth: 1,//参考线宽度 center: true,//是否开启中心对齐 hypotenuse: false,//是否开启对角线对齐 //暂没开发 directionKey: true,//是否开启方向键控制 delay: 6000,// 生成对齐线后多少ms 消失 默认为6000 isMultiMove: false, // 是否开启同时多个移个 createCanvas: function (canvas: HTMLElement) { // 创建 canvas 回调,用于自定义canvas let _body = doc.querySelector('body'); _body && _body.appendChild(canvas); }, move: (event: any, ele: HTMLElement, x: number, y: number) => { // 元素被移动时的回调 // 当前元素,x 对应style left ,y 对应style top }, end: (ele: HTMLElement, x: number, y: number) => { // 元素被移动后的回调 //当前元素,x 对应style left ,y 对应style top } }; interface drawCoordinate { vLine: { [x: string]: number }; hLine: { [y: string]: number }; } export default class ReferenceLine { regExp: RegExp = /([a-zA-Z]+)?([\.#\[])?([\w-_]+)?(?:=([\w-_"\]]+))?/; options: setting; [index: string]: any; st: any; sl: any; canvas: any; ctx: any; x: any; y: any; target: any; mapX: any; mapY: any; mapH: any; position: any[] = []; ele: any; gridX: any[] = []; gridY: any[] = []; constructor(opt: setting) { this.options = defaultsDeep(opt, DEFAULTS, {}) } /** * 初始化 */ init() { this.initStyle(); this.bindEvent(); let options = this.options; let box = document.querySelector(options.range); let bcr = box && box.getBoundingClientRect(); options.cache.boxLeft = bcr && bcr.left + box.clientLeft || 0; options.cache.boxTop = bcr && bcr.top + box.clientTop || 0; this.initGrid(bcr); } /** * 事件监听 */ bindEvent(): void { let _this = this; let options = this.options; let cache = options.cache; let box = options.container.nodeType ? doc : doc.querySelector(options.container); let subscriptionMove: Unsubscribable; // 是否开启方向键 if (options.directionKey) { fromEvent(doc, 'keydown').pipe( auditTime(50) ).subscribe((evt: any) => { if (!_this.target) { return } if (_this[evt.code] && (evt.ctrlKey || evt.shiftKey)) { cache.isShow = true; _this.canvas.style.display = 'block'; _this.sl = parseInt(_this.target.style.left); _this.st = parseInt(_this.target.style.top); _this[evt.code](evt.shiftKey ? 10 : 1); if (cache._h) { clearTimeout(cache._h); } cache._h = setTimeout(() => { _this.canvas.style.display = 'none'; cache.isShow = null; }, options.delay) } }) } fromEvent(doc, "wheel").subscribe(() => { if (cache.isShow) { _this.canvas.style.display = 'none'; clearTimeout(cache._h); } }); fromEvent(box, 'mousedown').subscribe((evt: any) => { evt.target.nodeName !== "INPUT" && evt.target.nodeName !== "TEXTAREA" && evt.target.nodeName !== "SELECT" && evt.preventDefault(); let ele: any; if (!(ele = _this.isItem(evt))) { return } ele.skip = true; _this.canvas.style.display = 'block'; _this.getPosition(); _this.target = ele; _this.sl = parseInt(ele.style.left); _this.st = parseInt(ele.style.top); if (_this.options.isMultiMove) { _this.multiMoveDo(); } if (ele.isRFItem) { _this.x = evt.clientX; _this.y = evt.clientY; subscriptionMove = fromEvent(box, 'mousemove').pipe( auditTime(options.auditTime) ).subscribe((evt) => { _this.move(evt, false); cache.isDo = true; }) } }); fromEvent(box, 'mouseup').subscribe(() => { subscriptionMove && subscriptionMove.unsubscribe(); cache._h = setTimeout(() => this.clearRect(), options.delay); if (cache.isMove && (cache.distanceY || cache.distanceX)) { //console.log(cache.isMove, cache.distanceX, cache.distanceY) this.autoMove(cache.bcr, cache.distanceX > 0, cache.distanceY > 0); } if (this.target) { this.target.skip = null; this.createLine(); const {distanceX, distanceY} = cache; if (distanceX || distanceY) { options.end.apply(this, [this.target, cache.x || this.sl, cache.y || this.st]); cache.distanceX = 0; cache.distanceY = 0; //this.target = null; } } cache.isMove = false; }); fromEvent(box, 'click').subscribe(() => { this.target && (this.target.skip = null); //subscriptionMove.unsubscribe(); if (cache.isDo) { cache.isDo = false; return } this.canvas.style.display = 'none'; this.clearRect(); this.target = null; }); } initGrid(bcr: any) { let {grid} = this.options; let {cache: {boxLeft: baseX, boxTop: baseY}} = this.options; if (!grid) { return; } let x: number = 15, y: number = 15; let type = Object.prototype.toString.call(grid); switch (type) { case '[object Array]': for (let v of grid as any) { (typeof v.x === 'number') && this.gridX.push(v.x + baseX); (typeof v.y === 'number') && this.gridY.push(v.y + baseY); } break; case '[object Number]': x = y = grid as number; break; case '[object Object]': x = (grid as any).width; y = (grid as any).height; break; } if (type === '[object Number]' || type === '[object Object]' || type === '[object Boolean]') { for (let i = 0, len = Math.floor(bcr.width / x); i < len; i++) { this.gridX.push(i * x + baseX) } for (let i = 0, len = Math.floor(bcr.height / y); i < len; i++) { this.gridY.push(i * y + baseY) } } } /** * 获取件bcr */ getPosition(): void { this.position = []; this.mapX = {}; this.mapY = {}; this.mapH = {}; //hypotenuse map let items = doc.querySelectorAll(this.options.item); for (let v of items as any) { v.isRFItem = true; if (v.skip) { continue; } let position = this.position; let bcr; let {left, top, right, bottom, width, height} = bcr = v.getBoundingClientRect(); let xCenter; let yCenter; left = Math.round(left); right = Math.round(right); top = Math.round(top); bottom = Math.round(bottom); let wh = divide(width, height); position.push(bcr); let tempXLeft = this.mapX[left]; tempXLeft ? tempXLeft.push(position.length - 1) : (this.mapX[left] = [position.length - 1]); let tempXRight = this.mapX[right]; tempXRight ? tempXRight.push(position.length - 1) : (this.mapX[right] = [position.length - 1]); if (this.options.center) { xCenter = Math.round(divide(add(bcr.right, bcr.left), 2)); yCenter = Math.round(divide(add(bcr.top, bcr.bottom), 2)); let tempXCenterX = this.mapX[xCenter]; tempXCenterX ? tempXCenterX.push(position.length - 1) : (this.mapX[xCenter] = [position.length - 1]); let tempYCenterY = this.mapY[yCenter]; tempYCenterY ? tempYCenterY.push(position.length - 1) : (this.mapY[yCenter] = [position.length - 1]); } if (this.options.hypotenuse) { this.mapH[wh] ? this.mapH[wh].push(position.length - 1) : (this.mapH[wh] = [position.length - 1]); } this.mapY[bcr.top] ? this.mapY[bcr.top].push(position.length - 1) : (this.mapY[Math.round(+bcr.top)] = [position.length - 1]); this.mapY[bcr.bottom] ? this.mapY[bcr.bottom].push(position.length - 1) : (this.mapY[Math.round(+bcr.bottom)] = [position.length - 1]); } //console.log(this.mapX, this.mapY, this.position); } /** * 获取画线信息 * @param x 坐标 * @param y 坐标 * @param isCenter 是否是中心对齐 */ getLine(x: number[], y: number[], isCenter: boolean): drawCoordinate { let options: setting = this.options; let position: any[] = this.position; let v: number[] = this.mapX[Math.round(x[0])] || []; let h: number[] = this.mapY[Math.round(y[0])] || []; let tempV: number[] = [...y]; let tempH: number[] = [...x]; let vLine: { [x: string]: number } = {x: x[0]}; let hLine: { [y: string]: number } = {y: y[0]}; let limit: number = isCenter ? 3 : 2; for (let i of v) { const {top, bottom} = position[i]; tempV.push(top); tempV.push(bottom); } for (let i of h) { const {left, right} = position[i]; tempH.push(left); tempH.push(right); } if (tempV.length) { vLine.start = Math.min(...tempV) - options.offset; vLine.end = Math.max(...tempV) + options.offset; } if (tempH.length) { hLine.start = Math.min(...tempH) - options.offset; hLine.end = Math.max(...tempH) + options.offset; } //console.log("vLine:", vLine, "hLine:", hLine); return <drawCoordinate>{vLine: tempV.length > limit ? vLine : null, hLine: tempH.length > limit ? hLine : null} } autoMoveProcess(list: any[], min: number, max: number, isToBig: boolean) { let options = this.options; let tempMin: any[] = []; let tempMax: any[] = []; let tempMapMin: any = {}; let tempMapMax: any = {}; for (let v of list) { let temp1 = Math.abs(isToBig ? +v - max : max - +v); let temp2 = Math.abs(isToBig ? +v - min : min - +v); if (temp1 < options.auto) { tempMax.push(temp1); tempMapMax[temp1] = v; } if (temp2 < options.auto) { tempMin.push(temp2); tempMapMin[temp2] = v; } } if (tempMin.length < 1 && tempMax.length < 1) { return false } // 如查向右或向左移动 if (tempMin.length > 0 && !isToBig) { return { value: tempMapMin[Math.min(...tempMin)], isMin: true } } if (tempMax.length > 0 && isToBig) { return { value: tempMapMax[Math.min(...tempMax)], isMin: false } } return false } /** * 自动吸附功能 */ autoMove(bcr: any, isMoveToRight: boolean, isMoveToBottom: boolean) { let resultX: any; let resultY: any; let cache = this.options.cache; const {left, top, width, height} = bcr; //console.log('left::', left, "top::", top, isMoveToRight, isMoveToBottom); //console.log("mapX::", Object.keys(this.mapX), "mapY::", Object.keys(this.mapY), "mapH::", Object.keys(this.mapH)); resultX = this.autoMoveProcess([...this.gridX, ...Object.keys(this.mapX)], left, left + width, isMoveToRight); resultY = this.autoMoveProcess([...this.gridY, ...Object.keys(this.mapY)], top, top + height, isMoveToBottom); if (typeof resultX !== 'boolean') { const {value, isMin} = resultX; let x = isMin ? value : value - width; cache.x = x - cache.boxLeft; this.target.style.left = `${cache.x}px`; } if (typeof resultY !== 'boolean') { const {value, isMin} = resultY; let y = isMin ? value : value - height; cache.y = y - cache.boxTop; this.target.style.top = `${cache.y}px`; } //console.log("XY:::", resultX, resultY); } /** * 移动回调 * @param evt event * @param isSimulate 是否是trigger */ move(evt: any, isSimulate: boolean): void { //console.log(evt.clientX, evt.clientY); let l: number = 0, t: number = 0; let p = this.target.getBoundingClientRect(); let options = this.options; let cache = options.cache; cache.isMove = true; if (options.drag) { let range: any = this.getRange(); let minLeft: number = 0; let maxLeft: number = range.width - (options.isMultiMove ? cache.widthMulti : p.width); let minTop: number = 0; let maxTop: number = range.height - (options.isMultiMove ? cache.heightMulti : p.height); let x: number = evt.clientX; let y: number = evt.clientY; l = this.sl + (cache.distanceX = x - this.x); t = this.st + (cache.distanceY = y - this.y); l < minLeft && (l = minLeft); l > maxLeft && (l = maxLeft); t < minTop && (t = minTop); t > maxTop && (t = maxTop); //console.log('test::::', result); //console.log("minLeft:", minLeft, 'maxLeft:', maxLeft, 'minTop:', minTop, 'maxTop:', maxTop); this.target.style.left = (l || 0) + "px"; this.target.style.top = (t || 0) + "px"; } cache.x = l; cache.y = t; this.options.move.apply(this, [evt, this.target, cache.x, cache.y]); this.clearRect(); this.createLine(); } /** * UI初始化 */ initStyle(): void { let ele: any = this.ele = doc.createElement('canvas'); let options = this.options; this.canvas = ele; ele.width = doc.documentElement && doc.documentElement.clientWidth; ele.height = doc.documentElement && doc.documentElement.clientHeight; ele.style.position = "fixed"; ele.style.left = 0; ele.style.top = 0; ele.style.display = 'none'; ele.style.zIndex = options.zIndex; this.options.createCanvas.apply(this, [ele]); this.ctx = ele.getContext("2d"); this.ctx.lineWidth = options.lineWidth; this.ctx.strokeStyle = options.lineColor; this.ctx.setLineDash([1, 1]); } createLine() { let cache = this.options.cache; let {left, top, right, bottom} = cache.bcr = this.target.getBoundingClientRect(); this.drawLine([left, right], [top, bottom], false); this.drawLine([right, left], [bottom, top], false); this.drawLine([divide(add(right, left), 2), left, right], [divide(add(bottom, top), 2), top, bottom], true); } /** * 垂直对齐线画线 * @param x 坐标 * @param ys 坐标开始 * @param ye 坐标结束 */ drawVLine(x: number, ys: number, ye: number): void { x = Math.round(x); ys = Math.round(ys); ye = Math.round(ye); this.ctx.beginPath(); this.ctx.moveTo(x + 0.5, ys + 0.5); this.ctx.lineTo(x + 0.5, ye + 0.5); this.ctx.closePath(); this.ctx.stroke(); } /** * 水平对齐线画线 * @param y * @param xs * @param xe */ drawHLine(y: number, xs: number, xe: number): void { y = Math.floor(y); xs = Math.floor(xs); xe = Math.floor(xe); this.ctx.beginPath(); this.ctx.moveTo(xs + 0.5, y + 0.5); this.ctx.lineTo(xe + 0.5, y + 0.5); this.ctx.closePath(); this.ctx.stroke(); } /** * 对齐线画线 * @param x * @param y * @param isCenter */ drawLine(x: number[], y: number[], isCenter: boolean): void { let temp: drawCoordinate = this.getLine(x, y, isCenter); let options = this.options; options.hLine && temp.hLine && this.drawHLine(temp.hLine.y, temp.hLine.start, temp.hLine.end); options.vLine && temp.vLine && this.drawVLine(temp.vLine.x, temp.vLine.start, temp.vLine.end); } /** * 清空画布 */ clearRect(): void { //console.log('clear::::::::') this.ctx.clearRect(0, 0, this.ele.width, this.ele.height); } /** * 获取画布范围 */ getRange(): any { let options = this.options; let ele = options.range.nodeType ? doc.documentElement : doc.querySelector(options.range); ele = ele || doc.documentElement; return { width: ele.clientWidth, height: ele.clientHeight } } /** * 键盘方向键左移 * @param offset 阀值 * @constructor */ ArrowLeft(offset: number): void { let cache = this.options.cache; this.x = 0; this.y = 0; this.move({ clientX: -offset, clientY: 0 }, false); this.options.end.apply(this, [this.target, cache.x || this.sl, cache.y || this.st]); } /** * 右移 * @param offset 阀值 * @constructor */ ArrowRight(offset: number): void { let cache = this.options.cache; this.x = 0; this.y = 0; this.move({ clientX: offset, clientY: 0 }, false); this.options.end.apply(this, [this.target, cache.x || this.sl, cache.y || this.st]); } /** * 下移 * @param offset * @constructor */ ArrowDown(offset: number): void { let cache = this.options.cache; this.x = 0; this.y = 0; this.move({ clientX: 0, clientY: offset }, false); this.options.end.apply(this, [this.target, cache.x || this.sl, cache.y || this.st]); } /** * 上移 * @param offset * @constructor */ ArrowUp(offset: number): void { let cache = this.options.cache; this.x = 0; this.y = 0; this.move({ clientX: 0, clientY: -offset }, false); this.options.end.apply(this, [this.target, cache.x || this.sl, cache.y || this.st]); } /** * 多选移动 */ multiMoveDo() { let options = this.options; let cache = options.cache; let tempLeftArray = []; let tempRightArray = []; let tempTopArray = []; let tempBottomArray = []; let tempMap = new Map(); cache.multiItems = document.querySelectorAll(options.moveItem); if (cache.multiItems.length < 1) { return } for (let v of cache.multiItems) { let bcr = v.getBoundingClientRect(); tempLeftArray.push(bcr.left); tempRightArray.push(bcr.right); tempTopArray.push(bcr.top); tempBottomArray.push(bcr.bottom); tempMap.set(bcr.left, v); tempMap.set(bcr.top, v); } let minX = Math.min(...tempLeftArray); let minY = Math.min(...tempTopArray); cache.widthMulti = Math.max(...tempRightArray) - minX; cache.heightMulti = Math.max(...tempBottomArray) - minY; this.sl = parseInt(tempMap.get(minX).style.left); this.st = parseInt(tempMap.get(minY).style.top); this.options.end.apply(this, [this.target, cache.x || this.sl, cache.y || this.st]); } /** * 过虑 todo 可以使用pipe filter map * @param evt */ isItem(evt: any): boolean | Node | Element { let match = this.options.item.match(this.regExp); let m4 = match[4] && match[4].replace(/["'\]]/g, ""); if (!match) { return false } if (match[2] === '.') { for (let v = evt.target; v; v = v.x) { if (v.nodeType !== 1) { continue } if (v.className === match[3]) { return v; } } } if (match[2] === '[') { for (let v = evt.target; v; v = v.parentNode) { if (v.nodeType !== 1) { continue } if (m4 ? v.getAttribute(match[3]) === m4 : v.getAttribute(match[3])) { return v; } } } return false; } } export {ReferenceLine}
the_stack
import type vscode from 'vscode'; import { IRPCProtocol } from '@opensumi/ide-connection'; import { IExtensionInfo, Uri } from '@opensumi/ide-core-common'; import { MainThreadAPIIdentifier, IMainThreadCommands, CommandHandler, } from '@opensumi/ide-extension/lib/common/vscode'; import * as types from '@opensumi/ide-extension/lib/common/vscode/ext-types'; import { SymbolKind } from '@opensumi/ide-extension/lib/common/vscode/ext-types'; import * as modes from '@opensumi/ide-extension/lib/common/vscode/model.api'; import { ExtHostCommands, createCommandsApiFactory, } from '@opensumi/ide-extension/lib/hosted/api/vscode/ext.host.command'; import { Range } from '@opensumi/monaco-editor-core/esm/vs/editor/common/core/range'; import { mockService } from '../../../../../../tools/dev-tool/src/mock-injector'; describe('extension/__tests__/hosted/api/vscode/ext.host.command.test.ts', () => { let vscodeCommand: typeof vscode.commands; let extCommand: ExtHostCommands; let mainService: IMainThreadCommands; const commandShouldAuth = 'ext.commandShouldAuthId'; // mock 判断是否有权限是根据是否为内置函数 const isPermitted = (extensionInfo: IExtensionInfo) => extensionInfo.isBuiltin; const map = new Map(); const builtinCommands = [ { id: 'test:builtinCommand', handler: { handler: async () => 'bingo!', }, }, { id: 'test:builtinCommand:unpermitted', handler: { handler: () => 'You shall not pass!', isPermitted: (extensionInfo: IExtensionInfo) => false, }, }, { id: 'test:builtinCommand:permitted', handler: { handler: () => 'permitted!', isPermitted: (extensionInfo: IExtensionInfo) => true, }, }, ]; const rpcProtocol: IRPCProtocol = { getProxy: (key) => map.get(key), set: (key, value) => { map.set(key, value); return value; }, get: (r) => map.get(r), }; beforeEach(() => { mainService = mockService({ $executeCommandWithExtensionInfo: jest.fn((id: string, extensionInfo: IExtensionInfo) => { // 模拟鉴权函数是为判断是否为内置函数 if (id === commandShouldAuth && !isPermitted(extensionInfo)) { throw new Error('not permitted'); } return Promise.resolve(true); }), $executeCommand: jest.fn(() => Promise.resolve()), }); const editorService = mockService({}); const extension = mockService({ id: 'vscode.vim', extensionId: 'cloud-ide.vim', isBuiltin: false, }); rpcProtocol.set(MainThreadAPIIdentifier.MainThreadCommands, mainService); extCommand = new ExtHostCommands(rpcProtocol, builtinCommands); vscodeCommand = createCommandsApiFactory(extCommand, editorService, extension); }); describe('vscode command', () => { it('execute a command', async () => { const extTest = jest.fn(); const commandId = 'ext.test'; vscodeCommand.registerCommand(commandId, extTest); await vscodeCommand.executeCommand(commandId); // 实际命令执行注册一次 expect(extTest).toBeCalledTimes(1); }); it('execute a no-permitted command', async () => { const commandHandler: CommandHandler = { handler: jest.fn(() => 123), isPermitted: () => false, }; const commandId = 'ext.test'; extCommand.registerCommand(false, commandId, commandHandler); expect(vscodeCommand.executeCommand(commandId)).rejects.toThrowError( new Error(`Extension vscode.vim has not permit to execute ${commandId}`), ); expect(commandHandler.handler).toBeCalledTimes(0); }); }); describe('ExtHostCommands', () => { it('register a command', async () => { const extTest = jest.fn(); const commandId = 'ext.test'; extCommand.registerCommand(true, commandId, extTest); // 远端注册被调用一次 expect(mainService.$registerCommand).toBeCalledTimes(1); await extCommand.executeCommand(commandId); // 实际命令执行注册一次 expect(extTest).toBeCalledTimes(1); }); it('throw error when register exist command', () => { const extTest = jest.fn(); const commandId = 'ext.test'; extCommand.registerCommand(true, commandId, extTest); // 再注册一次 expect(() => extCommand.registerCommand(true, commandId, extTest)).toThrowError(); }); it('register a command with thisArg', async () => { const commandId = 'ext.test'; const thisArg = {}; // https://github.com/Microsoft/TypeScript/issues/16016#issuecomment-303462193 const extTest = jest.fn(function (this: any) { return this; }); extCommand.registerCommand(true, commandId, extTest, thisArg); const thisArgResult = await extCommand.executeCommand(commandId); expect(thisArgResult === thisArg).toBeTruthy(); }); it('register a command without global', () => { const extTest = jest.fn(); const commandId = 'ext.test'; extCommand.registerCommand(false, commandId, extTest); // 如果 global 设置为 false,则不会执行远端命令注册 expect(mainService.$registerCommand).toBeCalledTimes(0); }); it('execute a command', async () => { const extTest = jest.fn(); const commandId = 'ext.test'; extCommand.registerCommand(false, commandId, extTest); await extCommand.executeCommand(commandId); // 本地有命令的,远端不会执行 expect(mainService.$executeCommand).toBeCalledTimes(0); }); it('execute a command then localCommand not found', async () => { const commandId = 'ext.notfound'; await extCommand.executeCommand(commandId); // 本地找不到会到远端找 expect(mainService.$executeCommand).toBeCalledTimes(1); }); it('execute a builtin command', async () => { extCommand.$registerBuiltInCommands(); const commandId = 'test:builtinCommand'; const result = await extCommand.executeCommand(commandId); expect(result).toBe('bingo!'); }); it('execute a builtin command will not permitted', async () => { extCommand.$registerBuiltInCommands(); const commandId = 'test:builtinCommand:unpermitted'; expect(() => vscodeCommand.executeCommand(commandId)).rejects.toThrowError( new Error(`Extension vscode.vim has not permit to execute ${commandId}`), ); }); it('execute a builtin command with permitted', async () => { extCommand.$registerBuiltInCommands(); const commandId = 'test:builtinCommand:permitted'; const result = await vscodeCommand.executeCommand(commandId); expect(result).toBe('permitted!'); }); it('dispose calls unregister', async () => { const extTest = jest.fn(); const command = extCommand.registerCommand(true, 'ext.test', extTest); command.dispose(); // 卸载远端命令 expect(mainService.$unregisterCommand).toBeCalledTimes(1); }); it('call getCommands', async () => { await extCommand.getCommands(); expect(mainService.$getCommands).toBeCalledTimes(1); }); it('call $executeContributedCommand with exist command', async () => { const extTest = jest.fn(); const commandId = 'ext.test'; extCommand.registerCommand(true, commandId, extTest); await extCommand.$executeContributedCommand(commandId); expect(extTest).toBeCalledTimes(1); }); it('call $executeContributedCommand with no-exist command', () => { const commandId = 'ext.notfound'; expect(extCommand.$executeContributedCommand(commandId)).rejects.toThrowError(); }); it('register argument processor', async () => { const argumentProcessor = { processArgument: jest.fn(), }; extCommand.registerArgumentProcessor(argumentProcessor); const extTest = jest.fn(); const commandId = 'ext.test'; extCommand.registerCommand(true, commandId, extTest); await extCommand.$executeContributedCommand(commandId, '123'); expect(argumentProcessor.processArgument).toBeCalledTimes(1); }); it('execute requiring authentication command to frontend command when permitted', async () => { const extensionInfo: IExtensionInfo = { id: 'vscode.vim', extensionId: 'cloud-ide.vim', isBuiltin: true, }; expect(await extCommand.$executeCommandWithExtensionInfo(commandShouldAuth, extensionInfo)).toBeTruthy(); }); it('execute requiring authentication command to frontend command when not permitted', () => { const extensionInfo: IExtensionInfo = { id: 'vscode.vim', extensionId: 'cloud-ide.vim', isBuiltin: false, }; expect(extCommand.$executeCommandWithExtensionInfo(commandShouldAuth, extensionInfo)).rejects.toThrowError( new Error('not permitted'), ); }); it('execute requiring authentication command to local command when not permitted', async () => { const commandId = 'ext.test'; const extensionInfo: IExtensionInfo = { id: 'vscode.vim', extensionId: 'cloud-ide.vim', isBuiltin: false, }; const commandHandler: CommandHandler = { handler: jest.fn(() => 123), isPermitted: () => false, }; extCommand.registerCommand(false, commandId, commandHandler); expect(extCommand.$executeCommandWithExtensionInfo(commandId, extensionInfo)).rejects.toThrowError( new Error(`Extension vscode.vim has not permit to execute ${commandId}`), ); }); it('execute requiring authentication command to local command when permitted', async () => { const commandId = 'ext.test'; const extensionInfo: IExtensionInfo = { id: 'vscode.vim', extensionId: 'cloud-ide.vim', isBuiltin: true, }; const commandHandler: CommandHandler = { handler: jest.fn(() => 123), isPermitted: (extension) => extension.isBuiltin, }; extCommand.registerCommand(false, commandId, commandHandler); expect(await extCommand.$executeCommandWithExtensionInfo(commandId, extensionInfo)).toBe(123); }); }); describe('vscode builtin command', () => { let mockMainThreadFunc; beforeEach(async () => { mockMainThreadFunc = jest.spyOn(mainService, '$executeCommand'); await extCommand.$registerBuiltInCommands(); await extCommand.$registerCommandConverter(); }); it('vscode.executeFormatDocumentProvider', async () => { const file = Uri.file('/a.txt'); await extCommand.executeCommand('vscode.executeFormatDocumentProvider', file); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeFormatDocumentProvider'); }); it('vscode.executeFormatRangeProvider', async () => { const file = Uri.file('/a.txt'); await extCommand.executeCommand('vscode.executeFormatRangeProvider', file, new types.Range(1, 1, 1, 1)); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeFormatRangeProvider'); }); it('vscode.executeFormatOnTypeProvider', async () => { const file = Uri.file('/a.txt'); await extCommand.executeCommand('vscode.executeFormatOnTypeProvider', file, new types.Position(1, 1), ''); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeFormatOnTypeProvider'); }); it('vscode.executeDefinitionProvider', async () => { const file = Uri.file('/a.txt'); await extCommand.executeCommand('vscode.executeDefinitionProvider', file, new types.Position(1, 1)); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeDefinitionProvider'); }); it('vscode.executeTypeDefinitionProvider', async () => { const file = Uri.file('/a.txt'); await extCommand.executeCommand('vscode.executeTypeDefinitionProvider', file, new types.Position(1, 1)); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeTypeDefinitionProvider'); }); it('vscode.executeDeclarationProvider', async () => { const file = Uri.file('/a.txt'); await extCommand.executeCommand('vscode.executeDeclarationProvider', file, new types.Position(1, 1)); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeDeclarationProvider'); }); it('vscode.executeDeclarationProvider', async () => { const file = Uri.file('/a.txt'); await extCommand.executeCommand('vscode.executeDeclarationProvider', file, new types.Position(1, 1)); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeDeclarationProvider'); }); it('vscode.executeImplementationProvider', async () => { const file = Uri.file('/a.txt'); await extCommand.executeCommand('vscode.executeImplementationProvider', file, new types.Position(1, 1)); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeImplementationProvider'); }); it('vscode.executeReferenceProvider', async () => { const file = Uri.file('/a.txt'); await extCommand.executeCommand('vscode.executeReferenceProvider', file, new types.Position(1, 1), []); expect(mainService.$executeCommand).toBeCalledWith('_executeReferenceProvider', expect.anything(), { column: 2, lineNumber: 2, }); }); it('vscode.executeHoverProvider', async () => { const file = Uri.file('/a.txt'); await extCommand.executeCommand('vscode.executeHoverProvider', file, new types.Position(1, 1)); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeHoverProvider'); }); it('vscode.executeSelectionRangeProvider', async () => { const file = Uri.file('/a.txt'); mockMainThreadFunc.mockReturnValueOnce(Promise.resolve([[new Range(1, 1, 1, 1)]])); await extCommand.executeCommand('vscode.executeSelectionRangeProvider', file, [new types.Position(1, 1)]); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeSelectionRangeProvider'); }); it('vscode.executeWorkspaceSymbolProvider', async () => { const file = Uri.file('/a.txt'); await extCommand.executeCommand('vscode.executeWorkspaceSymbolProvider', file.toString()); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeWorkspaceSymbolProvider'); }); it('vscode.prepareCallHierarchy', async () => { const file = Uri.file('/a.txt'); const resultItem = { _sessionId: '', _itemId: '', kind: SymbolKind.Class, name: 'test', uri: Uri.file('/a.txt'), range: new Range(1, 1, 1, 1), selectionRange: new Range(1, 1, 1, 1), } as modes.ICallHierarchyItemDto; mockMainThreadFunc.mockReturnValueOnce(Promise.resolve([resultItem])); const result = await extCommand.executeCommand<vscode.CallHierarchyItem[]>( 'vscode.prepareCallHierarchy', file, new types.Position(1, 1), ); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executePrepareCallHierarchy'); expect(result.length).toBe(1); expect(result[0].name).toBe('test'); }); it('vscode.provideIncomingCalls', async () => { const item = new types.CallHierarchyItem( types.SymbolKind.Class, 'test', 'test', Uri.file('/a.txt'), new types.Range(1, 1, 1, 1), new types.Range(1, 1, 1, 1), ); const resultItem = { fromRanges: [new Range(1, 1, 1, 1)], from: { _sessionId: '', _itemId: '', kind: SymbolKind.Class, name: 'test', uri: Uri.file('/a.txt'), range: new Range(1, 1, 1, 1), selectionRange: new Range(1, 1, 1, 1), }, } as modes.IIncomingCallDto; mockMainThreadFunc.mockReturnValueOnce(Promise.resolve([resultItem])); const result = await extCommand.executeCommand<vscode.CallHierarchyIncomingCall[]>( 'vscode.provideIncomingCalls', item, ); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeProvideIncomingCalls'); expect(result.length).toBe(1); expect(result[0].from.name).toBe('test'); }); it('vscode.provideOutgoingCalls', async () => { const item = new types.CallHierarchyItem( types.SymbolKind.Class, 'test', 'test', Uri.file('/a.txt'), new types.Range(1, 1, 1, 1), new types.Range(1, 1, 1, 1), ); const resultItem = { fromRanges: [new Range(1, 1, 1, 1)], to: { _sessionId: '', _itemId: '', kind: SymbolKind.Class, name: 'test', uri: Uri.file('/a.txt'), range: new Range(1, 1, 1, 1), selectionRange: new Range(1, 1, 1, 1), }, } as modes.IOutgoingCallDto; mockMainThreadFunc.mockReturnValueOnce(Promise.resolve([resultItem])); const result = await extCommand.executeCommand<vscode.CallHierarchyOutgoingCall[]>( 'vscode.provideOutgoingCalls', item, ); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeProvideOutgoingCalls'); expect(result.length).toBe(1); expect(result[0].to.name).toBe('test'); }); it('vscode.executeDocumentRenameProvider', async () => { const file = Uri.file('/a.txt'); await extCommand.executeCommand('vscode.executeDocumentRenameProvider', file, new types.Position(1, 1), 'b.txt'); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeDocumentRenameProvider'); }); it('vscode.executeLinkProvider', async () => { const file = Uri.file('/a.txt'); mockMainThreadFunc.mockReturnValueOnce(Promise.resolve([])); await extCommand.executeCommand('vscode.executeLinkProvider', file, 1); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeLinkProvider'); }); it('vscode.executeCompletionItemProvider', async () => { const file = Uri.file('/a.txt'); await extCommand.executeCommand( 'vscode.executeCompletionItemProvider', file, new types.Position(1, 1), 'triggerCharacter', 1, ); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeCompletionItemProvider'); }); it('vscode.executeSignatureHelpProvider', async () => { const file = Uri.file('/a.txt'); await extCommand.executeCommand( 'vscode.executeSignatureHelpProvider', file, new types.Position(1, 1), 'triggerCharacter', ); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeSignatureHelpProvider'); }); it('vscode.executeCodeLensProvider', async () => { const file = Uri.file('/a.txt'); await extCommand.executeCommand('vscode.executeCodeLensProvider', file, 1); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeCodeLensProvider'); }); it('vscode.executeCodeActionProvider', async () => { const file = Uri.file('/a.txt'); mockMainThreadFunc.mockReturnValueOnce(Promise.resolve([])); await extCommand.executeCommand('vscode.executeCodeActionProvider', file, new types.Range(1, 1, 1, 1), 'kind', 1); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeCodeActionProvider'); }); it('vscode.executeDocumentColorProvider', async () => { const file = Uri.file('/a.txt'); mockMainThreadFunc.mockReturnValueOnce(Promise.resolve([])); await extCommand.executeCommand('vscode.executeDocumentColorProvider', file); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeDocumentColorProvider'); }); it('vscode.executeColorPresentationProvider', async () => { const file = Uri.file('/a.txt'); mockMainThreadFunc.mockReturnValueOnce(Promise.resolve([])); await extCommand.executeCommand('vscode.executeColorPresentationProvider', new types.Color(0, 0, 0, 0), { uri: file, range: new types.Range(1, 1, 1, 1), }); expect(mockMainThreadFunc.mock.calls[0][0]).toBe('_executeColorPresentationProvider'); }); }); });
the_stack
import { Color, hexColorToInt } from '@alyle/ui/color'; import { _STYLE_MAP, Styles, LyClasses } from './theme/style'; import { StyleCollection, StyleTemplate } from './parse'; import { memoize } from './minimal/memoize'; export class LyStyleUtils { name: string; typography: { fontFamily?: string; htmlFontSize: number, fontSize: number; }; breakpoints: { XSmall: string, Small: string, Medium: string, Large: string, XLarge: string, Handset: string, Tablet: string, Web: string, HandsetPortrait: string, TabletPortrait: string, WebPortrait: string, HandsetLandscape: string, TabletLandscape: string, WebLandscape: string, [key: string]: string }; direction: Dir; /** Returns left or right according to the direction */ get before() { return this.getDirection(DirAlias.before); } /** Returns left or right according to the direction */ get after() { return this.getDirection(DirAlias.after); } /** Returns top */ readonly above = 'top'; /** Returns bottom */ readonly below = 'bottom'; pxToRem(value: number) { const size = this.typography.fontSize / 14; return `${value / this.typography.htmlFontSize * size}rem`; } colorOf(value: string | number, optional?: string): Color { if (typeof value === 'number') { return new Color(value); } if (value[0] === '#' && value.length === 7) { return new Color(hexColorToInt(value)); } const color = get(this, value, optional); if (color) { return color; } /** Create invalid color */ return new Color(); } getBreakpoint(key: string) { return `@media ${this.breakpoints[key] || key}`; } selectorsOf<T>(styles: T & Styles): LyClasses<T> { const styleMap = _STYLE_MAP.get(styles); if (styleMap) { return styleMap.classes || styleMap[this.name]; } else { throw Error('Classes not found'); } } getDirection(val: DirAlias | 'before' | 'after' | 'above' | 'below') { if (val === DirAlias.before) { return this.direction === 'rtl' ? 'right' : 'left'; } else if (val === DirAlias.after) { return this.direction === 'rtl' ? 'left' : 'right'; } else if (val === 'above') { return 'top'; } else if (val === 'below') { return 'bottom'; } return val; } } export enum Dir { rtl = 'rtl', ltr = 'ltr' } export enum DirAlias { before = 'before', after = 'after' } export enum DirPosition { left = 'left', right = 'right' } /** * get color of object * @param obj object * @param path path * @param optional get optional value, if not exist return default if not is string */ function get(obj: Object, path: string[] | string, optional?: string): Color { if (path === 'transparent') { return new Color(0, 0, 0, 0); } const _path: string[] = path instanceof Array ? path : path.split(':'); for (let i = 0; i < _path.length; i++) { const posibleOb = obj[_path[i]]; if (posibleOb) { obj = posibleOb; } else { /** if not exist */ return new Color(); } } if (obj instanceof Color) { return obj; } else if (optional) { return obj[optional] || obj['default']; } else { return obj['default']; } // return typeof obj === 'string' ? obj as string : obj['default'] as string; } export type MediaQueryArray = (string | number)[]; export type MediaQueryArrayDeprecated = ( (number | string | [(string | number), string]) )[]; /** * Extract breakpoints from a string to make it a unique `StyleTemplate` * @param str Media Queries in inline style * @param transformer A function with parameters to create a `StyleTemplate` * @deprecated */ export function withMediaInline( str: string | number | MediaQueryArray, transformer: ((val: string | number, media: string | null) => StyleTemplate) ) { const styleCollection = new StyleCollection(); if (typeof str === 'string') { const values = parseMediaQueriesFromString(str); for (let index = 0; index < values.length; index++) { parseMediaQueryFromString(values[index]).forEach((_) => { styleCollection.add(transformer(_[0], _[1])); }); } } else if (typeof str === 'number' || str === null || str === undefined) { styleCollection.add(transformer(str as any, null)); } else { for (let index = 0; index < str.length; index++) { const val = str[index]; if (typeof val === 'number' || val === null || val === undefined) { styleCollection.add(transformer(val, null)); } if (typeof val === 'string') { parseMediaQueryFromString(val).forEach((_) => { styleCollection.add(transformer(_[0], _[1])); }); } } } return styleCollection.css; } /** * Extract media query from a string */ export const parseMediaQueryFromString = memoize((key: string) => { const valItem = key.split(/\@/g); const strValue = valItem.shift()!; const len = valItem.length; const value = isNaN(+strValue) ? strValue : +strValue; const re: [string | number, string | null][] = []; if (len) { for (let j = 0; j < len; j++) { re.push([value, valItem[j]]); } } else { re.push([value, null]); } return re; }); /** * Extract media queries from a string */ export const parseMediaQueriesFromString = memoize((key: string) => { return key.split(' '); }); /** * @depracated use `withMediaInline` instead. */ export function eachMedia( str: string | number | MediaQueryArrayDeprecated, fn: ((val: string | number, media: string | null, index: number) => void) ): void; /** * @depracated use `withMediaInline` instead. */ export function eachMedia( str: string | number | MediaQueryArrayDeprecated, fn: ((val: string | number, media: string | null, index: number) => StyleTemplate), styleCollection: boolean ): StyleTemplate; /** * @depracated use `withMediaInline` instead. */ export function eachMedia( str: string | number | MediaQueryArrayDeprecated, fn: ((val: string | number, media: string | null, index: number) => (void | StyleTemplate)), withStyleCollection?: boolean ): StyleTemplate | void { let styleCollection: StyleCollection | undefined; if (withStyleCollection) { styleCollection = new StyleCollection(); } if (typeof str === 'string') { const values = str.split(/\ /g); for (let index = 0; index < values.length; index++) { const valItem = values[index].split(/\@/g); const strValue = valItem.shift()!; const len = valItem.length; const value = isNaN(+strValue) ? strValue : +strValue; if (len) { for (let j = 0; j < len; j++) { resolveMediaEachItemStyle(fn, value, valItem[j], index, styleCollection); } } else { resolveMediaEachItemStyle(fn, value, null, index, styleCollection); } } } else if (typeof str === 'number' || typeof str === 'string' || str === null || str === undefined) { resolveMediaEachItemStyle(fn, str as any, null, 0, styleCollection); } else { // is array for (let index = 0; index < str.length; index++) { const val = str[index]; if (typeof val === 'number' || typeof val === 'string') { resolveMediaEachItemStyle(fn, val, null, index, styleCollection); } else { const medias = val[1].split(/\@/g).filter(media => media); const strValue = val[0]; const len = medias.length; if (len) { for (let ii = 0; ii < len; ii++) { resolveMediaEachItemStyle(fn, strValue, medias[ii], index, styleCollection); } } else { resolveMediaEachItemStyle(fn, strValue, null, index, styleCollection); } } } } if (styleCollection) { return styleCollection.css; } } function resolveMediaEachItemStyle( fn: (val: string | number, media: string | null, index: number) => void | StyleTemplate, val: string | number, media: string | null, index: number, styleCollection?: StyleCollection ) { const styl = fn(val, media, index); if (styleCollection && styl) { styleCollection.add(styl); } } /** * Simple object check. * @param item */ function isObject(item) { return (item && typeof item === 'object' && !Array.isArray(item)); } export function mergeDeep<T, U>(target: T, source: U): T & U; export function mergeDeep<T, U, V>(target: T, source1: U, source2: V): T & U & V; export function mergeDeep<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W; export function mergeDeep(target: object, ...sources: any[]): any; /** * Deep merge two objects. * @param target * @param ...sources */ export function mergeDeep(target: any, ...sources: any[]) { if (!sources.length) { return target; } const source = sources.shift(); if (isObject(target) && isObject(source)) { for (const key in source) { if (isObject(source[key])) { if (!target[key]) { Object.assign(target, { [key]: {} }); } mergeDeep(target[key], source[key]); } else { Object.assign(target, { [key]: source[key] }); } } } return mergeDeep(target, ...sources); } /** * Simple object check. * @param item */ function isObjectForTheme(item: any) { return (item && typeof item === 'object' && !Array.isArray(item)) && !(item instanceof StyleCollection) && !(item instanceof Color); } export function mergeThemes<T, U>(target: T, source: U): T & U; export function mergeThemes<T, U, V>(target: T, source1: U, source2: V): T & U & V; export function mergeThemes<T, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W; export function mergeThemes(target: object, ...sources: any[]): any; export function mergeThemes(target: any, ...sources: any[]): any { if (!sources.length) { return target; } const source = sources.shift(); if (isObjectForTheme(target) && isObjectForTheme(source)) { for (const key in source) { if (isObjectForTheme(source[key])) { if (!target[key]) { Object.assign(target, { [key]: {} }); } mergeThemes(target[key], source[key]); } else { const targetKey = target[key]; const sourceKey = source[key]; // Merge styles if (targetKey instanceof StyleCollection && typeof sourceKey === 'function') { target[key] = (target[key] as StyleCollection).add(sourceKey); } else if (sourceKey instanceof Color) { target[key] = sourceKey; } else { Object.assign(target, { [key]: source[key] }); } } } } return mergeThemes(target, ...sources); }
the_stack
import { ConventionSiteModel, PanelTextModel, PanelFacadeModel, PanelShadowModel, PanelFilterModel, PanelAnimationModel, } from "../../panel-widget-appearance/model"; import { isObject } from "@ng-public/util"; import { ProfileModel } from "../../panel-scope-enchantment/model"; import { EventModel } from "../../panel-event/event-handler"; import { HostItemModel } from "./host.model"; import { debounceTime, tap } from "rxjs/operators"; import { get } from "lodash"; import { merge } from "rxjs"; /** * 拓展模式下的widget数据模型 */ export class PanelWidgetModel extends HostItemModel { /** * 该组件对应的轮廓数据 */ public profileModel: ProfileModel = new ProfileModel(); /** * 该组件对应的事件数据 */ public panelEventHandlerModel: EventModel = new EventModel(); /** * 该组件对应的外观样式数据 */ public conventionSiteModel: ConventionSiteModel = new ConventionSiteModel(); /** * 该组件对应的文本设置样式数据 */ public panelTextModel: PanelTextModel = new PanelTextModel(); /** * 该组件对应的边框设置样式数据 */ public panelFacadeModel: PanelFacadeModel = new PanelFacadeModel(); /** * 该组件对应的阴影设置样式数据 */ public panelShadowModel: PanelShadowModel = new PanelShadowModel(); /** * 该组件对应的滤镜设置样式数据 */ public panelFilterModel: PanelFilterModel = new PanelFilterModel(); /** * 该组件对应的动画效果数据 */ public panelAnimationModel: PanelAnimationModel = new PanelAnimationModel(); /** * 最终的映射到具体某个widget组件对象的样式数据 */ public ultimatelyStyle: { [key: string]: string } = {}; /** 是否进入到双击状态 */ public isDblClick: boolean = false; /** 是否隐藏文字 */ public isHiddenText: boolean = false; constructor(data?: HostItemModel) { super(data); // 初始化 this.conversionStyleToUltimatelyStyle(); this.panelInit(); this.conventionInit(); this.panelTextInit(); this.panelFacadeInit(); this.panelShadowInit(); this.panelFilterInit(); this.panelAnimationInit(); this.panelEventHandlerInit(); this.openSubValueChange(); } /** * 开启并订阅该widget类的可编辑的数据的所有更新变化,以用来实时更新autoWidget里的样式和事件数据 */ public openSubValueChange(): void { merge( this.profileModel.valueChange$, this.conventionSiteModel.valueChange$, this.panelTextModel.valueChange$, this.panelFacadeModel.valueChange$, this.panelShadowModel.valueChange$, this.panelFilterModel.valueChange$, this.panelAnimationModel.valueChange$ ) .pipe( // 10毫秒内只取最新的最后一个值,避免重复计算 debounceTime(1), tap(value => { if (value instanceof ProfileModel) { this.autoWidget.orientationmodel.left = value.left; this.autoWidget.orientationmodel.top = value.top; this.autoWidget.orientationmodel.width = value.width; this.autoWidget.orientationmodel.height = value.height; this.autoWidget.orientationmodel.rotate = value.rotate; this.autoWidget.orientationmodel.zIndex = value.zIndex; } }) ) .subscribe(() => { this.autoWidget.customfeature = this.panelEventHandlerModel.autoWidgetEvent; this.autoWidget.style.data = this.ultimatelyStyle; }); } /** * 获取该类上某个属性的值,没有则返回undefind */ public getObjKeyValue(key: string): any { if ((<Object>this).hasOwnProperty(key)) { return this[key]; } else { return undefined; } } /** * 为该类动态添加属性以及对应的值 */ public addObjKeyValue(arg: { [key: string]: any }): void { if (arg && isObject(arg)) { const _this_obj_key = Object.keys(this); for (let e in arg) { if (_this_obj_key.includes(e)) { // 该行待考虑 } else { } this[e] = arg[e]; } } } /** * 删除该类某个属性的keyvalue */ public delObjKeyValue(key: string): void { if ((<Object>this).hasOwnProperty(key)) { delete this[key]; } } /** * 把style.data里的样式值赋给ultimatelyStyle */ public conversionStyleToUltimatelyStyle(): void { if (get(this.autoWidget, "style.data")) { const _style = <Object>this.autoWidget.style.data; if (_style) { for (let e in _style) { this.ultimatelyStyle[e] = _style[e]; } } } } /** * 添加样式给ultimatelyStyle */ public addStyleToUltimatelyStyle(obj: { [key: string]: string }): void { if (isObject(obj)) { for (let e in obj) { this.ultimatelyStyle[e] = obj[e]; } } } /** * 删除某个样式于ultimatelyStyle */ public delStyleToUltimatelyStyle(key: string): void { if (isObject(this.ultimatelyStyle)) { for (let e in this.ultimatelyStyle) { if (e == key) { delete this.ultimatelyStyle[key]; break; } } } } /** * 初始化轮廓值 */ public panelInit(): void { if (get(this.autoWidget, "orientationmodel")) { const _ori = this.autoWidget.orientationmodel; // 重新计算宽度和高度 if ((<Object>this.ultimatelyStyle).hasOwnProperty("width") && this.ultimatelyStyle.width) { _ori.width = <any>this.ultimatelyStyle.width.replace("px", "") * 1; } if ((<Object>this.ultimatelyStyle).hasOwnProperty("height") && this.ultimatelyStyle.height) { _ori.height = <any>this.ultimatelyStyle.height.replace("px", "") * 1; } this.profileModel.setData({ unit: "px", left: _ori.left, top: _ori.top, width: _ori.width, height: _ori.height, rotate: _ori.rotate, zIndex: _ori.zIndex, }); this.profileModel.setMouseCoord([this.profileModel.left, this.profileModel.top]); } } /** * 初始化外观值 */ public conventionInit(): void { if (get(this.autoWidget, "orientationmodel") && get(this.autoWidget, "style.data")) { const _ori = this.autoWidget.orientationmodel; const _opacity = (<Object>this.autoWidget.style.data).hasOwnProperty("opacity") ? this.autoWidget.style.data.opacity * 100 : 100; this.conventionSiteModel.setData({ opacity: _opacity, left: _ori.left, top: _ori.top, width: _ori.width, height: _ori.height, rotate: _ori.rotate, }); } } /** * 初始化文本设置值 */ public panelTextInit(): void { if (get(this.autoWidget, "orientationmodel")) { const _ori = this.autoWidget.orientationmodel; const _style = <Object>this.ultimatelyStyle; let _set_obj = {}; _set_obj["height"] = _ori.height; if (_style.hasOwnProperty("font-size")) _set_obj["fontSize"] = _style["font-size"].replace("px", ""); if (_style.hasOwnProperty("font-weight")) _set_obj["isBold"] = _style["font-weight"] == "bold" ? true : false; if (_style.hasOwnProperty("font-style")) _set_obj["isItalic"] = _style["font-style"] == "italic" ? true : false; if (_style.hasOwnProperty("text-decoration")) { if (_style["text-decoration"] == "underline") { _set_obj["lineationType"] = "bottom"; } else if (_style["text-decoration"] == "line-through") { _set_obj["lineationType"] = "center"; } } if (_style.hasOwnProperty("color")) _set_obj["fontColor"] = _style["color"]; if (_style.hasOwnProperty("text-align")) _set_obj["crosswiseType"] = _style["text-align"]; if ( _style.hasOwnProperty("font-size") && _style.hasOwnProperty("line-height") && _style.hasOwnProperty("height") ) { const _font_size = _style["font-size"].replace("px", "") * 1; const _line_height = _style["line-height"].replace("px", "") * 1; const _height = _style["height"].replace("px", "") * 1; if (_font_size == _line_height) { _set_obj["verticalType"] = "top"; } else if (_height == _line_height) { _set_obj["verticalType"] = "center"; } else if (_height * 2 - _font_size == _line_height) { _set_obj["verticalType"] = "bottom"; } } this.panelTextModel.setData(_set_obj); } } /** * 初始化边框设置 */ public panelFacadeInit(): void { if (this.ultimatelyStyle) { const _style = <Object>this.ultimatelyStyle; let _set_obj = {}; if (_style.hasOwnProperty("background-color")) _set_obj["bgColor"] = _style["background-color"]; if (_style.hasOwnProperty("border-color")) _set_obj["borderColor"] = _style["border-color"]; if (_style.hasOwnProperty("border-style")) _set_obj["borderStyle"] = _style["border-style"]; if (_style.hasOwnProperty("border-width")) _set_obj["borderNumber"] = _style["border-width"].replace("px", "") * 1; if (_style.hasOwnProperty("border-radius") && _style["border-radius"]) { let _radius_arr = _style["border-radius"].split(" "); // 分四种情况 if (Array.isArray(_radius_arr)) { _radius_arr = _radius_arr.map(_r => _r.replace("px", "") * 1); if (_radius_arr.length == 1) { // 四个边的圆角相同 _set_obj["ltRadius"] = _radius_arr[0]; _set_obj["rtRadius"] = _radius_arr[0]; _set_obj["lbRadius"] = _radius_arr[0]; _set_obj["rbRadius"] = _radius_arr[0]; } else if (_radius_arr.length == 2) { // 左上右下 和 右上左下 _set_obj["ltRadius"] = _radius_arr[0]; _set_obj["rbRadius"] = _radius_arr[0]; _set_obj["rtRadius"] = _radius_arr[1]; _set_obj["lbRadius"] = _radius_arr[1]; } else if (_radius_arr.length == 3) { // 左上 和 右上左下 和右下 _set_obj["ltRadius"] = _radius_arr[0]; _set_obj["rtRadius"] = _radius_arr[1]; _set_obj["lbRadius"] = _radius_arr[1]; _set_obj["rbRadius"] = _radius_arr[2]; } else if (_radius_arr.length == 4) { // 左上 和 右上 和 右下 和 左下 _set_obj["ltRadius"] = _radius_arr[0]; _set_obj["rtRadius"] = _radius_arr[1]; _set_obj["rbRadius"] = _radius_arr[2]; _set_obj["lbRadius"] = _radius_arr[3]; } } } this.panelFacadeModel.setData(_set_obj); } } /** * 初始化阴影 */ public panelShadowInit(): void { if (this.ultimatelyStyle) { const _style = <Object>this.ultimatelyStyle; let _shadow_obj = {}; if (_style.hasOwnProperty("box-shadow") && _style["box-shadow"]) { let _shadow_arr = _style["box-shadow"].split(" "); if (Array.isArray(_shadow_arr)) { // 先抛弃颜色 let _no_color = []; let _color = ""; _shadow_arr.forEach(_s => { if (_s.includes("px")) { _no_color.push(_s.replace("px", "") * 1); } else { _color = _s; } }); if (Array.isArray(_no_color)) { _shadow_obj["x"] = _no_color[0] == undefined ? 0 : _no_color[0]; _shadow_obj["y"] = _no_color[1] == undefined ? 0 : _no_color[1]; _shadow_obj["fuzzy"] = _no_color[2] == undefined ? 0 : _no_color[2]; _shadow_obj["spread"] = _no_color[3] == undefined ? 0 : _no_color[3]; _shadow_obj["color"] = _color; } } this.panelShadowModel.setData(_shadow_obj); } } } /** * 初始化滤镜 * 只有图片组件才有滤镜 */ public panelFilterInit(): void { if (this.ultimatelyStyle) { const _style = <Object>this.ultimatelyStyle; let _filter_obj = {}; if (this.type == "picture" && _style.hasOwnProperty("filter") && _style["filter"]) { let _filter_arr = _style["filter"].split(" "); let _rep = (t: string): number => { return <any>t.replace(/[^\d\.]/g, "") * 1; }; if (Array.isArray(_filter_arr)) { _filter_arr.forEach(_e => { if (_e.includes("blur")) _filter_obj["blur"] = _rep(_e); if (_e.includes("brightness")) _filter_obj["brightness"] = _rep(_e); if (_e.includes("contrast")) _filter_obj["contrast"] = _rep(_e); if (_e.includes("saturate")) _filter_obj["saturate"] = _rep(_e); if (_e.includes("grayscale")) _filter_obj["grayscale"] = _rep(_e); if (_e.includes("sepia")) _filter_obj["sepia"] = _rep(_e); if (_e.includes("hue-rotate")) _filter_obj["hueRotate"] = _rep(_e); if (_e.includes("invert")) _filter_obj["invert"] = _rep(_e); }); } this.panelFilterModel.setData(_filter_obj); } } } /** * 初始化动画效果 */ public panelAnimationInit(): void { if (this.ultimatelyStyle) { const _style = <Object>this.ultimatelyStyle; let _animation_obj = {}; if (_style.hasOwnProperty("animation-name") && _style["animation-name"]) _animation_obj["animationName"] = _style["animation-name"]; if (_style.hasOwnProperty("animation-delay") && _style["animation-delay"]) _animation_obj["animationDelay"] = _style["animation-delay"].replace("s", ""); if (_style.hasOwnProperty("animation-duration") && _style["animation-duration"]) _animation_obj["animationDuration"] = _style["animation-duration"].replace("s", ""); if (_style.hasOwnProperty("animation-iteration-count") && _style["animation-iteration-count"]) _animation_obj["animationIterationCount"] = _style["animation-iteration-count"]; this.panelAnimationModel.setData(_animation_obj); } } /** * 初始化事件机制 */ public panelEventHandlerInit(): void { if (get(this.autoWidget, "customfeature")) { const _event = this.autoWidget.customfeature; let _event_obj = {}; if (_event.hasOwnProperty("eventHandler") && _event.eventHandler) { _event_obj["eventHandler"] = _event.eventHandler; } if (_event.hasOwnProperty("eventParams") && _event.eventParams) { _event_obj["eventParams"] = _event.eventParams; } this.panelEventHandlerModel.setData(_event_obj); } } }
the_stack
module Charting { declare var IPython:any; declare var datalab:any; // Wrappers for Plotly.js and Google Charts abstract class ChartLibraryDriver { chartModule:any; constructor(protected dom:HTMLElement, protected chartStyle:string) { } abstract requires(url: string, chartStyle:string):Array<string>; init(chartModule:any):void { this.chartModule = chartModule; } abstract draw(data:any, options:any):void; abstract getStaticImage(callback:Function):void; abstract addChartReadyHandler(handler:Function):void; addPageChangedHandler(handler:Function):void { } error(message:string):void { } } class PlotlyDriver extends ChartLibraryDriver { readyHandler:any; constructor(dom:HTMLElement, chartStyle:string) { super(dom, chartStyle) } requires(url: string, chartStyle:string):Array<string> { return ['d3', 'plotly']; } public draw(data:any, options:any):void { /* * TODO(gram): if we start moving more chart types over to Plotly.js we should change the * shape of the data we pass to render so we don't need to reshape it here. Also, a fair * amount of the computation done here could be moved to Python code. We should just be * passing in the mostly complete layout object in JSON, for example. */ var xlabels: Array<string> = []; var points: Array<any> = []; var layout: any = { xaxis: {}, yaxis: {}, height: 300, margin: { b: 60, t: 60, l: 60, r: 60 } }; if (options.title) { layout.title = options.title; } var minX: number = undefined; var maxX: number = undefined; if ('hAxis' in options) { if ('minValue' in options.hAxis) { minX = options.hAxis.minValue; } if ('maxValue' in options.hAxis) { maxX = options.hAxis.maxValue; } if (minX != undefined || maxX != undefined) { layout.xaxis.range = [minX, maxX]; } } var minY: number = undefined; var maxY: number = undefined; if ('vAxis' in options) { if ('minValue' in options.vAxis) { minY = options.vAxis.minValue; } else if ('minValues' in options.vAxis) { minY = options.vAxis.minValues[0]; } if ('maxValue' in options.vAxis) { maxY = options.vAxis.maxValue; } else if ('maxValues' in options.vAxis) { maxY = options.vAxis.maxValues[0]; } if (minY != undefined || maxY != undefined) { layout.yaxis.range = [minY, maxY]; } if ('minValues' in options.vAxis) { minY = options.vAxis.minValues[1]; // for second axis below } if ('maxValues' in options.vAxis) { maxY = options.vAxis.maxValues[1]; // for second axis below } } if (options.xAxisTitle) { layout.xaxis.title = options.xAxisTitle; } if (options.xAxisSide) { layout.xaxis.side = options.xAxisSide; } if (options.yAxisTitle) { layout.yaxis.title = options.yAxisTitle; } if (options.yAxesTitles) { layout.yaxis.title = options.yAxesTitles[0]; layout.yaxis2 = { title: options.yAxesTitles[1], side: 'right', overlaying: 'y' }; if (minY != undefined || maxY != undefined) { layout.yaxis2.range = [minY, maxY]; } } if ('width' in options) { layout.width = options.width; } if ('height' in options) { layout.height = options.height; if ('width' in options) { layout.autosize = false; } } var pdata: Array<any> = []; if (this.chartStyle == 'line' || this.chartStyle == 'scatter') { var hoverCol: number = 0; var x: Array<any> = []; // First col is X, other cols are Y's and optional hover text only column var y: Array<any> = []; var hover: Array<any> = []; for (var c = 1; c < data.cols.length; c++) { x[c - 1] = []; y[c - 1] = []; var line:any = { x: x[c - 1], y: y[c - 1], name: data.cols[c].label, type: 'scatter', mode: this.chartStyle == 'scatter' ? 'markers' : 'lines' }; if (options.hoverOnly) { hover[c - 1] = []; line.text = hover[c - 1]; line.hoverinfo = 'text'; } if (options.yAxesTitles && (c % 2) == 0) { line.yaxis = 'y2'; } pdata.push(line); } for (var c = 1; c < data.cols.length; c++) { if (c == hoverCol) { continue; } for (var r = 0; r < data.rows.length; r++) { var entry:Array<any> = data.rows[r].c; if ('v' in entry[c]) { var xVal = entry[0].v; var yVal = entry[c].v; if (options.hoverOnly) { // Each column is a dict with two values, one for y and one for // hover. Extract these. var hoverVal:any; var yDict:any = yVal; for (var prop in yDict) { var val = yDict[prop]; if (prop == options.hoverOnly) { hoverVal = val; } else { yVal = val; } } // TODO(gram): we may want to add explicit hover text this even without hoverOnly. var xlabel:any = options.xAxisTitle || data.cols[0].label; var ylabel:any = options.yAxisTitle || data.cols[c].label; var prefix = ''; if (options.yAxisTitle) { prefix += data.cols[c].label + ': '; } hover[c - 1].push(prefix + options.hoverOnly + '=' + hoverVal + ', ' + xlabel + '=' + xVal + ', ' + ylabel + '=' + yVal); } x[c - 1].push(xVal); y[c - 1].push(yVal); } } } } else if (this.chartStyle == 'heatmap') { var size:number = 200 + data.cols.length * 50; if (size > 800) size = 800; layout.height = size; layout.width = size; layout.autosize = false; for (var i = 0; i < data.cols.length; i++) { xlabels[i] = data.cols[i].label; } var ylabels = [].concat(xlabels); // Plotly draws the first row at the bottom, not the top, so we need // to reverse the y and z array ordering. // We will need to tweak this a bit if we later support non-square maps. ylabels.reverse(); var hovertext: Array<Array<string>> = []; var hoverx:string = options.xAxisTitle || 'x'; var hovery = options.yAxisTitle || 'y'; for (var i = 0; i < data.rows.length; i++) { var entry:Array<any> = data.rows[i].c; var row:Array<number> = []; var hoverrow:Array<string> = []; for (var j = 0; j < data.cols.length; j++) { row[j] = entry[j].v; hoverrow[j] = hoverx + '= ' + xlabels[j] + ', ' + hovery + '= ' + ylabels[i] + ': ' + row[j]; } points[i] = row; hovertext[i] = hoverrow; } points.reverse(); layout.hovermode = 'closest'; pdata = [{ x: xlabels, y: ylabels, z: points, type: 'heatmap', text: hovertext, hoverinfo: 'text' }]; if (options.colorScale) { pdata[0].colorscale = [ [0, options.colorScale.min], [1, options.colorScale.max] ]; } else { pdata[0].colorscale = [ [0, 'red'], [0.5, 'gray'], [1, 'blue'] ]; } if (options.hideScale) { pdata[0].showscale = false; } if (options.annotate) { layout.annotations = []; for (var i = 0; i < pdata[0].y.length; i++) { for (var j = 0; j < pdata[0].x.length; j++) { var currentValue = pdata[0].z[i][j]; var textColor = (currentValue == 0.0) ? 'black' : 'white'; var result = { xref: 'x1', yref: 'y1', x: pdata[0].x[j], y: pdata[0].y[i], text: pdata[0].z[i][j].toPrecision(3), showarrow: false, font: { color: textColor } }; layout.annotations.push(result); } } } } this.chartModule.newPlot(this.dom.id, pdata, layout, {displayModeBar: false}); if (this.readyHandler) { this.readyHandler(); } } getStaticImage(callback:Function):void { this.chartModule.Snapshot.toImage(document.getElementById(this.dom.id), {format: 'png'}).once('success', function (url:string) { callback(this.model, url); }); } addChartReadyHandler(handler:Function):void { this.readyHandler = handler; } } interface IStringMap { [key: string]: string; } class GChartsDriver extends ChartLibraryDriver { chart:any; nameMap: IStringMap = { annotation: 'AnnotationChart', area: 'AreaChart', columns: 'ColumnChart', bars: 'BarChart', bubbles: 'BubbleChart', calendar: 'Calendar', candlestick: 'CandlestickChart', combo: 'ComboChart', gauge: 'Gauge', geo: 'GeoChart', histogram: 'Histogram', line: 'LineChart', map: 'Map', org: 'OrgChart', paged_table: 'Table', pie: 'PieChart', sankey: 'Sankey', scatter: 'ScatterChart', stepped_area: 'SteppedAreaChart', table: 'Table', timeline: 'Timeline', treemap: 'TreeMap', }; scriptMap: IStringMap = { annotation: 'annotationchart', calendar: 'calendar', gauge: 'gauge', geo: 'geochart', map: 'map', org: 'orgchart', paged_table: 'table', sankey: 'sankey', table: 'table', timeline: 'timeline', treemap: 'treemap' }; constructor(dom:HTMLElement, chartStyle:string) { super(dom, chartStyle); } requires(url: string, chartStyle:string):Array<string> { var chartScript:string = 'corechart'; if (chartStyle in this.scriptMap) { chartScript = this.scriptMap[chartStyle]; } return [url + 'visualization!' + chartScript]; } init(chartModule:any):void { super.init(chartModule); var constructor:Function = this.chartModule[this.nameMap[this.chartStyle]]; this.chart = new (<any>constructor)(this.dom); } error(message:string):void { this.chartModule.errors.addError(this.dom, 'Unable to render the chart', message, {showInTooltip: false}); } draw(data:any, options:any):void { console.log('Drawing with options ' + JSON.stringify(options)); this.chart.draw(new this.chartModule.DataTable(data), options); } getStaticImage(callback:Function):void { if (this.chart.getImageURI) { callback(this.chart.getImageURI()); } } addChartReadyHandler(handler:Function) { this.chartModule.events.addListener(this.chart, 'ready', handler); } addPageChangedHandler(handler:Function) { this.chartModule.events.addListener(this.chart, 'page', function (e:any) { handler(e.page); }); } } class Chart { dataCache:any; // TODO: add interface types for the caches. optionsCache:any; hasIPython:boolean; cellElement:HTMLElement; totalRows:number; constructor(protected driver:ChartLibraryDriver, protected dom:Element, protected controlIds:Array<string>, protected base_options:any, protected refreshData:any, protected refreshInterval:number, totalRows:number) { this.totalRows = totalRows || -1; // Total rows in all (server-side) data. this.dataCache = {}; this.optionsCache = {}; this.hasIPython = false; try { if (IPython && IPython.notebook) { this.hasIPython = true; } } catch (e) { } (<HTMLElement>this.dom).innerHTML = ''; this.removeStaticChart(); this.addControls(); // Generate and add a new static chart once chart is ready. var _this = this; this.driver.addChartReadyHandler(function () { _this.addStaticChart(); }); } // Convert any string fields that are date type to JS Dates. public convertDates(data:any):void { // Format timestamps in the same way as in dataframes. const timestampFormatter = new this.driver.chartModule.DateFormat({ 'pattern' : 'yyyy-MM-dd HH:mm:ss', 'valueType' : 'datetime', 'timeZone' : -new Date().getTimezoneOffset() / 60, }); // Timestamp formatter with fractional seconds. // BQ and python store time down to the microsecond, but javascript Date // only stores it to the millisecond. const timestampWithFractionalSecondsFormatter = new this.driver.chartModule.DateFormat({ 'pattern' : 'yyyy-MM-dd HH:mm:ss.SSS', 'valueType' : 'datetime', 'timeZone' : -new Date().getTimezoneOffset() / 60, }); // Javascript has terrible support for timezones. When Date objects get converted to // strings, it always applies the local timezone. But we want dates and times to be // printed in UTC so that they match the output of dataframes and other conversions that // are happening in the kernel, which we assume is running in UTC in a docker container. // In order to make this work, we add an offset to our Date objects in an amount equal // to the local timezone offset from UTC so that when those Dates get output as a local // time they will appear as the right UTC time. This is made more confusing by the fact // that date, datetime, and timeofday data types are civil time for which timezone // should not even apply - but since we are passing them along as Date objects, we // pull the same trick with them. We add the 'f' field, for use by Google Charts when // displaying tables, to ensure we have the right string there, but when doing things // like line graphs, that field is not used, so we have to use the Date-offset trick // in order to get dates and times to display correctly as UTC in graphs. function dateAsUtc(localDate:Date):Date { const year = localDate.getUTCFullYear(); const month = localDate.getUTCMonth(); const day = localDate.getUTCDate(); const hours = localDate.getUTCHours(); const minutes = localDate.getUTCMinutes(); const seconds = localDate.getUTCSeconds(); const millis = localDate.getUTCMilliseconds(); return new Date(year, month, day, hours, minutes, seconds, millis); } const rows = data.rows; for (let col = 0; col < data.cols.length; col++) { // date, datetime, and timeofday are civil times that are independent of timezone if (data.cols[col].type == 'date' || data.cols[col].type == 'datetime') { for (let row = 0; row < rows.length; row++) { const v = rows[row].c[col].v; rows[row].c[col].v = dateAsUtc(new Date(v)); rows[row].c[col].f = v; // Display the string as-is to avoid timezone problems. } } else if (data.cols[col].type == 'timeofday') { for (let row = 0; row < rows.length; row++) { const v = rows[row].c[col].v; rows[row].c[col].f = v; // Display the string as-is to avoid timezone problems. const timeInSeconds = v.split('.')[0]; rows[row].c[col].v = timeInSeconds.split(':').map( function(n:string) { return parseInt(n, 10); }); } } else if (data.cols[col].type == 'timestamp') { data.cols[col].type = 'datetime'; // Run through all the dates to determine how to format them. let formatter = timestampFormatter; for (let row = 0; row < rows.length; row++) { const v = new Date(rows[row].c[col].v); if (v.getTime() % 1000 != 0) { formatter = timestampWithFractionalSecondsFormatter; break; } } for (let row = 0; row < rows.length; row++) { const v = new Date(rows[row].c[col].v); // Timestamp is sent back as UTC time string. rows[row].c[col].f = formatter.formatValue(v); rows[row].c[col].v = dateAsUtc(v); } } } } // Extend the properties in a 'base' object with the changes in an 'update' object. // We can add properties or override properties but not delete yet. private static extend(base:any, update:any):void { for (var p in update) { if (typeof base[p] !== 'object' || !base.hasOwnProperty(p)) { base[p] = update[p]; } else { this.extend(base[p], update[p]); } } } // Get the IPython cell associated with this chart. private getCell() { if (!this.hasIPython) { return undefined; } var cells = IPython.notebook.get_cells(); for (var cellIndex in cells) { var cell = cells[cellIndex]; if (cell.element && cell.element.length) { var element = cell.element[0]; var chartDivs = element.getElementsByClassName('bqgc'); if (chartDivs && chartDivs.length) { for (var i = 0; i < chartDivs.length; i++) { if (chartDivs[i].id == this.dom.id) { return cell; } } } } } return undefined; } protected getRefreshHandler(useCache:boolean):Function { var _this = this; return function () { _this.refresh(useCache); }; } // Bind event handlers to the chart controls, if any. private addControls():void { if (!this.controlIds) { return; } var controlHandler = this.getRefreshHandler(true); for (var i = 0; i < this.controlIds.length; i++) { var id = this.controlIds[i]; var split = id.indexOf(':'); var control:HTMLInputElement; if (split >= 0) { // Checkbox group. var count = parseInt(id.substring(split + 1)); var base = id.substring(0, split + 1); for (var j = 0; j < count; j++) { control = <HTMLInputElement>document.getElementById(base + j); control.disabled = !this.hasIPython; control.addEventListener('change', function() { controlHandler(); }); } continue; } // See if we have an associated control that needs dual binding. control = <HTMLInputElement>document.getElementById(id); if (!control) { // Kernel restart? return; } control.disabled = !this.hasIPython; var textControl = <HTMLInputElement>document.getElementById(id + '_value'); if (textControl) { textControl.disabled = !this.hasIPython; textControl.addEventListener('change', function () { if (control.value != textControl.value) { control.value = textControl.value; controlHandler(); } }); control.addEventListener('change', function () { textControl.value = control.value; controlHandler(); }); } else { control.addEventListener('change', function() { controlHandler(); }); } } } // Iterate through any widget controls and build up a JSON representation // of their values that can be passed to the Python kernel as part of the // magic to fetch data (also used as part of the cache key). protected getControlSettings():any { var env:any = {}; if (this.controlIds) { for (var i = 0; i < this.controlIds.length; i++) { var id = this.controlIds[i]; var parts = id.split('__'); var varName = parts[1]; var splitPoint = varName.indexOf(':'); if (splitPoint >= 0) { // this is a checkbox group var count = parseInt(varName.substring(splitPoint + 1)); varName = varName.substring(0, splitPoint); var cbBaseId = parts[0] + '__' + varName + ':'; var list:Array<string> = []; env[varName] = list; for (var j = 0; j < count; j++) { var cb = <HTMLInputElement>document.getElementById(cbBaseId + j); if (!cb) { // Stale refresh; user re-executed cell. return undefined; } if (cb.checked) { list.push(cb.value); } } } else { var e = <HTMLInputElement>document.getElementById(id); if (!e) { // Stale refresh; user re-executed cell. return undefined; } if (e && e.type == 'checkbox') { // boolean env[varName] = e.checked; } else { // picker/slider/text env[varName] = e.value; } } } } return env; } // Get a string representation of the current environment - i.e. control settings and // refresh data. This is used as a cache key. private getEnvironment():string { var controls:any = this.getControlSettings(); if (controls == undefined) { // This means the user has re-executed the cell and our controls are gone. return undefined; } var env:any = {controls: controls}; Chart.extend(env, this.refreshData); return JSON.stringify(env); } protected refresh(useCache:boolean):void { // TODO(gram): remember last cache key and don't redraw chart if cache // key is the same unless this is an ML key and the number of data points has changed. this.removeStaticChart(); var env:string = this.getEnvironment(); if (env == undefined) { // This means the user has re-executed the cell and our controls are gone. console.log('No chart control environment; abandoning refresh'); return; } if (useCache && env in this.dataCache) { this.draw(this.dataCache[env], this.optionsCache[env]); return; } var code = '%_get_chart_data\n' + env; // TODO: hook into the notebook UI to enable/disable 'Running...' while we fetch more data. if (!this.cellElement) { var cell = this.getCell(); if (cell && cell.element && cell.element.length == 1) { this.cellElement = cell.element[0]; } } // Start the cell spinner in the notebook UI. if (this.cellElement) { this.cellElement.classList.remove('completed'); } var _this = this; datalab.session.execute(code, function (error:string, response:any) { _this.handleNewData(env, error, response); }); } private handleNewData(env: any, error:any, response: any) { var data = response.data; // Stop the cell spinner in the notebook UI. if (this.cellElement) { this.cellElement.classList.add('completed'); } if (data == undefined || data.cols == undefined) { error = 'No data'; } if (error) { this.driver.error(error); return; } this.refreshInterval = response.refresh_interval; if (this.refreshInterval == 0) { console.log('No more refreshes for ' + this.refreshData.name); } this.convertDates(data); var options = this.base_options; if (response.options) { // update any options. We need to make a copy so we don't break the base options. options = JSON.parse(JSON.stringify(options)); Chart.extend(options, response.options); } // Don't update or keep refreshing this if control settings have changed. var newEnv = this.getEnvironment(); if (env == newEnv) { console.log('Got refresh for ' + this.refreshData.name + ', ' + env); this.draw(data, options); } else { console.log('Stopping refresh for ' + env + ' as controls are now ' + newEnv) } } // Remove a static chart (PNG) from the notebook and the DOM. protected removeStaticChart():void { var cell = this.getCell(); if (cell) { var pngDivs = <NodeListOf<HTMLDivElement>> cell.element[0].getElementsByClassName('output_png'); if (pngDivs) { for (var i = 0; i < pngDivs.length; i++) { pngDivs[i].innerHTML = ''; } } var cell_outputs = cell.output_area.outputs; var changed = true; while (changed) { changed = false; for (var outputIndex in cell_outputs) { var output = cell_outputs[outputIndex]; if (output.output_type == 'display_data' && output.metadata.source_id == this.dom.id) { cell_outputs.splice(outputIndex, 1); changed = true; break; } } } } else { // Not running under IPython; use a different approach and just clear the DOM. // Iterate through the IPython outputs... var outputDivs = document.getElementsByClassName('output_wrapper'); if (outputDivs) { for (var i = 0; i < outputDivs.length; i++) { // ...and any chart outputs in each... var outputDiv = <HTMLDivElement>outputDivs[i]; var chartDivs = outputDiv.getElementsByClassName('bqgc'); if (chartDivs) { for (var j = 0; j < chartDivs.length; j++) { // ...until we find the chart div ID we want... if (chartDivs[j].id == this.dom.id) { // ...then get any PNG outputs in that same output group... var pngDivs = <NodeListOf<HTMLDivElement>>outputDiv. getElementsByClassName('output_png'); if (pngDivs) { for (var k = 0; k < pngDivs.length; k++) { // ... and clear their contents. pngDivs[k].innerHTML = ''; } } return; } } } } } } } // Add a static chart (PNG) to the notebook. The notebook will in turn add it to the DOM when // the notebook is opened. private addStaticChart():void { var _this = this; this.driver.getStaticImage(function (img:string) { _this.handleStaticChart(img); }); } private handleStaticChart(img: string) { if (img) { var cell = this.getCell(); if (cell) { var encoding = img.substr(img.indexOf(',') + 1); // strip leading base64 etc. var static_output = { metadata: { source_id: this.dom.id }, data: { 'image/png': encoding }, output_type: 'display_data' }; cell.output_area.outputs.push(static_output); } } } // Set up a refresh callback if we have a non-zero interval and the DOM element still exists // (i.e. output hasn't been cleared). private configureRefresh(refreshInterval:number):void { if (refreshInterval > 0 && document.getElementById(this.dom.id)) { window.setTimeout(this.getRefreshHandler(false), 1000 * refreshInterval); } } // Cache the current data and options and draw the chart. public draw(data:any, options:any):void { var env:string = this.getEnvironment(); this.dataCache[env] = data; this.optionsCache[env] = options; if ('cols' in data) { this.driver.draw(data, options); } this.configureRefresh(this.refreshInterval); } } //----------------------------------------------------------- // A special version of Chart for supporting paginated data. class PagedTable extends Chart { firstRow:number; pageSize:number; constructor(driver:ChartLibraryDriver, dom:HTMLElement, controlIds:Array<string>, base_options:any, refreshData:any, refreshInterval:number, totalRows:number) { super(driver, dom, controlIds, base_options, refreshData, refreshInterval, totalRows); this.firstRow = 0; // Index of first row being displayed in page. this.pageSize = base_options.pageSize || 25; if (this.base_options.showRowNumber == undefined) { this.base_options.showRowNumber = true; } this.base_options.sort = 'disable'; var __this = this; this.driver.addPageChangedHandler(function (page:number) { __this.handlePageEvent(page); }); } // Get control settings for cache key. For paged table we add the first row offset of the table. protected getControlSettings():any { var env = super.getControlSettings(); if (env) { env.first = this.firstRow; } return env; } public draw(data:any, options:any):void { var count = this.pageSize; options.firstRowNumber = this.firstRow + 1; options.page = 'event'; if (this.totalRows < 0) { // We don't know where the end is, so we should have 'next' button. options.pagingButtonsConfiguration = this.firstRow > 0 ? 'both' : 'next'; } else { count = this.totalRows - this.firstRow; if (count > this.pageSize) { count = this.pageSize; } if (this.firstRow + count < this.totalRows) { // We are not on last page, so we should have 'next' button. options.pagingButtonsConfiguration = this.firstRow > 0 ? 'both' : 'next'; } else { // We are on last page if (this.firstRow == 0) { options.pagingButtonsConfiguration = 'none'; options.page = 'disable'; } else { options.pagingButtonsConfiguration = 'prev'; } } } super.draw(data, options); } // Handle page forward/back events. Page will only be 0 or 1. handlePageEvent(page:number):void { var offset = (page == 0) ? -1 : 1; this.firstRow += offset * this.pageSize; this.refreshData.first = this.firstRow; this.refreshData.count = this.pageSize; this.refresh(true); } } function convertListToDataTable(data:any):any { if (!data || !data.length) { return {cols: [], rows: []}; } var firstItem = data[0]; var names = Object.keys(firstItem); var columns = names.map(function (name) { return {id: name, label: name, type: typeof firstItem[name]} }); var rows = data.map(function (item:any) { var cells = names.map(function (name) { return {v: item[name]}; }); return {c: cells}; }); return {cols: columns, rows: rows}; } // The main render method, called from render() wrapper below. dom is the DOM element // for the chart, model is a set of parameters from Python, and options is a JSON // set of options provided by the user in the cell magic body, which takes precedence over // model. An initial set of data can be passed in as a final optional parameter. function _render(driver:ChartLibraryDriver, dom:HTMLElement, chartStyle:string, controlIds:Array<string>, data:any, options:any, refreshData:any, refreshInterval:number, totalRows:number):void { require(["base/js/namespace"], function(Jupyter: any) { var url = "datalab/"; require(driver.requires(url, chartStyle), function (/* ... */) { // chart module should be last dependency in require() call... var chartModule = arguments[arguments.length - 1]; // See if it needs to be a member. driver.init(chartModule); options = options || {}; var chart:Chart; if (chartStyle == 'paged_table') { chart = new PagedTable(driver, dom, controlIds, options, refreshData, refreshInterval, totalRows); } else { chart = new Chart(driver, dom, controlIds, options, refreshData, refreshInterval, totalRows); } chart.convertDates(data); chart.draw(data, options); // Do we need to do anything to prevent it getting GCed? }); }); } export function render(driverName:string, dom:HTMLElement, events:any, chartStyle:string, controlIds:Array<string>, data:any, options:any, refreshData:any, refreshInterval:number, totalRows:number):void { // If this is HTML from nbconvert we can't support paging so add some text making this clear. if (chartStyle == 'paged_table' && document.hasOwnProperty('_in_nbconverted')) { chartStyle = 'table'; var p = document.createElement("div"); p.innerHTML = '<br>(Truncated to first page of results)'; dom.parentNode.insertBefore(p, dom.nextSibling); } // Allocate an appropriate driver. var driver:ChartLibraryDriver; if (driverName == 'plotly') { driver = new PlotlyDriver(dom, chartStyle); } else if (driverName == 'gcharts') { driver = new GChartsDriver(dom, chartStyle); } else { throw new Error('Unsupported chart driver ' + driverName); } // Get data in form needed for GCharts. // We shouldn't need this; should be handled by caller. if (!data.cols && !data.rows) { data = this.convertListToDataTable(data); } // If there is no IPython instance, assume that this is being executed in a sandboxed output // environment and render immediately. // If we have a datalab session, we can go ahead and draw the chart; if not, add code to do the // drawing to an event handler for when the kernel is ready. if (!this.hasIPython || IPython.notebook.kernel.is_connected()) { _render(driver, dom, chartStyle, controlIds, data, options, refreshData, refreshInterval, totalRows) } else { // If the kernel is not connected, wait for the event. events.on('kernel_ready.Kernel', function (e:any) { _render(driver, dom, chartStyle, controlIds, data, options, refreshData, refreshInterval, totalRows) }); } } } export = Charting;
the_stack
import * as path from 'path'; import {google} from '../../protos/protos'; import {grpc} from 'google-gax'; import * as protoLoader from '@grpc/proto-loader'; // eslint-disable-next-line node/no-extraneous-import import {Metadata} from '@grpc/grpc-js'; import {Transaction} from '../../src'; import protobuf = google.spanner.v1; import Timestamp = google.protobuf.Timestamp; import RetryInfo = google.rpc.RetryInfo; import ExecuteBatchDmlResponse = google.spanner.v1.ExecuteBatchDmlResponse; import ResultSet = google.spanner.v1.ResultSet; import Status = google.rpc.Status; import Any = google.protobuf.Any; import QueryMode = google.spanner.v1.ExecuteSqlRequest.QueryMode; import NullValue = google.protobuf.NullValue; const PROTO_PATH = 'spanner.proto'; const IMPORT_PATH = __dirname + '/../../../protos'; const PROTO_DIR = __dirname + '/../../../protos/google/spanner/v1'; const GAX_PROTO_DIR = path.join( path.dirname(require.resolve('google-gax')), '..', 'protos' ); /** * Load the Spanner service proto. */ const packageDefinition = protoLoader.loadSync(PROTO_PATH, { keepCase: false, longs: String, enums: String, defaults: true, oneofs: true, includeDirs: [IMPORT_PATH, PROTO_DIR, GAX_PROTO_DIR], }); const protoDescriptor = grpc.loadPackageDefinition(packageDefinition); const spannerProtoDescriptor = protoDescriptor['google']['spanner']['v1']; const RETRY_INFO_BIN = 'google.rpc.retryinfo-bin'; const RETRY_INFO_TYPE = 'type.googleapis.com/google.rpc.retryinfo'; /** * The type of result for an SQL statement that the mock server should return. */ enum StatementResultType { ERROR, RESULT_SET, UPDATE_COUNT, } /** * StatementResult contains the result for an SQL statement on the mock server. */ export class StatementResult { private readonly _type: StatementResultType; get type(): StatementResultType { return this._type; } private readonly _error: Error | null; get error(): Error { if (this._error) { return this._error; } throw new Error('The StatementResult does not contain an Error'); } private readonly _resultSet: | protobuf.ResultSet | protobuf.PartialResultSet[] | null; get resultSet(): protobuf.ResultSet | protobuf.PartialResultSet[] { if (this._resultSet) { return this._resultSet; } throw new Error('The StatementResult does not contain a ResultSet'); } private readonly _updateCount: number | null; get updateCount(): number { if (this._updateCount) { return this._updateCount; } throw new Error('The StatementResult does not contain an UpdateCount'); } private constructor( type: StatementResultType, error: Error | null, resultSet: protobuf.ResultSet | protobuf.PartialResultSet[] | null, updateCount: number | null ) { this._type = type; this._error = error; this._resultSet = resultSet; this._updateCount = updateCount; } /** * Create a StatementResult that will return an error. * @param error The error to return for the statement. */ static error(error: Error): StatementResult { return new StatementResult(StatementResultType.ERROR, error, null, null); } /** * Create a StatementResult that will return a ResultSet or a stream of PartialResultSets. * @param resultSet The result set to return. */ static resultSet( resultSet: protobuf.ResultSet | protobuf.PartialResultSet[] ): StatementResult { return new StatementResult( StatementResultType.RESULT_SET, null, resultSet, null ); } /** * Create a StatementResult that will return an update count. * @param updateCount The row count to return. */ static updateCount(updateCount: number): StatementResult { return new StatementResult( StatementResultType.UPDATE_COUNT, null, null, updateCount ); } } export interface MockError extends grpc.ServiceError { streamIndex?: number; } export class SimulatedExecutionTime { private readonly _minimumExecutionTime?: number; get minimumExecutionTime(): number | undefined { return this._minimumExecutionTime; } private readonly _randomExecutionTime?: number; get randomExecutionTime(): number | undefined { return this._randomExecutionTime; } private readonly _errors?: grpc.ServiceError[]; get errors(): MockError[] | undefined { return this._errors; } // Keep error after execution. The error will continue to be returned until // it is cleared. private readonly _keepError?: boolean; private constructor(input: { minimumExecutionTime?: number; randomExecutionTime?: number; errors?: grpc.ServiceError[]; keepError?: boolean; }) { this._minimumExecutionTime = input.minimumExecutionTime; this._randomExecutionTime = input.randomExecutionTime; this._errors = input.errors; this._keepError = input.keepError; } static ofError(error: MockError): SimulatedExecutionTime { return new SimulatedExecutionTime({errors: [error]}); } static ofErrors(errors: MockError[]): SimulatedExecutionTime { return new SimulatedExecutionTime({errors}); } static ofMinAndRandomExecTime(minExecTime: number, randomExecTime: number) { return new SimulatedExecutionTime({ minimumExecutionTime: minExecTime, randomExecutionTime: randomExecTime, }); } async simulateExecutionTime() { if (!(this.randomExecutionTime || this.minimumExecutionTime)) { return; } const rnd = this.randomExecutionTime ? Math.random() * this.randomExecutionTime : 0; const total = (this.minimumExecutionTime ? this.minimumExecutionTime : 0) + rnd; await MockSpanner.sleep(total); } } export function createUnimplementedError(msg: string): grpc.ServiceError { const error = new Error(msg); return Object.assign(error, { code: grpc.status.UNIMPLEMENTED, }) as grpc.ServiceError; } // eslint-disable-next-line @typescript-eslint/no-empty-interface interface Request {} /** * MockSpanner is a mocked in-mem Spanner server that manages sessions and transactions automatically. Results for SQL statements must be registered on the server using the MockSpanner.putStatementResult function. */ export class MockSpanner { private requests: Request[] = []; private metadata: Metadata[] = []; private frozen = 0; private sessionCounter = 0; private sessions: Map<string, protobuf.Session> = new Map< string, protobuf.Session >(); private transactionCounters: Map<string, number> = new Map<string, number>(); private transactions: Map<string, protobuf.Transaction> = new Map< string, protobuf.Transaction >(); private transactionOptions: Map< string, protobuf.ITransactionOptions | null | undefined > = new Map<string, protobuf.ITransactionOptions | null | undefined>(); private abortedTransactions: Set<string> = new Set<string>(); private statementResults: Map<string, StatementResult> = new Map< string, StatementResult >(); private executionTimes: Map<string, SimulatedExecutionTime> = new Map< string, SimulatedExecutionTime >(); private constructor() { this.putStatementResult = this.putStatementResult.bind(this); this.batchCreateSessions = this.batchCreateSessions.bind(this); this.createSession = this.createSession.bind(this); this.deleteSession = this.deleteSession.bind(this); this.getSession = this.getSession.bind(this); this.listSessions = this.listSessions.bind(this); this.beginTransaction = this.beginTransaction.bind(this); this.commit = this.commit.bind(this); this.rollback = this.rollback.bind(this); this.executeBatchDml = this.executeBatchDml.bind(this); this.executeStreamingSql = this.executeStreamingSql.bind(this); this.read = this.read.bind(this); this.streamingRead = this.streamingRead.bind(this); } /** * Creates a MockSpanner instance. */ static create(): MockSpanner { return new MockSpanner(); } resetRequests(): void { this.requests = []; this.metadata = []; } /** * @return the requests that have been received by this mock server. */ getRequests(): Request[] { return this.requests; } /** * @return the metadata that have been received by this mock server. */ getMetadata(): Metadata[] { return this.metadata; } /** * Registers a result for an SQL statement on the server. * @param sql The SQL statement that should return the result. * @param result The result to return. */ putStatementResult(sql: string, result: StatementResult) { this.statementResults.set(sql, result); } removeExecutionTime(fn: Function) { this.executionTimes.delete(fn.name); } setExecutionTime(fn: Function, time: SimulatedExecutionTime) { this.executionTimes.set(fn.name, time); } removeExecutionTimes() { this.executionTimes.clear(); } abortTransaction(transaction: Transaction): void { const formattedId = `${transaction.session.formattedName_}/transactions/${transaction.id}`; if (this.transactions.has(formattedId)) { this.transactions.delete(formattedId); this.transactionOptions.delete(formattedId); this.abortedTransactions.add(formattedId); } else { throw new Error(`Transaction ${formattedId} does not exist`); } } freeze() { this.frozen++; } unfreeze() { if (this.frozen === 0) { throw new Error('This mock server is already unfrozen'); } this.frozen--; } /** * Creates a new session for the given database and adds it to the map of sessions of this server. * @param database The database to create the session for. */ private newSession(database: string): protobuf.Session { const id = this.sessionCounter++; const name = `${database}/sessions/${id}`; const session = protobuf.Session.create({name, createTime: now()}); this.sessions.set(name, session); return session; } private static createSessionNotFoundError(name: string): grpc.ServiceError { const error = new Error(`Session not found: ${name}`); return Object.assign(error, { code: grpc.status.NOT_FOUND, }) as grpc.ServiceError; } private static createTransactionNotFoundError( name: string ): grpc.ServiceError { const error = new Error(`Transaction not found: ${name}`); return Object.assign(error, { code: grpc.status.NOT_FOUND, }) as grpc.ServiceError; } private static createTransactionAbortedError( name: string ): grpc.ServiceError { const error = Object.assign(new Error(`Transaction aborted: ${name}`), { code: grpc.status.ABORTED, }); return Object.assign(error, { metadata: this.createMinimalRetryDelayMetadata(), }) as grpc.ServiceError; } static createMinimalRetryDelayMetadata(): grpc.Metadata { const metadata = new grpc.Metadata(); const retry = RetryInfo.encode({ retryDelay: { seconds: 0, nanos: 1, }, }); metadata.add(RETRY_INFO_BIN, Buffer.from(retry.finish())); return metadata; } static sleep(ms): Promise<void> { return new Promise(resolve => setTimeout(resolve, ms)); } private async simulateExecutionTime(functionName: string): Promise<void> { while (this.frozen > 0) { await MockSpanner.sleep(10); } const execTime = this.executionTimes.get(functionName); if (execTime) { await execTime.simulateExecutionTime(); } if ( execTime && execTime.errors && execTime.errors.length && !execTime.errors[0].streamIndex ) { throw execTime.errors.shift(); } return Promise.resolve(); } private shiftStreamError( functionName: string, index: number ): MockError | undefined { const execTime = this.executionTimes.get(functionName); if (execTime) { if ( execTime.errors && execTime.errors.length && execTime.errors[0].streamIndex === index ) { return execTime.errors.shift(); } } return undefined; } private pushRequest(request: Request, metadata: Metadata): void { this.requests.push(request); this.metadata.push(metadata); } batchCreateSessions( call: grpc.ServerUnaryCall< protobuf.BatchCreateSessionsRequest, protobuf.BatchCreateSessionsResponse >, callback: protobuf.Spanner.BatchCreateSessionsCallback ) { this.pushRequest(call.request!, call.metadata); this.simulateExecutionTime(this.batchCreateSessions.name) .then(() => { const sessions = new Array<protobuf.Session>(); for (let i = 0; i < call.request!.sessionCount; i++) { sessions.push(this.newSession(call.request!.database)); } callback( null, protobuf.BatchCreateSessionsResponse.create({session: sessions}) ); }) .catch(err => { callback(err); }); } createSession( call: grpc.ServerUnaryCall<protobuf.CreateSessionRequest, protobuf.Session>, callback: protobuf.Spanner.CreateSessionCallback ) { this.pushRequest(call.request!, call.metadata); this.simulateExecutionTime(this.createSession.name).then(() => { callback(null, this.newSession(call.request!.database)); }); } getSession( call: grpc.ServerUnaryCall<protobuf.GetSessionRequest, protobuf.Session>, callback: protobuf.Spanner.GetSessionCallback ) { this.pushRequest(call.request!, call.metadata); this.simulateExecutionTime(this.getSession.name).then(() => { const session = this.sessions[call.request!.name]; if (session) { callback(null, session); } else { callback(MockSpanner.createSessionNotFoundError(call.request!.name)); } }); } listSessions( call: grpc.ServerUnaryCall< protobuf.ListSessionsRequest, protobuf.ListSessionsResponse >, callback: protobuf.Spanner.ListSessionsCallback ) { this.pushRequest(call.request!, call.metadata); this.simulateExecutionTime(this.listSessions.name).then(() => { callback( null, protobuf.ListSessionsResponse.create({ sessions: Array.from(this.sessions.values()).filter(session => { return session.name.startsWith(call.request!.database); }), }) ); }); } deleteSession( call: grpc.ServerUnaryCall< protobuf.DeleteSessionRequest, google.protobuf.Empty >, callback: protobuf.Spanner.DeleteSessionCallback ) { this.pushRequest(call.request!, call.metadata); if (this.sessions.delete(call.request!.name)) { callback(null, google.protobuf.Empty.create()); } else { callback(MockSpanner.createSessionNotFoundError(call.request!.name)); } } executeSql( call: grpc.ServerUnaryCall<protobuf.ExecuteSqlRequest, {}>, callback: protobuf.Spanner.ExecuteSqlCallback ) { this.pushRequest(call.request!, call.metadata); callback(createUnimplementedError('ExecuteSql is not yet implemented')); } executeStreamingSql( call: grpc.ServerWritableStream< protobuf.ExecuteSqlRequest, protobuf.PartialResultSet > ) { this.pushRequest(call.request!, call.metadata); this.simulateExecutionTime(this.executeStreamingSql.name) .then(() => { if (call.request!.transaction && call.request!.transaction.id) { const fullTransactionId = `${call.request!.session}/transactions/${ call.request!.transaction.id }`; if (this.abortedTransactions.has(fullTransactionId)) { call.emit( 'error', MockSpanner.createTransactionAbortedError(`${fullTransactionId}`) ); call.end(); return; } } const res = this.statementResults.get(call.request!.sql); if (res) { let partialResultSets; let resumeIndex; let streamErr; switch (res.type) { case StatementResultType.RESULT_SET: if (Array.isArray(res.resultSet)) { partialResultSets = res.resultSet; } else { partialResultSets = MockSpanner.toPartialResultSets( res.resultSet, call.request!.queryMode ); } // Resume on the next index after the last one seen by the client. resumeIndex = call.request!.resumeToken.length === 0 ? 0 : Number.parseInt(call.request!.resumeToken.toString(), 10) + 1; for ( let index = resumeIndex; index < partialResultSets.length; index++ ) { const streamErr = this.shiftStreamError( this.executeStreamingSql.name, index ); if (streamErr) { call.emit('error', streamErr); break; } call.write(partialResultSets[index]); } break; case StatementResultType.UPDATE_COUNT: call.write( MockSpanner.emptyPartialResultSet( Buffer.from('1'.padStart(8, '0')) ) ); streamErr = this.shiftStreamError( this.executeStreamingSql.name, 1 ); if (streamErr) { call.emit('error', streamErr); break; } call.write(MockSpanner.toPartialResultSet(res.updateCount)); break; case StatementResultType.ERROR: call.emit('error', res.error); break; default: call.emit( 'error', new Error(`Unknown StatementResult type: ${res.type}`) ); } } else { call.emit( 'error', new Error(`There is no result registered for ${call.request!.sql}`) ); } call.end(); }) .catch(err => { call.emit('error', err); call.end(); }); } /** * Splits a ResultSet into one PartialResultSet per row. This ensure that we can also test returning multiple partial results sets from a streaming method. * @param resultSet The ResultSet to split. * @param queryMode The query mode that was used to execute the query. */ private static toPartialResultSets( resultSet: protobuf.ResultSet, queryMode: | google.spanner.v1.ExecuteSqlRequest.QueryMode | keyof typeof google.spanner.v1.ExecuteSqlRequest.QueryMode, rowsPerPartialResultSet = 1 ): protobuf.PartialResultSet[] { const res: protobuf.PartialResultSet[] = []; let first = true; for (let i = 0; i < resultSet.rows.length; i += rowsPerPartialResultSet) { const token = i.toString().padStart(8, '0'); const partial = protobuf.PartialResultSet.create({ resumeToken: Buffer.from(token), values: [], }); for ( let row = i; row < Math.min(i + rowsPerPartialResultSet, resultSet.rows.length); row++ ) { partial.values.push(...resultSet.rows[row].values!); } if (first) { partial.metadata = resultSet.metadata; first = false; } res.push(partial); } if (queryMode === QueryMode.PROFILE || queryMode === 'PROFILE') { // Include an empty query plan and statistics. res[res.length - 1].stats = { queryStats: {fields: {}}, queryPlan: {planNodes: []}, }; } return res; } private static emptyPartialResultSet( resumeToken: Uint8Array ): protobuf.PartialResultSet { return protobuf.PartialResultSet.create({ resumeToken, }); } private static toPartialResultSet( rowCount: number ): protobuf.PartialResultSet { const stats = { rowCountExact: rowCount, rowCount: 'rowCountExact', }; return protobuf.PartialResultSet.create({ stats, }); } private static toResultSet(rowCount: number): protobuf.ResultSet { const stats = { rowCountExact: rowCount, rowCount: 'rowCountExact', }; return protobuf.ResultSet.create({ stats, }); } executeBatchDml( call: grpc.ServerUnaryCall< protobuf.ExecuteBatchDmlRequest, protobuf.ExecuteBatchDmlResponse >, callback: protobuf.Spanner.ExecuteBatchDmlCallback ) { this.pushRequest(call.request!, call.metadata); this.simulateExecutionTime(this.executeBatchDml.name) .then(() => { if (call.request!.transaction && call.request!.transaction.id) { const fullTransactionId = `${call.request!.session}/transactions/${ call.request!.transaction.id }`; if (this.abortedTransactions.has(fullTransactionId)) { callback( MockSpanner.createTransactionAbortedError(`${fullTransactionId}`) ); return; } } const results: ResultSet[] = []; let statementStatus = Status.create({code: grpc.status.OK}); for ( let i = 0; i < call.request!.statements.length && statementStatus.code === grpc.status.OK; i++ ) { const streamErr = this.shiftStreamError(this.executeBatchDml.name, i); if (streamErr) { statementStatus = Status.create({ code: streamErr.code, message: streamErr.message, }); if (streamErr.metadata && streamErr.metadata.get(RETRY_INFO_BIN)) { const retryInfo = streamErr.metadata.get(RETRY_INFO_BIN)[0]; statementStatus.details = [ Any.create({ type_url: RETRY_INFO_TYPE, value: retryInfo, }), ]; } continue; } const statement = call.request!.statements[i]; const res = this.statementResults.get(statement.sql!); if (res) { switch (res.type) { case StatementResultType.RESULT_SET: callback(new Error('Wrong result type for batch DML')); break; case StatementResultType.UPDATE_COUNT: results.push(MockSpanner.toResultSet(res.updateCount)); break; case StatementResultType.ERROR: if ((res.error as grpc.ServiceError).code) { const serviceError = res.error as grpc.ServiceError; statementStatus = { code: serviceError.code, message: serviceError.message, } as Status; } else { statementStatus = { code: grpc.status.INTERNAL, message: res.error.message, } as Status; } break; default: callback( new Error(`Unknown StatementResult type: ${res.type}`) ); } } else { callback( new Error(`There is no result registered for ${statement.sql}`) ); } } callback( null, ExecuteBatchDmlResponse.create({ resultSets: results, status: statementStatus, }) ); }) .catch(err => { callback(err); }); } read( call: grpc.ServerUnaryCall<protobuf.ReadRequest, {}>, callback: protobuf.Spanner.ReadCallback ) { this.pushRequest(call.request!, call.metadata); callback(createUnimplementedError('Read is not yet implemented')); } streamingRead(call: grpc.ServerWritableStream<protobuf.ReadRequest, {}>) { this.pushRequest(call.request!, call.metadata); call.emit( 'error', createUnimplementedError('StreamingRead is not yet implemented') ); call.end(); } beginTransaction( call: grpc.ServerUnaryCall< protobuf.BeginTransactionRequest, protobuf.Transaction >, callback: protobuf.Spanner.BeginTransactionCallback ) { this.pushRequest(call.request!, call.metadata); this.simulateExecutionTime(this.beginTransaction.name) .then(() => { const session = this.sessions.get(call.request!.session); if (session) { let counter = this.transactionCounters.get(session.name); if (!counter) { counter = 0; } const id = ++counter; this.transactionCounters.set(session.name, counter); const transactionId = id.toString().padStart(12, '0'); const fullTransactionId = session.name + '/transactions/' + transactionId; const readTimestamp = call.request!.options && call.request!.options.readOnly ? now() : undefined; const transaction = protobuf.Transaction.create({ id: Buffer.from(transactionId), readTimestamp, }); this.transactions.set(fullTransactionId, transaction); this.transactionOptions.set(fullTransactionId, call.request!.options); callback(null, transaction); } else { callback( MockSpanner.createSessionNotFoundError(call.request!.session) ); } }) .catch(err => { callback(err); }); } commit( call: grpc.ServerUnaryCall<protobuf.CommitRequest, protobuf.CommitResponse>, callback: protobuf.Spanner.CommitCallback ) { this.pushRequest(call.request!, call.metadata); this.simulateExecutionTime(this.commit.name) .then(() => { if (call.request!.transactionId) { const fullTransactionId = `${call.request!.session}/transactions/${ call.request!.transactionId }`; if (this.abortedTransactions.has(fullTransactionId)) { callback( MockSpanner.createTransactionAbortedError(`${fullTransactionId}`) ); return; } } const session = this.sessions.get(call.request!.session); if (session) { if (call.request!.transactionId) { const buffer = Buffer.from(call.request!.transactionId as string); const transactionId = buffer.toString(); const fullTransactionId = session.name + '/transactions/' + transactionId; const transaction = this.transactions.get(fullTransactionId); if (transaction) { this.transactions.delete(fullTransactionId); this.transactionOptions.delete(fullTransactionId); callback( null, protobuf.CommitResponse.create({ commitTimestamp: now(), }) ); } else { callback( MockSpanner.createTransactionNotFoundError(fullTransactionId) ); } } else if (call.request!.singleUseTransaction) { callback( null, protobuf.CommitResponse.create({ commitTimestamp: now(), }) ); } } else { callback( MockSpanner.createSessionNotFoundError(call.request!.session) ); } }) .catch(err => { callback(err); }); } rollback( call: grpc.ServerUnaryCall<protobuf.RollbackRequest, google.protobuf.Empty>, callback: protobuf.Spanner.RollbackCallback ) { this.pushRequest(call.request!, call.metadata); const session = this.sessions.get(call.request!.session); if (session) { const buffer = Buffer.from(call.request!.transactionId as string); const transactionId = buffer.toString(); const fullTransactionId = session.name + '/transactions/' + transactionId; const transaction = this.transactions.get(fullTransactionId); if (transaction) { this.transactions.delete(fullTransactionId); this.transactionOptions.delete(fullTransactionId); callback(null, google.protobuf.Empty.create()); } else { callback(MockSpanner.createTransactionNotFoundError(fullTransactionId)); } } else { callback(MockSpanner.createSessionNotFoundError(call.request!.session)); } } partitionQuery( call: grpc.ServerUnaryCall<protobuf.PartitionQueryRequest, {}>, callback: protobuf.Spanner.PartitionQueryCallback ) { this.pushRequest(call.request!, call.metadata); callback(createUnimplementedError('PartitionQuery is not yet implemented')); } partitionRead( call: grpc.ServerUnaryCall<protobuf.PartitionReadRequest, {}>, callback: protobuf.Spanner.PartitionReadCallback ) { this.pushRequest(call.request!, call.metadata); callback(createUnimplementedError('PartitionQuery is not yet implemented')); } } /** * Creates and adds a MockSpanner instance to the given server. The MockSpanner instance does not contain any mocked results. */ export function createMockSpanner(server: grpc.Server): MockSpanner { const mock = MockSpanner.create(); server.addService(spannerProtoDescriptor.Spanner.service, { batchCreateSessions: mock.batchCreateSessions, createSession: mock.createSession, getSession: mock.getSession, listSessions: mock.listSessions, deleteSession: mock.deleteSession, executeSql: mock.executeSql, executeStreamingSql: mock.executeStreamingSql, executeBatchDml: mock.executeBatchDml, read: mock.read, streamingRead: mock.streamingRead, beginTransaction: mock.beginTransaction, commit: mock.commit, rollback: mock.rollback, partitionQuery: mock.partitionQuery, partitionRead: mock.partitionRead, }); return mock; } /** * Creates a simple result set containing the following data: * * |-----------------------------| * | NUM (INT64) | NAME (STRING) | * |-----------------------------| * | 1 | 'One' | * | 2 | 'Two' | * | 3 | 'Three' | * ------------------------------- * * This ResultSet can be used to easily mock queries on a mock Spanner server. */ export function createSimpleResultSet(): protobuf.ResultSet { const fields = [ protobuf.StructType.Field.create({ name: 'NUM', type: protobuf.Type.create({code: protobuf.TypeCode.INT64}), }), protobuf.StructType.Field.create({ name: 'NAME', type: protobuf.Type.create({code: protobuf.TypeCode.STRING}), }), ]; const metadata = new protobuf.ResultSetMetadata({ rowType: new protobuf.StructType({ fields, }), }); return protobuf.ResultSet.create({ metadata, rows: [ {values: [{stringValue: '1'}, {stringValue: 'One'}]}, {values: [{stringValue: '2'}, {stringValue: 'Two'}]}, {values: [{stringValue: '3'}, {stringValue: 'Three'}]}, ], }); } export const NUM_ROWS_LARGE_RESULT_SET = 100; export function createLargeResultSet(): protobuf.ResultSet { const fields = [ protobuf.StructType.Field.create({ name: 'NUM', type: protobuf.Type.create({code: protobuf.TypeCode.INT64}), }), protobuf.StructType.Field.create({ name: 'NAME', type: protobuf.Type.create({code: protobuf.TypeCode.STRING}), }), ]; const metadata = new protobuf.ResultSetMetadata({ rowType: new protobuf.StructType({ fields, }), }); const rows: google.protobuf.IListValue[] = []; for (let num = 1; num <= NUM_ROWS_LARGE_RESULT_SET; num++) { rows.push({ values: [ {stringValue: `${num}`}, {stringValue: generateRandomString(100)}, ], }); } return protobuf.ResultSet.create({ metadata, rows, }); } export function createSelect1ResultSet(): protobuf.ResultSet { const fields = [ protobuf.StructType.Field.create({ name: '', type: protobuf.Type.create({code: protobuf.TypeCode.INT64}), }), ]; const metadata = new protobuf.ResultSetMetadata({ rowType: new protobuf.StructType({ fields, }), }); return protobuf.ResultSet.create({ metadata, rows: [{values: [{stringValue: '1'}]}], }); } export function createResultSetWithAllDataTypes(): protobuf.ResultSet { const fields = [ protobuf.StructType.Field.create({ name: 'COLBOOL', type: protobuf.Type.create({code: protobuf.TypeCode.BOOL}), }), protobuf.StructType.Field.create({ name: 'COLINT64', type: protobuf.Type.create({code: protobuf.TypeCode.INT64}), }), protobuf.StructType.Field.create({ name: 'COLFLOAT64', type: protobuf.Type.create({code: protobuf.TypeCode.FLOAT64}), }), protobuf.StructType.Field.create({ name: 'COLNUMERIC', type: protobuf.Type.create({code: protobuf.TypeCode.NUMERIC}), }), protobuf.StructType.Field.create({ name: 'COLSTRING', type: protobuf.Type.create({code: protobuf.TypeCode.STRING}), }), protobuf.StructType.Field.create({ name: 'COLBYTES', type: protobuf.Type.create({code: protobuf.TypeCode.BYTES}), }), protobuf.StructType.Field.create({ name: 'COLJSON', type: protobuf.Type.create({code: protobuf.TypeCode.JSON}), }), protobuf.StructType.Field.create({ name: 'COLDATE', type: protobuf.Type.create({code: protobuf.TypeCode.DATE}), }), protobuf.StructType.Field.create({ name: 'COLTIMESTAMP', type: protobuf.Type.create({code: protobuf.TypeCode.TIMESTAMP}), }), protobuf.StructType.Field.create({ name: 'COLBOOLARRAY', type: protobuf.Type.create({ code: protobuf.TypeCode.ARRAY, arrayElementType: protobuf.Type.create({code: protobuf.TypeCode.BOOL}), }), }), protobuf.StructType.Field.create({ name: 'COLINT64ARRAY', type: protobuf.Type.create({ code: protobuf.TypeCode.ARRAY, arrayElementType: protobuf.Type.create({code: protobuf.TypeCode.INT64}), }), }), protobuf.StructType.Field.create({ name: 'COLFLOAT64ARRAY', type: protobuf.Type.create({ code: protobuf.TypeCode.ARRAY, arrayElementType: protobuf.Type.create({ code: protobuf.TypeCode.FLOAT64, }), }), }), protobuf.StructType.Field.create({ name: 'COLNUMERICARRAY', type: protobuf.Type.create({ code: protobuf.TypeCode.ARRAY, arrayElementType: protobuf.Type.create({ code: protobuf.TypeCode.NUMERIC, }), }), }), protobuf.StructType.Field.create({ name: 'COLSTRINGARRAY', type: protobuf.Type.create({ code: protobuf.TypeCode.ARRAY, arrayElementType: protobuf.Type.create({ code: protobuf.TypeCode.STRING, }), }), }), protobuf.StructType.Field.create({ name: 'COLBYTESARRAY', type: protobuf.Type.create({ code: protobuf.TypeCode.ARRAY, arrayElementType: protobuf.Type.create({code: protobuf.TypeCode.BYTES}), }), }), protobuf.StructType.Field.create({ name: 'COLJSONARRAY', type: protobuf.Type.create({ code: protobuf.TypeCode.ARRAY, arrayElementType: protobuf.Type.create({code: protobuf.TypeCode.JSON}), }), }), protobuf.StructType.Field.create({ name: 'COLDATEARRAY', type: protobuf.Type.create({ code: protobuf.TypeCode.ARRAY, arrayElementType: protobuf.Type.create({code: protobuf.TypeCode.DATE}), }), }), protobuf.StructType.Field.create({ name: 'COLTIMESTAMPARRAY', type: protobuf.Type.create({ code: protobuf.TypeCode.ARRAY, arrayElementType: protobuf.Type.create({ code: protobuf.TypeCode.TIMESTAMP, }), }), }), ]; const metadata = new protobuf.ResultSetMetadata({ rowType: new protobuf.StructType({ fields, }), }); return protobuf.ResultSet.create({ metadata, rows: [ { values: [ {boolValue: true}, {stringValue: '1'}, {numberValue: 3.14}, {stringValue: '6.626'}, {stringValue: 'One'}, {stringValue: Buffer.from('test').toString('base64')}, {stringValue: '{"result":true, "count":42}'}, {stringValue: '2021-05-11'}, {stringValue: '2021-05-11T16:46:04.872Z'}, { listValue: { values: [ {boolValue: true}, {boolValue: false}, {nullValue: NullValue.NULL_VALUE}, ], }, }, { listValue: { values: [ {stringValue: '1'}, {stringValue: '100'}, {nullValue: NullValue.NULL_VALUE}, ], }, }, { listValue: { values: [ {numberValue: 3.14}, {numberValue: 100.9}, {nullValue: NullValue.NULL_VALUE}, ], }, }, { listValue: { values: [ {stringValue: '6.626'}, {stringValue: '100'}, {nullValue: NullValue.NULL_VALUE}, ], }, }, { listValue: { values: [ {stringValue: 'One'}, {stringValue: 'test'}, {nullValue: NullValue.NULL_VALUE}, ], }, }, { listValue: { values: [ {stringValue: Buffer.from('test1').toString('base64')}, {stringValue: Buffer.from('test2').toString('base64')}, {nullValue: NullValue.NULL_VALUE}, ], }, }, { listValue: { values: [ {stringValue: '{"result":true, "count":42}'}, {stringValue: '{}'}, {nullValue: NullValue.NULL_VALUE}, ], }, }, { listValue: { values: [ {stringValue: '2021-05-12'}, {stringValue: '2000-02-29'}, {nullValue: NullValue.NULL_VALUE}, ], }, }, { listValue: { values: [ {stringValue: '2021-05-12T08:38:19.8474Z'}, {stringValue: '2000-02-29T07:00:00Z'}, {nullValue: NullValue.NULL_VALUE}, ], }, }, ], }, { values: [ {boolValue: false}, {stringValue: '2'}, {numberValue: 3.14}, {stringValue: '6.626'}, {stringValue: 'Two'}, {stringValue: Buffer.from('test').toString('base64')}, {stringValue: '{"result":true, "count":42}'}, {stringValue: '2021-05-11'}, {stringValue: '2021-05-11T16:46:04.872Z'}, { listValue: { values: [ {boolValue: true}, {boolValue: false}, {nullValue: NullValue.NULL_VALUE}, ], }, }, { listValue: { values: [ {stringValue: '2'}, {stringValue: '200'}, {nullValue: NullValue.NULL_VALUE}, ], }, }, { listValue: { values: [ {numberValue: 3.14}, {numberValue: 100.9}, {nullValue: NullValue.NULL_VALUE}, ], }, }, { listValue: { values: [ {stringValue: '6.626'}, {stringValue: '100'}, {nullValue: NullValue.NULL_VALUE}, ], }, }, { listValue: { values: [ {stringValue: 'Two'}, {stringValue: 'test'}, {nullValue: NullValue.NULL_VALUE}, ], }, }, { listValue: { values: [ {stringValue: Buffer.from('test1').toString('base64')}, {stringValue: Buffer.from('test2').toString('base64')}, {nullValue: NullValue.NULL_VALUE}, ], }, }, { listValue: { values: [ {stringValue: '{"result":true, "count":42}'}, {stringValue: '{}'}, {nullValue: NullValue.NULL_VALUE}, ], }, }, { listValue: { values: [ {stringValue: '2021-05-12'}, {stringValue: '2000-02-29'}, {nullValue: NullValue.NULL_VALUE}, ], }, }, { listValue: { values: [ {stringValue: '2021-05-12T08:38:19.8474Z'}, {stringValue: '2000-02-29T07:00:00Z'}, {nullValue: NullValue.NULL_VALUE}, ], }, }, ], }, { values: [ {nullValue: NullValue.NULL_VALUE}, {nullValue: NullValue.NULL_VALUE}, {nullValue: NullValue.NULL_VALUE}, {nullValue: NullValue.NULL_VALUE}, {nullValue: NullValue.NULL_VALUE}, {nullValue: NullValue.NULL_VALUE}, {nullValue: NullValue.NULL_VALUE}, {nullValue: NullValue.NULL_VALUE}, {nullValue: NullValue.NULL_VALUE}, {nullValue: NullValue.NULL_VALUE}, {nullValue: NullValue.NULL_VALUE}, {nullValue: NullValue.NULL_VALUE}, {nullValue: NullValue.NULL_VALUE}, {nullValue: NullValue.NULL_VALUE}, {nullValue: NullValue.NULL_VALUE}, {nullValue: NullValue.NULL_VALUE}, {nullValue: NullValue.NULL_VALUE}, {nullValue: NullValue.NULL_VALUE}, ], }, ], }); } export function createResultSetWithStringArray(): protobuf.ResultSet { const fields = [ protobuf.StructType.Field.create({ name: 'string1', type: protobuf.Type.create({code: protobuf.TypeCode.STRING}), }), protobuf.StructType.Field.create({ name: 'string2', type: protobuf.Type.create({code: protobuf.TypeCode.STRING}), }), protobuf.StructType.Field.create({ name: 'bool1', type: protobuf.Type.create({code: protobuf.TypeCode.BOOL}), }), protobuf.StructType.Field.create({ name: 'stringArray', type: protobuf.Type.create({ code: protobuf.TypeCode.ARRAY, arrayElementType: protobuf.Type.create({ code: protobuf.TypeCode.STRING, }), }), }), ]; const metadata = new protobuf.ResultSetMetadata({ rowType: new protobuf.StructType({ fields, }), }); return protobuf.ResultSet.create({ metadata, rows: [ { values: [ {stringValue: 'test1_1'}, {stringValue: 'test2_1'}, {boolValue: true}, { listValue: { values: [{stringValue: 'One'}, {stringValue: 'test 1'}], }, }, ], }, { values: [ {stringValue: 'test1_2'}, {stringValue: 'test2_2'}, {boolValue: true}, { listValue: { values: [{stringValue: 'Two'}, {stringValue: 'test 2'}], }, }, ], }, { values: [ {stringValue: 'test1_3'}, {stringValue: 'test2_3'}, {boolValue: true}, { listValue: { values: [{stringValue: 'Three'}, {stringValue: 'test 3'}], }, }, ], }, ], }); } function generateRandomString(length: number) { let result = ''; const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const charactersLength = characters.length; for (let i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; } /** * Returns a protobuf Timestamp containing the current local system time. */ export function now(): Timestamp { const now = Date.now(); return Timestamp.create({seconds: now / 1000, nanos: (now % 1000) * 1e6}); }
the_stack
import { ComponentType } from 'react'; import { obx, computed, autorun, makeObservable, IReactionPublic, IReactionOptions, IReactionDisposer } from '@alilc/lowcode-editor-core'; import { ProjectSchema, ComponentMetadata, ComponentAction, NpmInfo, IEditor, CompositeObject, PropsList, isNodeSchema, NodeSchema, } from '@alilc/lowcode-types'; import { megreAssets, AssetsJson } from '@alilc/lowcode-utils'; import { Project } from '../project'; import { Node, DocumentModel, insertChildren, ParentalNode, TransformStage } from '../document'; import { ComponentMeta } from '../component-meta'; import { INodeSelector, Component } from '../simulator'; import { Scroller, IScrollable } from './scroller'; import { Dragon, isDragNodeObject, isDragNodeDataObject, LocateEvent, DragObject } from './dragon'; import { ActiveTracker } from './active-tracker'; import { Detecting } from './detecting'; import { DropLocation, LocationData, isLocationChildrenDetail } from './location'; import { OffsetObserver, createOffsetObserver } from './offset-observer'; import { focusing } from './focusing'; import { SettingTopEntry } from './setting'; import { BemToolsManager } from '../builtin-simulator/bem-tools/manager'; export interface DesignerProps { editor: IEditor; className?: string; style?: object; defaultSchema?: ProjectSchema; hotkeys?: object; simulatorProps?: object | ((document: DocumentModel) => object); simulatorComponent?: ComponentType<any>; dragGhostComponent?: ComponentType<any>; suspensed?: boolean; componentMetadatas?: ComponentMetadata[]; globalComponentActions?: ComponentAction[]; onMount?: (designer: Designer) => void; onDragstart?: (e: LocateEvent) => void; onDrag?: (e: LocateEvent) => void; onDragend?: (e: { dragObject: DragObject; copy: boolean }, loc?: DropLocation) => void; [key: string]: any; } export class Designer { readonly dragon = new Dragon(this); readonly activeTracker = new ActiveTracker(); readonly detecting = new Detecting(); readonly project: Project; readonly editor: IEditor; readonly bemToolsManager = new BemToolsManager(this); get currentDocument() { return this.project.currentDocument; } get currentHistory() { return this.currentDocument?.history; } get currentSelection() { return this.currentDocument?.selection; } constructor(props: DesignerProps) { makeObservable(this); const { editor } = props; this.editor = editor; this.setProps(props); this.project = new Project(this, props.defaultSchema); let startTime: any; let src = ''; this.dragon.onDragstart((e) => { startTime = Date.now() / 1000; this.detecting.enable = false; const { dragObject } = e; if (isDragNodeObject(dragObject)) { const node = dragObject.nodes[0]?.parent; const npm = node?.componentMeta?.npm; src = [npm?.package, npm?.componentName].filter((item) => !!item).join('-') || node?.componentMeta?.componentName || ''; if (dragObject.nodes.length === 1) { if (dragObject.nodes[0].parent) { // ensure current selecting dragObject.nodes[0].select(); } else { this.currentSelection?.clear(); } } } else { this.currentSelection?.clear(); } if (this.props?.onDragstart) { this.props.onDragstart(e); } this.postEvent('dragstart', e); }); this.dragon.onDrag((e) => { if (this.props?.onDrag) { this.props.onDrag(e); } this.postEvent('drag', e); }); this.dragon.onDragend((e) => { const { dragObject, copy } = e; const loc = this._dropLocation; if (loc) { if (isLocationChildrenDetail(loc.detail) && loc.detail.valid !== false) { let nodes: Node[] | undefined; if (isDragNodeObject(dragObject)) { nodes = insertChildren(loc.target, [...dragObject.nodes], loc.detail.index, copy); } else if (isDragNodeDataObject(dragObject)) { // process nodeData const nodeData = Array.isArray(dragObject.data) ? dragObject.data : [dragObject.data]; const isNotNodeSchema = nodeData.find((item) => !isNodeSchema(item)); if (isNotNodeSchema) { return; } nodes = insertChildren(loc.target, nodeData, loc.detail.index); } if (nodes) { loc.document.selection.selectAll(nodes.map((o) => o.id)); setTimeout(() => this.activeTracker.track(nodes![0]), 10); const endTime: any = Date.now() / 1000; const parent = nodes[0]?.parent; const npm = parent?.componentMeta?.npm; const dest = [npm?.package, npm?.componentName].filter((item) => !!item).join('-') || parent?.componentMeta?.componentName || ''; // eslint-disable-next-line no-unused-expressions // this.postEvent('drag', { // time: (endTime - startTime).toFixed(2), // selected: nodes // ?.map((n) => { // if (!n) { // return; // } // // eslint-disable-next-line no-shadow // const npm = n?.componentMeta?.npm; // return ( // [npm?.package, npm?.componentName].filter((item) => !!item).join('-') || // n?.componentMeta?.componentName // ); // }) // .join('&'), // align: loc?.detail?.near?.align || '', // pos: loc?.detail?.near?.pos || '', // src, // dest, // }); } } } if (this.props?.onDragend) { this.props.onDragend(e, loc); } this.postEvent('dragend', e, loc); this.detecting.enable = true; }); this.activeTracker.onChange(({ node, detail }) => { node.document.simulator?.scrollToNode(node, detail); }); let historyDispose: undefined | (() => void); const setupHistory = () => { if (historyDispose) { historyDispose(); historyDispose = undefined; } this.postEvent('history.change', this.currentHistory); if (this.currentHistory) { const { currentHistory } = this; historyDispose = currentHistory.onStateChange(() => { this.postEvent('history.change', currentHistory); }); } }; this.project.onCurrentDocumentChange(() => { this.postEvent('current-document.change', this.currentDocument); this.postEvent('selection.change', this.currentSelection); this.postEvent('history.change', this.currentHistory); this.setupSelection(); setupHistory(); }); this.postEvent('init', this); this.setupSelection(); setupHistory(); // TODO: 先简单实现,后期通过焦点赋值 focusing.focusDesigner = this; } setupSelection = () => { let selectionDispose: undefined | (() => void); if (selectionDispose) { selectionDispose(); selectionDispose = undefined; } const { currentSelection } = this; // TODO: 避免选中 Page 组件,默认选中第一个子节点;新增规则 或 判断 Live 模式 if ( currentSelection && currentSelection.selected.length === 0 && this.simulatorProps?.designMode === 'live' ) { const rootNodeChildrens = this.currentDocument.getRoot().getChildren().children; if (rootNodeChildrens.length > 0) { currentSelection.select(rootNodeChildrens[0].id); } } this.postEvent('selection.change', currentSelection); if (currentSelection) { selectionDispose = currentSelection.onSelectionChange(() => { this.postEvent('selection.change', currentSelection); }); } }; postEvent(event: string, ...args: any[]) { this.editor.emit(`designer.${event}`, ...args); } private _dropLocation?: DropLocation; get dropLocation() { return this._dropLocation; } /** * 创建插入位置,考虑放到 dragon 中 */ createLocation(locationData: LocationData): DropLocation { const loc = new DropLocation(locationData); if (this._dropLocation && this._dropLocation.document !== loc.document) { this._dropLocation.document.internalSetDropLocation(null); } this._dropLocation = loc; this.postEvent('dropLocation.change', loc); loc.document.internalSetDropLocation(loc); this.activeTracker.track({ node: loc.target, detail: loc.detail }); return loc; } /** * 清除插入位置 */ clearLocation() { if (this._dropLocation) { this._dropLocation.document.internalSetDropLocation(null); } this.postEvent('dropLocation.change', undefined); this._dropLocation = undefined; } createScroller(scrollable: IScrollable) { return new Scroller(scrollable); } private oobxList: OffsetObserver[] = []; createOffsetObserver(nodeInstance: INodeSelector): OffsetObserver | null { const oobx = createOffsetObserver(nodeInstance); this.clearOobxList(); if (oobx) { this.oobxList.push(oobx); } return oobx; } private clearOobxList(force?: boolean) { let l = this.oobxList.length; if (l > 20 || force) { while (l-- > 0) { if (this.oobxList[l].isPurged()) { this.oobxList.splice(l, 1); } } } } touchOffsetObserver() { this.clearOobxList(true); this.oobxList.forEach((item) => item.compute()); } createSettingEntry(nodes: Node[]) { return new SettingTopEntry(this.editor, nodes); } /** * 获得合适的插入位置 */ getSuitableInsertion( insertNode?: Node | NodeSchema | NodeSchema[], ): { target: ParentalNode; index?: number } | null { const activeDoc = this.project.currentDocument; if (!activeDoc) { return null; } if ( Array.isArray(insertNode) && isNodeSchema(insertNode[0]) && this.getComponentMeta(insertNode[0].componentName).isModal ) { return { target: activeDoc.rootNode as ParentalNode, }; } const focusNode = activeDoc.focusNode!; const nodes = activeDoc.selection.getNodes(); const refNode = nodes.find(item => focusNode.contains(item)); let target; let index: number | undefined; if (!refNode || refNode === focusNode) { target = focusNode; } else if (refNode.componentMeta.isContainer) { target = refNode; } else { // FIXME!!, parent maybe null target = refNode.parent!; index = refNode.index + 1; } if (target && insertNode && !target.componentMeta.checkNestingDown(target, insertNode)) { return null; } return { target, index }; } private props?: DesignerProps; setProps(nextProps: DesignerProps) { const props = this.props ? { ...this.props, ...nextProps } : nextProps; if (this.props) { // check hotkeys // TODO: // check simulatorConfig if (props.simulatorComponent !== this.props.simulatorComponent) { this._simulatorComponent = props.simulatorComponent; } if (props.simulatorProps !== this.props.simulatorProps) { this._simulatorProps = props.simulatorProps; // 重新 setupSelection if (props.simulatorProps?.designMode !== this.props.simulatorProps?.designMode) { this.setupSelection(); } } if (props.suspensed !== this.props.suspensed && props.suspensed != null) { this.suspensed = props.suspensed; } if ( props.componentMetadatas !== this.props.componentMetadatas && props.componentMetadatas != null ) { this.buildComponentMetasMap(props.componentMetadatas); } } else { // init hotkeys // todo: // init simulatorConfig if (props.simulatorComponent) { this._simulatorComponent = props.simulatorComponent; } if (props.simulatorProps) { this._simulatorProps = props.simulatorProps; } // init suspensed if (props.suspensed != null) { this.suspensed = props.suspensed; } if (props.componentMetadatas != null) { this.buildComponentMetasMap(props.componentMetadatas); } } this.props = props; } async loadIncrementalAssets(incrementalAssets: AssetsJson): Promise<void> { const { components, packages } = incrementalAssets; components && this.buildComponentMetasMap(components); if (packages) { await this.project.simulator!.setupComponents(packages); } if (components) { // 合并assets let assets = this.editor.get('assets'); let newAssets = megreAssets(assets, incrementalAssets); this.editor.set('assets', newAssets); } // TODO: 因为涉及修改 prototype.view,之后在 renderer 里修改了 vc 的 view 获取逻辑后,可删除 this.refreshComponentMetasMap(); // 完成加载增量资源后发送事件,方便插件监听并处理相关逻辑 this.editor.emit('designer.incrementalAssetsReady'); } /** * 刷新 componentMetasMap,可间接触发模拟器里的 buildComponents */ refreshComponentMetasMap() { this._componentMetasMap = new Map(this._componentMetasMap); } get(key: string): any { return this.props ? this.props[key] : null; } @obx.ref private _simulatorComponent?: ComponentType<any>; @computed get simulatorComponent(): ComponentType<any> | undefined { return this._simulatorComponent; } @obx.ref private _simulatorProps?: object | ((document: DocumentModel) => object); @computed get simulatorProps(): object | ((project: Project) => object) { return this._simulatorProps || {}; } @obx.ref private _suspensed = false; get suspensed(): boolean { return this._suspensed; } set suspensed(flag: boolean) { this._suspensed = flag; // Todo afterwards... if (flag) { // this.project.suspensed = true? } } get schema(): ProjectSchema { return this.project.getSchema(); } setSchema(schema?: ProjectSchema) { this.project.load(schema); } @obx.ref private _componentMetasMap = new Map<string, ComponentMeta>(); private _lostComponentMetasMap = new Map<string, ComponentMeta>(); buildComponentMetasMap(metas: ComponentMetadata[]) { metas.forEach((data) => this.createComponentMeta(data)); } createComponentMeta(data: ComponentMetadata): ComponentMeta { const key = data.componentName; let meta = this._componentMetasMap.get(key); if (meta) { meta.setMetadata(data); this._componentMetasMap.set(key, meta); } else { meta = this._lostComponentMetasMap.get(key); if (meta) { meta.setMetadata(data); this._lostComponentMetasMap.delete(key); } else { meta = new ComponentMeta(this, data); } this._componentMetasMap.set(key, meta); } return meta; } getGlobalComponentActions(): ComponentAction[] | null { return this.props?.globalComponentActions || null; } getComponentMeta( componentName: string, generateMetadata?: () => ComponentMetadata | null, ): ComponentMeta { if (this._componentMetasMap.has(componentName)) { return this._componentMetasMap.get(componentName)!; } if (this._lostComponentMetasMap.has(componentName)) { return this._lostComponentMetasMap.get(componentName)!; } const meta = new ComponentMeta(this, { componentName, ...(generateMetadata ? generateMetadata() : null), }); this._lostComponentMetasMap.set(componentName, meta); return meta; } getComponentMetasMap() { return this._componentMetasMap; } @computed get componentsMap(): { [key: string]: NpmInfo | Component } { const maps: any = {}; const designer = this; designer._componentMetasMap.forEach((config, key) => { const metaData = config.getMetadata(); if (metaData.devMode === 'lowCode') { maps[key] = metaData.schema; } else { const view = metaData.configure.advanced?.view; if (view) { maps[key] = view; } else { maps[key] = config.npm; } } }); return maps; } private propsReducers = new Map<TransformStage, PropsReducer[]>(); transformProps(props: CompositeObject | PropsList, node: Node, stage: TransformStage) { if (Array.isArray(props)) { // current not support, make this future return props; } const reducers = this.propsReducers.get(stage); if (!reducers) { return props; } return reducers.reduce((xprops, reducer) => { try { return reducer(xprops, node.internalToShellNode() as any, { stage }); } catch (e) { // todo: add log console.warn(e); return xprops; } }, props); } addPropsReducer(reducer: PropsReducer, stage: TransformStage) { const reducers = this.propsReducers.get(stage); if (reducers) { reducers.push(reducer); } else { this.propsReducers.set(stage, [reducer]); } } autorun(effect: (reaction: IReactionPublic) => void, options?: IReactionOptions): IReactionDisposer { return autorun(effect, options); } purge() { // TODO: } } export type PropsReducerContext = { stage: TransformStage }; export type PropsReducer = ( props: CompositeObject, node: Node, ctx?: PropsReducerContext, ) => CompositeObject;
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [lex-v2](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonlexv2.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class LexV2 extends PolicyStatement { public servicePrefix = 'lex'; /** * Statement provider for service [lex-v2](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonlexv2.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to build an existing bot locale in a bot * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_BuildBotLocale.html */ public toBuildBotLocale() { return this.to('BuildBotLocale'); } /** * Grants permission to create a new bot and a test bot alias pointing to the DRAFT bot version * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/lexv2/latest/dg/API_CreateBot.html */ public toCreateBot() { return this.to('CreateBot'); } /** * Grants permission to create a new bot alias in a bot * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/lexv2/latest/dg/API_CreateBotAlias.html */ public toCreateBotAlias() { return this.to('CreateBotAlias'); } /** * Grants permission to create a bot channel in an existing bot * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/deploying-messaging-platform.html */ public toCreateBotChannel() { return this.to('CreateBotChannel'); } /** * Grants permission to create a new bot locale in an existing bot * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_CreateBotLocale.html */ public toCreateBotLocale() { return this.to('CreateBotLocale'); } /** * Grants permission to create a new version of an existing bot * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_CreateBotVersion.html */ public toCreateBotVersion() { return this.to('CreateBotVersion'); } /** * Grants permission to create an export for an existing resource * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_CreateExport.html */ public toCreateExport() { return this.to('CreateExport'); } /** * Grants permission to create a new intent in an existing bot locale * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_CreateIntent.html */ public toCreateIntent() { return this.to('CreateIntent'); } /** * Grants permission to create a new resource policy for a Lex resource * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_CreateResourcePolicy.html */ public toCreateResourcePolicy() { return this.to('CreateResourcePolicy'); } /** * Grants permission to create a new slot in an intent * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_CreateSlot.html */ public toCreateSlot() { return this.to('CreateSlot'); } /** * Grants permission to create a new slot type in an existing bot locale * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_CreateSlotType.html */ public toCreateSlotType() { return this.to('CreateSlotType'); } /** * Grants permission to create an upload url for import file * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_CreateUploadUrl.html */ public toCreateUploadUrl() { return this.to('CreateUploadUrl'); } /** * Grants permission to delete an existing bot * * Access Level: Write * * Dependent actions: * - lex:DeleteBotAlias * - lex:DeleteBotChannel * - lex:DeleteBotLocale * - lex:DeleteBotVersion * - lex:DeleteIntent * - lex:DeleteSlot * - lex:DeleteSlotType * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DeleteBot.html */ public toDeleteBot() { return this.to('DeleteBot'); } /** * Grants permission to delete an existing bot alias in a bot * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DeleteBotAlias.html */ public toDeleteBotAlias() { return this.to('DeleteBotAlias'); } /** * Grants permission to delete an existing bot channel * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/deploying-messaging-platform.html */ public toDeleteBotChannel() { return this.to('DeleteBotChannel'); } /** * Grants permission to delete an existing bot locale in a bot * * Access Level: Write * * Dependent actions: * - lex:DeleteIntent * - lex:DeleteSlot * - lex:DeleteSlotType * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DeleteBotLocale.html */ public toDeleteBotLocale() { return this.to('DeleteBotLocale'); } /** * Grants permission to delete an existing bot version * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DeleteBotVersion.html */ public toDeleteBotVersion() { return this.to('DeleteBotVersion'); } /** * Grants permission to delete an existing export * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DeleteExport.html */ public toDeleteExport() { return this.to('DeleteExport'); } /** * Grants permission to delete an existing import * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DeleteImport.html */ public toDeleteImport() { return this.to('DeleteImport'); } /** * Grants permission to delete an existing intent in a bot locale * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DeleteIntent.html */ public toDeleteIntent() { return this.to('DeleteIntent'); } /** * Grants permission to delete an existing resource policy for a Lex resource * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DeleteResourcePolicy.html */ public toDeleteResourcePolicy() { return this.to('DeleteResourcePolicy'); } /** * Grants permission to delete session information for a bot alias and user ID * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_DeleteSession.html */ public toDeleteSession() { return this.to('DeleteSession'); } /** * Grants permission to delete an existing slot in an intent * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DeleteSlot.html */ public toDeleteSlot() { return this.to('DeleteSlot'); } /** * Grants permission to delete an existing slot type in a bot locale * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DeleteSlotType.html */ public toDeleteSlotType() { return this.to('DeleteSlotType'); } /** * Grants permission to retrieve an existing bot * * Access Level: Read * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DescribeBot.html */ public toDescribeBot() { return this.to('DescribeBot'); } /** * Grants permission to retrieve an existing bot alias * * Access Level: Read * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DescribeBotAlias.html */ public toDescribeBotAlias() { return this.to('DescribeBotAlias'); } /** * Grants permission to retrieve an existing bot channel * * Access Level: Read * * https://docs.aws.amazon.com/lexv2/latest/dg/deploying-messaging-platform.html */ public toDescribeBotChannel() { return this.to('DescribeBotChannel'); } /** * Grants permission to retrieve an existing bot locale * * Access Level: Read * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DescribeBotLocale.html */ public toDescribeBotLocale() { return this.to('DescribeBotLocale'); } /** * Grants permission to retrieve an existing bot version. * * Access Level: Read * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DescribeBotVersion.html */ public toDescribeBotVersion() { return this.to('DescribeBotVersion'); } /** * Grants permission to retrieve an existing export * * Access Level: Read * * Dependent actions: * - lex:DescribeBot * - lex:DescribeBotLocale * - lex:DescribeIntent * - lex:DescribeSlot * - lex:DescribeSlotType * - lex:ListBotLocales * - lex:ListIntents * - lex:ListSlotTypes * - lex:ListSlots * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DescribeExport.html */ public toDescribeExport() { return this.to('DescribeExport'); } /** * Grants permission to retrieve an existing import * * Access Level: Read * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DescribeImport.html */ public toDescribeImport() { return this.to('DescribeImport'); } /** * Grants permission to retrieve an existing intent * * Access Level: Read * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DescribeIntent.html */ public toDescribeIntent() { return this.to('DescribeIntent'); } /** * Grants permission to retrieve an existing resource policy for a Lex resource * * Access Level: Read * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DescribeResourcePolicy.html */ public toDescribeResourcePolicy() { return this.to('DescribeResourcePolicy'); } /** * Grants permission to retrieve an existing slot * * Access Level: Read * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DescribeSlot.html */ public toDescribeSlot() { return this.to('DescribeSlot'); } /** * Grants permission to retrieve an existing slot type * * Access Level: Read * * https://docs.aws.amazon.com/lexv2/latest/dg/API_DescribeSlotType.html */ public toDescribeSlotType() { return this.to('DescribeSlotType'); } /** * Grants permission to retrieve session information for a bot alias and user ID * * Access Level: Read * * https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_GetSession.html */ public toGetSession() { return this.to('GetSession'); } /** * Grants permission to list bot aliases in an bot * * Access Level: List * * https://docs.aws.amazon.com/lexv2/latest/dg/API_ListBotAliases.html */ public toListBotAliases() { return this.to('ListBotAliases'); } /** * Grants permission to list bot channels * * Access Level: List * * https://docs.aws.amazon.com/lexv2/latest/dg/deploying-messaging-platform.html */ public toListBotChannels() { return this.to('ListBotChannels'); } /** * Grants permission to list bot locales in a bot * * Access Level: List * * https://docs.aws.amazon.com/lexv2/latest/dg/API_ListBotLocales.html */ public toListBotLocales() { return this.to('ListBotLocales'); } /** * Grants permission to list existing bot versions * * Access Level: List * * https://docs.aws.amazon.com/lexv2/latest/dg/API_ListBotVersions.html */ public toListBotVersions() { return this.to('ListBotVersions'); } /** * Grants permission to list existing bots * * Access Level: List * * https://docs.aws.amazon.com/lexv2/latest/dg/API_ListBots.html */ public toListBots() { return this.to('ListBots'); } /** * Grants permission to list built-in intents * * Access Level: List * * https://docs.aws.amazon.com/lexv2/latest/dg/API_ListBuiltInIntents.html */ public toListBuiltInIntents() { return this.to('ListBuiltInIntents'); } /** * Grants permission to list built-in slot types * * Access Level: List * * https://docs.aws.amazon.com/lexv2/latest/dg/API_ListBuiltInSlotTypes.html */ public toListBuiltInSlotTypes() { return this.to('ListBuiltInSlotTypes'); } /** * Grants permission to list existing exports * * Access Level: List * * https://docs.aws.amazon.com/lexv2/latest/dg/API_ListExports.html */ public toListExports() { return this.to('ListExports'); } /** * Grants permission to list existing imports * * Access Level: List * * https://docs.aws.amazon.com/lexv2/latest/dg/API_ListImports.html */ public toListImports() { return this.to('ListImports'); } /** * Grants permission to list intents in a bot * * Access Level: List * * https://docs.aws.amazon.com/lexv2/latest/dg/API_ListIntents.html */ public toListIntents() { return this.to('ListIntents'); } /** * Grants permission to list slot types in a bot * * Access Level: List * * https://docs.aws.amazon.com/lexv2/latest/dg/API_ListSlotTypes.html */ public toListSlotTypes() { return this.to('ListSlotTypes'); } /** * Grants permission to list slots in an intent * * Access Level: List * * https://docs.aws.amazon.com/lexv2/latest/dg/API_ListSlots.html */ public toListSlots() { return this.to('ListSlots'); } /** * Grants permission to lists tags for a Lex resource * * Access Level: Read * * https://docs.aws.amazon.com/lexv2/latest/dg/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to create a new session or modify an existing session for a bot alias and user ID * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_PutSession.html */ public toPutSession() { return this.to('PutSession'); } /** * Grants permission to send user input (text-only) to an bot alias * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_RecognizeText.html */ public toRecognizeText() { return this.to('RecognizeText'); } /** * Grants permission to send user input (text or speech) to an bot alias * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_RecognizeUtterance.html */ public toRecognizeUtterance() { return this.to('RecognizeUtterance'); } /** * Grants permission to stream user input (speech/text/DTMF) to a bot alias * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_runtime_StartConversation.html */ public toStartConversation() { return this.to('StartConversation'); } /** * Grants permission to start a new import with the uploaded import file * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * Dependent actions: * - lex:CreateBot * - lex:CreateBotLocale * - lex:CreateIntent * - lex:CreateSlot * - lex:CreateSlotType * - lex:DeleteBotLocale * - lex:DeleteIntent * - lex:DeleteSlot * - lex:DeleteSlotType * - lex:UpdateBot * - lex:UpdateBotLocale * - lex:UpdateIntent * - lex:UpdateSlot * - lex:UpdateSlotType * * https://docs.aws.amazon.com/lexv2/latest/dg/API_StartImport.html */ public toStartImport() { return this.to('StartImport'); } /** * Grants permission to add or overwrite tags of a Lex resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/lexv2/latest/dg/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to remove tags from a Lex resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/lexv2/latest/dg/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update an existing bot * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_UpdateBot.html */ public toUpdateBot() { return this.to('UpdateBot'); } /** * Grants permission to update an existing bot alias * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_UpdateBotAlias.html */ public toUpdateBotAlias() { return this.to('UpdateBotAlias'); } /** * Grants permission to update an existing bot locale * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_UpdateBotLocale.html */ public toUpdateBotLocale() { return this.to('UpdateBotLocale'); } /** * Grants permission to update an existing export * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_UpdateExport.html */ public toUpdateExport() { return this.to('UpdateExport'); } /** * Grants permission to update an existing intent * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_UpdateIntent.html */ public toUpdateIntent() { return this.to('UpdateIntent'); } /** * Grants permission to update an existing resource policy for a Lex resource * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_UpdateResourcePolicy.html */ public toUpdateResourcePolicy() { return this.to('UpdateResourcePolicy'); } /** * Grants permission to update an existing slot * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_UpdateSlot.html */ public toUpdateSlot() { return this.to('UpdateSlot'); } /** * Grants permission to update an existing slot type * * Access Level: Write * * https://docs.aws.amazon.com/lexv2/latest/dg/API_UpdateSlotType.html */ public toUpdateSlotType() { return this.to('UpdateSlotType'); } protected accessLevelList: AccessLevelList = { "Write": [ "BuildBotLocale", "CreateBot", "CreateBotAlias", "CreateBotChannel", "CreateBotLocale", "CreateBotVersion", "CreateExport", "CreateIntent", "CreateResourcePolicy", "CreateSlot", "CreateSlotType", "CreateUploadUrl", "DeleteBot", "DeleteBotAlias", "DeleteBotChannel", "DeleteBotLocale", "DeleteBotVersion", "DeleteExport", "DeleteImport", "DeleteIntent", "DeleteResourcePolicy", "DeleteSession", "DeleteSlot", "DeleteSlotType", "PutSession", "RecognizeText", "RecognizeUtterance", "StartConversation", "StartImport", "UpdateBot", "UpdateBotAlias", "UpdateBotLocale", "UpdateExport", "UpdateIntent", "UpdateResourcePolicy", "UpdateSlot", "UpdateSlotType" ], "Read": [ "DescribeBot", "DescribeBotAlias", "DescribeBotChannel", "DescribeBotLocale", "DescribeBotVersion", "DescribeExport", "DescribeImport", "DescribeIntent", "DescribeResourcePolicy", "DescribeSlot", "DescribeSlotType", "GetSession", "ListTagsForResource" ], "List": [ "ListBotAliases", "ListBotChannels", "ListBotLocales", "ListBotVersions", "ListBots", "ListBuiltInIntents", "ListBuiltInSlotTypes", "ListExports", "ListImports", "ListIntents", "ListSlotTypes", "ListSlots" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type bot to the statement * * https://docs.aws.amazon.com/lexv2/latest/dg/how-it-works.html * * @param botId - Identifier for the botId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onBot(botId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:lex:${Region}:${Account}:bot/${BotId}'; arn = arn.replace('${BotId}', botId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type bot alias to the statement * * https://docs.aws.amazon.com/lexv2/latest/dg/how-it-works.html * * @param botId - Identifier for the botId. * @param botAliasId - Identifier for the botAliasId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onBotAlias(botId: string, botAliasId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:lex:${Region}:${Account}:bot-alias/${BotId}/${BotAliasId}'; arn = arn.replace('${BotId}', botId); arn = arn.replace('${BotAliasId}', botAliasId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import React, { Component } from 'react' import { StyleSheet, Text, View, Image, Dimensions, InteractionManager, ActivityIndicator, StatusBar, Animated, Easing, Linking, ScrollView } from 'react-native' import Interactable from 'react-native-interactable' import Ionicons from 'react-native-vector-icons/Ionicons' import { standardColor, idColor } from '../../constant/colorConfig' import { getGameNewTopicAPI } from '../../dao' import CreateNewGameTab from './NewGameTab' declare var global let screen = Dimensions.get('window') const { height: SCREEN_HEIGHT } = screen let toolbarActions = [ { title: '官网', show: 'never' } ] let toolbarHeight = 56 const limit = 160 // - toolbarHeight import ImageBackground from '../../component/ImageBackground' export default class Home extends Component<any, any> { constructor(props) { super(props) this.state = { data: false, isLoading: true, toolbar: [], afterEachHooks: [], mainContent: false, rotation: new Animated.Value(1), scale: new Animated.Value(1), opacity: new Animated.Value(1), openVal: new Animated.Value(0), modalVisible: false, modalOpenVal: new Animated.Value(0), marginTop: new Animated.Value(0), onActionSelected: this._onActionSelected, leftIcon: false, rightIcon: false, _scrollHeight: this.props.screenProps.modeInfo.height - (StatusBar.currentHeight || 0) - 56 } } componentWillReceiveProps(nextProps) { if (this.props.screenProps.modeInfo.width !== nextProps.screenProps.modeInfo.width) { const { params } = this.props.navigation.state this.props.navigation.goBack() // this.props.navigation.navigate('Home', params) } } onActionSelected = (index) => { const { data: source } = this.state if (source && source.titleInfo && source.titleInfo.content && source.titleInfo.content.length) { const item = source.titleInfo.content.filter(item => item.includes('href')).pop() if (item) { let match = item.match(/\'(.*?)\'/) if (!match) match = item.match(/\"(.*?)\"/) if (match && match[1]) Linking.openURL(match[1]).catch(err => global.toast(err.toString())) } else { global.toast('官方网站尚未收录') } } else { global.toast('官方网站尚未收录') } } componentWillUnmount() { this.removeListener && this.removeListener.remove() if (this.timeout) clearTimeout(this.timeout) } componentWillMount() { this.preFetch() } preFetch = () => { const { params } = this.props.navigation.state this.setState({ isLoading: true }) InteractionManager.runAfterInteractions(() => { const data = getGameNewTopicAPI(params.URL).then(data => { this.setState({ data, isLoading: false }) }) }) } handleImageOnclick = (url) => this.props.navigation.navigate('ImageViewer', { images: [ { url } ] }) renderHeader = (rowData) => { const { modeInfo } = this.props.screenProps const { psnButtonInfo } = this.state.data const { marginTop } = this.state const { nightModeInfo } = modeInfo const color = 'rgba(255,255,255,1)' const infoColor = 'rgba(255,255,255,0.8)' const { width: SCREEN_WIDTH } = Dimensions.get('window') return ( <ImageBackground source={{uri: rowData.backgroundImage}} style={{ height: limit + toolbarHeight, width: SCREEN_WIDTH }} > <View style={{ backgroundColor: 'transparent', height: limit, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', padding: 10, marginTop: 56 }}> <View style={{ justifyContent: 'center', alignItems: 'center', flex: -1, marginLeft: 20, marginBottom: 15 }}> <Image source={{ uri: rowData.avatar}} style={[styles.avatar, { width: 120, height: 120, overlayColor: 'rgba(0,0,0,0.0)', backgroundColor: 'transparent' }]} /> </View> <View style={{ justifyContent: 'center', alignItems: 'flex-start', marginBottom: 15, maxWidth: SCREEN_WIDTH - 120, overflow: 'scroll', flexWrap: 'nowrap', padding: 10, paddingTop: 0, paddingLeft: 30 }}> {rowData.content.map((item, index) => { return item.includes('href') ? ( undefined /*<global.HTMLView value={item} key={index} modeInfo={modeInfo} stylesheet={styles} imagePaddingOffset={120 + 10} shouldForceInline={true} />*/ ) : <Text key={index} style={{ fontSize: index === 0 ? 18 : 12}}>{item}</Text> })} </View> </View> </ImageBackground> ) } renderTabContainer = (list) => { const { modeInfo } = this.props.screenProps const { params } = this.props.navigation.state const { marginTop } = this.state return ( <CreateNewGameTab screenProps={{ modeInfo: modeInfo, preFetch: this.preFetch, psnid: params.title, baseUrl: params.URL.replace(/\?.*?$/, ''), list: this.state.data.list, gameTable: this.state.data.gameTable, navigation: this.props.navigation, setToolbar: ({ index, afterSnap }) => { if (afterSnap && !this.afterSnapHooks[index]) { this.afterSnapHooks[index] = afterSnap {/* afterSnap(this.scrollEnable) */} } } }} onNavigationStateChange={(prevRoute, nextRoute, action) => { if (prevRoute.index !== nextRoute.index && action.type === 'Navigation/NAVIGATE') { this.currentTabIndex = nextRoute.index const target = this.afterSnapHooks[this.currentTabIndex] {/* target && target( this.scrollEnable) */} } }}/> ) } onSnap = (event) => { this.scrollEnable = event.nativeEvent.index === 1 const target = this.afterSnapHooks[this.currentTabIndex] // target && target(/* scrollEnable */ event.nativeEvent.index === 1) } currentTabIndex = 0 afterSnapHooks = [] scrollEnable = false _deltaY = new Animated.Value(0) render() { // console.log('GamePage.js rendered'); const { modeInfo } = this.props.screenProps const { data: source } = this.state const actions = toolbarActions.slice() if (source && source.titleInfo && source.titleInfo.content && source.titleInfo.content.length) { const has = source.titleInfo.content.some(item => item.includes('href')) if (!has) { actions.pop() } } return source.titleInfo && this.state.leftIcon ? ( <View style={{flex: 1}}> <Animated.View style={{ /* opacity: this._deltaY.interpolate({ inputRange: [-130, -50], outputRange: [1, 0], extrapolateRight: 'clamp' }), */ backgroundColor: this._deltaY.interpolate({ inputRange: [-158, 0], outputRange: [modeInfo.standardColor, 'transparent'], extrapolateRight: 'clamp' }), zIndex: 10 }}> <Ionicons.ToolbarAndroid navIconName='md-arrow-back' overflowIconName='md-more' iconColor={modeInfo.isNightMode ? '#000' : '#fff'} title={source.titleInfo.title} style={{backgroundColor: modeInfo.standardColor}} onIconClicked={() => this.props.navigation.goBack()} titleColor={modeInfo.isNightMode ? '#000' : '#fff'} actions={actions} style={{backgroundColor: '#transparent'}} onActionSelected={this.onActionSelected} /> </Animated.View> <Interactable.View verticalOnly={true} snapPoints={[{y: 0}, {y: -158}]} boundaries={{top: -158, bottom: 0}} animatedValueY={this._deltaY} onSnap={this.onSnap}> <Animated.View style={{ height: limit + toolbarHeight, backgroundColor: modeInfo.standardColor, marginTop: -toolbarHeight - 8, transform: [{ translateY: this._deltaY.interpolate({ inputRange: [-158, -0], outputRange: [79, 0], extrapolateRight: 'clamp' }) }] }}> {source.titleInfo && this.renderHeader(source.titleInfo)} </Animated.View> <View style={[styles.scrollView, { height: this.state._scrollHeight, backgroundColor: modeInfo.brighterLevelOne }]} ref={this._setScrollView}> {this.renderTabContainer()} </View> <Animated.View style={{ height: this._deltaY.interpolate({ inputRange: [-158, -0], outputRange: [0, this.state._scrollHeight - 40 + 1] }), backgroundColor: 'transparent', position: 'absolute', bottom: 0, left: 0, right: 0, opacity: this._deltaY.interpolate({ inputRange: [-158, -0], outputRange: [0, 1] }) }}/> </Interactable.View> </View> ) : <View style={{ flex: 1, backgroundColor: modeInfo.backgroundColor }}> <Ionicons.ToolbarAndroid navIconName='md-arrow-back' overflowIconName='md-more' iconColor={modeInfo.isNightMode ? '#000' : '#fff'} title={`${source.titleInfo ? source.titleInfo.title : '加载中...' }`} titleColor={modeInfo.isNightMode ? '#000' : '#fff'} style={[styles.toolbar, { backgroundColor: this.state.isLoading ? modeInfo.standardColor : 'transparent' }]} actions={actions} key={this.state.toolbar.map(item => item.text || '').join('::')} onIconClicked={() => this.props.navigation.goBack()} onActionSelected={this.onActionSelected} /> <ActivityIndicator animating={this.state.isLoading} style={{ flex: 999, justifyContent: 'center', alignItems: 'center' }} color={modeInfo.accentColor} size={50} /> </View> } _scrollHeight = 100 _coordinatorLayout = null _appBarLayout = null _scrollView = null _setCoordinatorLayout = component => { this._coordinatorLayout = component } _setAppBarLayout = component => { this._appBarLayout = component } _setScrollView = component => { this._scrollView = component } componentDidMount() { Promise.all([ Ionicons.getImageSource('md-arrow-back', 24, '#fff'), Ionicons.getImageSource('md-more', 24, '#fff') ]).then(result => { this.setState({ leftIcon: result[0], rightIcon: result[1] }) }) } _getItems(count) { let items: any = [] for (let i = 0; i < count; i++) { items.push( <View key={i} style={[ styles.item, { backgroundColor: ITEM_COLORS[i % ITEM_COLORS.length] } ]}> <Text style={styles.itemContent}>ITEM #{i}</Text> </View> ) } return items } } const ITEM_COLORS = ['#E91E63', '#673AB7', '#2196F3', '#00BCD4', '#4CAF50', '#CDDC39'] const styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', backgroundColor: '#F5FCFF' }, toolbar: { backgroundColor: standardColor, height: 56, elevation: 4 }, selectedTitle: { // backgroundColor: '#00ffff' // fontSize: 20 }, avatar: { width: 50, height: 50 }, a: { fontWeight: '300', color: idColor, // make links coloured pink, fontSize: 12 }, appbar: { backgroundColor: '#2278F6', height: 160 + 56 }, navbar: { height: 56, alignItems: 'center', justifyContent: 'center', backgroundColor: 'transparent', position: 'relative' }, backBtn: { top: 0, left: 0, height: 56, position: 'absolute' }, caption: { color: '#fff', fontSize: 20 }, heading: { height: 38, alignItems: 'center', justifyContent: 'center', backgroundColor: '#4889F1' }, headingText: { color: 'rgba(255, 255, 255, .6)' }, scrollView: { backgroundColor: '#f2f2f2' }, item: { borderRadius: 2, height: 200, marginLeft: 10, marginRight: 10, marginTop: 5, marginBottom: 5, justifyContent: 'center', alignItems: 'center' }, itemContent: { fontSize: 30, color: '#FFF' } })
the_stack
import React from "react"; import { storiesOf } from "@storybook/react"; import { action } from "@storybook/addon-actions"; import { withInfo } from "@storybook/addon-info"; import { LazyImage } from "../src/index"; import { Container, Divider } from "./utils"; import { LazyImageOpinionated } from "./OpinionatedComponents"; import "./styles.css"; // Helpers to save typing. You can imagine that in // some cases, you too will have more specific components. const PlaceholderImage = () => ( <img src="img/porto_buildings_lowres.jpg" alt="Buildings with tiled exteriors, lit by the sunset." className="w-100" /> ); const ActualImage = () => ( <img src="img/porto_buildings_large.jpg" alt="Buildings with tiled exteriors, lit by the sunset." className="w-100" /> ); // Utils for scrolling const scrollToRef = (ref: React.RefObject<any>) => ref.current.scrollIntoView({ behavior: "smooth" }); const endRef: React.RefObject<any> = React.createRef(); // Component that preloads the image and only swaps once ready //@ts-ignore const stories = storiesOf("LazyImage", module); stories .add( "Basic use", withInfo( "Component that preloads the image once in the viewport and only swaps once ready" )(() => ( <Container> <LazyImage src="img/porto_buildings_large.jpg" alt="Buildings with tiled exteriors, lit by the sunset." placeholder={({ imageProps, ref }) => ( <img ref={ref} src="img/porto_buildings_lowres.jpg" alt={imageProps.alt} className="w-100" /> )} actual={({ imageProps }) => <img {...imageProps} className="w-100" />} /> </Container> )) ) // With srcSet .add( "With srcSet", withInfo( "With srcset, the browser decides which image to load. In that case, src is not informative enough for preloading. You can use the `srcSet` prop to provide that additional information to LazyImage." )(() => ( <Container> <LazyImage src="https://www.fillmurray.com/g/300/200" srcSet="https://www.fillmurray.com/g/900/600 900w, https://www.fillmurray.com/g/600/400 600w, https://www.fillmurray.com/g/300/200 300w" alt="A portrait of Bill Murray." placeholder={({ imageProps, ref }) => ( <img ref={ref} src="https://www.fillmurray.com/g/60/40" alt={imageProps.alt} className="w-100" /> )} actual={({ imageProps }) => <img {...imageProps} className="w-100" />} /> </Container> )) ) // Always load an image ("eagerly"; how the browser does it already. // Useful if you want to load the actual content without waiting for Javascript. .add( "Eager loading (Server-Side Rendering)", withInfo( "Always load an image (i.e. eagerly; how the browser does it already). Useful if you want to load the actual content without waiting for Javascript. You should consider where you need this pattern. See the relevant section in README.md for more." )(() => ( <Container> <LazyImage loadEagerly src="img/porto_buildings_large.jpg" placeholder={() => <PlaceholderImage />} actual={() => <ActualImage />} /> </Container> )) ) // This isn't even specific to this library; just demonstrating how you might // eagerly load content above the fold, and defer the rest .add( "Eagerly load some images", withInfo( "This is an example of how you can use loadEagerly to load important content directly, and defer the rest." )(() => ( <Container> {[ ["first", "30/20", "300/200"], ["second", "60/40", "600/400"], ["third", "90/60", "900/600"] ].map(([key, placeholder, actual], i) => ( <LazyImage loadEagerly={i === 0} key={key} src={`https://www.fillmurray.com/g/${actual}`} alt="A portrait of Bill Murray." placeholder={({ imageProps, ref }) => ( <img src={`https://www.fillmurray.com/g/${placeholder}`} ref={ref} alt={imageProps.alt} className="w-100" /> )} actual={({ imageProps }) => ( <img {...imageProps} className="w-100" /> )} /> ))} </Container> )) ) .add( "Delayed loading", withInfo( "By specifying `debounceDurationMs`, you can prevent an image from loading, unless it has been in the viewport for a set amount of time." )(() => { return ( <div className="mw6"> <Divider> <h1>react-lazy-images Debounce test</h1> <p> The desired behaviour is to not to start loading the images before them being in the viewport for X amount of time. Press the button to scroll alll the way to the end of the page. Only the final image should be loaded. </p> <p> Open your devTools network monitor and check the "Img" tab. Only the last image should load. </p> <p> (Note that smooth scrolling should be working in your browser for the test to be realistic. If not, you can scroll manually. Instant scrolling does not trigger the IntersectionObserver afaict). </p> <button onClick={() => scrollToRef(endRef)}> Click here to scroll to the end </button> </Divider> <LazyImageOpinionated src="https://endangered.photo/1200/800" alt="" /> <Divider /> <h2 ref={endRef}>Only things below here should be loaded</h2> <LazyImageOpinionated src="https://endangered.photo/300/200" alt="" /> </div> ); }) ) // Loading state as render prop .add( "Loading state", withInfo("Loading")(() => ( <Container> <div className="bg-light-silver h5 w-100"> <LazyImage src="img/porto_buildings_large.jpg" placeholder={({ ref }) => <div ref={ref} />} actual={() => <ActualImage />} loading={() => ( <div> <p className="pa3 f5 lh-copy near-white">Loading...</p> </div> )} /> </div> </Container> )) ) // Loading and Error states as render props .add( "Loading and Error states", withInfo("Loading and Error states are exposed as render props")(() => ( <Container> <div className="bg-light-silver h5 w-100"> <LazyImage src="https://www.fillmurray.com/notanimage" placeholder={({ ref }) => <div ref={ref} />} actual={({ imageProps }) => <img {...imageProps} />} loading={() => ( <div> <p className="pa3 f5 lh-copy near-white">Loading...</p> </div> )} error={() => ( <div className={`bg-light-red h-100 w-100 $`}> <p>There was an error fetching this image :(</p> </div> )} /> </div> </Container> )) ) .add( "Horizontal scroll", withInfo("Horizontal scrolling should work out of the box.")(() => ( <Container> <div className="flex flex-row mw6 overflow-x-auto"> {[ ["first", "30/20", "300/200"], ["second", "60/40", "600/400"], ["third", "90/60", "900/600"] ].map(([key, placeholder, actual], i) => ( <div key={key} className="w5 pa3 mr3 ba bw1 b--near-black flex-shrink-0" > <LazyImage key={key} src={`https://www.fillmurray.com/g/${actual}`} alt="A portrait of Bill Murray." placeholder={({ imageProps, ref }) => ( <img src={`https://www.fillmurray.com/g/${placeholder}`} ref={ref} alt={imageProps.alt} className="w-100" /> )} actual={({ imageProps }) => ( <img {...imageProps} className="w-100" /> )} /> </div> ))} </div> </Container> )) ) .add( "Experimental decode", withInfo( "Decode off-main-thread before appending. Only supported in some browsers, but uses normal API otherwise. Test before using!" )(() => ( <Container> <LazyImage src="img/porto_buildings_large.jpg" alt="Buildings with tiled exteriors, lit by the sunset." placeholder={({ imageProps, ref }) => ( <img ref={ref} src="img/porto_buildings_lowres.jpg" alt={imageProps.alt} className="w-100" /> )} actual={({ imageProps }) => <img {...imageProps} className="w-100" />} experimentalDecode={true} /> </Container> )) ) .add( "Background image", withInfo( "You are in control of what gets rendered, so you can set the url of the background image, and swap in a component that uses it on load. It is not much different from the basic use case." )(() => { return ( <Container> <LazyImage src="img/porto_buildings_large.jpg" placeholder={({ ref }) => ( <div ref={ref} className={`$ w5 h5 contain bg-center`} style={{ backgroundImage: "url(img/porto_buildings_lowres.jpg)" }} /> )} actual={({ imageProps }) => ( <div className={`$ w5 h5 contain bg-center`} style={{ backgroundImage: `url(${imageProps.src})` }} /> )} /> </Container> ); }) );
the_stack
'use strict'; import cp = require('child_process'); import path = require("path"); import fs = require('fs'); import async = require('async'); import {getCleanTrace} from 'clean-trace'; import * as util from "util"; import * as assert from 'assert'; import * as Domain from 'domain'; // project import log from '../../logger'; import chalk from "chalk"; import {EVCb} from "../../index"; import {getFSMap} from "./get-fs-map"; import {renameDeps} from "./rename-deps"; import {installDeps} from "./copy-deps"; import pt from "prepend-transform"; import {timeout} from "async"; import deepMixin from "@oresoftware/deep.mixin"; /////////////////////////////////////////////// const r2gProject = path.resolve(process.env.HOME + '/.r2g/temp/project'); const r2gProjectCopy = path.resolve(process.env.HOME + '/.r2g/temp/copy'); const smokeTester = require.resolve('../../smoke-tester.js'); const defaultPackageJSONPath = require.resolve('../../../assets/default.package.json'); export interface Packages { [key: string]: boolean | string } interface BinFieldObject { [key: string]: string } const flattenDeep = (a: Array<any>): Array<any> => { return a.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []); }; const handleTask = (r2gProject: string) => { return (t: (root: string, cb: EVCb<any>) => void, cb: (err: any) => void) => { process.nextTick(() => { const d = Domain.create(); let first = true; const finish = (err: any, isTimeout: boolean) => { clearTimeout(to); if (err) { log.error(err); log.error('The following function experienced an error:', t); } if (isTimeout) { log.error('The following task timed out:', t); } if (first) { process.nextTick(() => { d.exit(); cb(err); }); } }; const to = setTimeout(() => { finish(new Error('timeout'), true); }, 5000); d.once('error', err => { log.error('Could not successfully run task:'); log.error(String(t)); finish(err, false); }); d.run(() => { t(r2gProject, function (err) { if (arguments.length > 1) { log.error('The following callback arguments were ignored:', Array.from(arguments).slice(0)); } finish(err, false); }); }); }); } }; export const run = (cwd: string, projectRoot: string, opts: any): void => { const userHome = path.resolve(process.env.HOME);`` let pkgJSON: any = null, r2gConf: any = null, packages: Packages = null, searchRoots: Array<string> = null, pkgName = '', cleanPackageName = '', zTest: string = null; if (opts.skip) { const skipped = String(opts.skip).split(',').map(v => String(v || '').trim().toLowerCase()).filter(Boolean); opts.z = opts.z || skipped.includes('z'); opts.s = opts.s || skipped.includes('s'); opts.t = opts.t || skipped.includes('t'); } const pkgJSONOverridePth = path.resolve(projectRoot + '/.r2g/package.override.js'); const pkgJSONPth = path.resolve(projectRoot + '/package.json'); const customActionsPath = path.resolve(projectRoot + '/.r2g/custom.actions.js'); try { pkgJSON = require(pkgJSONPth); pkgName = pkgJSON.name; cleanPackageName = pkgJSON.name || ''; } catch (err) { log.error(chalk.magentaBright('Could not read your projects package.json file.')); throw getCleanTrace(err); } if (!(pkgName && typeof pkgName === 'string')) { throw new Error( 'Your package.json file does not appear to have a proper name field. Here is the file:\n' + util.inspect(pkgJSON) ); } interface CustomActionExports { default?: CustomActionExports, inCopyBeforeInstall: Array<CustomAction>, inProjectBeforeInstall: Array<CustomAction>, inCopyAfterInstall: Array<CustomAction>, inProjectAfterInstall: Array<CustomAction>, } type CustomAction = (root: string, cb: EVCb<any>) => void; let customActions: CustomActionExports = null, customActionsStats = null; try { customActionsStats = fs.statSync(customActionsPath); } catch (err) { //ignore } try { if (customActionsStats) { customActions = require(customActionsPath); customActions = customActions.default || customActions; assert(customActions, 'custom.actions.js is missing certain exports.'); } } catch (err) { log.error('Could not load custom.actions.js'); log.error(err.message); process.exit(1); } let packageJSONOverride: any = null, packageJSONOverrideStats = null; try { packageJSONOverrideStats = fs.statSync(pkgJSONOverridePth); } catch (err) { // ignore } try { if (packageJSONOverrideStats) { assert(packageJSONOverrideStats.isFile(), 'package.override.js should be a file, but it is not.'); packageJSONOverride = require(pkgJSONOverridePth); packageJSONOverride = packageJSONOverride.default || packageJSONOverride; assert(packageJSONOverride && !Array.isArray(packageJSONOverride) && typeof packageJSONOverride === 'object', 'package.override.js does not export the right object.'); } } catch (err) { log.error('Could not run stat on file at path:', pkgJSONOverridePth); log.error(err.message); process.exit(1); } try { zTest = pkgJSON.r2g.test; } catch (err) { if (!opts.z) { log.info('using "npm test" to run phase-Z.'); } } zTest = zTest || 'npm test'; assert(typeof zTest === 'string', 'z-test is not a string => check the r2g.test property in your package.json.'); pkgName = String(pkgName).replace(/[^0-9a-z]/gi, '_'); if (pkgName.startsWith('_')) { pkgName = pkgName.slice(1); } const confPath = path.resolve(projectRoot + '/.r2g/config.js'); try { r2gConf = require(confPath); r2gConf = r2gConf.default || r2gConf; } catch (err) { if (opts.verbosity > 0) { log.warning(err.message); } log.warning(chalk.yellow('Could not read your .r2g/config.js file at path:', chalk.bold(confPath))); if (process.env.r2g_is_docker === 'yes') { throw getCleanTrace(err); } r2gConf = require('../../../assets/default.r2g.config.js'); r2gConf = r2gConf.default || r2gConf; process.once('exit', code => { if (code < 1) { if (opts.verbosity > 2) { log.warning(chalk.yellow.bold('Note that during this run, r2g could not read your .r2g/config.js file.')) } } }); } packages = r2gConf.packages; searchRoots = flattenDeep([r2gConf.searchRoots, path.resolve(r2gConf.searchRoot || '')]) .map(v => String(v || '').trim()) .filter(Boolean); if (!(packages && typeof packages === 'object')) { log.error(r2gConf); throw new Error('You need a property called "packages" in your .r2g/config.js file.'); } searchRoots.forEach(v => { if (!(v && typeof v === 'string')) { log.error(r2gConf); throw chalk.redBright('You need a property called "searchRoot"/"searchRoots" in your .r2g/config.js file.'); } if (!path.isAbsolute(v)) { log.error(r2gConf); log.error('The following path is not absolute:', chalk.magenta(v)); throw chalk.redBright('Your "searchRoot"/"searchRoots" property in your .r2g/config.js file, needs to be an absolute path.'); } try { assert(fs.lstatSync(v).isDirectory()); } catch (err) { log.error('Your "searchRoot" property does not seem to exist as a directory on the local/host filesystem.'); log.error('In other words, the following path does not seem to be a directory:'); log.error(v); throw getCleanTrace(err); } if (!v.startsWith(userHome)) { throw new Error('Your searchRoot needs to be within your user home directory.'); } }); const dependenciesToInstall = Object.keys(packages); if (dependenciesToInstall.length < 1) { log.debug('There were no local dependencies to install.'); log.debug('Here is your configuration:\n', r2gConf); } const deps = [ pkgJSON.dependencies || {}, pkgJSON.devDependencies || {}, pkgJSON.optionalDependencies || {} ]; const allDeps = deps.reduce(Object.assign, {}); Object.keys(packages).forEach(function (k) { if (!allDeps[k]) { log.warn(chalk.gray('You have the following packages key in your .r2g/config.js file:'), chalk.magentaBright(k)); log.warn(chalk.bold(`But "${chalk.magentaBright(k)}" is not present as a dependency in your package.json file.`)); } }); const depsDir = path.resolve(process.env.HOME + `/.r2g/temp/deps`); async.autoInject({ checkForUntrackedFiles(cb: EVCb<any>) { if (opts.ignore_dirty_git_index) { return process.nextTick(cb); } log.info('Checking for dirty git status...'); const k = cp.spawn('bash'); k.stderr.pipe(process.stderr); k.stdin.end(` set -e; cd ${projectRoot}; if [[ ! -d '.git' ]]; then exit 0; fi if test $(git status --porcelain | wc -l) != '0'; then exit 1; fi `); k.once('exit', code => { if (code > 0) { log.error('Changes to (untracked) files need to be committed. Check your git index using the `git status` command.'); log.error('Looks like the git index was dirty. Use "--ignore-dirty-git-index" to skip this warning.'); } cb(code); }); }, checkForDirtyGitIndex(checkForUntrackedFiles: any, cb: EVCb<any>) { if (opts.ignore_dirty_git_index) { return process.nextTick(cb); } log.info('Checking for dirty git index...'); const k = cp.spawn('bash'); k.stderr.pipe(process.stderr); k.stdin.end(` set -e; cd ${projectRoot}; if [[ -d '.git' ]]; then git diff --quiet fi `); k.once('exit', code => { if (code > 0) { log.error('Looks like the git index was dirty. Use "--ignore-dirty-git-index" to skip this warning.'); } cb(code); }); }, removeExistingProject(checkForDirtyGitIndex: any, cb: EVCb) { if (opts.keep || opts.multi) { log.info("We are keeping the previously installed packages because '--keep' / '--multi' was used."); return process.nextTick(cb); } log.info('Removing existing files within "$HOME/.r2g/temp"...'); const k = cp.spawn('bash'); k.stdin.end(`rm -rf "$HOME/.r2g/temp"`); k.once('exit', cb); }, mkdirpProject(removeExistingProject: any, cb: EVCb) { log.info('Making sure the right folders exist using mkdir -p ...'); const k = cp.spawn('bash'); k.stderr.pipe(process.stderr); k.stdin.end(`mkdir -p "${r2gProject}"; mkdir -p "${r2gProjectCopy}";`); k.once('exit', code => { if (code > 0) { log.error("Could not create temp/project or temp/copy directory."); } cb(code); }); }, rimrafDeps(mkdirpProject: any, cb: EVCb) { log.info('Removing existing files within "$HOME/.r2g.temp"...'); const k = cp.spawn('bash'); k.stdin.end(`rm -rf "${depsDir}"`); k.once('exit', cb); }, mkdirDeps(rimrafDeps: any, cb: EVCb) { log.info('Re-creating folders "$HOME/.r2g/temp"...'); const k = cp.spawn('bash'); k.stdin.end(`mkdir -p "${depsDir}"`); k.once('exit', cb); }, getMap(cb: EVCb) { if (!opts.full) { log.info('we are not creating a deps map since the --full option was not used.'); return process.nextTick(cb, null, {}); } if (process.env.r2g_is_docker === 'yes') { log.info('we are not creating a deps map since we are using r2g.docker'); return process.nextTick(cb, null, {}); } getFSMap(opts, searchRoots, packages, cb); }, copyProjectsInMap(getMap: any, cb: EVCb) { if (Object.keys(getMap).length < 1) { return process.nextTick(cb, null, {}); } installDeps(getMap, dependenciesToInstall, opts, cb); }, renamePackagesToAbsolute(copyProjectsInMap: any, copyProject: any, cb: EVCb) { if (Object.keys(copyProjectsInMap).length < 1) { return process.nextTick(cb, null, {}); } const pkgJSONPath = path.resolve(copyProject + '/package.json'); renameDeps(copyProjectsInMap, pkgJSONPath, cb); }, copyProject(mkdirpProject: any, cb: EVCb) { if (process.env.r2g_is_docker === 'yes') { log.info('We are not copying the project since we are using r2g.docker'); return process.nextTick(cb, null, projectRoot); } log.info('Copying your project to "$HOME/.r2g/temp/copy" using rsync ...'); const k = cp.spawn('bash'); k.stderr.pipe(process.stderr); k.stdin.end(` rm -rf "${r2gProjectCopy}"; rsync --perms --copy-links -r --exclude=".git" --exclude="node_modules" "${projectRoot}" "${r2gProjectCopy}"; `); k.once('exit', code => { if (code > 0) { log.error('Could not rimraf project copy path or could not copy to it using rsync.'); } cb(code, path.resolve(r2gProjectCopy + '/' + path.basename(projectRoot))); }); }, runNpmPack(renamePackagesToAbsolute: any, copyProject: string, cb: EVCb<string>) { const cmd = `npm pack --loglevel=warn;`; log.info(chalk.bold('Running the following command from your project copy root:'), chalk.cyan.bold(cmd)); const k = cp.spawn('bash'); k.stdin.end(`cd "${copyProject}" && ` + cmd); let stdout = ''; k.stdout.on('data', d => { stdout += String(d || '').trim(); }); k.stderr.pipe(process.stderr); k.once('exit', code => { if (code > 0) { log.error(`Could not run "npm pack" for this project => ${copyProject}.`); } cb(code, path.resolve(copyProject + '/' + stdout)); }); }, linkPackage(runNPMInstallInCopy: any, copyProject: string, cb: EVCb) { if (opts.z) { return process.nextTick(cb); } const getBinMap = function (bin: string | BinFieldObject, path: string, name: string) { if (!bin) { return ` echo "no bin items in package.json for package with name: ${name}" `; } if (typeof bin === 'string') { return ` mkdir -p "node_modules/.bin" && ln -s "${path}/${bin}" "node_modules/.bin/${name}" ` } const keys = Object.keys(bin); if (keys.length < 1) { return ` echo "no bin items in package.json for package with name: ${name}" `; } return keys.map(function (k) { return ` mkdir -p node_modules/.bin && ln -sf "${path}/${bin[k]}" "node_modules/.bin/${k}" ` }) .join(' && '); }; const cmd = [ `mkdir -p "node_modules/${cleanPackageName}"`, `rm -rf "node_modules/${cleanPackageName}"`, `ln -sf "${r2gProject}/node_modules/${cleanPackageName}" "node_modules/${cleanPackageName}"`, // `rsync -r "${r2gProject}/node_modules/${cleanPackageName}" "node_modules"`, getBinMap(pkgJSON.bin, `${copyProject}/node_modules/${cleanPackageName}`, cleanPackageName) ] .join(' && '); const cwd = String(copyProject).slice(0); log.info(chalk.bold(`Running the following command from "${cwd}":`), chalk.bold.cyan(cmd)); const k = cp.spawn('bash'); k.stderr.pipe(process.stderr); k.stdin.end(`cd "${cwd}" && ` + cmd); k.once('exit', code => { if (code > 0) { log.error('Could not link from project to copy.'); } cb(code); }); }, runNPMInstallInCopy(runNpmInstall: any, copyProject: string, cb: EVCb) { if (opts.z) { return process.nextTick(cb); } const cmd = `npm install --cache-min 9999999 --loglevel=warn`; log.info(`Running "${cmd}" in project copy.`); const k = cp.spawn('bash'); k.stderr.pipe(process.stderr); k.stdin.end(`cd "${copyProject}" && ` + cmd); k.once('exit', code => { if (code > 0) { log.error('Could not link from project to copy.'); } cb(code); }); }, runZTest(linkPackage: any, copyProject: string, cb: EVCb) { if (opts.z) { log.warn('Skipping phase-Z'); return process.nextTick(cb); } const cmd = String(zTest).slice(0); log.info(chalk.bold('Running the following command from the copy project dir:'), chalk.cyan.bold(cmd)); const k = cp.spawn('bash', [], { env: Object.assign({}, process.env, { PATH: path.resolve(copyProject + '/node_modules/.bin') + ':' + process.env.PATH }) }); k.stdin.end(`cd "${copyProject}" && ${cmd}`); k.stdout.pipe(pt(chalk.gray('phase-Z: '))).pipe(process.stdout); k.stderr.pipe(pt(chalk.yellow('phase-Z: '))).pipe(process.stderr); k.once('exit', code => { if (code > 0) { log.error(`Could not run your z-test command: ${cmd}`); } cb(code); }); }, copySmokeTester(mkdirpProject: any, cb: EVCb) { if (opts.s) { return process.nextTick(cb); } log.info(`Copying the smoke-tester.js file to "${r2gProject}" ...`); fs.createReadStream(smokeTester) .pipe(fs.createWriteStream(path.resolve(r2gProject + '/smoke-tester.js'))) .once('error', cb) .once('finish', cb); }, copyPackageJSON(mkdirpProject: any, cb: EVCb) { if (opts.keep) { log.warn(`Re-using the existing package.json file at path '${r2gProject}/package.json'...`); return process.nextTick(cb); } log.info(`Copying package.json file to "${r2gProject}" ...`); const defaultPkgJSON = require(defaultPackageJSONPath); const packageJSONPath = path.resolve(r2gProject + '/package.json'); let override = null; if (packageJSONOverride) { override = deepMixin(defaultPkgJSON, packageJSONOverride); log.warning('package.json overriden with:', {override}); } else { override = Object.assign({}, defaultPkgJSON); } const strm = fs.createWriteStream(packageJSONPath) .once('error', cb) .once('finish', cb); strm.end(JSON.stringify(override, null, 2) + '\n'); }, customActionsBeforeInstall(copyPackageJSON: any, cb: EVCb<any>) { if (!customActions) { log.info('No custom actions registered. Use custom.actions.js to add custom actions.'); return process.nextTick(cb); } log.info('Running custom actions...'); async.series({ inProject(cb) { const tasks = flattenDeep([customActions.inProjectBeforeInstall]).filter(Boolean); if (tasks.length < 1) { return process.nextTick(cb); } async.eachSeries(tasks, handleTask(r2gProject), cb); } }, cb); }, runNpmInstall(copyPackageJSON: any, customActionsBeforeInstall: any, runNpmPack: string, cb: EVCb) { if (opts.t && opts.s) { return process.nextTick(cb); } // note that runNpmPack is the path to .tgz file const cmd = `npm install --loglevel=warn --cache-min 9999999 --no-optional --production "${runNpmPack}";\n` + `npm i --loglevel=warn --cache-min 9999999 --no-optional --production;`; log.info(`Running the following command via this dir: "${r2gProject}" ...`); log.info(chalk.blueBright(cmd)); const k = cp.spawn('bash'); k.stdin.end(`cd "${r2gProject}" && ` + cmd); k.stderr.pipe(process.stderr); k.once('exit', code => { if (code > 0) { log.error(`Could not run the following command: ${cmd}.`); } cb(code); }); }, customActionsAfterInstall(runNpmInstall: any, cb: EVCb<any>) { if (!customActions) { log.info('No custom actions registered. Use custom.actions.js to add custom actions.'); return process.nextTick(cb); } log.info('Running custom actions...'); async.series({ inProject(cb) { const tasks = flattenDeep([customActions.inProjectAfterInstall]).filter(Boolean); if (tasks.length < 1) { return process.nextTick(cb); } async.eachSeries(tasks, handleTask(r2gProject), cb); } }, cb); }, r2gSmokeTest(runZTest: any, customActionsAfterInstall: any, copySmokeTester: any, cb: EVCb) { if (opts.s) { log.warn('Skipping phase-S.'); return process.nextTick(cb); } log.info(`Running your exported r2gSmokeTest function(s) in "${r2gProject}" ...`); const k = cp.spawn('bash', [], { env: Object.assign({}, process.env, { PATH: path.resolve(r2gProject + '/node_modules/.bin') + ':' + process.env.PATH }) }); k.stderr.pipe(pt(chalk.yellow('phase-S: '))).pipe(process.stderr); k.stdout.pipe(pt(chalk.gray('phase-S: '))).pipe(process.stdout); k.stdin.end(`cd "${r2gProject}" && node smoke-tester.js;`); k.once('exit', code => { if (code > 0) { log.error('r2g smoke test failed => one of your exported r2gSmokeTest function calls failed to resolve to true.'); log.error(chalk.magenta('for help fixing this error, see: https://github.com/ORESoftware/r2g/blob/master/docs/r2g-smoke-test-exported-main-fn-type-a.md')); } cb(code); }); }, copyUserDefinedTests(copyProject: string, cb: EVCb) { if (opts.t) { return process.nextTick(cb); } log.info(`Copying your user defined tests to: "${r2gProject}" ...`); const k = cp.spawn('bash'); k.stdout.pipe(process.stdout); k.stderr.pipe(process.stderr); k.stdin.end([ `cd "${copyProject}"`, `mkdir -p .r2g/tests`, `mkdir -p .r2g/fixtures`, `rsync --perms --copy-links -r .r2g/tests "${r2gProject}"`, `rsync --perms --copy-links -r .r2g/fixtures "${r2gProject}"` ].join(' && ')); k.once('exit', cb); }, runUserDefinedTests(copyUserDefinedTests: any, r2gSmokeTest: any, runNpmInstall: any, cb: EVCb) { if (opts.t) { log.warn('Skipping phase-T'); return process.nextTick(cb); } log.info(`Running user defined tests in "${r2gProject}/tests" ...`); const k = cp.spawn('bash', [], { env: Object.assign({}, process.env, { PATH: path.resolve(r2gProject + '/node_modules/.bin') + ':' + process.env.PATH }) }); k.stdout.pipe(pt(chalk.gray('phase-T: '))).pipe(process.stdout); k.stderr.pipe(pt(chalk.yellow('phase-T: '))).pipe(process.stderr); k.once('exit', code => { if (code > 0) { log.error('an r2g test failed => a script in this dir failed to exit with code 0:', chalk.bold(path.resolve(process.env.HOME + '/.r2g/temp/project/tests'))); log.error(chalk.magenta('for help fixing this error, see: https://github.com/ORESoftware/r2g/blob/master/docs/r2g-smoke-test-type-b.md')); } cb(code); }); const tests = path.resolve(r2gProject + '/tests'); let items: Array<string>; try { items = fs.readdirSync(tests); if (false) { const cmd = ` set -e;\n cd "${r2gProject}";\n echo 'Now we are in phase-T...'; \n` + items // .map(v => path.resolve()) .filter(v => fs.lstatSync(tests + '/' + v).isFile()) .map(v => ` chmod u+x ./tests/${v} && ./tests/${v}; `) .join('\n'); // .concat(' exit "$?" ').join('\n'); log.info('About to run tests in your .r2g/tests dir, the command is:'); log.info(chalk.blueBright(cmd)); k.stdin.end(cmd); } } catch (err) { return process.nextTick(cb, err); } // return; const cmd = items.filter(v => { try { return fs.lstatSync(path.resolve(tests + '/' + v)).isFile() } catch (err) { log.error(err.message); return false; } }) .map(v => ` ( echo 'running test' && chmod u+x './tests/${v}' && './tests/${v}' ) | r2g_handle_stdio '${v}' ; `) .join(' '); log.info('About to run tests in your .r2g/tests dir.'); k.stdin.end(` set -eo pipefail echo 'Now we are in phase-T...'; r2g_handle_stdio() { # REPLY is a built-in, see: while read; do echo -e "\${r2g_gray}$1:\${r2g_no_color} $REPLY"; done } export -f r2g_handle_stdio; cd "${r2gProject}"; ${cmd} `); } }, (err: any, results) => { if (err && err.OK) { log.warn(chalk.blueBright(' => r2g may have run with some problems.')); log.warn(util.inspect(err)); } else if (err) { throw getCleanTrace(err); } else { log.info(chalk.green('Successfully ran r2g.')) } process.exit(0); }); };
the_stack
import { ObserverLocator, Scope, Expression, ICollectionObserverSplice, OverrideContext, BindingExpression, } from 'aurelia-binding'; import { BoundViewFactory, ViewSlot, ViewResources, TargetInstruction, IStaticResourceConfig, ElementEvents, } from 'aurelia-templating'; import { AbstractRepeater, getItemsSourceExpression, isOneTime, unwrapExpression, updateOneTimeBinding, viewsRequireLifecycle, } from 'aurelia-templating-resources'; import { DOM, PLATFORM } from 'aurelia-pal'; import { TaskQueue } from 'aurelia-task-queue'; import { rebindAndMoveView, } from './utilities'; import { calcOuterHeight, getElementDistanceToTopOfDocument, hasOverflowScroll, calcScrollHeight, } from './utilities-dom'; import { VirtualRepeatStrategyLocator } from './virtual-repeat-strategy-locator'; import { TemplateStrategyLocator } from './template-strategy-locator'; import { IVirtualRepeatStrategy, ITemplateStrategy, IView, IScrollNextScrollContext, IViewSlot, IScrollerInfo, VirtualizationCalculation, VirtualizationEvents, IElement, IVirtualRepeater, ScrollingState, } from './interfaces'; import { getResizeObserverClass, ResizeObserver, DOMRectReadOnly, } from './resize-observer'; import { htmlElement, $raf } from './constants'; const enum VirtualRepeatCallContext { handleCollectionMutated = 'handleCollectionMutated', handleInnerCollectionMutated = 'handleInnerCollectionMutated', } export class VirtualRepeat extends AbstractRepeater implements IVirtualRepeater { /**@internal */ static inject() { return [ DOM.Element, BoundViewFactory, TargetInstruction, ViewSlot, ViewResources, ObserverLocator, VirtualRepeatStrategyLocator, TemplateStrategyLocator, ]; } /**@internal */ static $resource(): IStaticResourceConfig { return { type: 'attribute', name: 'virtual-repeat', templateController: true, // Wrong typings in templating bindables: ['items', 'local'] as any, }; } /** * First view index, for proper follow up calculations */ $first: number = 0; /** * Height of top buffer to properly push the visible rendered list items into right position * Usually determined by `_first` visible index * `itemHeight` */ topBufferHeight: number; /** * Height of bottom buffer to properly push the visible rendered list items into right position */ bottomBufferHeight: number; /**@internal*/ _isAttached = false; /**@internal*/ _ticking = false; // /** // * Indicates whether virtual repeat attribute is inside a fixed height container with overflow // * // * This helps identifies place to add scroll event listener // * @internal // */ // fixedHeightContainer = false; /**@internal*/ _calledGetMore = false; /** * While handling consecutive scroll events, repeater and its strategies may need to do * some of work that will not finish immediately in order to figure out visible effective elements / views. * There are scenarios when doing this too quickly is unnecessary * as there could be still some effect on going from previous handler. * * This flag is away to ensure a scroll handler always has a chance to * finish all the work it starts, no matter how user interact via scrolling * @internal */ _skipNextScrollHandle: boolean = false; /** * While handling mutation, repeater and its strategies could/should modify scroll position * to deliver a smooth user experience. This action may trigger a scroll event * which may disrupt the mutation handling or cause unwanted effects. * * This flag is a way to tell the scroll listener that there are scenarios that * scroll event should be ignored * @internal */ _handlingMutations: boolean = false; // Inherited properties declaration key: any; value: any; /** * @bindable */ items: any[]; /** * @bindable */ local: string; /**@internal */ scope: Scope; viewSlot: IViewSlot; readonly viewFactory: BoundViewFactory; /**@internal */ element: HTMLElement; /**@internal */ private instruction: TargetInstruction; /**@internal */ private lookupFunctions: any; /**@internal */ private observerLocator: ObserverLocator; /**@internal */ private taskQueue: TaskQueue; /**@internal */ private strategyLocator: VirtualRepeatStrategyLocator; /**@internal */ private templateStrategyLocator: TemplateStrategyLocator; /**@internal */ private sourceExpression: Expression; /**@internal */ private isOneTime: boolean; /** * Snapshot of current scroller info. Used to determine action against previous scroller info * @internal */ _currScrollerInfo: IScrollerInfo; /** * Reference to scrolling container of this virtual repeat * Usually determined by template strategy. * * The scrolling container may vary based on different position of `virtual-repeat` attribute */ scrollerEl: HTMLElement; /**@internal */ _sizeInterval: any; /** * When there are no scroller defined, fallback to use `documentElement` as scroller * This has implication that distance to top always needs to be recalculated as it can be changed at any time * @internal */ _calcDistanceToTopInterval: any; /** * Defines how many items there should be for a given index to be considered at edge */ edgeDistance: number; /** * Used to revert all checks related to scroll handling guard * Employed for manually blocking scroll handling * @internal */ revertScrollCheckGuard: () => void; /** * Template handling strategy for this repeat. */ templateStrategy: ITemplateStrategy; /** * Top buffer element, used to reflect the visualization of amount of items `before` the first visible item */ topBufferEl: HTMLElement; /** * Bot buffer element, used to reflect the visualization of amount of items `after` the first visible item */ bottomBufferEl: HTMLElement; /** * Height of each item. Calculated based on first item */ itemHeight: number; /** * Calculate current scrolltop position */ distanceToTop: number; /** * Number indicating minimum elements required to render to fill up the visible viewport */ minViewsRequired: number; /** * collection repeating strategy */ strategy: IVirtualRepeatStrategy; /** * Flags to indicate whether to ignore next mutation handling * @internal */ _ignoreMutation: boolean; /** * Observer for detecting changes on scroller element for proper recalculation * @internal */ _scrollerResizeObserver: ResizeObserver; /** * Cache of last calculated content rect of scroller * @internal */ _currScrollerContentRect: DOMRectReadOnly; /** * Event manager for * @internal */ _scrollerEvents: ElementEvents; /**@internal */ callContext: VirtualRepeatCallContext; collectionObserver: any; constructor( element: HTMLElement, viewFactory: BoundViewFactory, instruction: TargetInstruction, viewSlot: ViewSlot, viewResources: ViewResources, observerLocator: ObserverLocator, collectionStrategyLocator: VirtualRepeatStrategyLocator, templateStrategyLocator: TemplateStrategyLocator ) { super({ local: 'item', viewsRequireLifecycle: viewsRequireLifecycle(viewFactory), }); this.element = element; this.viewFactory = viewFactory; this.instruction = instruction; this.viewSlot = viewSlot as IViewSlot; this.lookupFunctions = viewResources['lookupFunctions']; this.observerLocator = observerLocator; this.taskQueue = observerLocator.taskQueue; this.strategyLocator = collectionStrategyLocator; this.templateStrategyLocator = templateStrategyLocator; this.edgeDistance = 5; this.sourceExpression = getItemsSourceExpression(this.instruction, 'virtual-repeat.for'); this.isOneTime = isOneTime(this.sourceExpression); this.topBufferHeight = this.bottomBufferHeight = this.itemHeight = this.distanceToTop = 0; this.revertScrollCheckGuard = () => { this._ticking = false; }; this._onScroll = this._onScroll.bind(this); } /**@override */ bind(bindingContext: any, overrideContext: OverrideContext): void { this.scope = { bindingContext, overrideContext }; } /**@override */ attached(): void { this._isAttached = true; const element = this.element; const templateStrategy = this.templateStrategy = this.templateStrategyLocator.getStrategy(element); const scrollerEl = this.scrollerEl = templateStrategy.getScrollContainer(element); const [topBufferEl, bottomBufferEl] = templateStrategy.createBuffers(element); const isFixedHeightContainer = scrollerEl !== htmlElement; // this.fixedHeightContainer = hasOverflowScroll(containerEl); // context bound listener const scrollListener = this._onScroll; this.topBufferEl = topBufferEl; this.bottomBufferEl = bottomBufferEl; this.itemsChanged(); // take a snapshot of current scrolling information this._currScrollerInfo = this.getScrollerInfo(); if (isFixedHeightContainer) { scrollerEl.addEventListener('scroll', scrollListener); } else { const firstElement = templateStrategy.getFirstElement(topBufferEl, bottomBufferEl); this.distanceToTop = firstElement === null ? 0 : getElementDistanceToTopOfDocument(topBufferEl); DOM.addEventListener('scroll', scrollListener, false); // when there is no fixed height container (container with overflow scroll/auto) // it's assumed that the whole document will be scrollable // in this situation, distance from top buffer to top of the document/application // plays an important role and needs to be correct to correctly determine the real scrolltop of this virtual repeat // unfortunately, there is no easy way to observe this value without using dirty checking this._calcDistanceToTopInterval = PLATFORM.global.setInterval(() => { const prevDistanceToTop = this.distanceToTop; const currDistanceToTop = getElementDistanceToTopOfDocument(topBufferEl); this.distanceToTop = currDistanceToTop; if (prevDistanceToTop !== currDistanceToTop) { const currentScrollerInfo = this.getScrollerInfo(); const prevScrollerInfo = this._currScrollerInfo; this._currScrollerInfo = currentScrollerInfo; this._handleScroll(currentScrollerInfo, prevScrollerInfo); } }, 500); } this.strategy.onAttached(this); } /**@override */ call(context: 'handleCollectionMutated' | 'handleInnerCollectionMutated', changes: ICollectionObserverSplice[]): void { this[context](this.items, changes); } /**@override */ detached(): void { const scrollCt = this.scrollerEl; const scrollListener = this._onScroll; if (hasOverflowScroll(scrollCt)) { scrollCt.removeEventListener('scroll', scrollListener); } else { DOM.removeEventListener('scroll', scrollListener, false); } this.unobserveScroller(); this._currScrollerContentRect = undefined; this._isAttached // = this.fixedHeightContainer = false; this._unsubscribeCollection(); this.resetCalculation(); this.templateStrategy.removeBuffers(this.element, this.topBufferEl, this.bottomBufferEl); this.topBufferEl = this.bottomBufferEl = this.scrollerEl = null; this.removeAllViews(/*return to cache?*/true, /*skip animation?*/false); const $clearInterval = PLATFORM.global.clearInterval; $clearInterval(this._calcDistanceToTopInterval); $clearInterval(this._sizeInterval); this.distanceToTop = this._sizeInterval = this._calcDistanceToTopInterval = 0; } /**@override */ unbind(): void { this.scope = null; this.items = null; } /** * @override * * If `items` is truthy, do the following calculation/work: * * - container fixed height flag * - necessary initial heights * - create new collection observer & observe for changes * - invoke `instanceChanged` on repeat strategy to create views / move views * - update indices * - update scrollbar position in special scenarios * - handle scroll as if scroll event happened */ itemsChanged(): void { // the current collection subscription may be irrelevant // unsubscribe and resubscribe later this._unsubscribeCollection(); // still bound? and still attached? if (!this.scope || !this._isAttached) { return; } const items = this.items; const strategy = this.strategy = this.strategyLocator.getStrategy(items); if (strategy === null) { throw new Error('Value is not iterateable for virtual repeat.'); } // after calculating required variables // invoke like normal repeat attribute if (!this.isOneTime && !this._observeInnerCollection()) { this._observeCollection(); } // sizing calculation result is used to setup a resize observer const calculationSignals = strategy.initCalculation(this, items); strategy.instanceChanged(this, items, this.$first); if (calculationSignals & VirtualizationCalculation.reset) { this.resetCalculation(); } // if initial size are non-caclulatable, // setup an interval as a naive strategy to observe size // this can comes from element is initialy hidden, or 0 height for animation // or any other reasons. // todo: proper API design for sizing observation if ((calculationSignals & VirtualizationCalculation.has_sizing) === 0) { const { setInterval: $setInterval, clearInterval: $clearInterval } = PLATFORM.global; $clearInterval(this._sizeInterval); this._sizeInterval = $setInterval(() => { if (this.items) { const firstView = this.firstView() || this.strategy.createFirstRow(this); const newCalcSize = calcOuterHeight(firstView.firstChild as Element); if (newCalcSize > 0) { $clearInterval(this._sizeInterval); this.itemsChanged(); } } else { $clearInterval(this._sizeInterval); } }, 500); } if (calculationSignals & VirtualizationCalculation.observe_scroller) { this.observeScroller(this.scrollerEl); } } /**@override */ handleCollectionMutated(collection: any[], changes: ICollectionObserverSplice[]): void { // guard against multiple mutation, or mutation combined with instance mutation if (this._ignoreMutation) { return; } this._handlingMutations = true; this.strategy.instanceMutated(this, collection, changes); } /**@override */ handleInnerCollectionMutated(collection: any[], changes: ICollectionObserverSplice[]): void { // guard against source expressions that have observable side-effects that could // cause an infinite loop- eg a value converter that mutates the source array. if (this._ignoreMutation) { return; } this._ignoreMutation = true; const newItems = this.sourceExpression.evaluate(this.scope, this.lookupFunctions); this.taskQueue.queueMicroTask(() => this._ignoreMutation = false); // call itemsChanged... if (newItems === this.items) { // call itemsChanged directly. this.itemsChanged(); } else { // call itemsChanged indirectly by assigning the new collection value to // the items property, which will trigger the self-subscriber to call itemsChanged. this.items = newItems; } } enableScroll(): void { this._ticking = false; this._handlingMutations = false; this._skipNextScrollHandle = false; } /** * Get the real scroller element of the DOM tree this repeat resides in */ getScroller(): HTMLElement { return this.scrollerEl; } /** * Get scrolling information of the real scroller element of the DOM tree this repeat resides in */ getScrollerInfo(): IScrollerInfo { const scroller = this.scrollerEl; return { scroller: scroller, // scrollHeight: scroller.scrollHeight, scrollTop: scroller.scrollTop, // height: calcScrollHeight(scroller) height: scroller === htmlElement ? innerHeight : calcScrollHeight(scroller), }; } resetCalculation(): void { this.$first // = this._viewsLength = this.topBufferHeight = this.bottomBufferHeight = this.itemHeight = this.minViewsRequired = 0; this._ignoreMutation = this._handlingMutations = this._ticking = false; this.updateBufferElements(/*skip update?*/true); } /**@internal*/ _onScroll(): void { const isHandlingMutations = this._handlingMutations; if (!this._ticking && !isHandlingMutations) { const prevScrollerInfo = this._currScrollerInfo; const currentScrollerInfo = this.getScrollerInfo(); this._currScrollerInfo = currentScrollerInfo; this.taskQueue.queueMicroTask(() => { this._ticking = false; this._handleScroll(currentScrollerInfo, prevScrollerInfo); }); this._ticking = true; } if (isHandlingMutations) { this._handlingMutations = false; } } /**@internal */ _handleScroll(current_scroller_info: IScrollerInfo, prev_scroller_info: IScrollerInfo): void { if (!this._isAttached) { return; } if (this._skipNextScrollHandle) { this._skipNextScrollHandle = false; return; } // todo: move this to repeat strategy const items = this.items; if (!items) { return; } const strategy = this.strategy; // todo: use _firstViewIndex() const old_range_start_index = this.$first; const old_range_end_index = this.lastViewIndex(); const { 0: new_range_start_index, 1: new_range_end_index } = strategy.getViewRange(this, current_scroller_info); let scrolling_state: ScrollingState = new_range_start_index > old_range_start_index ? ScrollingState.isScrollingDown : new_range_start_index < old_range_start_index ? ScrollingState.isScrollingUp : ScrollingState.none; // treating scrollbar like an axis, we have a few intersection types for two ranges // there are 6 range intersection types (inclusive) // range-1: before scroll (old range) // range-2: after scroll (new range) // // 1: scrolling down not but havent reached bot // range 1: ====[==============] // range-2: [==============]======== // // 2: scrolling up but havent reached top // range-1: [=======]========= // range-2: =======[=======] // // 3: scrolling down to bottom // range-1: =====[============] // range-2: [============] // // 4: scrolling up to top // range-1: [===========]====== // range-2: [===========] // // 5: jump // range-1: ======== // range-2: ========== // // 6: jump // range-1: ========== // range-2: ======== // // ------------------------------ // TODO: consider alwways use physical scroll position to determine scrolling scenarios let didMovedViews = 0; let should_call_scroll_next: -1 | 0 | 1 = 0; /** for debugging purposes only */ let scroll_scenario: 0 | 1 | 2 | 3 | 4 | 5 | 6 = 0; // optimizable case: intersection type 3 & 4 // nothing needs to be done. Check these 2 cases in advance to group other logic closer if ( // scrolling down and reach bot new_range_start_index >= old_range_start_index && old_range_end_index === new_range_end_index // scrolling up and reach top || new_range_end_index === old_range_end_index && old_range_end_index >= new_range_end_index ) { // do nothing related to updating view. Whatever is going to be visible was already visible // and updated correctly // // start checking whether scrollnext should be invoked // scrolling down, check if is close to bottom if (new_range_start_index >= old_range_start_index && old_range_end_index === new_range_end_index) { scroll_scenario = 3; if (strategy.isNearBottom(this, new_range_end_index)) { // should_call_scroll_next = 1; scrolling_state |= ScrollingState.isNearBottom; } } // scrolling up. check if near top else if (strategy.isNearTop(this, new_range_start_index)) { // should_call_scroll_next = -1; scroll_scenario = 4; scrolling_state |= ScrollingState.isNearTop; } // todo: fix the issues related to scroll smoothly to bottom not triggering scroll-next } else { // intersection type 1: scrolling down but haven't reached bot // needs to move bottom views from old range (range-2) to new range (range-1) if (new_range_start_index > old_range_start_index && old_range_end_index >= new_range_start_index && new_range_end_index >= old_range_end_index ) { scroll_scenario = 1; const views_to_move_count = new_range_start_index - old_range_start_index; this._moveViews(views_to_move_count, 1); didMovedViews = 1; // should_call_scroll_next = 1; if (strategy.isNearBottom(this, new_range_end_index)) { scrolling_state |= ScrollingState.isNearBottom; } } // intersection type 2: scrolling up but haven't reached top // this scenario requires move views from start of old range to end of new range else if (old_range_start_index > new_range_start_index && old_range_start_index <= new_range_end_index && old_range_end_index >= new_range_end_index ) { scroll_scenario = 2; const views_to_move_count = old_range_end_index - new_range_end_index; this._moveViews(views_to_move_count, -1); didMovedViews = 1; // should_call_scroll_next = -1; if (strategy.isNearTop(this, new_range_start_index)) { scrolling_state |= ScrollingState.isNearTop; } } // intersection type 5 and type 6: scrolling with jumping behavior // this scenario requires only updating views else if (old_range_end_index < new_range_start_index || old_range_start_index > new_range_end_index) { strategy.remeasure(this); // jump down, check if is close to bottom if (old_range_end_index < new_range_start_index) { if (strategy.isNearBottom(this, new_range_end_index)) { scroll_scenario = 5; // should_call_scroll_next = 1; scrolling_state |= ScrollingState.isNearBottom; } } // jump up. check if near top else if (strategy.isNearTop(this, new_range_start_index)) { scroll_scenario = 6; // should_call_scroll_next = -1; scrolling_state |= ScrollingState.isNearTop; } } // catch invalid cases // these are cases that were not handled properly. // If happens, need to fix the above logic related to range check else { if (old_range_start_index !== new_range_start_index || old_range_end_index !== new_range_end_index) { // (forcefully calling _handleScroll, scrolled too little, browser bug, touchpad sensitivity issues etc...) console.log(`[!] Scroll intersection not handled. With indices: ` + `new [${new_range_start_index}, ${new_range_end_index}] / old [${old_range_start_index}, ${old_range_end_index}]` ); strategy.remeasure(this); } else { console.log('[!] Scroll handled, and there\'s no changes'); } } } if (didMovedViews === 1) { this.$first = new_range_start_index; strategy.updateBuffers(this, new_range_start_index); } // after updating views // check if infinite scrollnext should be invoked // the following block cannot be nested inside didMoveViews condition // since there could be jumpy scrolling behavior causing infinite scrollnext if ( (scrolling_state & ScrollingState.isScrollingDownAndNearBottom) === ScrollingState.isScrollingDownAndNearBottom || (scrolling_state & ScrollingState.isScrollingUpAndNearTop) === ScrollingState.isScrollingUpAndNearTop ) { this.getMore( new_range_start_index, (scrolling_state & ScrollingState.isNearTop) > 0, (scrolling_state & ScrollingState.isNearBottom) > 0 ); } else { // it typically means there was no "semantic scrolling" happened. // The scroll direction couldn't be derived from the view index // (forcefully calling _handleScroll, scrolled too little, browser bug, touchpad sensitivity issues etc...) // // Though there may be some physical scrolling, // but it wasn't enough to actually shift the views around. // So in here, use physical scrolling to determine the direction const scroll_top_delta = current_scroller_info.scrollTop - prev_scroller_info.scrollTop; scrolling_state = scroll_top_delta > 0 ? ScrollingState.isScrollingDown : scroll_top_delta < 0 ? ScrollingState.isScrollingUp : ScrollingState.none; if (strategy.isNearTop(this, new_range_start_index)) { scrolling_state |= ScrollingState.isNearTop; } if (strategy.isNearBottom(this, new_range_end_index)) { scrolling_state |= ScrollingState.isNearBottom; } if ( (scrolling_state & ScrollingState.isScrollingDownAndNearBottom) === ScrollingState.isScrollingDownAndNearBottom || (scrolling_state & ScrollingState.isScrollingUpAndNearTop) === ScrollingState.isScrollingUpAndNearTop ) { this.getMore( new_range_start_index, (scrolling_state & ScrollingState.isNearTop) > 0, (scrolling_state & ScrollingState.isNearBottom) > 0 ); } } } /** * Move views based on scrolling direction and number of views to move * Must only be invoked only to move views while scrolling * @internal */ _moveViews(viewsCount: number, direction: /*up*/-1 | /*down*/1): void { const repeat = this; // move to top if (direction === -1) { let startIndex = repeat.firstViewIndex(); while (viewsCount--) { const view = repeat.lastView(); rebindAndMoveView( repeat, view, --startIndex, /*move to bottom?*/false ); } } // move to bottom else { let lastIndex = repeat.lastViewIndex(); while (viewsCount--) { const view = repeat.view(0); rebindAndMoveView( repeat, view, ++lastIndex, /*move to bottom?*/true ); } } } /** * A guard to track time between getMore execution to ensure it's not called too often * Make it slightly more than an frame time for 60fps * @internal */ _lastGetMore: number = 0; getMore(topIndex: number, isNearTop: boolean, isNearBottom: boolean, force?: boolean): void { if (isNearTop || isNearBottom || force) { // guard against too rapid fire when scrolling towards end/start if (!this._calledGetMore) { const executeGetMore = (time: number) => { if (time - this._lastGetMore < 16) { return; } this._lastGetMore = time; this._calledGetMore = true; const revertCalledGetMore = () => { this._calledGetMore = false; }; const firstView = this.firstView(); if (firstView === null) { revertCalledGetMore(); return; } const firstViewElement = firstView.firstChild as IElement; const scrollNextAttrName = 'infinite-scroll-next'; const func: string | (BindingExpression & { sourceExpression: Expression }) = firstViewElement && firstViewElement.au && firstViewElement.au[scrollNextAttrName] ? firstViewElement.au[scrollNextAttrName].instruction.attributes[scrollNextAttrName] : undefined; if (func === undefined) { // Still reset `_calledGetMore` flag as if it was invoked // though this should not happen as presence of infinite-scroll-next attribute // will make the value at least be an empty string // keeping this logic here for future enhancement/evolution revertCalledGetMore(); } else { const scrollContext: IScrollNextScrollContext = { topIndex: topIndex, isAtBottom: isNearBottom, isAtTop: isNearTop, }; const overrideContext = this.scope.overrideContext; overrideContext.$scrollContext = scrollContext; if (typeof func === 'string') { const bindingContext = overrideContext.bindingContext; const getMoreFuncName = (firstView.firstChild as Element).getAttribute(scrollNextAttrName); const funcCall = bindingContext[getMoreFuncName]; if (typeof funcCall === 'function') { revertCalledGetMore(); const result = funcCall.call(bindingContext, topIndex, isNearBottom, isNearTop); if (result instanceof Promise) { this._calledGetMore = true; return result.then(() => { // Reset for the next time revertCalledGetMore(); }); } } else { throw new Error(`'${scrollNextAttrName}' must be a function or evaluate to one`); } } else if (func.sourceExpression) { // Reset for the next time revertCalledGetMore(); return func.sourceExpression.evaluate(this.scope); } else { throw new Error(`'${scrollNextAttrName}' must be a function or evaluate to one`); } } }; $raf(executeGetMore); } } } updateBufferElements(skipUpdate?: boolean): void { this.topBufferEl.style.height = `${this.topBufferHeight}px`; this.bottomBufferEl.style.height = `${this.bottomBufferHeight}px`; if (skipUpdate) { this._ticking = true; $raf(this.revertScrollCheckGuard); } } /**@internal*/ _unsubscribeCollection(): void { const collectionObserver = this.collectionObserver; if (collectionObserver) { collectionObserver.unsubscribe(this.callContext, this); this.collectionObserver = this.callContext = null; } } firstView(): IView | null { return this.view(0); } lastView(): IView | null { return this.view(this.viewCount() - 1); } firstViewIndex(): number { const firstView = this.firstView(); return firstView === null ? -1 : firstView.overrideContext.$index; } lastViewIndex(): number { const lastView = this.lastView(); return lastView === null ? -1 : lastView.overrideContext.$index; } /** * Observe scroller element to react upon sizing changes */ observeScroller(scrollerEl: HTMLElement): void { // using `newRect` paramter to check if this size change handler is still the most recent update // only invoke items changed if it is // this is to ensure items changed calls are not invoked unncessarily const sizeChangeHandler = (newRect: DOMRectReadOnly) => { $raf(() => { if (newRect === this._currScrollerContentRect) { // console.log('3. resize observer handler invoked') this.itemsChanged(); } }); }; const ResizeObserverConstructor = getResizeObserverClass(); if (typeof ResizeObserverConstructor === 'function') { let observer = this._scrollerResizeObserver; if (observer) { observer.disconnect(); } // rebuild observer and reobserve scroller el, // for might-be-supported feature in future where scroller can be dynamically changed observer = this._scrollerResizeObserver = new ResizeObserverConstructor((entries) => { const oldRect = this._currScrollerContentRect; const newRect = entries[0].contentRect; this._currScrollerContentRect = newRect; // console.log('1. resize observer hit'); if (oldRect === undefined || newRect.height !== oldRect.height || newRect.width !== oldRect.width) { // console.log('2. resize observer handler queued'); // passing `newRect` paramter to later check if resize notification is the latest event // only invoke items changed if it is // this is to ensure items changed calls are not invoked unncessarily sizeChangeHandler(newRect); } }); observer.observe(scrollerEl); } // subscribe to selected custom events // for manual notification, in case all native strategies fail (no support/buggy browser implementation) let elEvents = this._scrollerEvents; if (elEvents) { elEvents.disposeAll(); } const sizeChangeEventsHandler = () => { $raf(() => { this.itemsChanged(); }); }; // rebuild element events, // for might-be-supported feature in future where scroller can be dynamically changed elEvents = this._scrollerEvents = new ElementEvents(scrollerEl); elEvents.subscribe(VirtualizationEvents.scrollerSizeChange, sizeChangeEventsHandler, false); elEvents.subscribe(VirtualizationEvents.itemSizeChange, sizeChangeEventsHandler, false); } /** * Dispose scroller content size observer, if has * Dispose all event listeners related to sizing of scroller, if any */ unobserveScroller(): void { const observer = this._scrollerResizeObserver; if (observer) { observer.disconnect(); } const scrollerEvents = this._scrollerEvents; if (scrollerEvents) { scrollerEvents.disposeAll(); } this._scrollerResizeObserver = this._scrollerEvents = undefined; } /** * If repeat items is behind a binding behavior or value converter * the real array is "inner" part of the expression * which should be observed via this method * @internal */ _observeInnerCollection(): boolean { const items = this._getInnerCollection(); const strategy = this.strategyLocator.getStrategy(items); if (!strategy) { return false; } const collectionObserver = strategy.getCollectionObserver(this.observerLocator, items); if (!collectionObserver) { return false; } const context = VirtualRepeatCallContext.handleInnerCollectionMutated; this.collectionObserver = collectionObserver; this.callContext = context; collectionObserver.subscribe(context, this); return true; } /**@internal*/ _getInnerCollection(): any { const expression = unwrapExpression(this.sourceExpression); if (!expression) { return null; } return expression.evaluate(this.scope, null); } /**@internal*/ _observeCollection(): void { const collectionObserver = this.strategy.getCollectionObserver(this.observerLocator, this.items); if (collectionObserver) { this.callContext = VirtualRepeatCallContext.handleCollectionMutated; this.collectionObserver = collectionObserver; collectionObserver.subscribe(this.callContext, this); } } // @override AbstractRepeater // How will these behaviors need to change since we are in a virtual list instead? /**@override */ viewCount(): number { return this.viewSlot.children.length; } /**@override */ views(): IView[] { return this.viewSlot.children; } /**@override */ view(index: number): IView | null { const viewSlot = this.viewSlot; return index < 0 || index > viewSlot.children.length - 1 ? null : viewSlot.children[index]; } /**@override */ addView(bindingContext: any, overrideContext: OverrideContext): IView { const view = this.viewFactory.create(); view.bind(bindingContext, overrideContext); this.viewSlot.add(view); return view as IView; } /**@override */ insertView(index: number, bindingContext: any, overrideContext: OverrideContext): void { const view = this.viewFactory.create(); view.bind(bindingContext, overrideContext); this.viewSlot.insert(index, view); } /**@override */ removeAllViews(returnToCache: boolean, skipAnimation: boolean): void | Promise<void> { return this.viewSlot.removeAll(returnToCache, skipAnimation); } /**@override */ removeView(index: number, returnToCache: boolean, skipAnimation: boolean): IView | Promise<IView> { return this.viewSlot.removeAt(index, returnToCache, skipAnimation) as IView | Promise<IView>; } /**@override */ updateBindings(view: IView): void { const bindings = view.bindings; let j = bindings.length; while (j--) { updateOneTimeBinding(bindings[j]); } const controllers = view.controllers; j = controllers.length; while (j--) { const boundProperties = controllers[j].boundProperties; let k = boundProperties.length; while (k--) { let binding = boundProperties[k].binding; updateOneTimeBinding(binding); } } } }
the_stack
import plugin from '../' import Client, { EventDeliveryPayload } from '@bugsnag/core/client' type EnhancedWindow = Window & typeof globalThis & { onerror: OnErrorEventHandlerNonNull } let window: EnhancedWindow describe('plugin: window onerror', () => { beforeEach(() => { window = {} as unknown as EnhancedWindow }) it('should set a window.onerror event handler', () => { const client = new Client({ apiKey: 'API_KEY_YEAH', plugins: [plugin(window)] }) expect(typeof window.onerror).toBe('function') expect(client).toBe(client) }) it('should not add a window.onerror event handler when autoDetectErrors=false', () => { const client = new Client({ apiKey: 'API_KEY_YEAH', autoDetectErrors: false, plugins: [plugin(window)] }) expect(window.onerror).toBe(undefined) expect(client).toBe(client) }) it('should not add a window.onerror event handler when enabledErrorTypes.unhandledExceptions=false', () => { const client = new Client({ apiKey: 'API_KEY_YEAH', enabledErrorTypes: { unhandledExceptions: false, unhandledRejections: false }, plugins: [plugin(window)] }) expect(window.onerror).toBe(undefined) expect(client).toBe(client) }) describe('window.onerror function', () => { it('captures uncaught errors in timer callbacks', done => { const client = new Client({ apiKey: 'API_KEY_YEAH', plugins: [plugin(window)] }) const payloads: EventDeliveryPayload[] = [] client._setDelivery(client => ({ sendEvent: (payload) => payloads.push(payload), sendSession: () => {} })) window.onerror('Uncaught Error: Bad things', 'foo.js', 10, 20, new Error('Bad things')) try { expect(payloads.length).toBe(1) const event = payloads[0].events[0].toJSON() expect(event.severity).toBe('error') expect(event.unhandled).toBe(true) expect(event.severityReason).toEqual({ type: 'unhandledException' }) done() } catch (e) { done(e) } }) // // it('captures uncaught errors in DOM (level 2) event handlers', done => { // const client = new Client(VALID_NOTIFIER) // const payloads = [] // client.setOptions({ apiKey: 'API_KEY_YEAH' }) // client.configure() // client.use(plugin, window) // client.delivery({ sendEvent: (payload) => payloads.push(payload) }) // // window.eval(` // var el = window.document.createElement('BUTTON') // el.onclick = function () { throw new Error('bad button l2') } // window.document.body.appendChild(el) // setTimeout(function () { el.click() }, 0) // `) // // try { // expect(payloads.length).toBe(1) // const event = payloads[0].events[0].toJSON() // expect(event.severity).toBe('error') // expect(event.unhandled).toBe(true) // expect(event.severityReason).toEqual({ type: 'unhandledException' }) // done() // } catch (e) { // done(e) // } // }) // eslint-disable-next-line jest/expect-expect it('calls any previously registered window.onerror callback', done => { window.onerror = () => done() const client = new Client({ apiKey: 'API_KEY_YEAH', plugins: [plugin(window)] }) const payloads: EventDeliveryPayload[] = [] client._setDelivery(client => ({ sendEvent: (payload) => payloads.push(payload), sendSession: () => {} })) window.onerror('Uncaught Error: Bad things', 'foo.js', 10, 20, new Error('Bad things')) }) it('handles single argument usage of window.onerror', () => { const client = new Client({ apiKey: 'API_KEY_YEAH', plugins: [plugin(window)] }) const payloads: EventDeliveryPayload[] = [] client._setDelivery(client => ({ sendEvent: (payload) => payloads.push(payload), sendSession: () => {} })) const evt = { type: 'error', detail: 'something bad happened' } as unknown as Event window.onerror(evt) expect(payloads.length).toBe(1) const event = payloads[0].events[0].toJSON() expect(event.severity).toBe('error') expect(event.unhandled).toBe(true) expect(event.exceptions[0].errorClass).toBe('Event: error') expect(event.exceptions[0].message).toBe('something bad happened') expect(event.severityReason).toEqual({ type: 'unhandledException' }) }) it('handles single argument usage of window.onerror with extra parameter', () => { const client = new Client({ apiKey: 'API_KEY_YEAH', plugins: [plugin(window)] }) const payloads: EventDeliveryPayload[] = [] client._setDelivery(client => ({ sendEvent: (payload) => payloads.push(payload), sendSession: () => {} })) // this situation is caused by the following kind of jQuery call: // jQuery('select.province').trigger(jQuery.Event('error.validator.bv'), { valid: false }) const evt = { type: 'error', detail: 'something bad happened' } as unknown as Event const extra = { valid: false } window.onerror(evt, extra as any) expect(payloads.length).toBe(1) const event = payloads[0].events[0].toJSON() expect(event.severity).toBe('error') expect(event.unhandled).toBe(true) expect(event.exceptions[0].errorClass).toBe('Event: error') expect(event.exceptions[0].message).toBe('something bad happened') expect(event.severityReason).toEqual({ type: 'unhandledException' }) }) // // if ('addEventListener' in window) { // it('captures uncaught errors in DOM (level 3) event handlers', done => { // const client = new Client(VALID_NOTIFIER) // const payloads = [] // client.setOptions({ apiKey: 'API_KEY_YEAH' }) // client.configure() // client.use(plugin) // client.delivery({ sendEvent: (payload) => payloads.push(payload) }) // // const el = document.createElement('BUTTON') // el.addEventListener('click', () => { throw new Error('bad button l3') }) // window.document.body.appendChild(el) // // setTimeout(() => el.click(), 0) // setTimeout(() => { // try { // expect(payloads.length).toBe(1) // const event = payloads[0].events[0].toJSON() // expect(event.severity).toBe('error') // expect(event.unhandled).toBe(true) // expect(event.severityReason).toEqual({ type: 'unhandledException' }) // done() // } catch (e) { // done(e) // } // }, 100) // }) // } // // if ('requestAnimationFrame' in window) { // it('captures uncaught errors in requestAnimationFrame callbacks', done => { // const client = new Client(VALID_NOTIFIER) // const payloads = [] // client.setOptions({ apiKey: 'API_KEY_YEAH' }) // client.configure() // client.use(plugin) // client.delivery({ sendEvent: (payload) => payloads.push(payload) }) // // window.requestAnimationFrame(() => { // throw new Error('ERR_RAF') // }) // // window.requestAnimationFrame(() => { // try { // expect(payloads.length).toBe(1) // const event = payloads[0].events[0].toJSON() // expect(event.severity).toBe('error') // expect(event.unhandled).toBe(true) // expect(event.severityReason).toEqual({ type: 'unhandledException' }) // done() // } catch (e) { // done(e) // } // }) // }) // } it('extracts meaning from non-error values as error messages', function (done) { const client = new Client({ apiKey: 'API_KEY_YEAH', plugins: [plugin(window)] }) const payloads: EventDeliveryPayload[] = [] client._setDelivery(client => ({ sendEvent: (payload) => payloads.push(payload), sendSession: () => {} })) // call onerror as it would be when `throw 'hello' is run` // @ts-expect-error window.onerror('uncaught exception: hello', '', 0, 0, 'hello') try { expect(payloads.length).toBe(1) const event = payloads[0].events[0].toJSON() expect(event.exceptions[0].errorClass).toBe('Error') expect(event.exceptions[0].message).toMatch( /^hello|uncaught hello|exception thrown and not caught|uncaught exception: hello$/i ) expect(event.severity).toBe('error') expect(event.unhandled).toBe(true) expect(event.severityReason).toEqual({ type: 'unhandledException' }) done() } catch (e) { done(e) } }) it('calls a previously installed window.onerror callback', function (done) { const args = ['Uncaught Error: derp!', 'http://localhost:4999', 10, 3, new Error('derp!')] as const window.onerror = (messageOrEvent, url, lineNo, charNo, error) => { expect(messageOrEvent).toBe(args[0]) expect(url).toBe(args[1]) expect(lineNo).toBe(args[2]) expect(charNo).toBe(args[3]) expect(error).toBe(args[4]) expect(payloads.length).toBe(1) done() } const client = new Client({ apiKey: 'API_KEY_YEAH', plugins: [plugin(window)] }) const payloads: EventDeliveryPayload[] = [] client._setDelivery(client => ({ sendEvent: (payload) => payloads.push(payload), sendSession: () => {} })) // call onerror as it would be when `throw 'hello' is run` window.onerror(...args) }) it('calls a previously installed window.onerror when a CORS error happens', function (done) { const args = ['Script error.', undefined, 0, undefined, undefined] as const window.onerror = (messageOrEvent, url, lineNo, charNo, error) => { expect(messageOrEvent).toBe(args[0]) expect(url).toBe(args[1]) expect(lineNo).toBe(args[2]) expect(charNo).toBe(args[3]) expect(error).toBe(args[4]) expect(payloads.length).toBe(0) done() } const client = new Client({ apiKey: 'API_KEY_YEAH', plugins: [plugin(window)] }) const payloads: EventDeliveryPayload[] = [] client._setDelivery(client => ({ sendEvent: (payload) => payloads.push(payload), sendSession: () => {} })) // call onerror as it would be when `throw 'hello' is run` window.onerror(...args) }) }) })
the_stack
import React from 'react' export const LogoAscii: React.FunctionComponent<{ fontSize?: number }> = ({ fontSize = 8 }) => { // colors are hardcoded as it's a 1-to-1 conversion from src-cli ASCII logo const color_af5f5f = { color: '#af5f5f' } const color_d75f00 = { color: '#d75f00' } const color_ff5f00 = { color: '#ff5f00' } const color_875faf = { color: '#875faf' } const color_af00d7 = { color: '#af00d7' } const color_af00ff = { color: '#af00ff' } const color_af5fd7 = { color: '#af5fd7' } const color_5f87af = { color: '#5f87af' } const color_5fafd7 = { color: '#5fafd7' } const color_00afd7 = { color: '#00afd7' } const color_00afff = { color: '#00afff' } const color_af0087 = { color: '#af0087' } const color_0087af = { color: '#0087af' } const color_005f5f = { color: '#005f5f' } const color_404040 = { color: '#404040' } const color_875f00 = { color: '#875f00' } const color_af5f00 = { color: '#af5f00' } const color_af005f = { color: '#af005f' } const color_0087d7 = { color: '#0087d7' } const color_005fd7 = { color: '#005fd7' } const color_5f00d7 = { color: '#5f00d7' } const color_5f5faf = { color: '#5f5faf' } const color_5fafaf = { color: '#5fafaf' } const color_8700ff = { color: '#8700ff' } const color_8700d7 = { color: '#8700d7' } const color_4a4a4a = { color: '#4a4a4a' } const color_005f87 = { color: '#005f87' } const color_875f5f = { color: '#875f5f' } const color_af5faf = { color: '#af5faf' } const color_af875f = { color: '#af875f' } return ( <> <pre style={{ fontSize }}> {' '} <span style={color_af5f5f}>╓</span> <span style={color_d75f00}>╦╬╬╬╦</span> <span style={color_af5f5f}>╖</span> {'\n'} {' '} <span style={color_d75f00}>╬</span> <span style={color_ff5f00}>╬╬╬╬╬╬╬╬</span> {'\n'} {' '} <span style={color_af5f5f}>╞</span> <span style={color_ff5f00}>╬╬╬╬╬╬╬╬╬</span> <span style={color_d75f00}>╬</span> {' '} <span style={color_875faf}>╓</span> <span style={color_af00d7}>╦╦╦╦</span> <span style={color_875faf}>┐</span> {'\n'} {' '} <span style={color_ff5f00}>╬╬╬╬╬╬╬╬╬╬</span> <span style={color_af5f5f}>╕</span> {' '} <span style={color_af00d7}>╔</span> <span style={color_af00ff}>╪╪╪╪╪╪╪╪</span> <span style={color_af5fd7}>╕</span> {'\n'} {' '} <span style={color_af5f5f}>╘</span> <span style={color_ff5f00}>╬╬╬╬╬╬╬╬╬╬</span> {' '} <span style={color_af00d7}>╔</span> <span style={color_af00ff}>╪╪╪╪╪╪╪╪╪╪╪</span> {'\n'} {' '} <span style={color_d75f00}>╬</span> <span style={color_ff5f00}>╬╬╬╬╬╬╬╬╬</span> <span style={color_d75f00}>╗</span> {' '} <span style={color_af5fd7}>╔</span> <span style={color_af00ff}>╪╪╪╪╪╪╪╪╪╪╪╪</span> <span style={color_af5fd7}>┘</span> {'\n'} {' '} <span style={color_5f87af}>╓</span> <span style={color_5fafd7}>╦</span> <span style={color_00afd7}>╦╖</span> <span style={color_5f87af}>┐</span> {' '} <span style={color_ff5f00}>╬╬╬╬╬╬╬╬╬╬</span> <span style={color_af5fd7}>╔</span> <span style={color_af00ff}>╝╪╪╪╪╪╪╪╪╪╪╪</span> <span style={color_af00d7}>╜</span> {'\n'} <span style={color_00afd7}>╬</span> <span style={color_00afff}>╪╪╪╪╪╪╪╪╬</span> <span style={color_00afd7}>╗╦</span> <span style={color_5f87af}>╖</span> {' '} <span style={color_d75f00}>╠</span> <span style={color_ff5f00}>╬╬╬╬╬╬╬╬</span> <span style={color_af0087}>╝</span> <span style={color_af00ff}>╪╪╪╪╪╪╪╪╪╪╪╪</span> <span style={color_af00d7}>╜</span> {'\n'} <span style={color_00afd7}>╠</span> <span style={color_00afff}>╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪</span> <span style={color_0087af}>╝</span> <span style={color_005f5f}>╝</span> <span style={color_404040}>╬</span> <span style={color_875f00}>╬</span> <span style={color_af5f00}>╬</span> <span style={color_d75f00}>╬</span> <span style={color_af005f}>╝</span> <span style={color_af00ff}>╪╪╪╪╪╪╪╪╪╪╪╪</span> <span style={color_af00d7}>╜</span> {'\n'} <span style={color_5f87af}>└</span> <span style={color_00afff}>╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪</span> <span style={color_0087d7}>╪</span> <span style={color_005fd7}>╪╪</span> <span style={color_5f00d7}>╪╪</span> <span style={color_af00ff}>╪╪╪╪╪╪</span> <span style={color_af00d7}>╩</span> {'\n'} {' '} <span style={color_00afd7}>╙╩</span> <span style={color_00afff}>╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪</span> <span style={color_0087d7}>╪</span> <span style={color_005fd7}>╪╪</span> <span style={color_5f5faf}>╖</span> {'\n'} {' '} <span style={color_5f87af}>└</span> <span style={color_00afd7}>╙╩</span> <span style={color_00afff}>╬╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╬</span> <span style={color_00afd7}>╦</span> <span style={color_5fafd7}>╗</span> <span style={color_5f87af}>┐</span> {'\n'} {' '} <span style={color_5fafaf}>╙</span> <span style={color_00afd7}>╜</span> <span style={color_0087d7}>╪</span> <span style={color_00afff}>╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪</span> <span style={color_00afd7}>╗╦</span> <span style={color_5fafaf}>╖</span> {'\n'} {' '} <span style={color_875faf}>┌</span> <span style={color_af00ff}>╬╪╪</span> <span style={color_8700ff}>╪</span> <span style={color_5f00d7}>╪╪</span> <span style={color_005fd7}>╪</span> <span style={color_0087d7}>╪</span> <span style={color_00afff}>╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╬</span> {'\n'} {' '} <span style={color_875faf}>┌</span> <span style={color_af00d7}>╗</span> <span style={color_af00ff}>╪╪╪╪╪╪╪╪╪╪╪</span> <span style={color_8700d7}>╪</span> <span style={color_4a4a4a}>╬</span> <span style={color_404040}>╬</span> <span style={color_005f87}>╬</span> <span style={color_0087af}>╪</span> <span style={color_00afff}>╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪╪</span> {'\n'} {' '} <span style={color_875faf}>┌</span> <span style={color_af00d7}>╗</span> <span style={color_af00ff}>╪╪╪╪╪╪╪╪╪╪╪╪</span> <span style={color_af0087}>╬</span> <span style={color_d75f00}>╬</span> <span style={color_ff5f00}>╬╬╬╬╬</span> <span style={color_d75f00}>╬</span> <span style={color_875f5f}>╬ </span> <span style={color_5fafaf}>╙</span> <span style={color_00afd7}>╜╩</span> <span style={color_00afff}>╪╪╪╪╪╪╪╪╪╪╪╪</span> <span style={color_00afd7}>╜</span> {'\n'} {' '} <span style={color_875faf}>┌</span> <span style={color_af00d7}>╦</span> <span style={color_af00ff}>╪╪╪╪╪╪╪╪╪╪╪╝</span> <span style={color_af5faf}>╙</span> <span style={color_d75f00}>╬</span> <span style={color_ff5f00}>╬╬╬╬╬╬╬╬╬</span> {' '} <span style={color_5f87af}>└</span> <span style={color_00afd7}>╙╩</span> <span style={color_00afff}>╬╪╪╝</span> <span style={color_00afd7}>╜</span> {'\n'} {' '} <span style={color_af00d7}>╦</span> <span style={color_af00ff}>╪╪╪╪╪╪╪╪╪╪╪╪</span> <span style={color_af5fd7}>┘</span> {' '} <span style={color_d75f00}>╠</span> <span style={color_ff5f00}>╬╬╬╬╬╬╬╬╬</span> <span style={color_d75f00}>╬</span> {'\n'} {' '} <span style={color_af00ff}>╬╪╪╪╪╪╪╪╪╪╪╪</span> <span style={color_af5fd7}>┘</span> {' '} <span style={color_ff5f00}>╬╬╬╬╬╬╬╬╬╬</span> <span style={color_af5f5f}>┐</span> {'\n'} {' '} <span style={color_af00d7}>╙</span> <span style={color_af00ff}>╪╪╪╪╪╪╪╪╪</span> <span style={color_af00d7}>╜</span> {' '} <span style={color_af5f5f}>╘</span> <span style={color_ff5f00}>╬╬╬╬╬╬╬╬╬╬</span> {'\n'} {' '} <span style={color_875faf}>└</span> <span style={color_af00d7}>╩</span> <span style={color_af00ff}>╪╪╪╪╝</span> <span style={color_af5fd7}>╙</span> {' '} <span style={color_d75f00}>╬</span> <span style={color_ff5f00}>╬╬╬╬╬╬╬╬╬</span> <span style={color_d75f00}>╕</span> {'\n'} {' '} <span style={color_af875f}>└</span> <span style={color_ff5f00}>╬╬╬╬╬╬╬╬╬</span> <span style={color_af5f5f}>╛</span> {'\n'} {' '} <span style={color_d75f00}>╩</span> <span style={color_ff5f00}>╬╬╬╬╬</span> <span style={color_d75f00}>╬</span> <span style={color_af5f5f}>┘</span> {'\n'} </pre> </> ) }
the_stack
export enum FilterType { repo = 'repo', repogroup = 'repogroup', repohasfile = 'repohasfile', repohascommitafter = 'repohascommitafter', file = 'file', type = 'type', case = 'case', lang = 'lang', fork = 'fork', archived = 'archived', visibility = 'visibility', count = 'count', timeout = 'timeout', before = 'before', after = 'after', author = 'author', committer = 'committer', message = 'message', content = 'content', patterntype = 'patterntype', index = 'index', // eslint-disable-next-line unicorn/prevent-abbreviations rev = 'rev', } /* eslint-disable unicorn/prevent-abbreviations */ export enum AliasedFilterType { r = 'repo', g = 'repogroup', f = 'file', l = 'lang', language = 'lang', until = 'before', since = 'after', m = 'message', msg = 'message', revision = 'rev', } /* eslint-enable unicorn/prevent-abbreviations */ export const isFilterType = (filter: string): filter is FilterType => filter in FilterType export const isAliasedFilterType = (filter: string): boolean => filter in AliasedFilterType export const filterTypeKeys: FilterType[] = Object.keys(FilterType) as FilterType[] export const filterTypeKeysWithAliases: (FilterType | AliasedFilterType)[] = [ ...filterTypeKeys, ...Object.keys(AliasedFilterType), ] as (FilterType | AliasedFilterType)[] export enum NegatedFilters { repo = '-repo', file = '-file', lang = '-lang', r = '-r', f = '-f', l = '-l', repohasfile = '-repohasfile', content = '-content', committer = '-committer', author = '-author', message = '-message', } /** The list of filters that are able to be negated. */ export type NegatableFilter = | FilterType.repo | FilterType.file | FilterType.repohasfile | FilterType.lang | FilterType.content | FilterType.committer | FilterType.author | FilterType.message export const isNegatableFilter = (filter: FilterType): filter is NegatableFilter => Object.keys(NegatedFilters).includes(filter) /** The list of all negated filters. i.e. all valid filters that have `-` as a suffix. */ export const negatedFilters = Object.values(NegatedFilters) export const isNegatedFilter = (filter: string): filter is NegatedFilters => negatedFilters.includes(filter as NegatedFilters) const negatedFilterToNegatableFilter: { [key: string]: NegatableFilter } = { '-repo': FilterType.repo, '-file': FilterType.file, '-lang': FilterType.lang, '-r': FilterType.repo, '-f': FilterType.file, '-l': FilterType.lang, '-repohasfile': FilterType.repohasfile, '-content': FilterType.content, '-committer': FilterType.committer, '-author': FilterType.author, '-message': FilterType.message, } export const resolveNegatedFilter = (filter: NegatedFilters): NegatableFilter => negatedFilterToNegatableFilter[filter] /** * Represents a zero-indexed character range in a single-line search query. */ export interface CharacterRange { /** Zero-based character on the line */ start: number /** Zero-based character on the line */ end: number } export enum PatternKind { Literal = 1, Regexp, Structural, } export interface Pattern { type: 'pattern' range: CharacterRange kind: PatternKind value: string } /** * Represents a literal in a search query. * * Example: `Conn`. */ export interface Literal { type: 'literal' range: CharacterRange value: string } /** * Represents a filter in a search query. * * Example: `repo:^github\.com\/sourcegraph\/sourcegraph$`. */ export interface Filter { type: 'filter' range: CharacterRange filterType: Literal filterValue: Quoted | Literal | undefined } /** * Represents an operator in a search query. * * Example: AND, OR, NOT. */ export interface Operator { type: 'operator' range: CharacterRange value: string } /** * Represents a sequence of tokens in a search query. */ export interface Sequence { type: 'sequence' range: CharacterRange members: Token[] } /** * Represents a quoted string in a search query. * * Example: "Conn". */ export interface Quoted { type: 'quoted' range: CharacterRange quotedValue: string } /** * Represents a C-style comment, terminated by a newline. * * Example: `// Oh hai` */ export interface Comment { type: 'comment' range: CharacterRange value: string } export interface Whitespace { type: 'whitespace' range: CharacterRange } export interface OpeningParen { type: 'openingParen' range: CharacterRange } export interface ClosingParen { type: 'closingParen' range: CharacterRange } export type Token = Whitespace | OpeningParen | ClosingParen | Operator | Comment | Literal | Pattern | Filter | Quoted export type Term = Token | Sequence /** * Represents the failed result of running a {@link Parser} on a search query. */ interface ParseError { type: 'error' /** * A string representing the token that would have been expected * for successful parsing at {@link ParseError#at}. */ expected: string /** * The index in the search query string where parsing failed. */ at: number } /** * Represents the successful result of running a {@link Parser} on a search query. */ export interface ParseSuccess<T = Term> { type: 'success' /** * The resulting term. */ token: T } /** * Represents the result of running a {@link Parser} on a search query. */ export type ParserResult<T = Term> = ParseError | ParseSuccess<T> type Parser<T = Term> = (input: string, start: number) => ParserResult<T> /** * Returns a {@link Parser} that succeeds if zero or more tokens parsed * by the given `parseToken` parsers are found in a search query. */ const zeroOrMore = (parseToken: Parser<Term>): Parser<Sequence> => (input, start) => { const members: Token[] = [] let adjustedStart = start let end = start + 1 while (input[adjustedStart] !== undefined) { const result = parseToken(input, adjustedStart) if (result.type === 'error') { return result } if (result.token.type === 'sequence') { for (const member of result.token.members) { members.push(member) } } else { members.push(result.token) } end = result.token.range.end adjustedStart = end } return { type: 'success', token: { type: 'sequence', members, range: { start, end } }, } } /** * Returns a {@link Parser} that succeeds if any of the given parsers succeeds. */ const oneOf = <T>(...parsers: Parser<T>[]): Parser<T> => (input, start) => { const expected: string[] = [] for (const parser of parsers) { const result = parser(input, start) if (result.type === 'success') { return result } expected.push(result.expected) } return { type: 'error', expected: `One of: ${expected.join(', ')}`, at: start, } } /** * A {@link Parser} that will attempt to parse delimited strings for an arbitrary * delimiter. `\` is treated as an escape character for the delimited string. */ const quoted = (delimiter: string): Parser<Quoted> => (input, start) => { if (input[start] !== delimiter) { return { type: 'error', expected: delimiter, at: start } } let end = start + 1 while (input[end] && (input[end] !== delimiter || input[end - 1] === '\\')) { end = end + 1 } if (!input[end]) { return { type: 'error', expected: delimiter, at: end } } return { type: 'success', // end + 1 as `end` is currently the index of the quote in the string. token: { type: 'quoted', quotedValue: input.slice(start + 1, end), range: { start, end: end + 1 } }, } } /** * Returns a {@link Parser} that will attempt to parse tokens matching * the given character in a search query. */ const character = (character: string): Parser<Literal> => (input, start) => { if (input[start] !== character) { return { type: 'error', expected: character, at: start } } return { type: 'success', token: { type: 'literal', value: character, range: { start, end: start + 1 } }, } } /** * Returns a {@link Parser} that will attempt to parse * tokens matching the given RegExp pattern in a search query. */ const scanToken = <T extends Term = Literal>( regexp: RegExp, output?: T | ((input: string, range: CharacterRange) => T), expected?: string ): Parser<T> => { if (!regexp.source.startsWith('^')) { regexp = new RegExp(`^${regexp.source}`, regexp.flags) } return (input, start) => { const matchTarget = input.slice(Math.max(0, start)) if (!matchTarget) { return { type: 'error', expected: expected || `/${regexp.source}/`, at: start } } const match = matchTarget.match(regexp) if (!match) { return { type: 'error', expected: expected || `/${regexp.source}/`, at: start } } const range = { start, end: start + match[0].length } return { type: 'success', token: output ? typeof output === 'function' ? output(input, range) : output : ({ type: 'literal', value: match[0], range } as T), } } } const whitespace = scanToken( /\s+/, (_input, range): Whitespace => ({ type: 'whitespace', range, }) ) const literal = scanToken(/[^\s)]+/) const operator = scanToken( /(and|AND|or|OR|not|NOT)/, (input, { start, end }): Operator => ({ type: 'operator', value: input.slice(start, end), range: { start, end } }) ) const comment = scanToken( /\/\/.*/, (input, { start, end }): Comment => ({ type: 'comment', value: input.slice(start, end), range: { start, end } }) ) const filterKeyword = scanToken(new RegExp(`-?(${filterTypeKeysWithAliases.join('|')})+(?=:)`, 'i')) const filterDelimiter = character(':') const filterValue = oneOf<Quoted | Literal>(quoted('"'), quoted("'"), literal) const openingParen = scanToken(/\(/, (_input, range): OpeningParen => ({ type: 'openingParen', range })) const closingParen = scanToken(/\)/, (_input, range): ClosingParen => ({ type: 'closingParen', range })) /** * Returns a {@link Parser} that succeeds if a token parsed by `parseToken`, * followed by whitespace or EOF, is found in the search query. */ const followedBy = (parseToken: Parser<Token>, parseNext: Parser<Token>): Parser<Sequence> => (input, start) => { const members: Token[] = [] const tokenResult = parseToken(input, start) if (tokenResult.type === 'error') { return tokenResult } members.push(tokenResult.token) let { end } = tokenResult.token.range if (input[end] !== undefined) { const separatorResult = parseNext(input, end) if (separatorResult.type === 'error') { return separatorResult } members.push(separatorResult.token) end = separatorResult.token.range.end } return { type: 'success', token: { type: 'sequence', members, range: { start, end } }, } } /** * A {@link Parser} that will attempt to parse {@link Filter} tokens * (consisting a of a filter type and a filter value, separated by a colon) * in a search query. */ const filter: Parser<Filter> = (input, start) => { const parsedKeyword = filterKeyword(input, start) if (parsedKeyword.type === 'error') { return parsedKeyword } const parsedDelimiter = filterDelimiter(input, parsedKeyword.token.range.end) if (parsedDelimiter.type === 'error') { return parsedDelimiter } const parsedValue = input[parsedDelimiter.token.range.end] === undefined ? undefined : filterValue(input, parsedDelimiter.token.range.end) if (parsedValue && parsedValue.type === 'error') { return parsedValue } return { type: 'success', token: { type: 'filter', range: { start, end: parsedValue ? parsedValue.token.range.end : parsedDelimiter.token.range.end }, filterType: parsedKeyword.token, filterValue: parsedValue?.token, }, } } const createPattern = (value: string, range: CharacterRange, kind: PatternKind): ParseSuccess<Pattern> => ({ type: 'success', token: { type: 'pattern', range, kind, value, }, }) const scanFilterOrOperator = oneOf<Literal | Sequence>(filterKeyword, followedBy(operator, whitespace)) const keepScanning = (input: string, start: number): boolean => scanFilterOrOperator(input, start).type !== 'success' /** * ScanBalancedPattern attempts to scan balanced parentheses as literal patterns. This * ensures that we interpret patterns containing parentheses _as patterns_ and not * groups. For example, it accepts these patterns: * * ((a|b)|c) - a regular expression with balanced parentheses for grouping * myFunction(arg1, arg2) - a literal string with parens that should be literally interpreted * foo(...) - a structural search pattern * * If it weren't for this scanner, the above parentheses would have to be * interpreted as part of the query language group syntax, like these: * * (foo or (bar and baz)) * * So, this scanner detects parentheses as patterns without needing the user to * explicitly escape them. As such, there are cases where this scanner should * not succeed: * * (foo or (bar and baz)) - a valid query with and/or expression groups in the query langugae * (repo:foo bar baz) - a valid query containing a recognized repo: field. Here parentheses are interpreted as a group, not a pattern. */ export const scanBalancedPattern = (kind = PatternKind.Literal): Parser<Pattern> => (input, start) => { let adjustedStart = start let balanced = 0 let current = '' const result: string[] = [] const nextChar = (): void => { current = input[adjustedStart] adjustedStart += 1 } if (!keepScanning(input, start)) { return { type: 'error', expected: 'no recognized filter or operator', at: start, } } while (input[adjustedStart] !== undefined) { nextChar() if (current === ' ' && balanced === 0) { // Stop scanning a potential pattern when we see whitespace in a balanced state. adjustedStart -= 1 // Backtrack. break } else if (current === '(') { if (!keepScanning(input, adjustedStart)) { return { type: 'error', expected: 'no recognized filter or operator', at: adjustedStart, } } balanced += 1 result.push(current) } else if (current === ')') { balanced -= 1 if (balanced < 0) { // This paren is an unmatched closing paren, so we stop treating it as a potential // pattern here--it might be closing a group. adjustedStart -= 1 // Backtrack. balanced = 0 // Pattern is balanced up to this point break } result.push(current) } else if (current === ' ') { if (!keepScanning(input, adjustedStart)) { return { type: 'error', expected: 'no recognized filter or operator', at: adjustedStart, } } result.push(current) } else if (current === '\\') { if (input[adjustedStart] !== undefined) { nextChar() // Accept anything anything escaped. The point is to consume escaped spaces like "\ " // so that we don't recognize it as terminating a pattern. result.push('\\', current) continue } result.push(current) } else { result.push(current) } } if (balanced !== 0) { return { type: 'error', expected: 'no unbalanced parentheses', at: adjustedStart, } } return createPattern(result.join(''), { start, end: adjustedStart }, kind) } const scanPattern = (kind: PatternKind): Parser<Pattern> => (input, start) => { const balancedPattern = scanBalancedPattern(kind)(input, start) if (balancedPattern.type === 'success') { return createPattern(balancedPattern.token.value, balancedPattern.token.range, kind) } const anyPattern = literal(input, start) if (anyPattern.type === 'success') { return createPattern(anyPattern.token.value, anyPattern.token.range, kind) } return anyPattern } const whitespaceOrClosingParen = oneOf<Whitespace | ClosingParen>(whitespace, closingParen) /** * A {@link Parser} for a Sourcegraph search query, interpreting patterns for {@link PatternKind}. * * @param interpretComments Interpets C-style line comments for multiline queries. */ const createParser = (kind: PatternKind, interpretComments?: boolean): Parser<Sequence> => { const baseQuotedScanner = [quoted('"'), quoted("'")] const quotedScanner = kind === PatternKind.Regexp ? [quoted('/'), ...baseQuotedScanner] : baseQuotedScanner const baseScanner = [operator, filter, ...quotedScanner, scanPattern(kind)] const tokenScanner: Parser<Token>[] = interpretComments ? [comment, ...baseScanner] : baseScanner const baseEarlyPatternScanner = [...quotedScanner, scanBalancedPattern(kind)] const earlyPatternScanner = interpretComments ? [comment, ...baseEarlyPatternScanner] : baseEarlyPatternScanner return zeroOrMore( oneOf<Term>( whitespace, ...earlyPatternScanner.map(token => followedBy(token, whitespaceOrClosingParen)), openingParen, closingParen, ...tokenScanner.map(token => followedBy(token, whitespaceOrClosingParen)) ) ) } /** * Parses a search query string. */ export const parseSearchQuery = ( query: string, interpretComments?: boolean, kind = PatternKind.Literal ): ParserResult<Sequence> => { const scanner = createParser(kind, interpretComments) return scanner(query, 0) }
the_stack
import React from 'react'; import { connect } from 'react-redux'; import { RouteComponentProps } from 'react-router-dom'; import { makeStyles, useTheme } from '@material-ui/core/styles'; import Typography from '@material-ui/core/Typography'; import IconButton from '@material-ui/core/IconButton'; import AddBoxIcon from '@material-ui/icons/AddBox'; import clsx from 'clsx'; import marked from 'marked'; import createDOMPurify from 'dompurify'; import { Qr } from 'red-agate-barcode/modules/barcode/Qr'; import { LaneDef, StatusLaneDef, KanbanRecord, KanbanBoardState, KanbanBoardRecord } from '../types'; import gensym from '../lib/gensym'; import { parseISODate } from '../lib/datetime'; import { isDark } from '../lib/theme'; import { mapDispatchToProps, mapStateToProps, KanbanBoardActions } from '../dispatchers/KanbanBoardDispatcher'; import KanbanDialog from '../components/KanbanDialog'; import TextInputDialog from '../components/TextInputDialog'; import { getConstructedAppStore } from '../store'; import './KanbanBoardView.css'; type StickysProps = KanbanBoardActions & { records: KanbanRecord[], taskStatus: StatusLaneDef, teamOrStory: LaneDef, taskStatuses: StatusLaneDef[], teamOrStories: LaneDef[], board: KanbanBoardRecord, }; type StickyProps = KanbanBoardActions & { record: KanbanRecord, taskStatus: StatusLaneDef, teamOrStory: LaneDef, taskStatuses: StatusLaneDef[], teamOrStories: LaneDef[], board: KanbanBoardRecord, }; type KanbanBoardViewProps = KanbanBoardState & KanbanBoardActions & RouteComponentProps<{id: string}> & { }; const DOMPurify = createDOMPurify(window); const useStyles = makeStyles(theme => ({ root: {}, smallIcon: { width: '20px', height: '20px', }, })); const mapNeverStateToProps = () => ({}); const agent = window.navigator.userAgent.toLowerCase(); const firefox = (agent.indexOf('firefox') !== -1); const Sticky_: React.FC<StickyProps> = (props) => { const [open, setOpen] = React.useState(false); const now = new Date(); const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); const dueDate = props.record.dueDate ? parseISODate(props.record.dueDate) : null; const expired = (! props.taskStatus.completed) && (dueDate ? dueDate < today : false); function handleOnDragStart(ev: React.DragEvent) { ev.dataTransfer.setData('elId', (ev.target as any).id); } function handleEditApply(rec: KanbanRecord) { props.updateSticky(rec); setOpen(false); } function handleArchive(id: string) { props.archiveSticky(id); setOpen(false); } function handleUnarchive(id: string) { props.unarchiveSticky(id); setOpen(false); } function handleDelete(id: string) { props.deleteSticky(id); setOpen(false); } function handleEditCancel() { setOpen(false); } return ( <> {/* eslint-disable-next-line jsx-a11y/anchor-is-valid */} <a id={gensym()} data-record-id={props.record._id || ''} className="KanbanBoardView-sticky-link" draggable onClick={ev => setOpen(true)} onDragStart={handleOnDragStart}> <div className={'KanbanBoardView-sticky-note' + (expired ? ' expired' : '')} > {props.board.displayTags && props.record.tags.length ? <ul className="KanbanBoardView-sticky-tags">{ props.record.tags.map((x, index) => { const tags = props.board.tags || []; const matched = tags.find(q => q.value === x); return ( <li key={props.record._id + '-tag-' + index} className={matched ? matched.className : ''}>{x}</li> ); }) }</ul> : <></> } <div className="KanbanBoardView-sticky-description" dangerouslySetInnerHTML={{__html: DOMPurify.sanitize(marked(props.record.description))}} /> {props.board.displayBarcode && props.record.barcode ? <div className="KanbanBoardView-sticky-barcode" dangerouslySetInnerHTML={{__html: new Qr({ fill: true, fillColor: isDark ? '#fff' : '#000', cellSize: 2, unit: 'px', data: props.record.barcode, }).toImgTag()}} /> : <></> } {props.record.flags.includes('Marked') ? <div className="marked">{'📍'}</div> : <></> } {props.record.dueDate ? <div className="due-date">{(expired ? '🔥' : '⏳' ) + props.record.dueDate}</div> : <></> } </div> </a> {open ? <KanbanDialog open={true} record={props.record} teamOrStories={props.teamOrStories} taskStatuses={props.taskStatuses} board={props.board} onApply={handleEditApply} onArchive={handleArchive} onUnarchive={handleUnarchive} onDelete={handleDelete} onCancel={handleEditCancel} /> : <></> } </> ); } const Sticky = connect(mapNeverStateToProps, mapDispatchToProps)(Sticky_); const Stickys_: React.FC<StickysProps> = (props) => { function handleOnDragOver(ev: React.DragEvent) { ev.preventDefault(); } function handleOnDrop(ev: React.DragEvent) { try { const elId = ev.dataTransfer.getData('elId'); const el = document.getElementById(elId); props.updateStickyLanes({ kanbanId: (el as any).dataset.recordId, taskStatusValue: props.taskStatus.value, teamOrStoryValue: props.teamOrStory.value, }) } catch (e) { alert(e.message); } ev.preventDefault(); } const filtered = props.records.filter(x => !x.flags || !x.flags.includes('Archived')); return ( <div className={ 'KanbanBoardView-sticky-wrap ' + (props.teamOrStory.className || '') + ' ' + (props.taskStatus.className || '')} data-status={props.taskStatus.value} data-team-or-story={props.teamOrStory.value} onDragOver={handleOnDragOver} onDrop={handleOnDrop} > {filtered.map(record => ( <Sticky key={record._id || gensym()} teamOrStory={props.teamOrStory} taskStatus={props.taskStatus} teamOrStories={props.teamOrStories} taskStatuses={props.taskStatuses} board={props.board} record={record}/> ))} {(firefox && filtered.length === 0) ? // NOTE: hack for the height of div becomes 0 in Firefox <div style={{width: '100%', height: '100%'}}>&nbsp;</div> : <></> } </div> ); } const Stickys = connect(mapNeverStateToProps, mapDispatchToProps)(Stickys_); const KanbanBoardView: React.FC<KanbanBoardViewProps> = (props) => { const classes = useStyles(); const theme = useTheme(); const [textInputOpen, setTextInputOpen] = React.useState({ open: false, title: '', message: '', fieldLabel: '', value: '', validator: (value: string) => value.trim().length <= 0, onClose: handleCloseDialogEditBoardName, }); function handleClickEditBoardName() { const currentState = getConstructedAppStore().getState(); setTextInputOpen(Object.assign({}, textInputOpen, { open: true, title: 'Edit board name', message: '', fieldLabel: 'Board name', value: currentState.kanbanBoard.activeBoard.name, })); } function handleCloseDialogEditBoardName(apply: boolean, value?: string) { setTextInputOpen(Object.assign({}, textInputOpen, { open: false })); if (apply && value) { const currentState = getConstructedAppStore().getState(); props.updateBoardName({ boardId: currentState.kanbanBoard.activeBoardId, boardName: value }); } } if (props.match.params.id) { if (props.activeBoard._id !== props.match.params.id) { const index = props.boards.findIndex(x => x._id === props.match.params.id); props.changeActiveBoard(props.match.params.id); return ( <div className="KanbanBoardView-content"> {index < 0 ? <> <Typography style={{marginTop: theme.spacing(10)}} variant="h4" align="center"> No boards found. </Typography> <Typography style={{marginTop: theme.spacing(5), cursor: 'pointer', textDecoration: 'underline'}} variant="body1" align="center" onClick={ev => {props.history.push('/')}} > Click here to show main board. </Typography> </> : <></> } </div> ); } } return ( <div className="KanbanBoardView-content"> <style dangerouslySetInnerHTML={{__html: props.activeBoard.boardStyle}}></style> <Typography variant="h6" align="center" style={{cursor: 'pointer'}} onClick={handleClickEditBoardName} >{props.activeBoard.name}</Typography> <table className="KanbanBoardView-board"> <thead> <tr> <th className="KanbanBoardView-header-cell-add-sticky"> <IconButton style={{margin: 0, padding: 0}} onClick={ev => props.addSticky()}> <AddBoxIcon className={clsx(classes.smallIcon)} /> </IconButton> </th> {props.activeBoard.taskStatuses.map(taskStatus => ( <th key={taskStatus.value} className={ 'KanbanBoardView-header-cell-task-statuses ' + (taskStatus.className || '')}> {taskStatus.caption || taskStatus.value} </th> ))} </tr> </thead> <tbody> {props.activeBoard.teamOrStories.map(teamOrStory => ( <tr key={teamOrStory.value}> <th className={ 'KanbanBoardView-header-cell-team-or-stories ' + (teamOrStory.className || '')}> {teamOrStory.caption || teamOrStory.value} </th> {props.activeBoard.taskStatuses.map(taskStatus => ( <td key={taskStatus.value} className={ (teamOrStory.className || '') + ' ' + (taskStatus.className || '')}> <Stickys teamOrStory={teamOrStory} taskStatus={taskStatus} teamOrStories={props.activeBoard.teamOrStories} taskStatuses={props.activeBoard.taskStatuses} board={props.activeBoard} records={props.activeBoard.records.filter( x => x.teamOrStory === teamOrStory.value && x.taskStatus === taskStatus.value)} /> </td> ))} </tr> ))} </tbody> </table> {props.activeBoard.boardNote ? <div className="KanbanBoardView-board-note-wrap"> <div className="KanbanBoardView-board-note" dangerouslySetInnerHTML={{__html : DOMPurify.sanitize(marked(props.activeBoard.boardNote))}} /> </div> : <></> } {textInputOpen.open ? <TextInputDialog open={true} title={textInputOpen.title} message={textInputOpen.message} fieldLabel={textInputOpen.fieldLabel} value={textInputOpen.value} validator={textInputOpen.validator} onClose={textInputOpen.onClose} /> : <></> } </div> ); } export default connect(mapStateToProps, mapDispatchToProps)(KanbanBoardView);
the_stack
import { userInfo } from 'os'; import type vscode from 'vscode'; import { IRPCProtocol } from '@opensumi/ide-connection'; import { Event, Emitter, getDebugLogger, isUndefined, DisposableStore, IDisposable, Deferred, Disposable, CancellationTokenSource, uuid, } from '@opensumi/ide-core-common'; import { ITerminalInfo, TerminalDataBufferer, ITerminalChildProcess, ITerminalDimensionsOverride, ITerminalDimensionsDto, ITerminalLaunchError, ITerminalExitEvent, ITerminalLinkDto, ICreateContributedTerminalProfileOptions, ITerminalProfile, TERMINAL_ID_SEPARATOR, } from '@opensumi/ide-terminal-next'; import { EnvironmentVariableMutatorType, ISerializableEnvironmentVariableCollection, } from '@opensumi/ide-terminal-next/lib/common/environmentVariable'; import { IExtension } from '../../../common'; import { IMainThreadTerminal, MainThreadAPIIdentifier, IExtHostTerminal, IExtensionDescription, } from '../../../common/vscode'; const debugLog = getDebugLogger(); let nextLinkId = 1; interface ICachedLinkEntry { provider: vscode.TerminalLinkProvider; link: vscode.TerminalLink; } export class ExtHostTerminal implements IExtHostTerminal { private proxy: IMainThreadTerminal; private changeActiveTerminalEvent: Emitter<Terminal | undefined> = new Emitter(); private closeTerminalEvent: Emitter<Terminal> = new Emitter(); private openTerminalEvent: Emitter<Terminal> = new Emitter(); private terminalStateChangeEvent: Emitter<Terminal> = new Emitter(); private terminalsMap: Map<string, Terminal> = new Map(); private _terminalDeferreds: Map<string, Deferred<Terminal | undefined>> = new Map(); private readonly _linkProviders: Set<vscode.TerminalLinkProvider> = new Set(); private readonly _terminalLinkCache: Map<string, Map<number, ICachedLinkEntry>> = new Map(); private readonly _terminalLinkCancellationSource: Map<string, CancellationTokenSource> = new Map(); private readonly _profileProviders: Map<string, vscode.TerminalProfileProvider> = new Map(); private _defaultProfile: ITerminalProfile | undefined; private _defaultAutomationProfile: ITerminalProfile | undefined; private environmentVariableCollections: Map<string, EnvironmentVariableCollection> = new Map(); private disposables: DisposableStore = new DisposableStore(); private readonly _bufferer: TerminalDataBufferer; protected _terminalProcesses: Map<string, ITerminalChildProcess> = new Map(); protected _terminalProcessDisposables: { [id: number]: IDisposable } = {}; protected _extensionTerminalAwaitingStart: { [id: number]: { initialDimensions: ITerminalDimensionsDto | undefined } | undefined; } = {}; activeTerminal: Terminal | undefined; get terminals(): Terminal[] { return Array.from(this.terminalsMap.values()); } constructor(rpcProtocol: IRPCProtocol) { this.proxy = rpcProtocol.getProxy(MainThreadAPIIdentifier.MainThreadTerminal); this._bufferer = new TerminalDataBufferer(this.proxy.$sendProcessData); } getTerminal(id: string) { if (this.terminalsMap.has(id)) { return this.terminalsMap.get(id); } return this.terminalsMap.get(this.getTerminalShortId(id)); } getTerminalShortId(id: string) { // 插件进程创建的 Terminal 可能会在前端被拼接为 `${clientId}${TERMINAL_ID_SEPARATOR}${shortId}` 的形式 if (id.includes(TERMINAL_ID_SEPARATOR)) { return id.split(TERMINAL_ID_SEPARATOR)[1]; } return id; } /** * FIXME:由于前端对于 id 的拼接逻辑,需要通过 terminalsMap 是否存在对应 terminal 实例来获取真实 id */ getRealTerminalId(id: string) { let terminalId = ''; const shortId = this.getTerminalShortId(id); if (this.terminalsMap.has(id)) { terminalId = id; } else if (this.terminalsMap.has(shortId)) { terminalId = shortId; } return terminalId; } $onDidChangeActiveTerminal(id: string) { const terminal = this.getTerminal(id); if (terminal) { this.activeTerminal = terminal; this.changeActiveTerminalEvent.fire(terminal); } else { debugLog.error('[onDidChangeActiveTerminal] cannot find terminal with id: ' + id); } } get onDidChangeActiveTerminal(): Event<Terminal | undefined> { return this.changeActiveTerminalEvent.event; } $onDidCloseTerminal(e: ITerminalExitEvent) { const terminalId = this.getRealTerminalId(e.id); const terminal = this.terminalsMap.get(terminalId); if (!terminal) { return debugLog.error(`Terminal ${e.id} not found`); } terminal.setExitCode(e.code); this.closeTerminalEvent.fire(terminal); this.terminalsMap.delete(terminalId); } get onDidCloseTerminal(): Event<Terminal> { return this.closeTerminalEvent.event; } $onDidOpenTerminal(info: ITerminalInfo) { let terminal = this.getTerminal(info.id); if (!terminal) { terminal = new Terminal(info.name, info, this.proxy, info.id); this.terminalsMap.set(info.id, terminal); const deferred = this._terminalDeferreds.get(info.id); deferred?.resolve(terminal); } this.openTerminalEvent.fire(terminal); } $onDidTerminalTitleChange(id: string, name: string) { const terminal = this.getTerminal(id); if (terminal) { if (name !== terminal.name) { terminal.setName(name); } } } get onDidOpenTerminal(): Event<Terminal> { return this.openTerminalEvent.event; } get shellPath() { return this._defaultProfile?.path || process.env.SHELL || userInfo().shell; } get onDidChangeTerminalState(): Event<Terminal> { return this.terminalStateChangeEvent.event; } createTerminal(name?: string, shellPath?: string, shellArgs?: string[] | string): vscode.Terminal { const shortId = uuid(); const terminal = new Terminal(name || '', { name, shellPath, shellArgs }, this.proxy); terminal.create( { name, shellPath, shellArgs, }, shortId, ); this.terminalsMap.set(shortId, terminal); return terminal; } createTerminalFromOptions(options: vscode.TerminalOptions) { // 插件 API 同步提供 terminal 实例 const shortId = uuid(); const terminal = new Terminal(options.name, options, this.proxy); terminal.create(options, shortId); this.terminalsMap.set(shortId, terminal); return terminal; } createExtensionTerminal(options: vscode.ExtensionTerminalOptions) { const shortId = uuid(); const terminal = new Terminal(options.name, options, this.proxy); const p = new ExtHostPseudoterminal(options.pty); terminal.createExtensionTerminal(shortId); this.terminalsMap.set(shortId, terminal); const disposable = this._setupExtHostProcessListeners(shortId, p); this._terminalProcessDisposables[shortId] = disposable; this.disposables.add( p.onProcessExit((e: number | undefined) => { terminal.setExitCode(e); }), ); return terminal; } public attachPtyToTerminal(id: string, pty: vscode.Pseudoterminal) { const terminal = this._getTerminalByIdEventually(id); if (!terminal) { throw new Error(`Cannot resolve terminal with id ${id} for virtual process`); } const p = new ExtHostPseudoterminal(pty); this._setupExtHostProcessListeners(id, p); } $setTerminals(idList: ITerminalInfo[]) { this.terminalsMap.clear(); this.activeTerminal = undefined; idList.forEach((info: ITerminalInfo) => { if (this.getTerminal(info.id)) { return; } const terminal = new Terminal(info.name, info, this.proxy, info.id); if (info.isActive) { this.activeTerminal = terminal; } // 终端恢复时,id 为前端创建,故不需要处理 id 信息 this.terminalsMap.set(info.id, terminal); }); } registerLinkProvider(provider: vscode.TerminalLinkProvider): IDisposable { this._linkProviders.add(provider); if (this._linkProviders.size === 1) { this.proxy.$startLinkProvider(); } return Disposable.create(() => { this._linkProviders.delete(provider); if (this._linkProviders.size === 0) { this.proxy.$stopLinkProvider(); } }); } async $provideLinks(id: string, line: string): Promise<ITerminalLinkDto[]> { const terminalId = this.getRealTerminalId(id); const terminal = this.getTerminal(terminalId); if (!terminal) { return []; } // Discard any cached links the terminal has been holding, currently all links are released // when new links are provided. this._terminalLinkCache.delete(terminalId); const oldToken = this._terminalLinkCancellationSource.get(terminalId); if (oldToken) { oldToken.dispose(true); } const cancellationSource = new CancellationTokenSource(); this._terminalLinkCancellationSource.set(terminalId, cancellationSource); const result: ITerminalLinkDto[] = []; const context: vscode.TerminalLinkContext = { terminal, line }; const promises: vscode.ProviderResult<{ provider: vscode.TerminalLinkProvider; links: vscode.TerminalLink[] }>[] = []; for (const provider of this._linkProviders) { promises.push( new Promise(async (r) => { cancellationSource.token.onCancellationRequested(() => r({ provider, links: [] })); const links = (await provider.provideTerminalLinks(context, cancellationSource.token)) || []; if (!cancellationSource.token.isCancellationRequested) { r({ provider, links }); } }), ); } const provideResults = await Promise.all(promises); if (cancellationSource.token.isCancellationRequested) { return []; } const cacheLinkMap = new Map<number, ICachedLinkEntry>(); for (const provideResult of provideResults) { if (provideResult && provideResult.links.length > 0) { result.push( ...provideResult.links.map((providerLink) => { const link = { id: nextLinkId++, startIndex: providerLink.startIndex, length: providerLink.length, label: providerLink.tooltip, }; cacheLinkMap.set(link.id, { provider: provideResult.provider, link: providerLink, }); return link; }), ); } } this._terminalLinkCache.set(terminalId, cacheLinkMap); return result; } $activateLink(id: string, linkId: number): void { const terminalId = this.getRealTerminalId(id); const cachedLink = this._terminalLinkCache.get(terminalId)?.get(linkId); if (!cachedLink) { return; } cachedLink.provider.handleTerminalLink(cachedLink.link); } dispose() { this.changeActiveTerminalEvent.dispose(); this.closeTerminalEvent.dispose(); this.openTerminalEvent.dispose(); this.disposables.dispose(); } registerTerminalProfileProvider( extension: IExtensionDescription, id: string, provider: vscode.TerminalProfileProvider, ): IDisposable { if (this._profileProviders.has(id)) { throw new Error(`Terminal profile provider "${id}" already registered`); } this._profileProviders.set(id, provider); this.proxy.$registerProfileProvider(id, extension.identifier.value); return Disposable.create(() => { this._profileProviders.delete(id); this.proxy.$unregisterProfileProvider(id); }); } /** * @deprecated this function is useless, will removed in 2.17.0 */ $acceptDefaultShell(shellPath: string) { // will remove } public $acceptDefaultProfile(profile: ITerminalProfile, automationProfile?: ITerminalProfile): void { this._defaultProfile = profile; // 还不知道这个 automation 有啥用 this._defaultAutomationProfile = automationProfile; } public async $createContributedProfileTerminal( id: string, options: ICreateContributedTerminalProfileOptions, ): Promise<void> { const token = new CancellationTokenSource().token; let profile = await this._profileProviders.get(id)?.provideTerminalProfile(token); if (token.isCancellationRequested) { return; } if (profile && !('options' in profile)) { profile = { options: profile }; } if (!profile || !('options' in profile)) { throw new Error(`No terminal profile options provided for id "${id}"`); } if ('pty' in profile.options) { // TODO: 传入第二个参数 // this.createExtensionTerminal(profile.options, options); this.createExtensionTerminal(profile.options); return; } // TODO: 传入第二个参数 // this.createTerminalFromOptions(profile.options, options); this.createTerminalFromOptions(profile.options); } private async _getTerminalByIdEventually(id: string, timeout = 1000) { let terminal = this.getTerminal(id); if (!terminal) { const deferred = this._terminalDeferreds.get(id) || new Deferred<Terminal | undefined>(); setTimeout(() => { deferred.resolve(terminal); }, timeout); this._terminalDeferreds.set(id, deferred); terminal = await deferred.promise; this._terminalDeferreds.delete(id); } return terminal; } public async $startExtensionTerminal( id: string, initialDimensions: ITerminalDimensionsDto | undefined, ): Promise<ITerminalLaunchError | undefined> { // Make sure the ExtHostTerminal exists so onDidOpenTerminal has fired before we call // Pseudoterminal.start const terminal = await this._getTerminalByIdEventually(id); if (!terminal) { return { message: `Could not find the terminal with id ${id} on the extension host` }; } // TerminalController::_createClient 会立即触发 onDidOpenTerminal,所以无需等待 const terminalProcess = this._terminalProcesses.get(id); if (terminalProcess) { (terminalProcess as ExtHostPseudoterminal).startSendingEvents(initialDimensions); } else { // Defer startSendingEvents call to when _setupExtHostProcessListeners is called this._extensionTerminalAwaitingStart[id] = { initialDimensions }; } return undefined; } protected _setupExtHostProcessListeners(id: string, p: ITerminalChildProcess): IDisposable { const disposables = new DisposableStore(); disposables.add( p.onProcessReady((e: { pid: number; cwd: string }) => this.proxy.$sendProcessReady(id, e.pid, e.cwd)), ); disposables.add( p.onProcessTitleChanged((title) => { this.proxy.$sendProcessTitle(id, title); this._getTerminalByIdEventually(id).then((terminal) => { if (terminal) { terminal.setName(title); } }); }), ); // Buffer data events to reduce the amount of messages going to the renderer this._bufferer.startBuffering(id, p.onProcessData); disposables.add(p.onProcessExit((exitCode) => this._onProcessExit(id, exitCode))); if (p.onProcessOverrideDimensions) { disposables.add(p.onProcessOverrideDimensions((e) => this.proxy.$sendOverrideDimensions(id, e))); } this._terminalProcesses.set(id, p); const awaitingStart = this._extensionTerminalAwaitingStart[id]; if (awaitingStart && p instanceof ExtHostPseudoterminal) { p.startSendingEvents(awaitingStart.initialDimensions); delete this._extensionTerminalAwaitingStart[id]; } return disposables; } private _onProcessExit(id: string, exitCode: number | undefined): void { this._bufferer.stopBuffering(id); // Remove process reference this._terminalProcesses.delete(id); delete this._extensionTerminalAwaitingStart[id]; // Clean up process disposables const processDiposable = this._terminalProcessDisposables[id]; if (processDiposable) { processDiposable.dispose(); delete this._terminalProcessDisposables[id]; } // Send exit event to main side this.proxy.$sendProcessExit(id, exitCode); } public $acceptProcessInput(id: string, data: string): void { this._terminalProcesses.get(id)?.input(data); } public $acceptProcessShutdown(id: string, immediate: boolean): void { this._terminalProcesses.get(id)?.shutdown(immediate); } public $acceptProcessRequestInitialCwd(id: string): void { this._terminalProcesses .get(id) ?.getInitialCwd() .then((initialCwd) => this.proxy.$sendProcessInitialCwd(id, initialCwd)); } public $acceptProcessRequestCwd(id: string): void { this._terminalProcesses .get(id) ?.getCwd() .then((cwd) => this.proxy.$sendProcessCwd(id, cwd)); } public $acceptTerminalTitleChange(terminalId: string, name: string) { const terminal = this.getTerminal(terminalId); if (terminal) { terminal.setName(name); } } public $acceptTerminalInteraction(terminalId: string) { const terminal = this.getTerminal(terminalId); if (terminal?.setInteractedWith()) { this.terminalStateChangeEvent.fire(terminal); } } getEnviromentVariableCollection(extension: IExtension) { let collection = this.environmentVariableCollections.get(extension.id); if (!collection) { collection = new EnvironmentVariableCollection(); this._setEnvironmentVariableCollection(extension.id, collection); } return collection; } private syncEnvironmentVariableCollection( extensionIdentifier: string, collection: EnvironmentVariableCollection, ): void { const serialized = [...collection.map.entries()]; this.proxy.$setEnvironmentVariableCollection( extensionIdentifier, collection.persistent, serialized.length === 0 ? undefined : serialized, ); } private _setEnvironmentVariableCollection( extensionIdentifier: string, collection: EnvironmentVariableCollection, ): void { this.environmentVariableCollections.set(extensionIdentifier, collection); collection.onDidChangeCollection(() => { // When any collection value changes send this immediately, this is done to ensure // following calls to createTerminal will be created with the new environment. It will // result in more noise by sending multiple updates when called but collections are // expected to be small. this.syncEnvironmentVariableCollection(extensionIdentifier, collection); }); } } /** * EnvironmentVariableCollection * Some code copied and modified from * https://github.com/microsoft/vscode/blob/1.55.0/src/vs/workbench/api/common/extHostTerminalService.ts#L696 */ export class EnvironmentVariableCollection implements vscode.EnvironmentVariableCollection { readonly map: Map<string, vscode.EnvironmentVariableMutator> = new Map(); protected readonly _onDidChangeCollection: Emitter<void> = new Emitter<void>(); get onDidChangeCollection(): Event<void> { return this._onDidChangeCollection && this._onDidChangeCollection.event; } constructor(serialized?: ISerializableEnvironmentVariableCollection) { this.map = new Map(serialized); } private _persistent = true; public get persistent(): boolean { return this._persistent; } public set persistent(value: boolean) { this._persistent = value; this._onDidChangeCollection.fire(); } private _setIfDiffers(variable: string, mutator: vscode.EnvironmentVariableMutator): void { const current = this.map.get(variable); if (!current || current.value !== mutator.value || current.type !== mutator.type) { this.map.set(variable, mutator); this._onDidChangeCollection.fire(); } } replace(variable: string, value: string): void { this._setIfDiffers(variable, { value, type: EnvironmentVariableMutatorType.Replace }); } append(variable: string, value: string): void { this._setIfDiffers(variable, { value, type: EnvironmentVariableMutatorType.Append }); } prepend(variable: string, value: string): void { this._setIfDiffers(variable, { value, type: EnvironmentVariableMutatorType.Prepend }); } get(variable: string): vscode.EnvironmentVariableMutator | undefined { return this.map.get(variable); } forEach( callback: ( variable: string, mutator: vscode.EnvironmentVariableMutator, collection: vscode.EnvironmentVariableCollection, ) => any, thisArg?: any, ): void { this.map.forEach((value, key) => callback.call(thisArg, key, value, this)); } delete(variable: string): void { this.map.delete(variable); this._onDidChangeCollection.fire(); } clear(): void { this.map.clear(); this._onDidChangeCollection.fire(); } } export class Terminal implements vscode.Terminal { private id: string; public __id: string; private _exitStatus: vscode.TerminalExitStatus | undefined; private _state: vscode.TerminalState = { isInteractedWith: false }; private createdPromiseResolve; private when: Promise<any> = new Promise((resolve) => { this.createdPromiseResolve = resolve; }); constructor( private _name: string = '', private readonly _creationOptions: vscode.TerminalOptions | vscode.ExtensionTerminalOptions, protected proxy: IMainThreadTerminal, id?: string, ) { if (!isUndefined(id)) { this.created(id); } } get name() { return this._name; } get state(): vscode.TerminalState { return this._state; } get exitStatus() { return this._exitStatus; } get processId(): Thenable<number> { return this.when.then(() => this.proxy.$getProcessId(this.id)); } public get creationOptions(): Readonly<vscode.TerminalOptions | vscode.ExtensionTerminalOptions> { return this._creationOptions; } sendText(text: string, addNewLine?: boolean): void { this.when.then(() => { this.proxy.$sendText(this.id, text, addNewLine); }); } show(preserveFocus?: boolean): void { this.when.then(() => { this.proxy.$show(this.id, preserveFocus); }); } hide(): void { this.when.then(() => { this.proxy.$hide(this.id); }); } /** * 所有插件进程的终端调用都需要指定 id * 该逻辑用于保障依赖 `vscode.window.onDidOpenTerminal` 获取 terminal 实例的相关逻辑 * 让相关 terminal 的值引用一致 * 如 vscode-js-debug 中的 https://github.com/microsoft/vscode-js-debug/blob/a201e735c94b9aeb1e13d8c586b91a1fe1ab62b3/src/ui/debugTerminalUI.ts#L198 */ async create(options: vscode.TerminalOptions, shortId: string): Promise<void> { await this.proxy.$createTerminal(options, shortId); this.created(shortId); } created(shortId: string) { this.id = shortId; this.__id = shortId; this.createdPromiseResolve(); } dispose(): void { this.proxy.$dispose(this.id); } async createExtensionTerminal(id: string): Promise<void> { await this.proxy.$createTerminal({ name: this.name, isExtensionTerminal: true }, id); this.created(id); } public setExitCode(code: number | undefined) { this._exitStatus = Object.freeze({ code }); } public setName(name: string) { this._name = name; } public setInteractedWith() { if (!this._state.isInteractedWith) { (this._state as any).isInteractedWith = true; return true; } return false; } } export class ExtHostPseudoterminal implements ITerminalChildProcess { private readonly _onProcessData = new Emitter<string>(); public readonly onProcessData: Event<string> = this._onProcessData.event; private readonly _onProcessExit = new Emitter<number | undefined>(); public readonly onProcessExit: Event<number | undefined> = this._onProcessExit.event; private readonly _onProcessReady = new Emitter<{ pid: number; cwd: string }>(); public get onProcessReady(): Event<{ pid: number; cwd: string }> { return this._onProcessReady.event; } private readonly _onProcessTitleChanged = new Emitter<string>(); public readonly onProcessTitleChanged: Event<string> = this._onProcessTitleChanged.event; private readonly _onProcessOverrideDimensions = new Emitter<ITerminalDimensionsOverride | undefined>(); public get onProcessOverrideDimensions(): Event<ITerminalDimensionsOverride | undefined> { return this._onProcessOverrideDimensions.event; } constructor(private readonly _pty: vscode.Pseudoterminal) {} async start(): Promise<undefined> { return undefined; } shutdown(): void { this._pty.close(); } input(data: string): void { if (this._pty.handleInput) { this._pty.handleInput(data); } } resize(cols: number, rows: number): void { if (this._pty.setDimensions) { this._pty.setDimensions({ columns: cols, rows }); } } getInitialCwd(): Promise<string> { return Promise.resolve(''); } getCwd(): Promise<string> { return Promise.resolve(''); } getLatency(): Promise<number> { return Promise.resolve(0); } startSendingEvents(initialDimensions: ITerminalDimensionsDto | undefined): void { // Attach the listeners this._pty.onDidWrite((e) => this._onProcessData.fire(e)); if (this._pty.onDidClose) { this._pty.onDidClose((e: number | void = undefined) => { this._onProcessExit.fire(e === void 0 ? undefined : e); }); } if (this._pty.onDidOverrideDimensions) { this._pty.onDidOverrideDimensions((e) => this._onProcessOverrideDimensions.fire(e ? { cols: e.columns, rows: e.rows } : e), ); } if (this._pty.onDidChangeName) { this._pty.onDidChangeName((title) => this._onProcessTitleChanged.fire(title)); } this._pty.open(initialDimensions ? initialDimensions : undefined); this._onProcessReady.fire({ pid: -1, cwd: '' }); } }
the_stack
import { useCallbackRef } from '@radix-ui/react-use-callback-ref' import { useEscapeKeydown } from '@radix-ui/react-use-escape-keydown' import { useComposedRefs } from '@tamagui/compose-refs' import { composeEventHandlers } from '@tamagui/core' import * as React from 'react' import * as ReactDOM from 'react-dom' import { DismissableBranchProps, DismissableProps } from './DismissableProps' function dispatchDiscreteCustomEvent<E extends CustomEvent>(target: E['target'], event: E) { if (target) ReactDOM.flushSync(() => target.dispatchEvent(event)) } /* ------------------------------------------------------------------------------------------------- * Dismissable * -----------------------------------------------------------------------------------------------*/ const DISMISSABLE_LAYER_NAME = 'Dismissable' const CONTEXT_UPDATE = 'dismissable.update' const POINTER_DOWN_OUTSIDE = 'dismissable.pointerDownOutside' const FOCUS_OUTSIDE = 'dismissable.focusOutside' let originalBodyPointerEvents: string const DismissableContext = React.createContext({ layers: new Set<HTMLDivElement>(), layersWithOutsidePointerEventsDisabled: new Set<HTMLDivElement>(), branches: new Set<HTMLDivElement>(), }) const Dismissable = React.forwardRef<HTMLDivElement, DismissableProps>((props, forwardedRef) => { const { disableOutsidePointerEvents = false, onEscapeKeyDown, onPointerDownOutside, onFocusOutside, onInteractOutside, onDismiss, ...layerProps } = props const context = React.useContext(DismissableContext) const [node, setNode] = React.useState<HTMLDivElement | null>(null) const [, force] = React.useState({}) const composedRefs = useComposedRefs(forwardedRef, (node) => setNode(node)) const layers = Array.from(context.layers) const [highestLayerWithOutsidePointerEventsDisabled] = [...context.layersWithOutsidePointerEventsDisabled].slice(-1); // prettier-ignore const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled); // prettier-ignore const index = node ? layers.indexOf(node) : -1 const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0 const isPointerEventsEnabled = index >= highestLayerWithOutsidePointerEventsDisabledIndex const pointerDownOutside = usePointerDownOutside((event) => { const target = event.target as HTMLDivElement const isPointerDownOnBranch = [...context.branches].some((branch) => branch.contains(target)) if (!isPointerEventsEnabled || isPointerDownOnBranch) return onPointerDownOutside?.(event) onInteractOutside?.(event) if (!event.defaultPrevented) onDismiss?.() }) const focusOutside = useFocusOutside((event) => { const target = event.target as HTMLDivElement const isFocusInBranch = [...context.branches].some((branch) => branch.contains(target)) if (isFocusInBranch) return onFocusOutside?.(event) onInteractOutside?.(event) if (!event.defaultPrevented) onDismiss?.() }) useEscapeKeydown((event) => { const isHighestLayer = index === context.layers.size - 1 if (!isHighestLayer) return onEscapeKeyDown?.(event) if (!event.defaultPrevented && onDismiss) { event.preventDefault() onDismiss() } }) React.useEffect(() => { if (!node) return if (disableOutsidePointerEvents) { if (context.layersWithOutsidePointerEventsDisabled.size === 0) { originalBodyPointerEvents = document.body.style.pointerEvents document.body.style.pointerEvents = 'none' } context.layersWithOutsidePointerEventsDisabled.add(node) } context.layers.add(node) dispatchUpdate() return () => { if ( disableOutsidePointerEvents && context.layersWithOutsidePointerEventsDisabled.size === 1 ) { document.body.style.pointerEvents = originalBodyPointerEvents } } }, [node, disableOutsidePointerEvents, context]) /** * We purposefully prevent combining this effect with the `disableOutsidePointerEvents` effect * because a change to `disableOutsidePointerEvents` would remove this layer from the stack * and add it to the end again so the layering order wouldn't be _creation order_. * We only want them to be removed from context stacks when unmounted. */ React.useEffect(() => { return () => { if (!node) return context.layers.delete(node) context.layersWithOutsidePointerEventsDisabled.delete(node) dispatchUpdate() } }, [node, context]) React.useEffect(() => { const handleUpdate = () => force({}) document.addEventListener(CONTEXT_UPDATE, handleUpdate) return () => document.removeEventListener(CONTEXT_UPDATE, handleUpdate) }, []) return ( <div {...layerProps} // @ts-ignore ref={composedRefs} style={{ display: 'contents', pointerEvents: isBodyPointerEventsDisabled ? isPointerEventsEnabled ? 'auto' : 'none' : undefined, // @ts-ignore ...props.style, }} onFocusCapture={composeEventHandlers( // @ts-ignore props.onFocusCapture, focusOutside.onFocusCapture )} onBlurCapture={composeEventHandlers( // @ts-ignore props.onBlurCapture, focusOutside.onBlurCapture )} // @ts-ignore onPointerDownCapture={composeEventHandlers( // @ts-ignore props.onPointerDownCapture, pointerDownOutside.onPointerDownCapture )} /> ) }) Dismissable.displayName = DISMISSABLE_LAYER_NAME /* ------------------------------------------------------------------------------------------------- * DismissableBranch * -----------------------------------------------------------------------------------------------*/ const BRANCH_NAME = 'DismissableBranch' const DismissableBranch = React.forwardRef<HTMLDivElement, DismissableBranchProps>( (props, forwardedRef) => { const context = React.useContext(DismissableContext) const ref = React.useRef<HTMLDivElement>(null) const composedRefs = useComposedRefs(forwardedRef, ref) React.useEffect(() => { const node = ref.current if (node) { context.branches.add(node) return () => { context.branches.delete(node) } } }, [context.branches]) return <div style={{ display: 'contents' }} {...props} ref={composedRefs} /> } ) DismissableBranch.displayName = BRANCH_NAME /* -----------------------------------------------------------------------------------------------*/ export type PointerDownOutsideEvent = CustomEvent<{ originalEvent: PointerEvent }> export type FocusOutsideEvent = CustomEvent<{ originalEvent: FocusEvent }> /** * Listens for `pointerdown` outside a react subtree. We use `pointerdown` rather than `pointerup` * to mimic layer dismissing behaviour present in OS. * Returns props to pass to the node we want to check for outside events. */ function usePointerDownOutside(onPointerDownOutside?: (event: PointerDownOutsideEvent) => void) { const handlePointerDownOutside = useCallbackRef(onPointerDownOutside) as EventListener const isPointerInsideReactTreeRef = React.useRef(false) const handleClickRef = React.useRef(() => {}) React.useEffect(() => { const handlePointerDown = (event: PointerEvent) => { if (event.target && !isPointerInsideReactTreeRef.current) { const eventDetail = { originalEvent: event } function handleAndDispatchPointerDownOutsideEvent() { handleAndDispatchCustomEvent( POINTER_DOWN_OUTSIDE, handlePointerDownOutside, eventDetail, { discrete: true } ) } /** * On touch devices, we need to wait for a click event because browsers implement * a ~350ms delay between the time the user stops touching the display and when the * browser executres events. We need to ensure we don't reactivate pointer-events within * this timeframe otherwise the browser may execute events that should have been prevented. * * Additionally, this also lets us deal automatically with cancellations when a click event * isn't raised because the page was considered scrolled/drag-scrolled, long-pressed, etc. * * This is why we also continuously remove the previous listener, because we cannot be * certain that it was raised, and therefore cleaned-up. */ if (event.pointerType === 'touch') { document.removeEventListener('click', handleClickRef.current) handleClickRef.current = handleAndDispatchPointerDownOutsideEvent document.addEventListener('click', handleClickRef.current, { once: true }) } else { handleAndDispatchPointerDownOutsideEvent() } } isPointerInsideReactTreeRef.current = false } /** * if this hook executes in a component that mounts via a `pointerdown` event, the event * would bubble up to the document and trigger a `pointerDownOutside` event. We avoid * this by delaying the event listener registration on the document. * This is not React specific, but rather how the DOM works, ie: * ``` * button.addEventListener('pointerdown', () => { * console.log('I will log'); * document.addEventListener('pointerdown', () => { * console.log('I will also log'); * }) * }); */ const timerId = window.setTimeout(() => { document.addEventListener('pointerdown', handlePointerDown) }, 0) return () => { window.clearTimeout(timerId) document.removeEventListener('pointerdown', handlePointerDown) document.removeEventListener('click', handleClickRef.current) } }, [handlePointerDownOutside]) return { // ensures we check React component tree (not just DOM tree) onPointerDownCapture: () => (isPointerInsideReactTreeRef.current = true), } } /** * Listens for when focus happens outside a react subtree. * Returns props to pass to the root (node) of the subtree we want to check. */ function useFocusOutside(onFocusOutside?: (event: FocusOutsideEvent) => void) { const handleFocusOutside = useCallbackRef(onFocusOutside) as EventListener const isFocusInsideReactTreeRef = React.useRef(false) React.useEffect(() => { const handleFocus = (event: FocusEvent) => { if (event.target && !isFocusInsideReactTreeRef.current) { const eventDetail = { originalEvent: event } handleAndDispatchCustomEvent(FOCUS_OUTSIDE, handleFocusOutside, eventDetail, { discrete: false, }) } } document.addEventListener('focusin', handleFocus) return () => document.removeEventListener('focusin', handleFocus) }, [handleFocusOutside]) return { onFocusCapture: () => (isFocusInsideReactTreeRef.current = true), onBlurCapture: () => (isFocusInsideReactTreeRef.current = false), } } function dispatchUpdate() { const event = new CustomEvent(CONTEXT_UPDATE) document.dispatchEvent(event) } function handleAndDispatchCustomEvent<E extends CustomEvent, OriginalEvent extends Event>( name: string, handler: ((event: E) => void) | undefined, detail: { originalEvent: OriginalEvent } & (E extends CustomEvent<infer D> ? D : never), { discrete }: { discrete: boolean } ) { const target = detail.originalEvent.target const event = new CustomEvent(name, { bubbles: false, cancelable: true, detail }) if (handler) target.addEventListener(name, handler as EventListener, { once: true }) if (discrete) { dispatchDiscreteCustomEvent(target, event) } else { target.dispatchEvent(event) } } const Root = Dismissable const Branch = DismissableBranch export { Dismissable, DismissableBranch, // Root, Branch, } export type { DismissableProps }
the_stack
import { options } from '@tko/utils'; import { applyBindings } from '@tko/bind'; import { observable as Observable } from '@tko/observable'; import { DataBindProvider } from '@tko/provider.databind' import { MultiProvider } from '@tko/provider.multi' import { VirtualProvider } from '@tko/provider.virtual' import { bindings as coreBindings } from '@tko/binding.core'; import { bindings as templateBindings } from '@tko/binding.template'; import { bindings as ifBindings } from '@tko/binding.if'; import { TextMustacheProvider } from '../dist'; import '@tko/utils/helpers/jasmine-13-helper'; import '../helpers/jasmine-interpolation-helpers'; describe('Interpolation Markup preprocessor', function () { function testPreprocess (node) { const provider = new TextMustacheProvider() return provider.preprocessNode(node) } it('Should do nothing when there are no expressions', function () { var result = testPreprocess(document.createTextNode('some text')); expect(result).toBeUndefined(); }); it('Should do nothing when empty', function () { var result = testPreprocess(document.createTextNode('')); expect(result).toBeUndefined(); }); it('Should not parse unclosed binding', function () { var result = testPreprocess(document.createTextNode('some {{ text')); expect(result).toBeUndefined(); }); it('Should not parse unopened binding', function () { var result = testPreprocess(document.createTextNode('some }} text')); expect(result).toBeUndefined(); }); it('Should create binding from {{...}} expression', function () { var result = testPreprocess(document.createTextNode('some {{ expr }} text')); expect(result).toHaveNodeTypes([3, 8, 8, 3]); // text, comment, comment, text expect(result[1].nodeValue).toEqual('ko text:expr'); expect(result[2].nodeValue).toEqual('/ko'); }); it('Should ignore unmatched delimiters', function () { var result = testPreprocess(document.createTextNode('some {{ expr }} }} text')); expect(result).toHaveNodeTypes([3, 8, 8, 3]); // text, comment, comment, text expect(result[1].nodeValue).toEqual('ko text:expr }}'); }); it('Should support two expressions', function () { var result = testPreprocess(document.createTextNode('some {{ expr1 }} middle {{ expr2 }} text')); expect(result).toHaveNodeTypes([3, 8, 8, 3, 8, 8, 3]); // text, comment, comment, text, comment, comment, text expect(result[1].nodeValue).toEqual('ko text:expr1'); expect(result[4].nodeValue).toEqual('ko text:expr2'); }); it('Should skip empty text', function () { var result = testPreprocess(document.createTextNode('{{ expr1 }}{{ expr2 }}')); expect(result).toHaveNodeTypes([8, 8, 8, 8]); // comment, comment, comment, comment expect(result[0].nodeValue).toEqual('ko text:expr1'); expect(result[2].nodeValue).toEqual('ko text:expr2'); }); it('Should support more than two expressions', function () { var result = testPreprocess(document.createTextNode('x {{ expr1 }} y {{ expr2 }} z {{ expr3 }}')); expect(result).toHaveNodeTypes([3, 8, 8, 3, 8, 8, 3, 8, 8]); // text, comment, comment, text, comment, comment, text, comment, comment expect(result[1].nodeValue).toEqual('ko text:expr1'); expect(result[4].nodeValue).toEqual('ko text:expr2'); expect(result[7].nodeValue).toEqual('ko text:expr3'); }); describe('Using unescaped HTML syntax', function () { it('Should not parse unclosed binding', function () { var result = testPreprocess(document.createTextNode('some {{{ text')); expect(result).toBeUndefined(); }); it('Should not parse unopened binding', function () { var result = testPreprocess(document.createTextNode('some }}} text')); expect(result).toBeUndefined(); }); it('Should create binding from {{{...}}} expression', function () { var result = testPreprocess(document.createTextNode('some {{{ expr }}} text')); expect(result).toHaveNodeTypes([3, 8, 8, 3]); // text, comment, comment, text expect(result[1].nodeValue).toEqual('ko html:expr'); expect(result[2].nodeValue).toEqual('/ko'); }); it('Should ignore unmatched delimiters', function () { var result = testPreprocess(document.createTextNode('some {{{ expr }}} }}} text')); expect(result).toHaveNodeTypes([3, 8, 8, 3]); // text, comment, comment, text expect(result[1].nodeValue).toEqual('ko html:expr }}}'); }); it('Should support two expressions', function () { var result = testPreprocess(document.createTextNode('some {{{ expr1 }}} middle {{{ expr2 }}} text')); expect(result).toHaveNodeTypes([3, 8, 8, 3, 8, 8, 3]); // text, comment, comment, text, comment, comment, text expect(result[1].nodeValue).toEqual('ko html:expr1'); expect(result[4].nodeValue).toEqual('ko html:expr2'); }); }); describe('Using block syntax', function () { it('Should create binding from {{#....}}{{/....}} expression', function () { var result = testPreprocess(document.createTextNode('some {{#binding:value}}{{/binding}} text')); expect(result).toHaveNodeTypes([3, 8, 8, 3]); // text, comment, comment, text expect(result[1].nodeValue).toEqual('ko binding:value'); expect(result[2].nodeValue).toEqual('/ko'); }); it('Should tolerate spaces around expressions from {{ #.... }}{{ /.... }} expression', function () { var result = testPreprocess(document.createTextNode('some {{ #binding:value }}{{ /binding }} text')); expect(result).toHaveNodeTypes([3, 8, 8, 3]); // text, comment, comment, text expect(result[1].nodeValue).toEqual('ko binding:value'); expect(result[2].nodeValue).toEqual('/ko'); }); it('Should tolerate spaces around various components', function () { var result = testPreprocess(document.createTextNode('some {{# binding : value }}{{/ binding }} text')); expect(result).toHaveNodeTypes([3, 8, 8, 3]); // text, comment, comment, text expect(result[1].nodeValue).toEqual('ko binding : value'); expect(result[2].nodeValue).toEqual('/ko'); }); it('Should insert semicolon if missing', function () { var result = testPreprocess(document.createTextNode('some {{#binding value}}{{/binding}} text')); expect(result).toHaveNodeTypes([3, 8, 8, 3]); // text, comment, comment, text expect(result[1].nodeValue).toEqual('ko binding:value'); }); it('Should not insert semicolon if binding has no value', function () { var result = testPreprocess(document.createTextNode('some {{#binding}}{{/binding}} text')); expect(result).toHaveNodeTypes([3, 8, 8, 3]); // text, comment, comment, text expect(result[1].nodeValue).toEqual('ko binding'); }); it('Should support self-closing syntax', function () { var result = testPreprocess(document.createTextNode('some {{#binding:value/}} text')); expect(result).toHaveNodeTypes([3, 8, 8, 3]); // text, comment, comment, text expect(result[1].nodeValue).toEqual('ko binding:value'); expect(result[2].nodeValue).toEqual('/ko'); }); it('Should tolerate space around self-closing syntax', function () { var result = testPreprocess(document.createTextNode('some {{ # binding:value / }} text')); expect(result).toHaveNodeTypes([3, 8, 8, 3]); // text, comment, comment, text expect(result[1].nodeValue).toEqual('ko binding:value '); expect(result[2].nodeValue).toEqual('/ko'); }) }); }); describe('Interpolation Markup bindings', function () { var bindingHandlers; beforeEach(jasmine.prepareTestNode); beforeEach(function () { var provider = new MultiProvider({ providers: [ new TextMustacheProvider(), new DataBindProvider(), new VirtualProvider() ] }) options.bindingProviderInstance = provider; bindingHandlers = provider.bindingHandlers; bindingHandlers.set(coreBindings); bindingHandlers.set(templateBindings); bindingHandlers.set(ifBindings); }); it('Should replace {{...}} expression with virtual text binding', function () { jasmine.setNodeText(testNode, "hello {{'name'}}!"); applyBindings(null, testNode); expect(testNode).toContainText('hello name!'); expect(testNode).toContainHtml("hello <!--ko text:'name'-->name<!--/ko-->!"); }); it('Should replace multiple expressions', function () { jasmine.setNodeText(testNode, "hello {{'name'}}{{'!'}}"); applyBindings(null, testNode); expect(testNode).toContainText('hello name!'); }); xit('Should support lambdas (=>) and {{}}', function () { // See NOTE on lambda support in the HTML binding, below jasmine.setNodeText(testNode, "hello {{ => '{{name}}' }}!"); applyBindings(null, testNode); expect(testNode).toContainText('hello {{name}}!'); }); it('Should ignore unmatched }} and {{', function () { jasmine.setNodeText(testNode, "hello }}'name'{{'!'}}{{"); applyBindings(null, testNode); expect(testNode).toContainText("hello }}'name'!{{"); }); it('Should update when observable changes', function () { jasmine.setNodeText(testNode, 'The best {{what}}.'); var observable = Observable('time'); applyBindings({what: observable}, testNode); expect(testNode).toContainText('The best time.'); observable('fun'); expect(testNode).toContainText('The best fun.'); }); xit('Should be able to override wrapExpression to define a different set of elements', function () { // Skipping this because it's neither documented nor does it appear // essential to the desired functionality. // // The functionality has moved off to the mustacheParser's Expression // `textNodeReplacement` function, which - if inclined - could be placed // back into the TextMustacheProvider. var originalWrapExpresssion = interpolationMarkup.wrapExpression; this.after(function () { interpolationMarkup.wrapExpression = originalWrapExpresssion; }); interpolationMarkup.wrapExpression = function (expressionText, node) { return originalWrapExpresssion('"--" + ' + expressionText + ' + "--"', node); } jasmine.setNodeText(testNode, "hello {{'name'}}!"); applyBindings(null, testNode); expect(testNode).toContainText('hello --name--!'); }); it('Should not modify the content of <textarea> tags', function () { testNode.innerHTML = "<p>Hello</p><textarea>{{'name'}}</textarea><p>Goodbye</p>"; applyBindings(null, testNode); expect(testNode).toContainHtml("<p>hello</p><textarea>{{'name'}}</textarea><p>goodbye</p>"); }); it('Should not modify the content of <script> tags', function () { testNode.innerHTML = '<p>Hello</p><script>{{return}}</script><p>Goodbye</p>'; applyBindings(null, testNode); expect(testNode).toContainHtml('<p>hello</p><script>{{return}}</script><p>goodbye</p>'); }); it('Should work when used in template declared using <script>', function () { testNode.innerHTML = "<div data-bind='template: \"tmpl\"'></div><script type='text/html' id='tmpl'>{{'name'}}</script>"; applyBindings(null, testNode); expect(testNode.childNodes[0]).toContainText('name'); }); it('Should work when used in template declared using <textarea>', function () { testNode.innerHTML = "<div data-bind='template: \"tmpl\"'></div><textarea id='tmpl'>{{'name'}}</textarea>"; applyBindings(null, testNode); expect(testNode.childNodes[0]).toContainText('name'); }); describe('Using unescaped HTML syntax', function () { it('Should replace {{{...}}} expression with virtual html binding', function () { jasmine.setNodeText(testNode, "hello {{{'<b>name</b>'}}}!"); applyBindings(null, testNode); expect(testNode).toContainText('hello name!'); expect(testNode).toContainHtml("hello <!--ko html:'<b>name</b>'--><b>name</b><!--/ko-->!"); expect(testNode.childNodes[2].nodeName.toLowerCase()).toEqual('b'); }); it('Should support mix of escaped and unescape expressions', function () { jasmine.setNodeText(testNode, "hello {{{'<b>name</b>'}}}{{'!'}}"); applyBindings(null, testNode); expect(testNode).toContainText('hello name!'); expect(testNode).toContainHtml("hello <!--ko html:'<b>name</b>'--><b>name</b><!--/ko--><!--ko text:'!'-->!<!--/ko-->"); expect(testNode.childNodes[2].nodeName.toLowerCase()).toEqual('b'); }); xit('Should support backticks and {{{}}}', function () { // NOTE This was from ko.punches tests, namely when including // anonymous function(){}'s, but it's not clear what might be // analogous in tko. // // Two dynamics similar to anonymous functions would be backtick // interpolation, and lambdas. jasmine.setNodeText(testNode, "hello {{{ `<b>${'{{{name}}}'}</b>` }}}!"); applyBindings({name: 'nAmE'}, testNode); expect(testNode).toContainText('hello {{{name}}}!'); expect(testNode.childNodes[2].nodeName.toLowerCase()).toEqual('b'); }); it('Should ignore unmatched }}} and {{{', function () { jasmine.setNodeText(testNode, "hello }}}'name'{{{'!'}}}{{{"); applyBindings(null, testNode); expect(testNode).toContainText("hello }}}'name'!{{{"); }); it('Should update when observable changes', function () { jasmine.setNodeText(testNode, 'The best {{{what}}}.'); var observable = Observable('<b>time</b>'); applyBindings({what: observable}, testNode); expect(testNode).toContainText('The best time.'); expect(testNode.childNodes[2].nodeName.toLowerCase()).toEqual('b'); observable('<i>fun</i>'); expect(testNode).toContainText('The best fun.'); expect(testNode.childNodes[2].nodeName.toLowerCase()).toEqual('i'); }); }); describe('Using block syntax', function () { it('Should support "with"', function () { testNode.innerHTML = '<div><h1>{{title}}</h1>{{#with: story}}<div>{{{intro}}}</div><div>{{{body}}}</div>{{/with}}</div>'; applyBindings({ title: 'First Post', story: { intro: 'Before the jump', body: 'After the jump' } }, testNode); expect(testNode).toContainHtmlElementsAndText('<div><h1>first post</h1><div>before the jump</div><div>after the jump</div></div>'); }); it('Should support "foreach"', function () { testNode.innerHTML = '<ul>{{#foreach: people}}<li>{{$data}}</li>{{/foreach}}</ul>'; applyBindings({ people: [ 'Bill Gates', 'Steve Jobs', 'Larry Ellison' ] }, testNode); expect(testNode).toContainHtmlElementsAndText('<ul><li>bill gates</li><li>steve jobs</li><li>larry ellison</li></ul>'); }); it('Should support nested blocks', function () { testNode.innerHTML = '<ul>{{#foreach: people}} {{#if: $data}}<li>{{$data}}</li>{{/if}}{{/foreach}}</ul>'; applyBindings({ people: [ 'Bill Gates', null, 'Steve Jobs', 'Larry Ellison' ] }, testNode); expect(testNode).toContainHtmlElementsAndText('<ul><li>bill gates</li><li>steve jobs</li><li>larry ellison</li></ul>'); }); it('Should work without the colon', function () { testNode.innerHTML = '<ul>{{#foreach people}}<li>{{$data}}</li>{{/foreach}}</ul>'; applyBindings({ people: [ 'Bill Gates', 'Steve Jobs', 'Larry Ellison' ] }, testNode); expect(testNode).toContainHtmlElementsAndText('<ul><li>bill gates</li><li>steve jobs</li><li>larry ellison</li></ul>'); }); it('Should support self-closing blocks', function () { jasmine.setNodeText(testNode, "hello {{#text 'name'/}}"); applyBindings(null, testNode); expect(testNode).toContainText('hello name'); }); }); });
the_stack
import AWSMock from 'aws-sdk-mock' import AWS, { CostExplorer, CloudWatch, CloudWatchLogs } from 'aws-sdk' import { Logger } from '@cloud-carbon-footprint/common' import { StorageEstimator } from '@cloud-carbon-footprint/core' import EBS from '../lib/EBS' import { AWS_REGIONS } from '../lib/AWSRegions' import { ServiceWrapper } from '../lib/ServiceWrapper' import { buildCostExplorerGetUsageResponse } from './fixtures/builders' import { AWS_EMISSIONS_FACTORS_METRIC_TON_PER_KWH, AWS_CLOUD_CONSTANTS, } from '../domain' beforeAll(() => { AWSMock.setSDKInstance(AWS) }) describe('Ebs', () => { const startDate = '2020-06-27' const endDate = '2020-06-30' const region = AWS_REGIONS.US_EAST_1 const emissionsFactors = AWS_EMISSIONS_FACTORS_METRIC_TON_PER_KWH const constants = { powerUsageEffectiveness: AWS_CLOUD_CONSTANTS.getPUE(), } const getServiceWrapper = () => new ServiceWrapper( new CloudWatch(), new CloudWatchLogs(), new CostExplorer(), ) afterEach(() => { AWSMock.restore() jest.restoreAllMocks() }) it('gets EBS usage', async () => { AWSMock.mock( 'CostExplorer', 'getCostAndUsage', ( params: CostExplorer.GetCostAndUsageRequest, callback: (a: Error, response: any) => any, ) => { expect(params).toEqual({ Filter: { And: [ { Dimensions: { Key: 'USAGE_TYPE_GROUP', Values: [ 'EC2: EBS - SSD(gp2)', 'EC2: EBS - SSD(io1)', 'EC2: EBS - HDD(sc1)', 'EC2: EBS - HDD(st1)', 'EC2: EBS - Magnetic', ], }, }, { Dimensions: { Key: 'REGION', Values: [region] } }, ], }, Granularity: 'DAILY', Metrics: ['UsageQuantity'], TimePeriod: { End: endDate, Start: startDate, }, GroupBy: [ { Key: 'USAGE_TYPE', Type: 'DIMENSION', }, ], }) callback( null, buildCostExplorerGetUsageResponse([ { start: startDate, amount: 1.2120679, keys: ['EBS:VolumeUsage.gp2'], }, ]), ) }, ) const ebsService = new EBS(getServiceWrapper()) const result = await ebsService.getUsage( new Date(startDate), new Date(endDate), region, ) expect(result).toEqual([ { terabyteHours: 0.8726888880000001, timestamp: new Date(startDate), diskType: 'SSD', }, ]) }) it('filters out results with no usage', async () => { // for valid date ranges, getCostAndUsage API will always return results for the date range, but with all zero usages AWSMock.mock( 'CostExplorer', 'getCostAndUsage', ( params: AWS.CostExplorer.GetCostAndUsageRequest, callback: (a: Error, response: any) => any, ) => { callback( null, buildCostExplorerGetUsageResponse([ { start: startDate, amount: 0, keys: ['EBS:VolumeUsage.gp2'] }, { start: startDate, amount: 1.2120679, keys: ['EBS:VolumeUsage.gp2'], }, ]), ) }, ) const ebsService = new EBS(getServiceWrapper()) const result = await ebsService.getUsage( new Date(startDate), new Date(startDate), region, ) expect(result).toEqual([ { terabyteHours: 0.8726888880000001, timestamp: new Date(startDate), diskType: 'SSD', }, ]) }) it('should return empty array if no usage', async () => { AWSMock.mock( 'CostExplorer', 'getCostAndUsage', ( params: AWS.CostExplorer.GetCostAndUsageRequest, callback: (a: Error, response: any) => any, ) => { callback(null, buildCostExplorerGetUsageResponse([])) }, ) const ebsService = new EBS(getServiceWrapper()) const result = await ebsService.getUsage( new Date(startDate), new Date(endDate), region, ) expect(result).toEqual([]) }) it('filters out results with no Amount', async () => { AWSMock.mock( 'CostExplorer', 'getCostAndUsage', ( params: CostExplorer.GetCostAndUsageRequest, callback: (a: Error, response: any) => any, ) => { callback( null, buildCostExplorerGetUsageResponse([ { start: startDate, amount: undefined, keys: ['EBS:VolumeUsage.gp2'], }, { start: startDate, amount: 1.2120679, keys: ['EBS:VolumeUsage.gp2'], }, ]), ) }, ) const ebsService = new EBS(getServiceWrapper()) const result = await ebsService.getUsage( new Date(startDate), new Date(endDate), region, ) expect(result).toEqual([ { terabyteHours: 0.8726888880000001, timestamp: new Date(startDate), diskType: 'SSD', }, ]) }) it('should calculate EBS HDD storage', async () => { AWSMock.mock( 'CostExplorer', 'getCostAndUsage', ( params: CostExplorer.GetCostAndUsageRequest, callback: (a: Error, response: any) => any, ) => { callback( null, buildCostExplorerGetUsageResponse([ { start: startDate, amount: 1, keys: ['EBS:VolumeUsage.st1'] }, ]), ) }, ) const ebsService = new EBS(getServiceWrapper()) const result = await ebsService.getUsage( new Date(startDate), new Date(endDate), region, ) expect(result).toEqual([ { terabyteHours: 0.72, timestamp: new Date(startDate), diskType: 'HDD', }, ]) }) it('should get estimates for ebs st1 HDD storage', async () => { AWSMock.mock( 'CostExplorer', 'getCostAndUsage', ( params: CostExplorer.GetCostAndUsageRequest, callback: (a: Error, response: any) => any, ) => { callback( null, buildCostExplorerGetUsageResponse([ { start: startDate, amount: 1, keys: ['EBS:VolumeUsage.st1'] }, ]), ) }, ) const ebsService = new EBS(getServiceWrapper()) const hddStorageEstimator = new StorageEstimator( AWS_CLOUD_CONSTANTS.HDDCOEFFICIENT, ) const result = await ebsService.getEstimates( new Date(startDate), new Date(endDate), region, emissionsFactors, constants, ) expect(result).toEqual( hddStorageEstimator.estimate( [{ terabyteHours: 0.72, timestamp: new Date(startDate) }], region, emissionsFactors, constants, ), ) }) it('should get estimates for magnetic EBS HDD storage', async () => { AWSMock.mock( 'CostExplorer', 'getCostAndUsage', ( params: AWS.CostExplorer.GetCostAndUsageRequest, callback: (a: Error, response: any) => any, ) => { callback( null, buildCostExplorerGetUsageResponse([ { start: startDate, amount: 1, keys: ['EBS:VolumeUsage'] }, ]), ) }, ) const ebsService = new EBS(getServiceWrapper()) const hddStorageEstimator = new StorageEstimator( AWS_CLOUD_CONSTANTS.HDDCOEFFICIENT, ) const result = await ebsService.getEstimates( new Date(startDate), new Date(endDate), region, emissionsFactors, constants, ) expect(result).toEqual( hddStorageEstimator.estimate( [{ terabyteHours: 0.72, timestamp: new Date(startDate) }], region, emissionsFactors, constants, ), ) }) it('should get estimates for magnetic sc1 HDD storage', async () => { AWSMock.mock( 'CostExplorer', 'getCostAndUsage', ( params: CostExplorer.GetCostAndUsageRequest, callback: (a: Error, response: any) => any, ) => { callback( null, buildCostExplorerGetUsageResponse([ { start: startDate, amount: 1, keys: ['EBS:VolumeUsage.sc1'] }, ]), ) }, ) const ebsService = new EBS(getServiceWrapper()) const hddStorageEstimator = new StorageEstimator( AWS_CLOUD_CONSTANTS.HDDCOEFFICIENT, ) const result = await ebsService.getEstimates( new Date(startDate), new Date(endDate), region, emissionsFactors, constants, ) expect(result).toEqual( hddStorageEstimator.estimate( [{ terabyteHours: 0.72, timestamp: new Date(startDate) }], region, emissionsFactors, constants, ), ) }) it('should get estimates for EBS SSD storage', async () => { AWSMock.mock( 'CostExplorer', 'getCostAndUsage', ( params: CostExplorer.GetCostAndUsageRequest, callback: (a: Error, response: any) => any, ) => { callback( null, buildCostExplorerGetUsageResponse([ { start: startDate, amount: 1, keys: ['EBS:VolumeUsage.piops'] }, ]), ) }, ) const ebsService = new EBS(getServiceWrapper()) const sddStorageEstimator = new StorageEstimator( AWS_CLOUD_CONSTANTS.SSDCOEFFICIENT, ) const result = await ebsService.getEstimates( new Date(startDate), new Date(endDate), region, emissionsFactors, constants, ) expect(result).toEqual( sddStorageEstimator.estimate( [{ terabyteHours: 0.72, timestamp: new Date(startDate) }], region, emissionsFactors, constants, ), ) }) it('should filter unexpected cost explorer volume name', async () => { jest.spyOn(Logger.prototype, 'warn').mockImplementation() AWSMock.mock( 'CostExplorer', 'getCostAndUsage', ( params: AWS.CostExplorer.GetCostAndUsageRequest, callback: (a: Error, response: any) => any, ) => { callback( null, buildCostExplorerGetUsageResponse([ { start: startDate, amount: 1, keys: ['EBS:anything'] }, ]), ) }, ) const ebsService = new EBS(getServiceWrapper()) const result = await ebsService.getEstimates( new Date(startDate), new Date(endDate), region, emissionsFactors, constants, ) expect(result).toEqual([]) }) it('should log warning if unexpected cost explorer volume name', async () => { jest.spyOn(Logger.prototype, 'warn').mockImplementation() AWSMock.mock( 'CostExplorer', 'getCostAndUsage', ( params: CostExplorer.GetCostAndUsageRequest, callback: (a: Error, response: any) => any, ) => { callback( null, buildCostExplorerGetUsageResponse([ { start: startDate, amount: 1, keys: ['EBS:anything'] }, ]), ) }, ) const ebsService = new EBS(getServiceWrapper()) await ebsService.getEstimates( new Date(startDate), new Date(endDate), region, emissionsFactors, constants, ) expect(Logger.prototype.warn).toHaveBeenCalledWith( 'Unexpected Cost explorer Dimension Name: EBS:anything', ) }) it('should get estimates for EBS SDD and HDD storage', async () => { AWSMock.mock( 'CostExplorer', 'getCostAndUsage', ( params: CostExplorer.GetCostAndUsageRequest, callback: (a: Error, response: any) => any, ) => { callback( null, buildCostExplorerGetUsageResponse([ { start: startDate, amount: 1, keys: ['EBS:VolumeUsage.st1'] }, { start: startDate, amount: 1, keys: ['EBS:VolumeUsage.gp2'] }, ]), ) }, ) const ebsService = new EBS(getServiceWrapper()) const hddStorageEstimator = new StorageEstimator( AWS_CLOUD_CONSTANTS.HDDCOEFFICIENT, ) const sddStorageEstimator = new StorageEstimator( AWS_CLOUD_CONSTANTS.SSDCOEFFICIENT, ) const result = await ebsService.getEstimates( new Date(startDate), new Date(endDate), region, emissionsFactors, constants, ) const ssdEstimates = sddStorageEstimator.estimate( [{ terabyteHours: 0.72, timestamp: new Date(startDate) }], region, emissionsFactors, constants, ) const hddEstimates = hddStorageEstimator.estimate( [{ terabyteHours: 0.72, timestamp: new Date(startDate) }], region, emissionsFactors, constants, ) expect(result).toEqual([ { timestamp: new Date(startDate), kilowattHours: ssdEstimates[0].kilowattHours + hddEstimates[0].kilowattHours, co2e: ssdEstimates[0].co2e + hddEstimates[0].co2e, }, ]) }) })
the_stack
import * as React from 'react'; import { connect } from 'react-redux'; import { Dispatch } from 'redux'; import { resetSettings, updateSetting } from '../../../redux/Actions'; import { initialState } from '../../../redux/State'; import { cadLog, isChrome, isFirefox, isFirefoxNotAndroid, } from '../../../services/Libs'; import { ReduxAction } from '../../../typings/ReduxConstants'; import CheckboxSetting from '../../common_components/CheckboxSetting'; import IconButton from '../../common_components/IconButton'; import SelectInput from '../../common_components/SelectInput'; import { downloadObjectAsJSON } from '../../UILibs'; import SettingsTooltip from './SettingsTooltip'; const styles = { buttonStyle: { height: 'max-content', padding: '0.75em', width: 'max-content', }, inlineNumberInput: { display: 'inline', margin: '0 5px', }, }; interface OwnProps { style?: React.CSSProperties; } interface StateProps { cache: CacheMap; settings: MapToSettingObject; } interface DispatchProps { onUpdateSetting: (setting: Setting) => void; onResetButtonClick: () => void; } type SettingProps = OwnProps & StateProps & DispatchProps; class InitialState { public error = ''; public success = ''; } class Settings extends React.Component<SettingProps> { public state = new InitialState(); // Import Settings public importCoreSettings(importFile: File) { const { settings } = this.props; const debug = settings[SettingID.DEBUG_MODE].value as boolean; cadLog( { msg: 'Import Core Settings received file for parsing.', x: { name: importFile.name, size: importFile.size, type: importFile.type, }, }, debug, ); // Do check for import first! if (importFile.type !== 'application/json') { this.setError( new Error( `${browser.i18n.getMessage('importFileTypeInvalid')}: ${ importFile.name } (${importFile.type})`, ), ); return; } const { onUpdateSetting } = this.props; const initialSettingKeys = Object.keys(initialState.settings); const reader = new FileReader(); reader.onload = (file) => { try { if (!file.target) { this.setError( new Error( browser.i18n.getMessage('importFileNotFound', [importFile.name]), ), ); return; } // https://stackoverflow.com/questions/35789498/new-typescript-1-8-4-build-error-build-property-result-does-not-exist-on-t const target: FileReader = file.target; const result: string = target.result as string; const jsonImport: { [k: string]: Record<string, unknown> } = JSON.parse( result, ); if (!jsonImport.settings) { cadLog( { msg: 'importCoreSettings: Imported JSON does not have "settings" array', x: jsonImport, }, debug, ); this.setError( new Error( `${browser.i18n.getMessage( 'importFileValidationFailed', )}. ${browser.i18n.getMessage('importMissingKey')} 'settings': ${ importFile.name }`, ), ); return; } // from { name, value } to name:{ name, value } const newSettings: MapToSettingObject = ((jsonImport.settings as unknown) as Setting[]).reduce( (a: { [k: string]: Setting }, c: Setting) => { a[c.name] = c; return a; }, {}, ); const settingKeys = Object.keys(newSettings); const unknownKeys = settingKeys.filter( (key) => !initialSettingKeys.includes(key), ); if (unknownKeys.length > 0) { this.setError( new Error( `${browser.i18n.getMessage( 'importCoreSettingsFailed', )}: ${unknownKeys.join(', ')}`, ), ); return; } settingKeys.forEach((setting) => { if (settings[setting].value !== newSettings[setting].value) { cadLog( { msg: `Setting updated: ${setting} (${settings[setting].value} => ${newSettings[setting].value})`, }, debug, ); onUpdateSetting(newSettings[setting]); } else { cadLog( { msg: `Setting remains unchanged: ${setting} (${settings[setting].value})`, }, debug, ); } }); this.setState({ error: '', success: browser.i18n.getMessage('importCoreSettingsText'), }); } catch (error) { this.setState({ error: error.toString(), success: '', }); } }; reader.readAsText(importFile); } public exportCoreSettings() { const { settings } = this.props; // Convert from name:{name, value} to {name, value} const exportSettings: Setting[] = Object.values(settings); const r = downloadObjectAsJSON( { settings: exportSettings }, 'CoreSettings', ); cadLog( { msg: 'exportCoreSettings: Core Settings Exported.', type: 'info', x: r, }, settings[SettingID.DEBUG_MODE].value as boolean, ); this.setState({ error: '', success: `${browser.i18n.getMessage('exportSettingsText')}: ${ r.downloadName }`, }); } public render() { const { cache, onResetButtonClick, onUpdateSetting, settings, style, } = this.props; const { error, success } = this.state; return ( <div style={style}> <h1>{browser.i18n.getMessage('settingsText')}</h1> <br /> <div className="row no-gutters justify-content-between justify-content-md-start"> <div className="col-7 col-md-auto"> <IconButton className="btn-primary" iconName="download" role="button" onClick={() => this.exportCoreSettings()} title={browser.i18n.getMessage('exportTitleTimestamp')} text={browser.i18n.getMessage('exportSettingsText')} styleReact={styles.buttonStyle} /> </div> <div className="col-7 col-md-auto"> <IconButton tag="input" className="btn-info" iconName="upload" type="file" accept="application/json, .json" onChange={(e) => this.importCoreSettings(e.target.files[0])} title={browser.i18n.getMessage('importCoreSettingsText')} text={browser.i18n.getMessage('importCoreSettingsText')} styleReact={styles.buttonStyle} /> </div> <div className="col-7 col-md-auto"> <IconButton className="btn-danger" role="button" onClick={() => { onResetButtonClick(); this.setState({ error: '', success: browser.i18n.getMessage('defaultSettingsText'), }); }} iconName="undo" title={browser.i18n.getMessage('defaultSettingsText')} text={browser.i18n.getMessage('defaultSettingsText')} styleReact={styles.buttonStyle} /> </div> </div> <br /> {error !== '' ? ( <div onClick={() => this.setState({ error: '' })} className="row alert alert-danger alertPreWrap" > {error} </div> ) : ( '' )} {success !== '' ? ( <div onClick={() => this.setState({ success: '' })} className="row alert alert-success alertPreWrap" > {browser.i18n.getMessage('successText')} {success} </div> ) : ( '' )} <fieldset> <legend>{browser.i18n.getMessage('settingGroupAutoClean')}</legend> <div className="form-group"> <CheckboxSetting text={browser.i18n.getMessage('activeModeText')} inline={true} settingObject={settings[SettingID.ACTIVE_MODE]} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#enable-automatic-cleaning'} /> </div> <div className="form-group"> <input id="delayBeforeClean" type="number" className="form-control w-auto" style={styles.inlineNumberInput} onChange={(e) => { const eValue = Number.parseInt(e.target.value, 10); if (!Number.isNaN(eValue) && eValue >= 1 && eValue <= 2147483) { onUpdateSetting({ name: SettingID.CLEAN_DELAY, value: eValue, }); } }} value={settings[SettingID.CLEAN_DELAY].value as number} min="1" max="2147483" size={10} /> <label htmlFor="delayBeforeClean"> {browser.i18n.getMessage('secondsText')}{' '} {browser.i18n.getMessage('activeModeDelayText')} </label> <SettingsTooltip hrefURL={'#delay-before-automatic-cleaning'} /> </div> <div className="form-group"> <CheckboxSetting text={browser.i18n.getMessage('cleanDiscardedText')} settingObject={settings[SettingID.CLEAN_DISCARDED]} inline={true} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#enable-cleanup-for-discardedunloaded-tabs'} /> </div> <div className="form-group"> <CheckboxSetting text={browser.i18n.getMessage('cleanupDomainChangeText')} settingObject={settings[SettingID.CLEAN_DOMAIN_CHANGE]} inline={true} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#enable-cleanup-on-domain-change'} /> </div> <div className="form-group"> <CheckboxSetting text={browser.i18n.getMessage(SettingID.ENABLE_GREYLIST)} settingObject={settings[SettingID.ENABLE_GREYLIST]} inline={true} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#enable-greylist-cleanup-on-browser-restart'} /> </div> <div className="form-group"> <CheckboxSetting text={browser.i18n.getMessage('cookieCleanUpOnStartText')} settingObject={settings[SettingID.CLEAN_OPEN_TABS_STARTUP]} inline={true} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#clean-cookies-from-open-tabs-on-startup'} /> </div> <div className="form-group"> <CheckboxSetting settingObject={settings[SettingID.CLEAN_EXPIRED]} inline={true} text={browser.i18n.getMessage('cleanExpiredCookiesText')} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#clean-all-expired-cookies'} /> </div> </fieldset> <hr /> <fieldset> <legend>{browser.i18n.getMessage('settingGroupExpression')}</legend> <div className="alert alert-info"> {browser.i18n.getMessage('groupExpressionDefaultNotice', [ browser.i18n.getMessage('expressionListText'), ])}{' '} <SettingsTooltip hrefURL={'#default-expression-options'} /> </div> </fieldset> <hr /> {(isFirefoxNotAndroid(cache) || isChrome(cache)) && ( <fieldset> <legend> {browser.i18n.getMessage('settingGroupOtherBrowsing')} </legend> <div className="alert alert-warning"> {browser.i18n.getMessage('browsingDataWarning')} </div> {((isFirefoxNotAndroid(cache) && cache.browserVersion >= '78') || isChrome(cache)) && ( <div className="form-group"> <CheckboxSetting text={browser.i18n.getMessage('cacheCleanupText')} settingObject={settings[SettingID.CLEANUP_CACHE]} inline={true} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#other-browsing-data-cleanup-options'} /> </div> )} {((isFirefoxNotAndroid(cache) && cache.browserVersion >= '77') || isChrome(cache)) && ( <div className="form-group"> <CheckboxSetting text={browser.i18n.getMessage('indexedDBCleanupText')} settingObject={settings[SettingID.CLEANUP_INDEXEDDB]} inline={true} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#other-browsing-data-cleanup-options'} /> </div> )} {((isFirefoxNotAndroid(cache) && cache.browserVersion >= '58') || isChrome(cache)) && ( <div className="form-group"> <CheckboxSetting text={browser.i18n.getMessage('localStorageCleanupText')} settingObject={settings[SettingID.CLEANUP_LOCALSTORAGE]} inline={true} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#other-browsing-data-cleanup-options'} /> </div> )} {((isFirefoxNotAndroid(cache) && cache.browserVersion >= '78') || isChrome(cache)) && ( <div className="form-group"> <CheckboxSetting text={browser.i18n.getMessage('pluginDataCleanupText')} settingObject={settings[SettingID.CLEANUP_PLUGIN_DATA]} inline={true} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#other-browsing-data-cleanup-options'} /> </div> )} {((isFirefoxNotAndroid(cache) && cache.browserVersion >= '77') || isChrome(cache)) && ( <div className="form-group"> <CheckboxSetting text={browser.i18n.getMessage('serviceWorkersCleanupText')} settingObject={settings[SettingID.CLEANUP_SERVICE_WORKERS]} inline={true} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#other-browsing-data-cleanup-options'} /> </div> )} </fieldset> )} {(isFirefoxNotAndroid(cache) || isChrome(cache)) && <hr />} <fieldset> <legend>{browser.i18n.getMessage('settingGroupExtension')}</legend> {isFirefoxNotAndroid(cache) && ( <div className="form-group"> <div className="alert alert-warning"> {browser.i18n.getMessage('containerSiteDataWarning')} </div> <CheckboxSetting text={browser.i18n.getMessage( 'contextualIdentitiesEnabledText', )} settingObject={settings[SettingID.CONTEXTUAL_IDENTITIES]} inline={true} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#enable-support-for-firefoxs-container-tabs'} /> </div> )} {isFirefoxNotAndroid(cache) && settings[SettingID.CONTEXTUAL_IDENTITIES].value && ( <div className="form-group"> <CheckboxSetting text={browser.i18n.getMessage( 'contextualIdentitiesAutoRemoveText', )} settingObject={ settings[SettingID.CONTEXTUAL_IDENTITIES_AUTOREMOVE] } inline={true} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={ '#enable-automatic-removal-of-expression-list-when-its-container-is-removed' } /> </div> )} <div className="form-group"> <CheckboxSetting text={browser.i18n.getMessage('enableCleanupLogText')} settingObject={settings[SettingID.STAT_LOGGING]} inline={true} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#enable-cleanup-log-and-counter'} /> {settings[SettingID.STAT_LOGGING].value && ( <div className="alert alert-warning"> {browser.i18n.getMessage('noPrivateLogging')} </div> )} </div> {(!isFirefox(cache) || isFirefoxNotAndroid(cache)) && ( <div className="form-group"> <CheckboxSetting text={browser.i18n.getMessage('showNumberOfCookiesInIconText')} settingObject={settings[SettingID.NUM_COOKIES_ICON]} inline={true} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#show-number-of-cookies-for-that-domain'} /> </div> )} {(!isFirefox(cache) || isFirefoxNotAndroid(cache)) && settings[SettingID.NUM_COOKIES_ICON].value === true && ( <div className="form-group"> <CheckboxSetting text={browser.i18n.getMessage(SettingID.KEEP_DEFAULT_ICON)} settingObject={settings[SettingID.KEEP_DEFAULT_ICON]} inline={true} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#keep-default-icon-on-all-list-types'} /> </div> )} <div className="form-group"> <CheckboxSetting text={browser.i18n.getMessage('notifyCookieCleanUpText')} settingObject={settings[SettingID.NOTIFY_AUTO]} inline={true} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#show-notification-after-automatic-cleanup'} /> </div> <div className="form-group"> <CheckboxSetting inline={true} settingObject={settings[SettingID.NOTIFY_MANUAL]} text={browser.i18n.getMessage('manualNotificationsText')} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#show-notification-from-manual-site-data-cleanups'} /> </div> <div className="form-group"> <SelectInput numSize={9} numStart={1} settingObject={settings[SettingID.NOTIFY_DURATION]} text={`${browser.i18n.getMessage( 'secondsText', )} ${browser.i18n.getMessage('notifyCookieCleanupDelayText')}`} updateSetting={(payload) => { onUpdateSetting(payload); }} /> <SettingsTooltip hrefURL={'#duration-for-notifications'} /> </div> <div className="form-group"> <CheckboxSetting text={browser.i18n.getMessage(SettingID.ENABLE_NEW_POPUP)} settingObject={settings[SettingID.ENABLE_NEW_POPUP]} inline={true} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#enable-popup-when-new-version-is-released'} /> </div> <div className="form-group"> <SelectInput numSize={14} numStart={10} settingObject={settings[SettingID.SIZE_POPUP]} text={browser.i18n.getMessage('sizePopupText')} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#size-of-popup'} /> </div> <div className="form-group"> <SelectInput numSize={14} numStart={10} settingObject={settings[SettingID.SIZE_SETTING]} text={browser.i18n.getMessage('sizeSettingText')} updateSetting={(payload) => { onUpdateSetting(payload); }} /> <SettingsTooltip hrefURL={'#size-of-setting'} /> </div> {(isFirefoxNotAndroid(cache) || isChrome(cache)) && ( <div className="form-group"> <CheckboxSetting text={browser.i18n.getMessage('enableContextMenus')} settingObject={settings[SettingID.CONTEXT_MENUS]} inline={true} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#enable-context-menus'} /> </div> )} {(isFirefoxNotAndroid(cache) || isChrome(cache)) && ( <div className="form-group"> <CheckboxSetting text={browser.i18n.getMessage(SettingID.DEBUG_MODE)} settingObject={settings[SettingID.DEBUG_MODE]} inline={true} updateSetting={(payload) => onUpdateSetting(payload)} /> <SettingsTooltip hrefURL={'#debug-mode'} /> {settings[SettingID.DEBUG_MODE].value && ( <div className="alert alert-info"> <p>{browser.i18n.getMessage('openDebugMode')}</p> <pre> <b> {(isFirefox(cache) && 'about:devtools-toolbox?type=extension&id=') || (isChrome(cache) && `chrome://extensions/?id=`)} {encodeURIComponent(browser.runtime.id)} </b> </pre> {isChrome(cache) && ( <p>{browser.i18n.getMessage('chromeDebugMode')}</p> )} <p> {browser.i18n.getMessage('consoleDebugMode')}.{' '} {browser.i18n.getMessage('filterDebugMode')} </p> <p> <b>CAD_</b> </p> </div> )} </div> )} </fieldset> <br /> <br /> </div> ); } private setError(e: Error): void { this.setState({ error: e.toString(), success: '', }); } } const mapStateToProps = (state: State) => { const { settings, cache } = state; return { cache, settings, }; }; const mapDispatchToProps = (dispatch: Dispatch<ReduxAction>) => ({ onUpdateSetting(newSetting: Setting) { dispatch(updateSetting(newSetting)); }, onResetButtonClick() { dispatch(resetSettings()); }, }); export default connect(mapStateToProps, mapDispatchToProps)(Settings);
the_stack
export interface Node { id: string /* The id of the node. */ parent?: Node | null /* The parent of this node. */ children?: Node[] | null /* The children of this node. */ } export interface RootQueryType { allSitePage?: SitePageConnection | null /* Connection to all SitePage nodes */ allSitePlugin?: SitePluginConnection | null /* Connection to all SitePlugin nodes */ allFile?: FileConnection | null /* Connection to all File nodes */ allMarkdownRemark?: MarkdownRemarkConnection | null /* Connection to all MarkdownRemark nodes */ allContentfulBlogPostBodyTextNode?: contentfulBlogPostBodyTextNodeConnection | null /* Connection to all contentfulBlogPostBodyTextNode nodes */ allContentfulContentType?: ContentfulContentTypeConnection | null /* Connection to all ContentfulContentType nodes */ allContentfulBlogPost?: ContentfulBlogPostConnection | null /* Connection to all ContentfulBlogPost nodes */ allContentfulAsset?: ContentfulAssetConnection | null /* Connection to all ContentfulAsset nodes */ sitePage?: SitePage | null sitePlugin?: SitePlugin | null site?: Site | null file?: File | null markdownRemark?: MarkdownRemark | null contentfulBlogPostBodyTextNode?: contentfulBlogPostBodyTextNode | null contentfulContentType?: ContentfulContentType | null contentfulBlogPost?: ContentfulBlogPost | null contentfulAsset?: ContentfulAsset | null } /* A connection to a list of items. */ export interface SitePageConnection { pageInfo: PageInfo /* Information to aid in pagination. */ edges?: SitePageEdge[] | null /* A list of edges. */ totalCount?: number | null distinct?: string[] | null group?: sitePageGroupConnectionConnection[] | null } /* Information about pagination in a connection. */ export interface PageInfo { hasNextPage: boolean /* When paginating, are there more items? */ } /* An edge in a connection. */ export interface SitePageEdge { node?: SitePage | null /* The item at the end of the edge */ next?: SitePage | null /* The next edge in the connection */ previous?: SitePage | null /* The previous edge in the connection */ } /* Node of type SitePage */ export interface SitePage extends Node { id: string /* The id of this node. */ parent?: Node | null /* The parent of this node. */ children?: Node[] | null /* The children of this node. */ layout?: string | null jsonName?: string | null internalComponentName?: string | null path?: string | null component?: string | null componentChunkName?: string | null context?: context | null updatedAt?: number | null pluginCreator?: SitePlugin | null pluginCreatorId?: string | null componentPath?: string | null internal?: internal_10 | null } export interface context { path?: string | null fileSlug?: string | null id?: string | null } /* Node of type SitePlugin */ export interface SitePlugin extends Node { id: string /* The id of this node. */ parent?: Node | null /* The parent of this node. */ children?: Node[] | null /* The children of this node. */ resolve?: string | null name?: string | null version?: string | null pluginOptions?: pluginOptions_2 | null nodeAPIs?: string[] | null pluginFilepath?: string | null packageJson?: packageJson_2 | null internal?: internal_11 | null } export interface pluginOptions_2 { plugins?: plugins_2[] | null name?: string | null path?: string | null spaceId?: string | null accessToken?: string | null query?: string | null feeds?: feeds_2[] | null } export interface plugins_2 { resolve?: string | null id?: string | null name?: string | null version?: string | null pluginFilepath?: string | null } export interface feeds_2 { query?: string | null output?: string | null } export interface packageJson_2 { name?: string | null description?: string | null version?: string | null main?: string | null keywords?: string[] | null author?: string | null license?: string | null dependencies?: dependencies_2[] | null devDependencies?: devDependencies_2[] | null } export interface dependencies_2 { name?: string | null version?: string | null } export interface devDependencies_2 { name?: string | null version?: string | null } export interface internal_11 { contentDigest?: string | null type?: string | null owner?: string | null } export interface internal_10 { type?: string | null contentDigest?: string | null owner?: string | null } /* A connection to a list of items. */ export interface sitePageGroupConnectionConnection { pageInfo: PageInfo /* Information to aid in pagination. */ edges?: sitePageGroupConnectionEdge[] | null /* A list of edges. */ field?: string | null fieldValue?: string | null totalCount?: number | null } /* An edge in a connection. */ export interface sitePageGroupConnectionEdge { node?: SitePage | null /* The item at the end of the edge */ next?: SitePage | null /* The next edge in the connection */ previous?: SitePage | null /* The previous edge in the connection */ } /* A connection to a list of items. */ export interface SitePluginConnection { pageInfo: PageInfo /* Information to aid in pagination. */ edges?: SitePluginEdge[] | null /* A list of edges. */ totalCount?: number | null distinct?: string[] | null group?: sitePluginGroupConnectionConnection[] | null } /* An edge in a connection. */ export interface SitePluginEdge { node?: SitePlugin | null /* The item at the end of the edge */ next?: SitePlugin | null /* The next edge in the connection */ previous?: SitePlugin | null /* The previous edge in the connection */ } /* A connection to a list of items. */ export interface sitePluginGroupConnectionConnection { pageInfo: PageInfo /* Information to aid in pagination. */ edges?: sitePluginGroupConnectionEdge[] | null /* A list of edges. */ field?: string | null fieldValue?: string | null totalCount?: number | null } /* An edge in a connection. */ export interface sitePluginGroupConnectionEdge { node?: SitePlugin | null /* The item at the end of the edge */ next?: SitePlugin | null /* The next edge in the connection */ previous?: SitePlugin | null /* The previous edge in the connection */ } /* A connection to a list of items. */ export interface FileConnection { pageInfo: PageInfo /* Information to aid in pagination. */ edges?: FileEdge[] | null /* A list of edges. */ totalCount?: number | null distinct?: string[] | null group?: fileGroupConnectionConnection[] | null } /* An edge in a connection. */ export interface FileEdge { node?: File | null /* The item at the end of the edge */ next?: File | null /* The next edge in the connection */ previous?: File | null /* The previous edge in the connection */ } /* Node of type File */ export interface File extends Node { id: string /* The id of this node. */ parent?: Node | null /* The parent of this node. */ children?: Node[] | null /* The children of this node. */ childMarkdownRemark?: MarkdownRemark | null /* The child of this node of type markdownRemark */ internal?: internal_12 | null sourceInstanceName?: string | null absolutePath?: string | null relativePath?: string | null extension?: string | null size?: string | null prettySize?: string | null modifiedTime?: string | null accessTime?: string | null changeTime?: string | null birthTime?: string | null root?: string | null dir?: string | null base?: string | null ext?: string | null name?: string | null dev?: number | null mode?: number | null nlink?: number | null uid?: number | null gid?: number | null rdev?: number | null blksize?: string | null ino?: number | null blocks?: number | null atimeMs?: number | null mtimeMs?: number | null ctimeMs?: number | null birthtimeMs?: number | null atime?: string | null mtime?: string | null ctime?: string | null birthtime?: string | null } /* Node of type MarkdownRemark */ export interface MarkdownRemark extends Node { id: string /* The id of this node. */ parent?: Node | null /* The parent of this node. */ children?: Node[] | null /* The children of this node. */ internal?: internal_13 | null frontmatter?: frontmatter_2 | null fileAbsolutePath?: string | null fields?: fields_2 | null html?: string | null excerpt?: string | null headings?: MarkdownHeading[] | null timeToRead?: number | null tableOfContents?: string | null wordCount?: wordCount | null } export interface internal_13 { content?: string | null contentDigest?: string | null type?: string | null owner?: string | null fieldOwners?: fieldOwners_2 | null } export interface fieldOwners_2 { slug?: string | null } export interface frontmatter_2 { title?: string | null layout?: string | null permalink?: string | null _PARENT?: string | null parent?: string | null } export interface fields_2 { slug?: string | null } export interface MarkdownHeading { value?: string | null depth?: number | null } export interface wordCount { paragraphs?: number | null sentences?: number | null words?: number | null } export interface internal_12 { contentDigest?: string | null mediaType?: string | null type?: string | null owner?: string | null } /* A connection to a list of items. */ export interface fileGroupConnectionConnection { pageInfo: PageInfo /* Information to aid in pagination. */ edges?: fileGroupConnectionEdge[] | null /* A list of edges. */ field?: string | null fieldValue?: string | null totalCount?: number | null } /* An edge in a connection. */ export interface fileGroupConnectionEdge { node?: File | null /* The item at the end of the edge */ next?: File | null /* The next edge in the connection */ previous?: File | null /* The previous edge in the connection */ } /* A connection to a list of items. */ export interface MarkdownRemarkConnection { pageInfo: PageInfo /* Information to aid in pagination. */ edges?: MarkdownRemarkEdge[] | null /* A list of edges. */ totalCount?: number | null distinct?: string[] | null group?: markdownRemarkGroupConnectionConnection[] | null } /* An edge in a connection. */ export interface MarkdownRemarkEdge { node?: MarkdownRemark | null /* The item at the end of the edge */ next?: MarkdownRemark | null /* The next edge in the connection */ previous?: MarkdownRemark | null /* The previous edge in the connection */ } /* A connection to a list of items. */ export interface markdownRemarkGroupConnectionConnection { pageInfo: PageInfo /* Information to aid in pagination. */ edges?: markdownRemarkGroupConnectionEdge[] | null /* A list of edges. */ field?: string | null fieldValue?: string | null totalCount?: number | null } /* An edge in a connection. */ export interface markdownRemarkGroupConnectionEdge { node?: MarkdownRemark | null /* The item at the end of the edge */ next?: MarkdownRemark | null /* The next edge in the connection */ previous?: MarkdownRemark | null /* The previous edge in the connection */ } /* A connection to a list of items. */ export interface contentfulBlogPostBodyTextNodeConnection { pageInfo: PageInfo /* Information to aid in pagination. */ edges?: contentfulBlogPostBodyTextNodeEdge[] | null /* A list of edges. */ totalCount?: number | null distinct?: string[] | null group?: contentfulBlogPostBodyTextNodeGroupConnectionConnection[] | null } /* An edge in a connection. */ export interface contentfulBlogPostBodyTextNodeEdge { node?: contentfulBlogPostBodyTextNode | null /* The item at the end of the edge */ next?: contentfulBlogPostBodyTextNode | null /* The next edge in the connection */ previous?: contentfulBlogPostBodyTextNode | null /* The previous edge in the connection */ } /* Node of type contentfulBlogPostBodyTextNode */ export interface contentfulBlogPostBodyTextNode extends Node { id: string /* The id of this node. */ parent?: Node | null /* The parent of this node. */ children?: Node[] | null /* The children of this node. */ childMarkdownRemark?: MarkdownRemark | null /* The child of this node of type markdownRemark */ body?: string | null internal?: internal_14 | null } export interface internal_14 { type?: string | null mediaType?: string | null content?: string | null contentDigest?: string | null owner?: string | null } /* A connection to a list of items. */ export interface contentfulBlogPostBodyTextNodeGroupConnectionConnection { pageInfo: PageInfo /* Information to aid in pagination. */ edges?: contentfulBlogPostBodyTextNodeGroupConnectionEdge[] | null /* A list of edges. */ field?: string | null fieldValue?: string | null totalCount?: number | null } /* An edge in a connection. */ export interface contentfulBlogPostBodyTextNodeGroupConnectionEdge { node?: contentfulBlogPostBodyTextNode | null /* The item at the end of the edge */ next?: contentfulBlogPostBodyTextNode | null /* The next edge in the connection */ previous?: contentfulBlogPostBodyTextNode | null /* The previous edge in the connection */ } /* A connection to a list of items. */ export interface ContentfulContentTypeConnection { pageInfo: PageInfo /* Information to aid in pagination. */ edges?: ContentfulContentTypeEdge[] | null /* A list of edges. */ totalCount?: number | null distinct?: string[] | null group?: contentfulContentTypeGroupConnectionConnection[] | null } /* An edge in a connection. */ export interface ContentfulContentTypeEdge { node?: ContentfulContentType | null /* The item at the end of the edge */ next?: ContentfulContentType | null /* The next edge in the connection */ previous?: ContentfulContentType | null /* The previous edge in the connection */ } /* Node of type ContentfulContentType */ export interface ContentfulContentType extends Node { id: string /* The id of this node. */ parent?: Node | null /* The parent of this node. */ children?: Node[] | null /* The children of this node. */ name?: string | null displayField?: string | null description?: string | null internal?: internal_15 | null } export interface internal_15 { type?: string | null contentDigest?: string | null owner?: string | null } /* A connection to a list of items. */ export interface contentfulContentTypeGroupConnectionConnection { pageInfo: PageInfo /* Information to aid in pagination. */ edges?: contentfulContentTypeGroupConnectionEdge[] | null /* A list of edges. */ field?: string | null fieldValue?: string | null totalCount?: number | null } /* An edge in a connection. */ export interface contentfulContentTypeGroupConnectionEdge { node?: ContentfulContentType | null /* The item at the end of the edge */ next?: ContentfulContentType | null /* The next edge in the connection */ previous?: ContentfulContentType | null /* The previous edge in the connection */ } /* A connection to a list of items. */ export interface ContentfulBlogPostConnection { pageInfo: PageInfo /* Information to aid in pagination. */ edges?: ContentfulBlogPostEdge[] | null /* A list of edges. */ totalCount?: number | null distinct?: string[] | null group?: contentfulBlogPostGroupConnectionConnection[] | null } /* An edge in a connection. */ export interface ContentfulBlogPostEdge { node?: ContentfulBlogPost | null /* The item at the end of the edge */ next?: ContentfulBlogPost | null /* The next edge in the connection */ previous?: ContentfulBlogPost | null /* The previous edge in the connection */ } /* Node of type ContentfulBlogPost */ export interface ContentfulBlogPost extends Node { id: string /* The id of this node. */ parent?: Node | null /* The parent of this node. */ children?: Node[] | null /* The children of this node. */ childContentfulBlogPostBodyTextNode?: contentfulBlogPostBodyTextNode | null /* The child of this node of type contentfulBlogPostBodyTextNode */ title?: string | null slug?: string | null publishDate?: string | null author?: string | null tags?: string[] | null heroImage?: ContentfulAsset | null body?: contentfulBlogPostBodyTextNode | null createdAt?: string | null updatedAt?: string | null internal?: internal_16 | null node_locale?: string | null } /* Node of type ContentfulAsset */ export interface ContentfulAsset extends Node { id: string /* The id of this node. */ parent?: Node | null /* The parent of this node. */ children?: Node[] | null /* The children of this node. */ file?: file_2 | null title?: string | null description?: string | null node_locale?: string | null internal?: internal_17 | null resolutions?: ContentfulResolutions | null sizes?: ContentfulSizes | null responsiveResolution?: ContentfulResponsiveResolution | null responsiveSizes?: ContentfulResponsiveSizes | null resize?: ContentfulResize | null } export interface file_2 { url?: string | null details?: details_2 | null fileName?: string | null contentType?: string | null } export interface details_2 { size?: number | null image?: image_2 | null } export interface image_2 { width?: number | null height?: number | null } export interface internal_17 { type?: string | null contentDigest?: string | null owner?: string | null } export interface ContentfulResolutions { base64?: string | null aspectRatio?: number | null width?: number | null height?: number | null src?: string | null srcSet?: string | null } export interface ContentfulSizes { base64?: string | null aspectRatio?: number | null src?: string | null srcSet?: string | null sizes?: string | null } export interface ContentfulResponsiveResolution { base64?: string | null aspectRatio?: number | null width?: number | null height?: number | null src?: string | null srcSet?: string | null } export interface ContentfulResponsiveSizes { base64?: string | null aspectRatio?: number | null src?: string | null srcSet?: string | null sizes?: string | null } export interface ContentfulResize { src?: string | null width?: number | null height?: number | null aspectRatio?: number | null } export interface internal_16 { type?: string | null contentDigest?: string | null owner?: string | null } /* A connection to a list of items. */ export interface contentfulBlogPostGroupConnectionConnection { pageInfo: PageInfo /* Information to aid in pagination. */ edges?: contentfulBlogPostGroupConnectionEdge[] | null /* A list of edges. */ field?: string | null fieldValue?: string | null totalCount?: number | null } /* An edge in a connection. */ export interface contentfulBlogPostGroupConnectionEdge { node?: ContentfulBlogPost | null /* The item at the end of the edge */ next?: ContentfulBlogPost | null /* The next edge in the connection */ previous?: ContentfulBlogPost | null /* The previous edge in the connection */ } /* A connection to a list of items. */ export interface ContentfulAssetConnection { pageInfo: PageInfo /* Information to aid in pagination. */ edges?: ContentfulAssetEdge[] | null /* A list of edges. */ totalCount?: number | null distinct?: string[] | null group?: contentfulAssetGroupConnectionConnection[] | null } /* An edge in a connection. */ export interface ContentfulAssetEdge { node?: ContentfulAsset | null /* The item at the end of the edge */ next?: ContentfulAsset | null /* The next edge in the connection */ previous?: ContentfulAsset | null /* The previous edge in the connection */ } /* A connection to a list of items. */ export interface contentfulAssetGroupConnectionConnection { pageInfo: PageInfo /* Information to aid in pagination. */ edges?: contentfulAssetGroupConnectionEdge[] | null /* A list of edges. */ field?: string | null fieldValue?: string | null totalCount?: number | null } /* An edge in a connection. */ export interface contentfulAssetGroupConnectionEdge { node?: ContentfulAsset | null /* The item at the end of the edge */ next?: ContentfulAsset | null /* The next edge in the connection */ previous?: ContentfulAsset | null /* The previous edge in the connection */ } /* Node of type Site */ export interface Site extends Node { id: string /* The id of this node. */ parent?: Node | null /* The parent of this node. */ children?: Node[] | null /* The children of this node. */ siteMetadata?: siteMetadata_2 | null port?: string | null host?: string | null pathPrefix?: string | null polyfill?: boolean | null buildTime?: string | null internal?: internal_18 | null } export interface siteMetadata_2 { title?: string | null description?: string | null siteUrl?: string | null } export interface internal_18 { contentDigest?: string | null type?: string | null owner?: string | null } export interface sitePageConnectionSort { fields: SitePageConnectionSortByFieldsEnum[] order?: sitePageConnectionSortOrderValues | null } /* Filter connection on its fields */ export interface filterSitePage { layout?: sitePageConnectionLayoutQueryString | null jsonName?: sitePageConnectionJsonNameQueryString | null internalComponentName?: sitePageConnectionInternalComponentNameQueryString | null path?: sitePageConnectionPathQueryString_2 | null component?: sitePageConnectionComponentQueryString | null componentChunkName?: sitePageConnectionComponentChunkNameQueryString | null context?: sitePageConnectionContextInputObject | null updatedAt?: sitePageConnectionUpdatedAtQueryInteger | null pluginCreatorId?: sitePageConnectionPluginCreatorIdQueryString | null componentPath?: sitePageConnectionComponentPathQueryString | null id?: sitePageConnectionIdQueryString_2 | null internal?: sitePageConnectionInternalInputObject_2 | null } export interface sitePageConnectionLayoutQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageConnectionJsonNameQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageConnectionInternalComponentNameQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageConnectionPathQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageConnectionComponentQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageConnectionComponentChunkNameQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageConnectionContextInputObject { path?: sitePageConnectionContextPathQueryString | null fileSlug?: sitePageConnectionContextFileSlugQueryString | null id?: sitePageConnectionContextIdQueryString | null } export interface sitePageConnectionContextPathQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageConnectionContextFileSlugQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageConnectionContextIdQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageConnectionUpdatedAtQueryInteger { eq?: number | null ne?: number | null } export interface sitePageConnectionPluginCreatorIdQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageConnectionComponentPathQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageConnectionIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageConnectionInternalInputObject_2 { type?: sitePageConnectionInternalTypeQueryString_2 | null contentDigest?: sitePageConnectionInternalContentDigestQueryString_2 | null owner?: sitePageConnectionInternalOwnerQueryString_2 | null } export interface sitePageConnectionInternalTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageConnectionInternalContentDigestQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageConnectionInternalOwnerQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionSort { fields: SitePluginConnectionSortByFieldsEnum[] order?: sitePluginConnectionSortOrderValues | null } /* Filter connection on its fields */ export interface filterSitePlugin { resolve?: sitePluginConnectionResolveQueryString_2 | null id?: sitePluginConnectionIdQueryString_2 | null name?: sitePluginConnectionNameQueryString_2 | null version?: sitePluginConnectionVersionQueryString_2 | null pluginOptions?: sitePluginConnectionPluginOptionsInputObject_2 | null nodeAPIs?: sitePluginConnectionNodeApIsQueryList_2 | null pluginFilepath?: sitePluginConnectionPluginFilepathQueryString_2 | null packageJson?: sitePluginConnectionPackageJsonInputObject_2 | null internal?: sitePluginConnectionInternalInputObject_2 | null } export interface sitePluginConnectionResolveQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionVersionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPluginOptionsInputObject_2 { plugins?: sitePluginConnectionPluginOptionsPluginsQueryList_2 | null name?: sitePluginConnectionPluginOptionsNameQueryString_2 | null path?: sitePluginConnectionPluginOptionsPathQueryString_2 | null spaceId?: sitePluginConnectionPluginOptionsSpaceIdQueryString_2 | null accessToken?: sitePluginConnectionPluginOptionsAccessTokenQueryString_2 | null query?: sitePluginConnectionPluginOptionsQueryQueryString_2 | null feeds?: sitePluginConnectionPluginOptionsFeedsQueryList_2 | null } export interface sitePluginConnectionPluginOptionsPluginsQueryList_2 { in?: sitePluginConnectionPluginOptionsPluginsInputObject_2[] | null } export interface sitePluginConnectionPluginOptionsPluginsInputObject_2 { resolve?: sitePluginConnectionPluginOptionsPluginsResolveQueryString_2 | null id?: sitePluginConnectionPluginOptionsPluginsIdQueryString_2 | null name?: sitePluginConnectionPluginOptionsPluginsNameQueryString_2 | null version?: sitePluginConnectionPluginOptionsPluginsVersionQueryString_2 | null pluginFilepath?: sitePluginConnectionPluginOptionsPluginsPluginFilepathQueryString_2 | null } export interface sitePluginConnectionPluginOptionsPluginsResolveQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPluginOptionsPluginsIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPluginOptionsPluginsNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPluginOptionsPluginsVersionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPluginOptionsPluginsPluginFilepathQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPluginOptionsNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPluginOptionsPathQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPluginOptionsSpaceIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPluginOptionsAccessTokenQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPluginOptionsQueryQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPluginOptionsFeedsQueryList_2 { in?: sitePluginConnectionPluginOptionsFeedsInputObject_2[] | null } export interface sitePluginConnectionPluginOptionsFeedsInputObject_2 { query?: sitePluginConnectionPluginOptionsFeedsQueryQueryString_2 | null output?: sitePluginConnectionPluginOptionsFeedsOutputQueryString_2 | null } export interface sitePluginConnectionPluginOptionsFeedsQueryQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPluginOptionsFeedsOutputQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionNodeApIsQueryList_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null in?: string[] | null } export interface sitePluginConnectionPluginFilepathQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPackageJsonInputObject_2 { name?: sitePluginConnectionPackageJsonNameQueryString_2 | null description?: sitePluginConnectionPackageJsonDescriptionQueryString_2 | null version?: sitePluginConnectionPackageJsonVersionQueryString_2 | null main?: sitePluginConnectionPackageJsonMainQueryString_2 | null keywords?: sitePluginConnectionPackageJsonKeywordsQueryList_2 | null author?: sitePluginConnectionPackageJsonAuthorQueryString_2 | null license?: sitePluginConnectionPackageJsonLicenseQueryString_2 | null dependencies?: sitePluginConnectionPackageJsonDependenciesQueryList_2 | null devDependencies?: sitePluginConnectionPackageJsonDevDependenciesQueryList_2 | null } export interface sitePluginConnectionPackageJsonNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPackageJsonDescriptionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPackageJsonVersionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPackageJsonMainQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPackageJsonKeywordsQueryList_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null in?: string[] | null } export interface sitePluginConnectionPackageJsonAuthorQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPackageJsonLicenseQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPackageJsonDependenciesQueryList_2 { in?: sitePluginConnectionPackageJsonDependenciesInputObject_2[] | null } export interface sitePluginConnectionPackageJsonDependenciesInputObject_2 { name?: sitePluginConnectionPackageJsonDependenciesNameQueryString_2 | null version?: sitePluginConnectionPackageJsonDependenciesVersionQueryString_2 | null } export interface sitePluginConnectionPackageJsonDependenciesNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPackageJsonDependenciesVersionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPackageJsonDevDependenciesQueryList_2 { in?: sitePluginConnectionPackageJsonDevDependenciesInputObject_2[] | null } export interface sitePluginConnectionPackageJsonDevDependenciesInputObject_2 { name?: sitePluginConnectionPackageJsonDevDependenciesNameQueryString_2 | null version?: sitePluginConnectionPackageJsonDevDependenciesVersionQueryString_2 | null } export interface sitePluginConnectionPackageJsonDevDependenciesNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionPackageJsonDevDependenciesVersionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionInternalInputObject_2 { contentDigest?: sitePluginConnectionInternalContentDigestQueryString_2 | null type?: sitePluginConnectionInternalTypeQueryString_2 | null owner?: sitePluginConnectionInternalOwnerQueryString_2 | null } export interface sitePluginConnectionInternalContentDigestQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionInternalTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginConnectionInternalOwnerQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionSort { fields: FileConnectionSortByFieldsEnum[] order?: fileConnectionSortOrderValues | null } /* Filter connection on its fields */ export interface filterFile { id?: fileConnectionIdQueryString_2 | null internal?: fileConnectionInternalInputObject_2 | null sourceInstanceName?: fileConnectionSourceInstanceNameQueryString_2 | null absolutePath?: fileConnectionAbsolutePathQueryString_2 | null relativePath?: fileConnectionRelativePathQueryString_2 | null extension?: fileConnectionExtensionQueryString_2 | null size?: fileConnectionSizeQueryInteger_2 | null prettySize?: fileConnectionPrettySizeQueryString_2 | null modifiedTime?: fileConnectionModifiedTimeQueryString_2 | null accessTime?: fileConnectionAccessTimeQueryString_2 | null changeTime?: fileConnectionChangeTimeQueryString_2 | null birthTime?: fileConnectionBirthTimeQueryString_2 | null root?: fileConnectionRootQueryString_2 | null dir?: fileConnectionDirQueryString_2 | null base?: fileConnectionBaseQueryString_2 | null ext?: fileConnectionExtQueryString_2 | null name?: fileConnectionNameQueryString_2 | null dev?: fileConnectionDevQueryInteger_2 | null mode?: fileConnectionModeQueryInteger_2 | null nlink?: fileConnectionNlinkQueryInteger_2 | null uid?: fileConnectionUidQueryInteger_2 | null gid?: fileConnectionGidQueryInteger_2 | null rdev?: fileConnectionRdevQueryInteger_2 | null blksize?: fileConnectionBlksizeQueryInteger_2 | null ino?: fileConnectionInoQueryInteger_2 | null blocks?: fileConnectionBlocksQueryInteger_2 | null atimeMs?: fileConnectionAtimeMsQueryInteger_2 | null mtimeMs?: fileConnectionMtimeMsQueryInteger_2 | null ctimeMs?: fileConnectionCtimeMsQueryInteger_2 | null birthtimeMs?: fileConnectionBirthtimeMsQueryInteger_2 | null atime?: fileConnectionAtimeQueryString_2 | null mtime?: fileConnectionMtimeQueryString_2 | null ctime?: fileConnectionCtimeQueryString_2 | null birthtime?: fileConnectionBirthtimeQueryString_2 | null } export interface fileConnectionIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionInternalInputObject_2 { contentDigest?: fileConnectionInternalContentDigestQueryString_2 | null mediaType?: fileConnectionInternalMediaTypeQueryString_2 | null type?: fileConnectionInternalTypeQueryString_2 | null owner?: fileConnectionInternalOwnerQueryString_2 | null } export interface fileConnectionInternalContentDigestQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionInternalMediaTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionInternalTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionInternalOwnerQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionSourceInstanceNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionAbsolutePathQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionRelativePathQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionExtensionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionSizeQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileConnectionPrettySizeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionModifiedTimeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionAccessTimeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionChangeTimeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionBirthTimeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionRootQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionDirQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionBaseQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionExtQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionDevQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileConnectionModeQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileConnectionNlinkQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileConnectionUidQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileConnectionGidQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileConnectionRdevQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileConnectionBlksizeQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileConnectionInoQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileConnectionBlocksQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileConnectionAtimeMsQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileConnectionMtimeMsQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileConnectionCtimeMsQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileConnectionBirthtimeMsQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileConnectionAtimeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionMtimeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionCtimeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileConnectionBirthtimeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkConnectionSort { fields: MarkdownRemarkConnectionSortByFieldsEnum[] order?: markdownRemarkConnectionSortOrderValues | null } /* Filter connection on its fields */ export interface filterMarkdownRemark { id?: markdownRemarkConnectionIdQueryString_2 | null internal?: markdownRemarkConnectionInternalInputObject_2 | null frontmatter?: markdownRemarkConnectionFrontmatterInputObject_2 | null fileAbsolutePath?: markdownRemarkConnectionFileAbsolutePathQueryString_2 | null fields?: markdownRemarkConnectionFieldsInputObject_2 | null html?: htmlQueryString_4 | null excerpt?: excerptQueryString_4 | null headings?: headingsQueryList_4 | null timeToRead?: timeToReadQueryInt_4 | null tableOfContents?: tableOfContentsQueryString_4 | null wordCount?: wordCountTypeName_4 | null } export interface markdownRemarkConnectionIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkConnectionInternalInputObject_2 { content?: markdownRemarkConnectionInternalContentQueryString_2 | null contentDigest?: markdownRemarkConnectionInternalContentDigestQueryString_2 | null type?: markdownRemarkConnectionInternalTypeQueryString_2 | null owner?: markdownRemarkConnectionInternalOwnerQueryString_2 | null fieldOwners?: markdownRemarkConnectionInternalFieldOwnersInputObject_2 | null } export interface markdownRemarkConnectionInternalContentQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkConnectionInternalContentDigestQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkConnectionInternalTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkConnectionInternalOwnerQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkConnectionInternalFieldOwnersInputObject_2 { slug?: markdownRemarkConnectionInternalFieldOwnersSlugQueryString_2 | null } export interface markdownRemarkConnectionInternalFieldOwnersSlugQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkConnectionFrontmatterInputObject_2 { title?: markdownRemarkConnectionFrontmatterTitleQueryString_2 | null layout?: markdownRemarkConnectionFrontmatterLayoutQueryString_2 | null permalink?: markdownRemarkConnectionFrontmatterPermalinkQueryString_2 | null _PARENT?: markdownRemarkConnectionFrontmatterParentQueryString_3 | null parent?: markdownRemarkConnectionFrontmatterParentQueryString_4 | null } export interface markdownRemarkConnectionFrontmatterTitleQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkConnectionFrontmatterLayoutQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkConnectionFrontmatterPermalinkQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkConnectionFrontmatterParentQueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkConnectionFrontmatterParentQueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkConnectionFileAbsolutePathQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkConnectionFieldsInputObject_2 { slug?: markdownRemarkConnectionFieldsSlugQueryString_2 | null } export interface markdownRemarkConnectionFieldsSlugQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface htmlQueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface excerptQueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface headingsQueryList_4 { value?: headingsListElemValueQueryString_4 | null depth?: headingsListElemDepthQueryInt_4 | null in?: markdownHeadingInputObject_4[] | null } export interface headingsListElemValueQueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface headingsListElemDepthQueryInt_4 { eq?: number | null ne?: number | null } export interface markdownHeadingInputObject_4 { value?: string | null depth?: number | null } export interface timeToReadQueryInt_4 { eq?: number | null ne?: number | null } export interface tableOfContentsQueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface wordCountTypeName_4 { paragraphs?: wordCountParagraphsQueryInt_4 | null sentences?: wordCountSentencesQueryInt_4 | null words?: wordCountWordsQueryInt_4 | null } export interface wordCountParagraphsQueryInt_4 { eq?: number | null ne?: number | null } export interface wordCountSentencesQueryInt_4 { eq?: number | null ne?: number | null } export interface wordCountWordsQueryInt_4 { eq?: number | null ne?: number | null } export interface contentfulBlogPostBodyTextNodeConnectionSort { fields: contentfulBlogPostBodyTextNodeConnectionSortByFieldsEnum[] order?: contentfulBlogPostBodyTextNodeConnectionSortOrderValues | null } /* Filter connection on its fields */ export interface filterContentfulBlogPostBodyTextNode { id?: contentfulBlogPostBodyTextNodeConnectionIdQueryString_2 | null body?: contentfulBlogPostBodyTextNodeConnectionBodyQueryString_2 | null internal?: contentfulBlogPostBodyTextNodeConnectionInternalInputObject_2 | null } export interface contentfulBlogPostBodyTextNodeConnectionIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostBodyTextNodeConnectionBodyQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostBodyTextNodeConnectionInternalInputObject_2 { type?: contentfulBlogPostBodyTextNodeConnectionInternalTypeQueryString_2 | null mediaType?: contentfulBlogPostBodyTextNodeConnectionInternalMediaTypeQueryString_2 | null content?: contentfulBlogPostBodyTextNodeConnectionInternalContentQueryString_2 | null contentDigest?: contentfulBlogPostBodyTextNodeConnectionInternalContentDigestQueryString_2 | null owner?: contentfulBlogPostBodyTextNodeConnectionInternalOwnerQueryString_2 | null } export interface contentfulBlogPostBodyTextNodeConnectionInternalTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostBodyTextNodeConnectionInternalMediaTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostBodyTextNodeConnectionInternalContentQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostBodyTextNodeConnectionInternalContentDigestQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostBodyTextNodeConnectionInternalOwnerQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulContentTypeConnectionSort { fields: ContentfulContentTypeConnectionSortByFieldsEnum[] order?: contentfulContentTypeConnectionSortOrderValues | null } /* Filter connection on its fields */ export interface filterContentfulContentType { id?: contentfulContentTypeConnectionIdQueryString_2 | null name?: contentfulContentTypeConnectionNameQueryString_2 | null displayField?: contentfulContentTypeConnectionDisplayFieldQueryString_2 | null description?: contentfulContentTypeConnectionDescriptionQueryString_2 | null internal?: contentfulContentTypeConnectionInternalInputObject_2 | null } export interface contentfulContentTypeConnectionIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulContentTypeConnectionNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulContentTypeConnectionDisplayFieldQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulContentTypeConnectionDescriptionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulContentTypeConnectionInternalInputObject_2 { type?: contentfulContentTypeConnectionInternalTypeQueryString_2 | null contentDigest?: contentfulContentTypeConnectionInternalContentDigestQueryString_2 | null owner?: contentfulContentTypeConnectionInternalOwnerQueryString_2 | null } export interface contentfulContentTypeConnectionInternalTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulContentTypeConnectionInternalContentDigestQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulContentTypeConnectionInternalOwnerQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostConnectionSort { fields: ContentfulBlogPostConnectionSortByFieldsEnum[] order?: contentfulBlogPostConnectionSortOrderValues | null } /* Filter connection on its fields */ export interface filterContentfulBlogPost { title?: contentfulBlogPostConnectionTitleQueryString_2 | null slug?: contentfulBlogPostConnectionSlugQueryString_2 | null publishDate?: contentfulBlogPostConnectionPublishDateQueryString_2 | null author?: contentfulBlogPostConnectionAuthorQueryString_2 | null tags?: contentfulBlogPostConnectionTagsQueryList_2 | null id?: contentfulBlogPostConnectionIdQueryString_2 | null createdAt?: contentfulBlogPostConnectionCreatedAtQueryString_2 | null updatedAt?: contentfulBlogPostConnectionUpdatedAtQueryString_2 | null internal?: contentfulBlogPostConnectionInternalInputObject_2 | null node_locale?: contentfulBlogPostConnectionNodeLocaleQueryString_2 | null } export interface contentfulBlogPostConnectionTitleQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostConnectionSlugQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostConnectionPublishDateQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostConnectionAuthorQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostConnectionTagsQueryList_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null in?: string[] | null } export interface contentfulBlogPostConnectionIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostConnectionCreatedAtQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostConnectionUpdatedAtQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostConnectionInternalInputObject_2 { type?: contentfulBlogPostConnectionInternalTypeQueryString_2 | null contentDigest?: contentfulBlogPostConnectionInternalContentDigestQueryString_2 | null owner?: contentfulBlogPostConnectionInternalOwnerQueryString_2 | null } export interface contentfulBlogPostConnectionInternalTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostConnectionInternalContentDigestQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostConnectionInternalOwnerQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostConnectionNodeLocaleQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetConnectionSort { fields: ContentfulAssetConnectionSortByFieldsEnum[] order?: contentfulAssetConnectionSortOrderValues | null } /* Filter connection on its fields */ export interface filterContentfulAsset { id?: contentfulAssetConnectionIdQueryString_2 | null file?: contentfulAssetConnectionFileInputObject_2 | null title?: contentfulAssetConnectionTitleQueryString_2 | null description?: contentfulAssetConnectionDescriptionQueryString_2 | null node_locale?: contentfulAssetConnectionNodeLocaleQueryString_2 | null internal?: contentfulAssetConnectionInternalInputObject_2 | null resolutions?: resolutionsTypeName_4 | null sizes?: sizesTypeName_4 | null responsiveResolution?: responsiveResolutionTypeName_4 | null responsiveSizes?: responsiveSizesTypeName_4 | null resize?: resizeTypeName_4 | null } export interface contentfulAssetConnectionIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetConnectionFileInputObject_2 { url?: contentfulAssetConnectionFileUrlQueryString_2 | null details?: contentfulAssetConnectionFileDetailsInputObject_2 | null fileName?: contentfulAssetConnectionFileFileNameQueryString_2 | null contentType?: contentfulAssetConnectionFileContentTypeQueryString_2 | null } export interface contentfulAssetConnectionFileUrlQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetConnectionFileDetailsInputObject_2 { size?: contentfulAssetConnectionFileDetailsSizeQueryInteger_2 | null image?: contentfulAssetConnectionFileDetailsImageInputObject_2 | null } export interface contentfulAssetConnectionFileDetailsSizeQueryInteger_2 { eq?: number | null ne?: number | null } export interface contentfulAssetConnectionFileDetailsImageInputObject_2 { width?: contentfulAssetConnectionFileDetailsImageWidthQueryInteger_2 | null height?: contentfulAssetConnectionFileDetailsImageHeightQueryInteger_2 | null } export interface contentfulAssetConnectionFileDetailsImageWidthQueryInteger_2 { eq?: number | null ne?: number | null } export interface contentfulAssetConnectionFileDetailsImageHeightQueryInteger_2 { eq?: number | null ne?: number | null } export interface contentfulAssetConnectionFileFileNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetConnectionFileContentTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetConnectionTitleQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetConnectionDescriptionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetConnectionNodeLocaleQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetConnectionInternalInputObject_2 { type?: contentfulAssetConnectionInternalTypeQueryString_2 | null contentDigest?: contentfulAssetConnectionInternalContentDigestQueryString_2 | null owner?: contentfulAssetConnectionInternalOwnerQueryString_2 | null } export interface contentfulAssetConnectionInternalTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetConnectionInternalContentDigestQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetConnectionInternalOwnerQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface resolutionsTypeName_4 { base64?: resolutionsBase64QueryString_4 | null aspectRatio?: resolutionsAspectRatioQueryFloat_4 | null width?: resolutionsWidthQueryFloat_4 | null height?: resolutionsHeightQueryFloat_4 | null src?: resolutionsSrcQueryString_4 | null srcSet?: resolutionsSrcSetQueryString_4 | null } export interface resolutionsBase64QueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface resolutionsAspectRatioQueryFloat_4 { eq?: number | null ne?: number | null } export interface resolutionsWidthQueryFloat_4 { eq?: number | null ne?: number | null } export interface resolutionsHeightQueryFloat_4 { eq?: number | null ne?: number | null } export interface resolutionsSrcQueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface resolutionsSrcSetQueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sizesTypeName_4 { base64?: sizesBase64QueryString_4 | null aspectRatio?: sizesAspectRatioQueryFloat_4 | null src?: sizesSrcQueryString_4 | null srcSet?: sizesSrcSetQueryString_4 | null sizes?: sizesSizesQueryString_4 | null } export interface sizesBase64QueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sizesAspectRatioQueryFloat_4 { eq?: number | null ne?: number | null } export interface sizesSrcQueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sizesSrcSetQueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sizesSizesQueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface responsiveResolutionTypeName_4 { base64?: responsiveResolutionBase64QueryString_4 | null aspectRatio?: responsiveResolutionAspectRatioQueryFloat_4 | null width?: responsiveResolutionWidthQueryFloat_4 | null height?: responsiveResolutionHeightQueryFloat_4 | null src?: responsiveResolutionSrcQueryString_4 | null srcSet?: responsiveResolutionSrcSetQueryString_4 | null } export interface responsiveResolutionBase64QueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface responsiveResolutionAspectRatioQueryFloat_4 { eq?: number | null ne?: number | null } export interface responsiveResolutionWidthQueryFloat_4 { eq?: number | null ne?: number | null } export interface responsiveResolutionHeightQueryFloat_4 { eq?: number | null ne?: number | null } export interface responsiveResolutionSrcQueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface responsiveResolutionSrcSetQueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface responsiveSizesTypeName_4 { base64?: responsiveSizesBase64QueryString_4 | null aspectRatio?: responsiveSizesAspectRatioQueryFloat_4 | null src?: responsiveSizesSrcQueryString_4 | null srcSet?: responsiveSizesSrcSetQueryString_4 | null sizes?: responsiveSizesSizesQueryString_4 | null } export interface responsiveSizesBase64QueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface responsiveSizesAspectRatioQueryFloat_4 { eq?: number | null ne?: number | null } export interface responsiveSizesSrcQueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface responsiveSizesSrcSetQueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface responsiveSizesSizesQueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface resizeTypeName_4 { src?: resizeSrcQueryString_4 | null width?: resizeWidthQueryInt_4 | null height?: resizeHeightQueryInt_4 | null aspectRatio?: resizeAspectRatioQueryFloat_4 | null } export interface resizeSrcQueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface resizeWidthQueryInt_4 { eq?: number | null ne?: number | null } export interface resizeHeightQueryInt_4 { eq?: number | null ne?: number | null } export interface resizeAspectRatioQueryFloat_4 { eq?: number | null ne?: number | null } export interface sitePageLayoutQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageJsonNameQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageInternalComponentNameQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePagePathQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageComponentQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageComponentChunkNameQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageContextInputObject { path?: sitePageContextPathQueryString | null fileSlug?: sitePageContextFileSlugQueryString | null id?: sitePageContextIdQueryString | null } export interface sitePageContextPathQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageContextFileSlugQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageContextIdQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageUpdatedAtQueryInteger { eq?: number | null ne?: number | null } export interface sitePagePluginCreatorIdQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageComponentPathQueryString { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageInternalInputObject_2 { type?: sitePageInternalTypeQueryString_2 | null contentDigest?: sitePageInternalContentDigestQueryString_2 | null owner?: sitePageInternalOwnerQueryString_2 | null } export interface sitePageInternalTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageInternalContentDigestQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePageInternalOwnerQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginResolveQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginVersionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPluginOptionsInputObject_2 { plugins?: sitePluginPluginOptionsPluginsQueryList_2 | null name?: sitePluginPluginOptionsNameQueryString_2 | null path?: sitePluginPluginOptionsPathQueryString_2 | null spaceId?: sitePluginPluginOptionsSpaceIdQueryString_2 | null accessToken?: sitePluginPluginOptionsAccessTokenQueryString_2 | null query?: sitePluginPluginOptionsQueryQueryString_2 | null feeds?: sitePluginPluginOptionsFeedsQueryList_2 | null } export interface sitePluginPluginOptionsPluginsQueryList_2 { in?: sitePluginPluginOptionsPluginsInputObject_2[] | null } export interface sitePluginPluginOptionsPluginsInputObject_2 { resolve?: sitePluginPluginOptionsPluginsResolveQueryString_2 | null id?: sitePluginPluginOptionsPluginsIdQueryString_2 | null name?: sitePluginPluginOptionsPluginsNameQueryString_2 | null version?: sitePluginPluginOptionsPluginsVersionQueryString_2 | null pluginFilepath?: sitePluginPluginOptionsPluginsPluginFilepathQueryString_2 | null } export interface sitePluginPluginOptionsPluginsResolveQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPluginOptionsPluginsIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPluginOptionsPluginsNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPluginOptionsPluginsVersionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPluginOptionsPluginsPluginFilepathQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPluginOptionsNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPluginOptionsPathQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPluginOptionsSpaceIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPluginOptionsAccessTokenQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPluginOptionsQueryQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPluginOptionsFeedsQueryList_2 { in?: sitePluginPluginOptionsFeedsInputObject_2[] | null } export interface sitePluginPluginOptionsFeedsInputObject_2 { query?: sitePluginPluginOptionsFeedsQueryQueryString_2 | null output?: sitePluginPluginOptionsFeedsOutputQueryString_2 | null } export interface sitePluginPluginOptionsFeedsQueryQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPluginOptionsFeedsOutputQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginNodeApIsQueryList_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null in?: string[] | null } export interface sitePluginPluginFilepathQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPackageJsonInputObject_2 { name?: sitePluginPackageJsonNameQueryString_2 | null description?: sitePluginPackageJsonDescriptionQueryString_2 | null version?: sitePluginPackageJsonVersionQueryString_2 | null main?: sitePluginPackageJsonMainQueryString_2 | null keywords?: sitePluginPackageJsonKeywordsQueryList_2 | null author?: sitePluginPackageJsonAuthorQueryString_2 | null license?: sitePluginPackageJsonLicenseQueryString_2 | null dependencies?: sitePluginPackageJsonDependenciesQueryList_2 | null devDependencies?: sitePluginPackageJsonDevDependenciesQueryList_2 | null } export interface sitePluginPackageJsonNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPackageJsonDescriptionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPackageJsonVersionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPackageJsonMainQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPackageJsonKeywordsQueryList_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null in?: string[] | null } export interface sitePluginPackageJsonAuthorQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPackageJsonLicenseQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPackageJsonDependenciesQueryList_2 { in?: sitePluginPackageJsonDependenciesInputObject_2[] | null } export interface sitePluginPackageJsonDependenciesInputObject_2 { name?: sitePluginPackageJsonDependenciesNameQueryString_2 | null version?: sitePluginPackageJsonDependenciesVersionQueryString_2 | null } export interface sitePluginPackageJsonDependenciesNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPackageJsonDependenciesVersionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPackageJsonDevDependenciesQueryList_2 { in?: sitePluginPackageJsonDevDependenciesInputObject_2[] | null } export interface sitePluginPackageJsonDevDependenciesInputObject_2 { name?: sitePluginPackageJsonDevDependenciesNameQueryString_2 | null version?: sitePluginPackageJsonDevDependenciesVersionQueryString_2 | null } export interface sitePluginPackageJsonDevDependenciesNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginPackageJsonDevDependenciesVersionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginInternalInputObject_2 { contentDigest?: sitePluginInternalContentDigestQueryString_2 | null type?: sitePluginInternalTypeQueryString_2 | null owner?: sitePluginInternalOwnerQueryString_2 | null } export interface sitePluginInternalContentDigestQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginInternalTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePluginInternalOwnerQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface siteSiteMetadataInputObject_2 { title?: siteSiteMetadataTitleQueryString_2 | null description?: siteSiteMetadataDescriptionQueryString_2 | null siteUrl?: siteSiteMetadataSiteUrlQueryString_2 | null } export interface siteSiteMetadataTitleQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface siteSiteMetadataDescriptionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface siteSiteMetadataSiteUrlQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePortQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface siteHostQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePathPrefixQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sitePolyfillQueryBoolean_2 { eq?: boolean | null ne?: boolean | null } export interface siteBuildTimeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface siteIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface siteInternalInputObject_2 { contentDigest?: siteInternalContentDigestQueryString_2 | null type?: siteInternalTypeQueryString_2 | null owner?: siteInternalOwnerQueryString_2 | null } export interface siteInternalContentDigestQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface siteInternalTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface siteInternalOwnerQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileInternalInputObject_2 { contentDigest?: fileInternalContentDigestQueryString_2 | null mediaType?: fileInternalMediaTypeQueryString_2 | null type?: fileInternalTypeQueryString_2 | null owner?: fileInternalOwnerQueryString_2 | null } export interface fileInternalContentDigestQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileInternalMediaTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileInternalTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileInternalOwnerQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileSourceInstanceNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileAbsolutePathQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileRelativePathQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileExtensionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileSizeQueryInteger_2 { eq?: number | null ne?: number | null } export interface filePrettySizeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileModifiedTimeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileAccessTimeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileChangeTimeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileBirthTimeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileRootQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileDirQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileBaseQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileExtQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileDevQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileModeQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileNlinkQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileUidQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileGidQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileRdevQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileBlksizeQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileInoQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileBlocksQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileAtimeMsQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileMtimeMsQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileCtimeMsQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileBirthtimeMsQueryInteger_2 { eq?: number | null ne?: number | null } export interface fileAtimeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileMtimeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileCtimeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface fileBirthtimeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkInternalInputObject_2 { content?: markdownRemarkInternalContentQueryString_2 | null contentDigest?: markdownRemarkInternalContentDigestQueryString_2 | null type?: markdownRemarkInternalTypeQueryString_2 | null owner?: markdownRemarkInternalOwnerQueryString_2 | null fieldOwners?: markdownRemarkInternalFieldOwnersInputObject_2 | null } export interface markdownRemarkInternalContentQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkInternalContentDigestQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkInternalTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkInternalOwnerQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkInternalFieldOwnersInputObject_2 { slug?: markdownRemarkInternalFieldOwnersSlugQueryString_2 | null } export interface markdownRemarkInternalFieldOwnersSlugQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkFrontmatterInputObject_2 { title?: markdownRemarkFrontmatterTitleQueryString_2 | null layout?: markdownRemarkFrontmatterLayoutQueryString_2 | null permalink?: markdownRemarkFrontmatterPermalinkQueryString_2 | null _PARENT?: markdownRemarkFrontmatterParentQueryString_3 | null parent?: markdownRemarkFrontmatterParentQueryString_4 | null } export interface markdownRemarkFrontmatterTitleQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkFrontmatterLayoutQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkFrontmatterPermalinkQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkFrontmatterParentQueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkFrontmatterParentQueryString_4 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkFileAbsolutePathQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface markdownRemarkFieldsInputObject_2 { slug?: markdownRemarkFieldsSlugQueryString_2 | null } export interface markdownRemarkFieldsSlugQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface htmlQueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface excerptQueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface headingsQueryList_3 { value?: headingsListElemValueQueryString_3 | null depth?: headingsListElemDepthQueryInt_3 | null in?: markdownHeadingInputObject_3[] | null } export interface headingsListElemValueQueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface headingsListElemDepthQueryInt_3 { eq?: number | null ne?: number | null } export interface markdownHeadingInputObject_3 { value?: string | null depth?: number | null } export interface timeToReadQueryInt_3 { eq?: number | null ne?: number | null } export interface tableOfContentsQueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface wordCountTypeName_3 { paragraphs?: wordCountParagraphsQueryInt_3 | null sentences?: wordCountSentencesQueryInt_3 | null words?: wordCountWordsQueryInt_3 | null } export interface wordCountParagraphsQueryInt_3 { eq?: number | null ne?: number | null } export interface wordCountSentencesQueryInt_3 { eq?: number | null ne?: number | null } export interface wordCountWordsQueryInt_3 { eq?: number | null ne?: number | null } export interface contentfulBlogPostBodyTextNodeIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostBodyTextNodeBodyQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostBodyTextNodeInternalInputObject_2 { type?: contentfulBlogPostBodyTextNodeInternalTypeQueryString_2 | null mediaType?: contentfulBlogPostBodyTextNodeInternalMediaTypeQueryString_2 | null content?: contentfulBlogPostBodyTextNodeInternalContentQueryString_2 | null contentDigest?: contentfulBlogPostBodyTextNodeInternalContentDigestQueryString_2 | null owner?: contentfulBlogPostBodyTextNodeInternalOwnerQueryString_2 | null } export interface contentfulBlogPostBodyTextNodeInternalTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostBodyTextNodeInternalMediaTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostBodyTextNodeInternalContentQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostBodyTextNodeInternalContentDigestQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostBodyTextNodeInternalOwnerQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulContentTypeIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulContentTypeNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulContentTypeDisplayFieldQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulContentTypeDescriptionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulContentTypeInternalInputObject_2 { type?: contentfulContentTypeInternalTypeQueryString_2 | null contentDigest?: contentfulContentTypeInternalContentDigestQueryString_2 | null owner?: contentfulContentTypeInternalOwnerQueryString_2 | null } export interface contentfulContentTypeInternalTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulContentTypeInternalContentDigestQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulContentTypeInternalOwnerQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostTitleQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostSlugQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostPublishDateQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostAuthorQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostTagsQueryList_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null in?: string[] | null } export interface contentfulBlogPostIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostCreatedAtQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostUpdatedAtQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostInternalInputObject_2 { type?: contentfulBlogPostInternalTypeQueryString_2 | null contentDigest?: contentfulBlogPostInternalContentDigestQueryString_2 | null owner?: contentfulBlogPostInternalOwnerQueryString_2 | null } export interface contentfulBlogPostInternalTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostInternalContentDigestQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostInternalOwnerQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulBlogPostNodeLocaleQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetIdQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetFileInputObject_2 { url?: contentfulAssetFileUrlQueryString_2 | null details?: contentfulAssetFileDetailsInputObject_2 | null fileName?: contentfulAssetFileFileNameQueryString_2 | null contentType?: contentfulAssetFileContentTypeQueryString_2 | null } export interface contentfulAssetFileUrlQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetFileDetailsInputObject_2 { size?: contentfulAssetFileDetailsSizeQueryInteger_2 | null image?: contentfulAssetFileDetailsImageInputObject_2 | null } export interface contentfulAssetFileDetailsSizeQueryInteger_2 { eq?: number | null ne?: number | null } export interface contentfulAssetFileDetailsImageInputObject_2 { width?: contentfulAssetFileDetailsImageWidthQueryInteger_2 | null height?: contentfulAssetFileDetailsImageHeightQueryInteger_2 | null } export interface contentfulAssetFileDetailsImageWidthQueryInteger_2 { eq?: number | null ne?: number | null } export interface contentfulAssetFileDetailsImageHeightQueryInteger_2 { eq?: number | null ne?: number | null } export interface contentfulAssetFileFileNameQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetFileContentTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetTitleQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetDescriptionQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetNodeLocaleQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetInternalInputObject_2 { type?: contentfulAssetInternalTypeQueryString_2 | null contentDigest?: contentfulAssetInternalContentDigestQueryString_2 | null owner?: contentfulAssetInternalOwnerQueryString_2 | null } export interface contentfulAssetInternalTypeQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetInternalContentDigestQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface contentfulAssetInternalOwnerQueryString_2 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface resolutionsTypeName_3 { base64?: resolutionsBase64QueryString_3 | null aspectRatio?: resolutionsAspectRatioQueryFloat_3 | null width?: resolutionsWidthQueryFloat_3 | null height?: resolutionsHeightQueryFloat_3 | null src?: resolutionsSrcQueryString_3 | null srcSet?: resolutionsSrcSetQueryString_3 | null } export interface resolutionsBase64QueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface resolutionsAspectRatioQueryFloat_3 { eq?: number | null ne?: number | null } export interface resolutionsWidthQueryFloat_3 { eq?: number | null ne?: number | null } export interface resolutionsHeightQueryFloat_3 { eq?: number | null ne?: number | null } export interface resolutionsSrcQueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface resolutionsSrcSetQueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sizesTypeName_3 { base64?: sizesBase64QueryString_3 | null aspectRatio?: sizesAspectRatioQueryFloat_3 | null src?: sizesSrcQueryString_3 | null srcSet?: sizesSrcSetQueryString_3 | null sizes?: sizesSizesQueryString_3 | null } export interface sizesBase64QueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sizesAspectRatioQueryFloat_3 { eq?: number | null ne?: number | null } export interface sizesSrcQueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sizesSrcSetQueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface sizesSizesQueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface responsiveResolutionTypeName_3 { base64?: responsiveResolutionBase64QueryString_3 | null aspectRatio?: responsiveResolutionAspectRatioQueryFloat_3 | null width?: responsiveResolutionWidthQueryFloat_3 | null height?: responsiveResolutionHeightQueryFloat_3 | null src?: responsiveResolutionSrcQueryString_3 | null srcSet?: responsiveResolutionSrcSetQueryString_3 | null } export interface responsiveResolutionBase64QueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface responsiveResolutionAspectRatioQueryFloat_3 { eq?: number | null ne?: number | null } export interface responsiveResolutionWidthQueryFloat_3 { eq?: number | null ne?: number | null } export interface responsiveResolutionHeightQueryFloat_3 { eq?: number | null ne?: number | null } export interface responsiveResolutionSrcQueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface responsiveResolutionSrcSetQueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface responsiveSizesTypeName_3 { base64?: responsiveSizesBase64QueryString_3 | null aspectRatio?: responsiveSizesAspectRatioQueryFloat_3 | null src?: responsiveSizesSrcQueryString_3 | null srcSet?: responsiveSizesSrcSetQueryString_3 | null sizes?: responsiveSizesSizesQueryString_3 | null } export interface responsiveSizesBase64QueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface responsiveSizesAspectRatioQueryFloat_3 { eq?: number | null ne?: number | null } export interface responsiveSizesSrcQueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface responsiveSizesSrcSetQueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface responsiveSizesSizesQueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface resizeTypeName_3 { src?: resizeSrcQueryString_3 | null width?: resizeWidthQueryInt_3 | null height?: resizeHeightQueryInt_3 | null aspectRatio?: resizeAspectRatioQueryFloat_3 | null } export interface resizeSrcQueryString_3 { eq?: string | null ne?: string | null regex?: string | null glob?: string | null } export interface resizeWidthQueryInt_3 { eq?: number | null ne?: number | null } export interface resizeHeightQueryInt_3 { eq?: number | null ne?: number | null } export interface resizeAspectRatioQueryFloat_3 { eq?: number | null ne?: number | null } export interface AllSitePageRootQueryTypeArgs { skip?: number | null limit?: number | null sort?: sitePageConnectionSort | null filter?: filterSitePage | null } export interface AllSitePluginRootQueryTypeArgs { skip?: number | null limit?: number | null sort?: sitePluginConnectionSort | null filter?: filterSitePlugin | null } export interface AllFileRootQueryTypeArgs { skip?: number | null limit?: number | null sort?: fileConnectionSort | null filter?: filterFile | null } export interface AllMarkdownRemarkRootQueryTypeArgs { skip?: number | null limit?: number | null sort?: markdownRemarkConnectionSort | null filter?: filterMarkdownRemark | null } export interface AllContentfulBlogPostBodyTextNodeRootQueryTypeArgs { skip?: number | null limit?: number | null sort?: contentfulBlogPostBodyTextNodeConnectionSort | null filter?: filterContentfulBlogPostBodyTextNode | null } export interface AllContentfulContentTypeRootQueryTypeArgs { skip?: number | null limit?: number | null sort?: contentfulContentTypeConnectionSort | null filter?: filterContentfulContentType | null } export interface AllContentfulBlogPostRootQueryTypeArgs { skip?: number | null limit?: number | null sort?: contentfulBlogPostConnectionSort | null filter?: filterContentfulBlogPost | null } export interface AllContentfulAssetRootQueryTypeArgs { skip?: number | null limit?: number | null sort?: contentfulAssetConnectionSort | null filter?: filterContentfulAsset | null } export interface SitePageRootQueryTypeArgs { layout?: sitePageLayoutQueryString | null jsonName?: sitePageJsonNameQueryString | null internalComponentName?: sitePageInternalComponentNameQueryString | null path?: sitePagePathQueryString_2 | null component?: sitePageComponentQueryString | null componentChunkName?: sitePageComponentChunkNameQueryString | null context?: sitePageContextInputObject | null updatedAt?: sitePageUpdatedAtQueryInteger | null pluginCreatorId?: sitePagePluginCreatorIdQueryString | null componentPath?: sitePageComponentPathQueryString | null id?: sitePageIdQueryString_2 | null internal?: sitePageInternalInputObject_2 | null } export interface SitePluginRootQueryTypeArgs { resolve?: sitePluginResolveQueryString_2 | null id?: sitePluginIdQueryString_2 | null name?: sitePluginNameQueryString_2 | null version?: sitePluginVersionQueryString_2 | null pluginOptions?: sitePluginPluginOptionsInputObject_2 | null nodeAPIs?: sitePluginNodeApIsQueryList_2 | null pluginFilepath?: sitePluginPluginFilepathQueryString_2 | null packageJson?: sitePluginPackageJsonInputObject_2 | null internal?: sitePluginInternalInputObject_2 | null } export interface SiteRootQueryTypeArgs { siteMetadata?: siteSiteMetadataInputObject_2 | null port?: sitePortQueryString_2 | null host?: siteHostQueryString_2 | null pathPrefix?: sitePathPrefixQueryString_2 | null polyfill?: sitePolyfillQueryBoolean_2 | null buildTime?: siteBuildTimeQueryString_2 | null id?: siteIdQueryString_2 | null internal?: siteInternalInputObject_2 | null } export interface FileRootQueryTypeArgs { id?: fileIdQueryString_2 | null internal?: fileInternalInputObject_2 | null sourceInstanceName?: fileSourceInstanceNameQueryString_2 | null absolutePath?: fileAbsolutePathQueryString_2 | null relativePath?: fileRelativePathQueryString_2 | null extension?: fileExtensionQueryString_2 | null size?: fileSizeQueryInteger_2 | null prettySize?: filePrettySizeQueryString_2 | null modifiedTime?: fileModifiedTimeQueryString_2 | null accessTime?: fileAccessTimeQueryString_2 | null changeTime?: fileChangeTimeQueryString_2 | null birthTime?: fileBirthTimeQueryString_2 | null root?: fileRootQueryString_2 | null dir?: fileDirQueryString_2 | null base?: fileBaseQueryString_2 | null ext?: fileExtQueryString_2 | null name?: fileNameQueryString_2 | null dev?: fileDevQueryInteger_2 | null mode?: fileModeQueryInteger_2 | null nlink?: fileNlinkQueryInteger_2 | null uid?: fileUidQueryInteger_2 | null gid?: fileGidQueryInteger_2 | null rdev?: fileRdevQueryInteger_2 | null blksize?: fileBlksizeQueryInteger_2 | null ino?: fileInoQueryInteger_2 | null blocks?: fileBlocksQueryInteger_2 | null atimeMs?: fileAtimeMsQueryInteger_2 | null mtimeMs?: fileMtimeMsQueryInteger_2 | null ctimeMs?: fileCtimeMsQueryInteger_2 | null birthtimeMs?: fileBirthtimeMsQueryInteger_2 | null atime?: fileAtimeQueryString_2 | null mtime?: fileMtimeQueryString_2 | null ctime?: fileCtimeQueryString_2 | null birthtime?: fileBirthtimeQueryString_2 | null } export interface MarkdownRemarkRootQueryTypeArgs { id?: markdownRemarkIdQueryString_2 | null internal?: markdownRemarkInternalInputObject_2 | null frontmatter?: markdownRemarkFrontmatterInputObject_2 | null fileAbsolutePath?: markdownRemarkFileAbsolutePathQueryString_2 | null fields?: markdownRemarkFieldsInputObject_2 | null html?: htmlQueryString_3 | null excerpt?: excerptQueryString_3 | null headings?: headingsQueryList_3 | null timeToRead?: timeToReadQueryInt_3 | null tableOfContents?: tableOfContentsQueryString_3 | null wordCount?: wordCountTypeName_3 | null } export interface ContentfulBlogPostBodyTextNodeRootQueryTypeArgs { id?: contentfulBlogPostBodyTextNodeIdQueryString_2 | null body?: contentfulBlogPostBodyTextNodeBodyQueryString_2 | null internal?: contentfulBlogPostBodyTextNodeInternalInputObject_2 | null } export interface ContentfulContentTypeRootQueryTypeArgs { id?: contentfulContentTypeIdQueryString_2 | null name?: contentfulContentTypeNameQueryString_2 | null displayField?: contentfulContentTypeDisplayFieldQueryString_2 | null description?: contentfulContentTypeDescriptionQueryString_2 | null internal?: contentfulContentTypeInternalInputObject_2 | null } export interface ContentfulBlogPostRootQueryTypeArgs { title?: contentfulBlogPostTitleQueryString_2 | null slug?: contentfulBlogPostSlugQueryString_2 | null publishDate?: contentfulBlogPostPublishDateQueryString_2 | null author?: contentfulBlogPostAuthorQueryString_2 | null tags?: contentfulBlogPostTagsQueryList_2 | null id?: contentfulBlogPostIdQueryString_2 | null createdAt?: contentfulBlogPostCreatedAtQueryString_2 | null updatedAt?: contentfulBlogPostUpdatedAtQueryString_2 | null internal?: contentfulBlogPostInternalInputObject_2 | null node_locale?: contentfulBlogPostNodeLocaleQueryString_2 | null } export interface ContentfulAssetRootQueryTypeArgs { id?: contentfulAssetIdQueryString_2 | null file?: contentfulAssetFileInputObject_2 | null title?: contentfulAssetTitleQueryString_2 | null description?: contentfulAssetDescriptionQueryString_2 | null node_locale?: contentfulAssetNodeLocaleQueryString_2 | null internal?: contentfulAssetInternalInputObject_2 | null resolutions?: resolutionsTypeName_3 | null sizes?: sizesTypeName_3 | null responsiveResolution?: responsiveResolutionTypeName_3 | null responsiveSizes?: responsiveSizesTypeName_3 | null resize?: resizeTypeName_3 | null } export interface DistinctSitePageConnectionArgs { field?: sitePageDistinctEnum | null } export interface GroupSitePageConnectionArgs { skip?: number | null limit?: number | null field?: sitePageGroupEnum | null } export interface DistinctSitePluginConnectionArgs { field?: sitePluginDistinctEnum | null } export interface GroupSitePluginConnectionArgs { skip?: number | null limit?: number | null field?: sitePluginGroupEnum | null } export interface DistinctFileConnectionArgs { field?: fileDistinctEnum | null } export interface GroupFileConnectionArgs { skip?: number | null limit?: number | null field?: fileGroupEnum | null } export interface SizeFileArgs { formatString?: string | null fromNow?: boolean | null /* Returns a string generated with Moment.js&#x27; fromNow function */ difference?: | string | null /* Returns the difference between this date and the current time. Defaults to miliseconds but you can also pass in as the measurement years, months, weeks, days, hours, minutes, and seconds. */ locale?: string | null /* Configures the locale Moment.js will use to format the date. */ } export interface ModifiedTimeFileArgs { formatString?: string | null fromNow?: boolean | null /* Returns a string generated with Moment.js&#x27; fromNow function */ difference?: | string | null /* Returns the difference between this date and the current time. Defaults to miliseconds but you can also pass in as the measurement years, months, weeks, days, hours, minutes, and seconds. */ locale?: string | null /* Configures the locale Moment.js will use to format the date. */ } export interface AccessTimeFileArgs { formatString?: string | null fromNow?: boolean | null /* Returns a string generated with Moment.js&#x27; fromNow function */ difference?: | string | null /* Returns the difference between this date and the current time. Defaults to miliseconds but you can also pass in as the measurement years, months, weeks, days, hours, minutes, and seconds. */ locale?: string | null /* Configures the locale Moment.js will use to format the date. */ } export interface ChangeTimeFileArgs { formatString?: string | null fromNow?: boolean | null /* Returns a string generated with Moment.js&#x27; fromNow function */ difference?: | string | null /* Returns the difference between this date and the current time. Defaults to miliseconds but you can also pass in as the measurement years, months, weeks, days, hours, minutes, and seconds. */ locale?: string | null /* Configures the locale Moment.js will use to format the date. */ } export interface BirthTimeFileArgs { formatString?: string | null fromNow?: boolean | null /* Returns a string generated with Moment.js&#x27; fromNow function */ difference?: | string | null /* Returns the difference between this date and the current time. Defaults to miliseconds but you can also pass in as the measurement years, months, weeks, days, hours, minutes, and seconds. */ locale?: string | null /* Configures the locale Moment.js will use to format the date. */ } export interface BlksizeFileArgs { formatString?: string | null fromNow?: boolean | null /* Returns a string generated with Moment.js&#x27; fromNow function */ difference?: | string | null /* Returns the difference between this date and the current time. Defaults to miliseconds but you can also pass in as the measurement years, months, weeks, days, hours, minutes, and seconds. */ locale?: string | null /* Configures the locale Moment.js will use to format the date. */ } export interface AtimeFileArgs { formatString?: string | null fromNow?: boolean | null /* Returns a string generated with Moment.js&#x27; fromNow function */ difference?: | string | null /* Returns the difference between this date and the current time. Defaults to miliseconds but you can also pass in as the measurement years, months, weeks, days, hours, minutes, and seconds. */ locale?: string | null /* Configures the locale Moment.js will use to format the date. */ } export interface MtimeFileArgs { formatString?: string | null fromNow?: boolean | null /* Returns a string generated with Moment.js&#x27; fromNow function */ difference?: | string | null /* Returns the difference between this date and the current time. Defaults to miliseconds but you can also pass in as the measurement years, months, weeks, days, hours, minutes, and seconds. */ locale?: string | null /* Configures the locale Moment.js will use to format the date. */ } export interface CtimeFileArgs { formatString?: string | null fromNow?: boolean | null /* Returns a string generated with Moment.js&#x27; fromNow function */ difference?: | string | null /* Returns the difference between this date and the current time. Defaults to miliseconds but you can also pass in as the measurement years, months, weeks, days, hours, minutes, and seconds. */ locale?: string | null /* Configures the locale Moment.js will use to format the date. */ } export interface BirthtimeFileArgs { formatString?: string | null fromNow?: boolean | null /* Returns a string generated with Moment.js&#x27; fromNow function */ difference?: | string | null /* Returns the difference between this date and the current time. Defaults to miliseconds but you can also pass in as the measurement years, months, weeks, days, hours, minutes, and seconds. */ locale?: string | null /* Configures the locale Moment.js will use to format the date. */ } export interface ExcerptMarkdownRemarkArgs { pruneLength?: number | null } export interface HeadingsMarkdownRemarkArgs { depth?: HeadingLevels | null } export interface DistinctMarkdownRemarkConnectionArgs { field?: markdownRemarkDistinctEnum | null } export interface GroupMarkdownRemarkConnectionArgs { skip?: number | null limit?: number | null field?: markdownRemarkGroupEnum | null } export interface DistinctContentfulBlogPostBodyTextNodeConnectionArgs { field?: contentfulBlogPostBodyTextNodeDistinctEnum | null } export interface GroupContentfulBlogPostBodyTextNodeConnectionArgs { skip?: number | null limit?: number | null field?: contentfulBlogPostBodyTextNodeGroupEnum | null } export interface DistinctContentfulContentTypeConnectionArgs { field?: contentfulContentTypeDistinctEnum | null } export interface GroupContentfulContentTypeConnectionArgs { skip?: number | null limit?: number | null field?: contentfulContentTypeGroupEnum | null } export interface DistinctContentfulBlogPostConnectionArgs { field?: contentfulBlogPostDistinctEnum | null } export interface GroupContentfulBlogPostConnectionArgs { skip?: number | null limit?: number | null field?: contentfulBlogPostGroupEnum | null } export interface PublishDateContentfulBlogPostArgs { formatString?: string | null fromNow?: boolean | null /* Returns a string generated with Moment.js&#x27; fromNow function */ difference?: | string | null /* Returns the difference between this date and the current time. Defaults to miliseconds but you can also pass in as the measurement years, months, weeks, days, hours, minutes, and seconds. */ locale?: string | null /* Configures the locale Moment.js will use to format the date. */ } export interface CreatedAtContentfulBlogPostArgs { formatString?: string | null fromNow?: boolean | null /* Returns a string generated with Moment.js&#x27; fromNow function */ difference?: | string | null /* Returns the difference between this date and the current time. Defaults to miliseconds but you can also pass in as the measurement years, months, weeks, days, hours, minutes, and seconds. */ locale?: string | null /* Configures the locale Moment.js will use to format the date. */ } export interface UpdatedAtContentfulBlogPostArgs { formatString?: string | null fromNow?: boolean | null /* Returns a string generated with Moment.js&#x27; fromNow function */ difference?: | string | null /* Returns the difference between this date and the current time. Defaults to miliseconds but you can also pass in as the measurement years, months, weeks, days, hours, minutes, and seconds. */ locale?: string | null /* Configures the locale Moment.js will use to format the date. */ } export interface ResolutionsContentfulAssetArgs { width?: number | null height?: number | null quality?: number | null toFormat?: ContentfulImageFormat | null resizingBehavior?: ImageResizingBehavior | null cropFocus?: ContentfulImageCropFocus | null } export interface SizesContentfulAssetArgs { maxWidth?: number | null maxHeight?: number | null quality?: number | null toFormat?: ContentfulImageFormat | null resizingBehavior?: ImageResizingBehavior | null cropFocus?: ContentfulImageCropFocus | null sizes?: string | null } export interface ResponsiveResolutionContentfulAssetArgs { width?: number | null height?: number | null quality?: number | null toFormat?: ContentfulImageFormat | null resizingBehavior?: ImageResizingBehavior | null cropFocus?: ContentfulImageCropFocus | null } export interface ResponsiveSizesContentfulAssetArgs { maxWidth?: number | null maxHeight?: number | null quality?: number | null toFormat?: ContentfulImageFormat | null resizingBehavior?: ImageResizingBehavior | null cropFocus?: ContentfulImageCropFocus | null sizes?: string | null } export interface ResizeContentfulAssetArgs { width?: number | null height?: number | null quality?: number | null jpegProgressive?: boolean | null resizingBehavior?: ImageResizingBehavior | null base64?: boolean | null toFormat?: ContentfulImageFormat | null cropFocus?: ContentfulImageCropFocus | null } export interface DistinctContentfulAssetConnectionArgs { field?: contentfulAssetDistinctEnum | null } export interface GroupContentfulAssetConnectionArgs { skip?: number | null limit?: number | null field?: contentfulAssetGroupEnum | null } export interface PortSiteArgs { formatString?: string | null fromNow?: boolean | null /* Returns a string generated with Moment.js&#x27; fromNow function */ difference?: | string | null /* Returns the difference between this date and the current time. Defaults to miliseconds but you can also pass in as the measurement years, months, weeks, days, hours, minutes, and seconds. */ locale?: string | null /* Configures the locale Moment.js will use to format the date. */ } export interface BuildTimeSiteArgs { formatString?: string | null fromNow?: boolean | null /* Returns a string generated with Moment.js&#x27; fromNow function */ difference?: | string | null /* Returns the difference between this date and the current time. Defaults to miliseconds but you can also pass in as the measurement years, months, weeks, days, hours, minutes, and seconds. */ locale?: string | null /* Configures the locale Moment.js will use to format the date. */ } export type SitePageConnectionSortByFieldsEnum = | 'layout' | 'jsonName' | 'internalComponentName' | 'path' | 'matchPath' | 'component' | 'componentChunkName' | 'context___path' | 'context___fileSlug' | 'context___id' | 'updatedAt' | 'pluginCreator___NODE' | 'pluginCreatorId' | 'componentPath' | 'id' | 'parent' | 'children' | 'internal___type' | 'internal___contentDigest' | 'internal___owner' export type sitePageConnectionSortOrderValues = 'ASC' | 'DESC' export type sitePageDistinctEnum = | 'layout' | 'jsonName' | 'internalComponentName' | 'path' | 'component' | 'componentChunkName' | 'context___path' | 'context___fileSlug' | 'context___id' | 'updatedAt' | 'pluginCreator___NODE' | 'pluginCreatorId' | 'componentPath' | 'id' | 'parent' | 'internal___type' | 'internal___contentDigest' | 'internal___owner' export type sitePageGroupEnum = | 'layout' | 'jsonName' | 'internalComponentName' | 'path' | 'component' | 'componentChunkName' | 'context___path' | 'context___fileSlug' | 'context___id' | 'updatedAt' | 'pluginCreator___NODE' | 'pluginCreatorId' | 'componentPath' | 'id' | 'parent' | 'internal___type' | 'internal___contentDigest' | 'internal___owner' export type SitePluginConnectionSortByFieldsEnum = | 'resolve' | 'id' | 'name' | 'version' | 'pluginOptions___plugins' | 'pluginOptions___name' | 'pluginOptions___path' | 'pluginOptions___spaceId' | 'pluginOptions___accessToken' | 'pluginOptions___query' | 'pluginOptions___feeds' | 'nodeAPIs' | 'pluginFilepath' | 'packageJson___name' | 'packageJson___description' | 'packageJson___version' | 'packageJson___main' | 'packageJson___keywords' | 'packageJson___author' | 'packageJson___license' | 'packageJson___dependencies' | 'packageJson___devDependencies' | 'packageJson___peerDependencies' | 'packageJson___optionalDependecies' | 'packageJson___bundledDependecies' | 'parent' | 'children' | 'internal___contentDigest' | 'internal___type' | 'internal___owner' export type sitePluginConnectionSortOrderValues = 'ASC' | 'DESC' export type sitePluginDistinctEnum = | 'resolve' | 'id' | 'name' | 'version' | 'pluginOptions___plugins' | 'pluginOptions___name' | 'pluginOptions___path' | 'pluginOptions___spaceId' | 'pluginOptions___accessToken' | 'pluginOptions___query' | 'pluginOptions___feeds' | 'nodeAPIs' | 'pluginFilepath' | 'packageJson___name' | 'packageJson___description' | 'packageJson___version' | 'packageJson___main' | 'packageJson___keywords' | 'packageJson___author' | 'packageJson___license' | 'packageJson___dependencies' | 'packageJson___devDependencies' | 'parent' | 'internal___contentDigest' | 'internal___type' | 'internal___owner' export type sitePluginGroupEnum = | 'resolve' | 'id' | 'name' | 'version' | 'pluginOptions___plugins' | 'pluginOptions___name' | 'pluginOptions___path' | 'pluginOptions___spaceId' | 'pluginOptions___accessToken' | 'pluginOptions___query' | 'pluginOptions___feeds' | 'nodeAPIs' | 'pluginFilepath' | 'packageJson___name' | 'packageJson___description' | 'packageJson___version' | 'packageJson___main' | 'packageJson___keywords' | 'packageJson___author' | 'packageJson___license' | 'packageJson___dependencies' | 'packageJson___devDependencies' | 'parent' | 'internal___contentDigest' | 'internal___type' | 'internal___owner' export type FileConnectionSortByFieldsEnum = | 'id' | 'children' | 'parent' | 'internal___contentDigest' | 'internal___mediaType' | 'internal___type' | 'internal___owner' | 'sourceInstanceName' | 'absolutePath' | 'relativePath' | 'extension' | 'size' | 'prettySize' | 'modifiedTime' | 'accessTime' | 'changeTime' | 'birthTime' | 'root' | 'dir' | 'base' | 'ext' | 'name' | 'dev' | 'mode' | 'nlink' | 'uid' | 'gid' | 'rdev' | 'blksize' | 'ino' | 'blocks' | 'atimeMs' | 'mtimeMs' | 'ctimeMs' | 'birthtimeMs' | 'atime' | 'mtime' | 'ctime' | 'birthtime' export type fileConnectionSortOrderValues = 'ASC' | 'DESC' export type HeadingLevels = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' export type fileDistinctEnum = | 'id' | 'children' | 'parent' | 'internal___contentDigest' | 'internal___mediaType' | 'internal___type' | 'internal___owner' | 'sourceInstanceName' | 'absolutePath' | 'relativePath' | 'extension' | 'size' | 'prettySize' | 'modifiedTime' | 'accessTime' | 'changeTime' | 'birthTime' | 'root' | 'dir' | 'base' | 'ext' | 'name' | 'dev' | 'mode' | 'nlink' | 'uid' | 'gid' | 'rdev' | 'blksize' | 'ino' | 'blocks' | 'atimeMs' | 'mtimeMs' | 'ctimeMs' | 'birthtimeMs' | 'atime' | 'mtime' | 'ctime' | 'birthtime' export type fileGroupEnum = | 'id' | 'children' | 'parent' | 'internal___contentDigest' | 'internal___mediaType' | 'internal___type' | 'internal___owner' | 'sourceInstanceName' | 'absolutePath' | 'relativePath' | 'extension' | 'size' | 'prettySize' | 'modifiedTime' | 'accessTime' | 'changeTime' | 'birthTime' | 'root' | 'dir' | 'base' | 'ext' | 'name' | 'dev' | 'mode' | 'nlink' | 'uid' | 'gid' | 'rdev' | 'blksize' | 'ino' | 'blocks' | 'atimeMs' | 'mtimeMs' | 'ctimeMs' | 'birthtimeMs' | 'atime' | 'mtime' | 'ctime' | 'birthtime' export type MarkdownRemarkConnectionSortByFieldsEnum = | 'id' | 'children' | 'parent' | 'internal___content' | 'internal___contentDigest' | 'internal___type' | 'internal___owner' | 'internal___fieldOwners___slug' | 'frontmatter___title' | 'frontmatter___layout' | 'frontmatter___permalink' | 'frontmatter____PARENT' | 'frontmatter___parent' | 'fileAbsolutePath' | 'fields___slug' | 'html' | 'excerpt' | 'headings' | 'timeToRead' | 'tableOfContents' | 'wordCount___paragraphs' | 'wordCount___sentences' | 'wordCount___words' export type markdownRemarkConnectionSortOrderValues = 'ASC' | 'DESC' export type markdownRemarkDistinctEnum = | 'id' | 'parent' | 'internal___content' | 'internal___contentDigest' | 'internal___type' | 'internal___owner' | 'internal___fieldOwners___slug' | 'frontmatter___title' | 'frontmatter___layout' | 'frontmatter___permalink' | 'frontmatter____PARENT' | 'frontmatter___parent' | 'fileAbsolutePath' | 'fields___slug' export type markdownRemarkGroupEnum = | 'id' | 'parent' | 'internal___content' | 'internal___contentDigest' | 'internal___type' | 'internal___owner' | 'internal___fieldOwners___slug' | 'frontmatter___title' | 'frontmatter___layout' | 'frontmatter___permalink' | 'frontmatter____PARENT' | 'frontmatter___parent' | 'fileAbsolutePath' | 'fields___slug' export type contentfulBlogPostBodyTextNodeConnectionSortByFieldsEnum = | 'id' | 'parent' | 'children' | 'body' | 'internal___type' | 'internal___mediaType' | 'internal___content' | 'internal___contentDigest' | 'internal___owner' export type contentfulBlogPostBodyTextNodeConnectionSortOrderValues = 'ASC' | 'DESC' export type contentfulBlogPostBodyTextNodeDistinctEnum = | 'id' | 'parent' | 'children' | 'body' | 'internal___type' | 'internal___mediaType' | 'internal___content' | 'internal___contentDigest' | 'internal___owner' export type contentfulBlogPostBodyTextNodeGroupEnum = | 'id' | 'parent' | 'children' | 'body' | 'internal___type' | 'internal___mediaType' | 'internal___content' | 'internal___contentDigest' | 'internal___owner' export type ContentfulContentTypeConnectionSortByFieldsEnum = | 'id' | 'parent' | 'children' | 'name' | 'displayField' | 'description' | 'internal___type' | 'internal___contentDigest' | 'internal___owner' export type contentfulContentTypeConnectionSortOrderValues = 'ASC' | 'DESC' export type contentfulContentTypeDistinctEnum = | 'id' | 'name' | 'displayField' | 'description' | 'internal___type' | 'internal___contentDigest' | 'internal___owner' export type contentfulContentTypeGroupEnum = | 'id' | 'name' | 'displayField' | 'description' | 'internal___type' | 'internal___contentDigest' | 'internal___owner' export type ContentfulBlogPostConnectionSortByFieldsEnum = | 'title' | 'slug' | 'publishDate' | 'author' | 'tags' | 'heroImage___NODE' | 'body___NODE' | 'id' | 'createdAt' | 'updatedAt' | 'parent' | 'children' | 'internal___type' | 'internal___contentDigest' | 'internal___owner' | 'node_locale' export type contentfulBlogPostConnectionSortOrderValues = 'ASC' | 'DESC' export type ContentfulImageFormat = 'NO_CHANGE' | 'JPG' | 'PNG' | 'WEBP' export type ImageResizingBehavior = 'NO_CHANGE' | 'PAD' | 'CROP' | 'FILL' | 'THUMB' | 'SCALE' export type ContentfulImageCropFocus = | 'TOP' | 'TOP_LEFT' | 'TOP_RIGHT' | 'BOTTOM' | 'BOTTOM_RIGHT' | 'BOTTOM_LEFT' | 'RIGHT' | 'LEFT' | 'FACES' export type contentfulBlogPostDistinctEnum = | 'title' | 'slug' | 'publishDate' | 'author' | 'tags' | 'heroImage___NODE' | 'body___NODE' | 'id' | 'createdAt' | 'updatedAt' | 'parent' | 'children' | 'internal___type' | 'internal___contentDigest' | 'internal___owner' | 'node_locale' export type contentfulBlogPostGroupEnum = | 'title' | 'slug' | 'publishDate' | 'author' | 'tags' | 'heroImage___NODE' | 'body___NODE' | 'id' | 'createdAt' | 'updatedAt' | 'parent' | 'children' | 'internal___type' | 'internal___contentDigest' | 'internal___owner' | 'node_locale' export type ContentfulAssetConnectionSortByFieldsEnum = | 'id' | 'parent' | 'children' | 'file___url' | 'file___details___size' | 'file___details___image' | 'file___fileName' | 'file___contentType' | 'title' | 'description' | 'node_locale' | 'internal___type' | 'internal___contentDigest' | 'internal___owner' | 'resolutions___base64' | 'resolutions___aspectRatio' | 'resolutions___width' | 'resolutions___height' | 'resolutions___src' | 'resolutions___srcSet' | 'sizes___base64' | 'sizes___aspectRatio' | 'sizes___src' | 'sizes___srcSet' | 'sizes___sizes' | 'responsiveResolution___base64' | 'responsiveResolution___aspectRatio' | 'responsiveResolution___width' | 'responsiveResolution___height' | 'responsiveResolution___src' | 'responsiveResolution___srcSet' | 'responsiveSizes___base64' | 'responsiveSizes___aspectRatio' | 'responsiveSizes___src' | 'responsiveSizes___srcSet' | 'responsiveSizes___sizes' | 'resize___src' | 'resize___width' | 'resize___height' | 'resize___aspectRatio' export type contentfulAssetConnectionSortOrderValues = 'ASC' | 'DESC' export type contentfulAssetDistinctEnum = | 'id' | 'file___url' | 'file___details___size' | 'file___details___image' | 'file___fileName' | 'file___contentType' | 'title' | 'description' | 'node_locale' | 'internal___type' | 'internal___contentDigest' | 'internal___owner' export type contentfulAssetGroupEnum = | 'id' | 'file___url' | 'file___details___size' | 'file___details___image' | 'file___fileName' | 'file___contentType' | 'title' | 'description' | 'node_locale' | 'internal___type' | 'internal___contentDigest' | 'internal___owner'
the_stack
import * as Common from '../../../../core/common/common.js'; import * as i18n from '../../../../core/i18n/i18n.js'; import * as Platform from '../../../../core/platform/platform.js'; import * as Formatter from '../../../../models/formatter/formatter.js'; import * as TextUtils from '../../../../models/text_utils/text_utils.js'; import type * as Workspace from '../../../../models/workspace/workspace.js'; import * as UI from '../../legacy.js'; import type {SourcesTextEditorDelegate} from './SourcesTextEditor.js'; import {Events, SourcesTextEditor} from './SourcesTextEditor.js'; const UIStrings = { /** *@description Text for the source of something */ source: 'Source', /** *@description Text to pretty print a file */ prettyPrint: 'Pretty print', /** *@description Text when something is loading */ loading: 'Loading…', /** * @description Shown at the bottom of the Sources panel when the user has made multiple * simultaneous text selections in the text editor. * @example {2} PH1 */ dSelectionRegions: '{PH1} selection regions', /** * @description Position indicator in Source Frame of the Sources panel. The placeholder is a * hexadecimal number value, which is why it is prefixed with '0x'. * @example {abc} PH1 */ bytecodePositionXs: 'Bytecode position `0x`{PH1}', /** *@description Text in Source Frame of the Sources panel *@example {2} PH1 *@example {2} PH2 */ lineSColumnS: 'Line {PH1}, Column {PH2}', /** *@description Text in Source Frame of the Sources panel *@example {2} PH1 */ dCharactersSelected: '{PH1} characters selected', /** *@description Text in Source Frame of the Sources panel *@example {2} PH1 *@example {2} PH2 */ dLinesDCharactersSelected: '{PH1} lines, {PH2} characters selected', }; const str_ = i18n.i18n.registerUIStrings('ui/legacy/components/source_frame/SourceFrame.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class SourceFrameImpl extends UI.View.SimpleView implements UI.SearchableView.Searchable, UI.SearchableView.Replaceable, SourcesTextEditorDelegate, Transformer { private readonly lazyContent: () => Promise<TextUtils.ContentProvider.DeferredContent>; private prettyInternal: boolean; private rawContent: string|null; private formattedContentPromise: Promise<Formatter.ScriptFormatter.FormattedContent>|null; private formattedMap: Formatter.ScriptFormatter.FormatterSourceMapping|null; private readonly prettyToggle: UI.Toolbar.ToolbarToggle; private shouldAutoPrettyPrint: boolean; private readonly progressToolbarItem: UI.Toolbar.ToolbarItem; private textEditorInternal: SourcesTextEditor; private prettyCleanGeneration: number|null; private cleanGeneration: number; private searchConfig: UI.SearchableView.SearchConfig|null; private delayedFindSearchMatches: (() => void)|null; private currentSearchResultIndex: number; private searchResults: TextUtils.TextRange.TextRange[]; private searchRegex: RegExp|null; private loadError: boolean; private muteChangeEventsForSetContent: boolean; private readonly sourcePosition: UI.Toolbar.ToolbarText; private searchableView: UI.SearchableView.SearchableView|null; private editable: boolean; private positionToReveal: { line: number, column: (number|undefined), shouldHighlight: (boolean|undefined), }|null; private lineToScrollTo: number|null; private selectionToSet: TextUtils.TextRange.TextRange|null; private loadedInternal: boolean; private contentRequested: boolean; private highlighterTypeInternal: string; private wasmDisassemblyInternal: Common.WasmDisassembly.WasmDisassembly|null; contentSet: boolean; constructor( lazyContent: () => Promise<TextUtils.ContentProvider.DeferredContent>, codeMirrorOptions?: UI.TextEditor.Options) { super(i18nString(UIStrings.source)); this.lazyContent = lazyContent; this.prettyInternal = false; this.rawContent = null; this.formattedContentPromise = null; this.formattedMap = null; this.prettyToggle = new UI.Toolbar.ToolbarToggle(i18nString(UIStrings.prettyPrint), 'largeicon-pretty-print'); this.prettyToggle.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, () => { this.setPretty(!this.prettyToggle.toggled()); }); this.shouldAutoPrettyPrint = false; this.prettyToggle.setVisible(false); this.progressToolbarItem = new UI.Toolbar.ToolbarItem(document.createElement('div')); this.textEditorInternal = new SourcesTextEditor(this, codeMirrorOptions); this.textEditorInternal.show(this.element); this.prettyCleanGeneration = null; this.cleanGeneration = 0; this.searchConfig = null; this.delayedFindSearchMatches = null; this.currentSearchResultIndex = -1; this.searchResults = []; this.searchRegex = null; this.loadError = false; this.textEditorInternal.addEventListener(Events.EditorFocused, this.resetCurrentSearchResultIndex, this); this.textEditorInternal.addEventListener(Events.SelectionChanged, this.updateSourcePosition, this); this.textEditorInternal.addEventListener(UI.TextEditor.Events.TextChanged, event => { if (!this.muteChangeEventsForSetContent) { this.onTextChanged(event.data.oldRange, event.data.newRange); } }); this.muteChangeEventsForSetContent = false; this.sourcePosition = new UI.Toolbar.ToolbarText(); this.searchableView = null; this.editable = false; this.textEditorInternal.setReadOnly(true); this.positionToReveal = null; this.lineToScrollTo = null; this.selectionToSet = null; this.loadedInternal = false; this.contentRequested = false; this.highlighterTypeInternal = ''; this.wasmDisassemblyInternal = null; this.contentSet = false; } get wasmDisassembly(): Common.WasmDisassembly.WasmDisassembly|null { return this.wasmDisassemblyInternal; } editorLocationToUILocation(lineNumber: number, columnNumber?: number): { lineNumber: number, columnNumber?: number|undefined, } { if (this.wasmDisassemblyInternal) { columnNumber = this.wasmDisassemblyInternal.lineNumberToBytecodeOffset(lineNumber); lineNumber = 0; } else if (this.prettyInternal) { [lineNumber, columnNumber] = this.prettyToRawLocation(lineNumber, columnNumber); } return {lineNumber, columnNumber}; } uiLocationToEditorLocation(lineNumber: number, columnNumber: number|undefined = 0): { lineNumber: number, columnNumber: number, } { if (this.wasmDisassemblyInternal) { lineNumber = this.wasmDisassemblyInternal.bytecodeOffsetToLineNumber(columnNumber); columnNumber = 0; } else if (this.prettyInternal) { [lineNumber, columnNumber] = this.rawToPrettyLocation(lineNumber, columnNumber); } return {lineNumber, columnNumber}; } setCanPrettyPrint(canPrettyPrint: boolean, autoPrettyPrint?: boolean): void { this.shouldAutoPrettyPrint = canPrettyPrint && Boolean(autoPrettyPrint); this.prettyToggle.setVisible(canPrettyPrint); } private async setPretty(value: boolean): Promise<void> { this.prettyInternal = value; this.prettyToggle.setEnabled(false); const wasLoaded = this.loaded; const selection = this.selection(); let newSelection; if (this.prettyInternal) { const formatInfo = await this.requestFormattedContent(); this.formattedMap = formatInfo.formattedMapping; this.setContent(formatInfo.formattedContent, null); this.prettyCleanGeneration = this.textEditorInternal.markClean(); const start = this.rawToPrettyLocation(selection.startLine, selection.startColumn); const end = this.rawToPrettyLocation(selection.endLine, selection.endColumn); newSelection = new TextUtils.TextRange.TextRange(start[0], start[1], end[0], end[1]); } else { this.setContent(this.rawContent, null); this.cleanGeneration = this.textEditorInternal.markClean(); const start = this.prettyToRawLocation(selection.startLine, selection.startColumn); const end = this.prettyToRawLocation(selection.endLine, selection.endColumn); newSelection = new TextUtils.TextRange.TextRange(start[0], start[1], end[0], end[1]); } if (wasLoaded) { this.textEditor.revealPosition(newSelection.endLine, newSelection.endColumn, this.editable); this.textEditor.setSelection(newSelection); } this.prettyToggle.setEnabled(true); this.updatePrettyPrintState(); } private updateLineNumberFormatter(): void { if (this.wasmDisassemblyInternal) { const disassembly = this.wasmDisassemblyInternal; const lastBytecodeOffset = disassembly.lineNumberToBytecodeOffset(disassembly.lineNumbers - 1); const bytecodeOffsetDigits = lastBytecodeOffset.toString(16).length + 1; this.textEditorInternal.setLineNumberFormatter(lineNumber => { const bytecodeOffset = disassembly.lineNumberToBytecodeOffset(lineNumber - 1); return `0x${bytecodeOffset.toString(16).padStart(bytecodeOffsetDigits, '0')}`; }); } else if (this.prettyInternal) { this.textEditorInternal.setLineNumberFormatter(lineNumber => { const line = this.prettyToRawLocation(lineNumber - 1, 0)[0] + 1; if (lineNumber === 1) { return String(line); } if (line !== this.prettyToRawLocation(lineNumber - 2, 0)[0] + 1) { return String(line); } return '-'; }); } else { this.textEditorInternal.setLineNumberFormatter(lineNumber => { return String(lineNumber); }); } } private updatePrettyPrintState(): void { this.prettyToggle.setToggled(this.prettyInternal); this.textEditorInternal.element.classList.toggle('pretty-printed', this.prettyInternal); this.updateLineNumberFormatter(); } private prettyToRawLocation(line: number, column: number|undefined = 0): number[] { if (!this.formattedMap) { return [line, column]; } return this.formattedMap.formattedToOriginal(line, column); } private rawToPrettyLocation(line: number, column: number): number[] { if (!this.formattedMap) { return [line, column]; } return this.formattedMap.originalToFormatted(line, column); } setEditable(editable: boolean): void { this.editable = editable; if (this.loadedInternal) { this.textEditorInternal.setReadOnly(!editable); } } hasLoadError(): boolean { return this.loadError; } wasShown(): void { this.ensureContentLoaded(); this.wasShownOrLoaded(); } willHide(): void { super.willHide(); this.clearPositionToReveal(); } async toolbarItems(): Promise<UI.Toolbar.ToolbarItem[]> { return [this.prettyToggle, this.sourcePosition, this.progressToolbarItem]; } get loaded(): boolean { return this.loadedInternal; } get textEditor(): SourcesTextEditor { return this.textEditorInternal; } get pretty(): boolean { return this.prettyInternal; } private async ensureContentLoaded(): Promise<void> { if (!this.contentRequested) { this.contentRequested = true; const progressIndicator = new UI.ProgressIndicator.ProgressIndicator(); progressIndicator.setTitle(i18nString(UIStrings.loading)); progressIndicator.setTotalWork(100); this.progressToolbarItem.element.appendChild(progressIndicator.element); const deferredContent = await this.lazyContent(); let error, content; if (deferredContent.content === null) { error = deferredContent.error; this.rawContent = deferredContent.error; } else { content = deferredContent.content; this.rawContent = deferredContent.isEncoded ? window.atob(deferredContent.content) : deferredContent.content; } progressIndicator.setWorked(1); if (!error && this.highlighterTypeInternal === 'application/wasm') { const worker = Common.Worker.WorkerWrapper.fromURL( new URL('../../../../entrypoints/wasmparser_worker/wasmparser_worker-entrypoint.js', import.meta.url)); const promise = new Promise<{ source: string, offsets: number[], functionBodyOffsets: { start: number, end: number, }[], }>((resolve, reject) => { worker.onmessage = /** @type {{event:string, params:{percentage:number}}} */ // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // eslint-disable-next-line @typescript-eslint/no-explicit-any ({data}: MessageEvent<any>): void => { if ('event' in data) { switch (data.event) { case 'progress': progressIndicator.setWorked(data.params.percentage); break; } } else if ('method' in data) { switch (data.method) { case 'disassemble': if ('error' in data) { reject(data.error); } else if ('result' in data) { resolve(data.result); } break; } } }; worker.onerror = reject; }); worker.postMessage({method: 'disassemble', params: {content}}); try { const {source, offsets, functionBodyOffsets} = await promise; this.rawContent = content = source; this.wasmDisassemblyInternal = new Common.WasmDisassembly.WasmDisassembly(offsets, functionBodyOffsets); } catch (e) { this.rawContent = content = error = e.message; } finally { worker.terminate(); } } progressIndicator.setWorked(100); progressIndicator.done(); this.formattedContentPromise = null; this.formattedMap = null; this.prettyToggle.setEnabled(true); if (error) { this.setContent(null, error); this.prettyToggle.setEnabled(false); // Occasionally on load, there can be a race in which it appears the CodeMirror plugin // runs the highlighter type assignment out of order. In case of an error then, set // the highlighter type after a short delay. This appears to only occur the first // time that CodeMirror is initialized, likely because the highlighter type was first // initialized based on the file type, and the syntax highlighting is in a race // with the new highlighter assignment. As the option is just an option and is not // observable, we can't handle waiting for it here. // https://github.com/codemirror/CodeMirror/issues/6019 // CRBug 1011445 setTimeout(() => this.setHighlighterType('text/plain'), 50); } else { if (this.shouldAutoPrettyPrint && TextUtils.TextUtils.isMinified(content)) { await this.setPretty(true); } else { this.setContent(this.rawContent, null); } } this.contentSet = true; } } private requestFormattedContent(): Promise<Formatter.ScriptFormatter.FormattedContent> { if (this.formattedContentPromise) { return this.formattedContentPromise; } this.formattedContentPromise = Formatter.ScriptFormatter.formatScriptContent(this.highlighterTypeInternal, this.rawContent || ''); return this.formattedContentPromise; } revealPosition(line: number, column?: number, shouldHighlight?: boolean): void { this.lineToScrollTo = null; this.selectionToSet = null; this.positionToReveal = {line: line, column: column, shouldHighlight: shouldHighlight}; this.innerRevealPositionIfNeeded(); } private innerRevealPositionIfNeeded(): void { if (!this.positionToReveal) { return; } if (!this.loaded || !this.isShowing()) { return; } const {lineNumber, columnNumber} = this.uiLocationToEditorLocation(this.positionToReveal.line, this.positionToReveal.column); this.textEditorInternal.revealPosition(lineNumber, columnNumber, this.positionToReveal.shouldHighlight); this.positionToReveal = null; } private clearPositionToReveal(): void { this.textEditorInternal.clearPositionHighlight(); this.positionToReveal = null; } scrollToLine(line: number): void { this.clearPositionToReveal(); this.lineToScrollTo = line; this.innerScrollToLineIfNeeded(); } private innerScrollToLineIfNeeded(): void { if (this.lineToScrollTo !== null) { if (this.loaded && this.isShowing()) { this.textEditorInternal.scrollToLine(this.lineToScrollTo); this.lineToScrollTo = null; } } } selection(): TextUtils.TextRange.TextRange { return this.textEditor.selection(); } setSelection(textRange: TextUtils.TextRange.TextRange): void { this.selectionToSet = textRange; this.innerSetSelectionIfNeeded(); } private innerSetSelectionIfNeeded(): void { if (this.selectionToSet && this.loaded && this.isShowing()) { this.textEditorInternal.setSelection(this.selectionToSet, true); this.selectionToSet = null; } } private wasShownOrLoaded(): void { this.innerRevealPositionIfNeeded(); this.innerSetSelectionIfNeeded(); this.innerScrollToLineIfNeeded(); } onTextChanged(_oldRange: TextUtils.TextRange.TextRange, _newRange: TextUtils.TextRange.TextRange): void { const wasPretty = this.pretty; this.prettyInternal = this.prettyCleanGeneration !== null && this.textEditor.isClean(this.prettyCleanGeneration); if (this.prettyInternal !== wasPretty) { this.updatePrettyPrintState(); } this.prettyToggle.setEnabled(this.isClean()); if (this.searchConfig && this.searchableView) { this.performSearch(this.searchConfig, false, false); } } isClean(): boolean { return this.textEditor.isClean(this.cleanGeneration) || (this.prettyCleanGeneration !== null && this.textEditor.isClean(this.prettyCleanGeneration)); } contentCommitted(): void { this.cleanGeneration = this.textEditorInternal.markClean(); this.prettyCleanGeneration = null; this.rawContent = this.textEditor.text(); this.formattedMap = null; this.formattedContentPromise = null; if (this.prettyInternal) { this.prettyInternal = false; this.updatePrettyPrintState(); } this.prettyToggle.setEnabled(true); } private simplifyMimeType(content: string, mimeType: string): string { if (!mimeType) { return ''; } // There are plenty of instances where TSX/JSX files are served with out the trailing x, i.e. JSX with a 'js' suffix // which breaks the formatting. Therefore, if the mime type is TypeScript or JavaScript, we switch to the TSX/JSX // superset so that we don't break formatting. if (mimeType.indexOf('typescript') >= 0) { return 'text/typescript-jsx'; } if (mimeType.indexOf('javascript') >= 0 || mimeType.indexOf('jscript') >= 0 || mimeType.indexOf('ecmascript') >= 0) { return 'text/jsx'; } // A hack around the fact that files with "php" extension might be either standalone or html embedded php scripts. if (mimeType === 'text/x-php' && content.match(/\<\?.*\?\>/g)) { return 'application/x-httpd-php'; } if (mimeType === 'application/wasm') { // text/webassembly is not a proper MIME type, but CodeMirror uses it for WAT syntax highlighting. // We generally use application/wasm, which is the correct MIME type for Wasm binary data. return 'text/webassembly'; } return mimeType; } setHighlighterType(highlighterType: string): void { this.highlighterTypeInternal = highlighterType; this.updateHighlighterType(''); } highlighterType(): string { return this.highlighterTypeInternal; } private updateHighlighterType(content: string): void { this.textEditorInternal.setMimeType(this.simplifyMimeType(content, this.highlighterTypeInternal)); } setContent(content: string|null, loadError: string|null): void { this.muteChangeEventsForSetContent = true; if (!this.loadedInternal) { this.loadedInternal = true; if (!loadError) { this.textEditorInternal.setText(content || ''); this.cleanGeneration = this.textEditorInternal.markClean(); this.textEditorInternal.setReadOnly(!this.editable); this.loadError = false; } else { this.textEditorInternal.setText(loadError || ''); this.highlighterTypeInternal = 'text/plain'; this.textEditorInternal.setReadOnly(true); this.loadError = true; } } else { const scrollTop = this.textEditorInternal.scrollTop(); const selection = this.textEditorInternal.selection(); this.textEditorInternal.setText(content || ''); this.textEditorInternal.setScrollTop(scrollTop); this.textEditorInternal.setSelection(selection); } // Mark non-breakable lines in the Wasm disassembly after setting // up the content for the text editor (which creates the gutter). if (this.wasmDisassemblyInternal) { for (const lineNumber of this.wasmDisassemblyInternal.nonBreakableLineNumbers()) { this.textEditorInternal.toggleLineClass(lineNumber, 'cm-non-breakable-line', true); } } this.updateLineNumberFormatter(); this.updateHighlighterType(content || ''); this.wasShownOrLoaded(); if (this.delayedFindSearchMatches) { this.delayedFindSearchMatches(); this.delayedFindSearchMatches = null; } this.muteChangeEventsForSetContent = false; } setSearchableView(view: UI.SearchableView.SearchableView|null): void { this.searchableView = view; } private doFindSearchMatches( searchConfig: UI.SearchableView.SearchConfig, shouldJump: boolean, jumpBackwards: boolean): void { this.currentSearchResultIndex = -1; this.searchResults = []; const regex = searchConfig.toSearchRegex(); this.searchRegex = regex; this.searchResults = this.collectRegexMatches(regex); if (this.searchableView) { this.searchableView.updateSearchMatchesCount(this.searchResults.length); } if (!this.searchResults.length) { this.textEditorInternal.cancelSearchResultsHighlight(); } else if (shouldJump && jumpBackwards) { this.jumpToPreviousSearchResult(); } else if (shouldJump) { this.jumpToNextSearchResult(); } else { this.textEditorInternal.highlightSearchResults(regex, null); } } performSearch(searchConfig: UI.SearchableView.SearchConfig, shouldJump: boolean, jumpBackwards?: boolean): void { if (this.searchableView) { this.searchableView.updateSearchMatchesCount(0); } this.resetSearch(); this.searchConfig = searchConfig; if (this.loaded) { this.doFindSearchMatches(searchConfig, shouldJump, Boolean(jumpBackwards)); } else { this.delayedFindSearchMatches = this.doFindSearchMatches.bind(this, searchConfig, shouldJump, Boolean(jumpBackwards)); } this.ensureContentLoaded(); } private resetCurrentSearchResultIndex(): void { if (!this.searchResults.length) { return; } this.currentSearchResultIndex = -1; if (this.searchableView) { this.searchableView.updateCurrentMatchIndex(this.currentSearchResultIndex); } this.textEditorInternal.highlightSearchResults((this.searchRegex as RegExp), null); } private resetSearch(): void { this.searchConfig = null; this.delayedFindSearchMatches = null; this.currentSearchResultIndex = -1; this.searchResults = []; this.searchRegex = null; } searchCanceled(): void { const range = this.currentSearchResultIndex !== -1 ? this.searchResults[this.currentSearchResultIndex] : null; this.resetSearch(); if (!this.loaded) { return; } this.textEditorInternal.cancelSearchResultsHighlight(); if (range) { this.setSelection(range); } } jumpToLastSearchResult(): void { this.jumpToSearchResult(this.searchResults.length - 1); } private searchResultIndexForCurrentSelection(): number { return Platform.ArrayUtilities.lowerBound( this.searchResults, this.textEditorInternal.selection().collapseToEnd(), TextUtils.TextRange.TextRange.comparator); } jumpToNextSearchResult(): void { const currentIndex = this.searchResultIndexForCurrentSelection(); const nextIndex = this.currentSearchResultIndex === -1 ? currentIndex : currentIndex + 1; this.jumpToSearchResult(nextIndex); } jumpToPreviousSearchResult(): void { const currentIndex = this.searchResultIndexForCurrentSelection(); this.jumpToSearchResult(currentIndex - 1); } supportsCaseSensitiveSearch(): boolean { return true; } supportsRegexSearch(): boolean { return true; } jumpToSearchResult(index: number): void { if (!this.loaded || !this.searchResults.length) { return; } this.currentSearchResultIndex = (index + this.searchResults.length) % this.searchResults.length; if (this.searchableView) { this.searchableView.updateCurrentMatchIndex(this.currentSearchResultIndex); } this.textEditorInternal.highlightSearchResults( (this.searchRegex as RegExp), this.searchResults[this.currentSearchResultIndex]); } replaceSelectionWith(searchConfig: UI.SearchableView.SearchConfig, replacement: string): void { const range = this.searchResults[this.currentSearchResultIndex]; if (!range) { return; } this.textEditorInternal.highlightSearchResults((this.searchRegex as RegExp), null); const oldText = this.textEditorInternal.text(range); const regex = searchConfig.toSearchRegex(); let text; if (regex.__fromRegExpQuery) { text = oldText.replace(regex, replacement); } else { text = oldText.replace(regex, function() { return replacement; }); } const newRange = this.textEditorInternal.editRange(range, text); this.textEditorInternal.setSelection(newRange.collapseToEnd()); } replaceAllWith(searchConfig: UI.SearchableView.SearchConfig, replacement: string): void { this.resetCurrentSearchResultIndex(); let text = this.textEditorInternal.text(); const range = this.textEditorInternal.fullRange(); const regex = searchConfig.toSearchRegex(true); if (regex.__fromRegExpQuery) { text = text.replace(regex, replacement); } else { text = text.replace(regex, function() { return replacement; }); } const ranges = this.collectRegexMatches(regex); if (!ranges.length) { return; } // Calculate the position of the end of the last range to be edited. const currentRangeIndex = Platform.ArrayUtilities.lowerBound( ranges, this.textEditorInternal.selection(), TextUtils.TextRange.TextRange.comparator); const lastRangeIndex = Platform.NumberUtilities.mod(currentRangeIndex - 1, ranges.length); const lastRange = ranges[lastRangeIndex]; const replacementLineEndings = Platform.StringUtilities.findLineEndingIndexes(replacement); const replacementLineCount = replacementLineEndings.length; const lastLineNumber = lastRange.startLine + replacementLineEndings.length - 1; let lastColumnNumber: number = lastRange.startColumn; if (replacementLineEndings.length > 1) { lastColumnNumber = replacementLineEndings[replacementLineCount - 1] - replacementLineEndings[replacementLineCount - 2] - 1; } this.textEditorInternal.editRange(range, text); this.textEditorInternal.revealPosition(lastLineNumber, lastColumnNumber); this.textEditorInternal.setSelection( TextUtils.TextRange.TextRange.createFromLocation(lastLineNumber, lastColumnNumber)); } private collectRegexMatches(regexObject: RegExp): TextUtils.TextRange.TextRange[] { const ranges = []; for (let i = 0; i < this.textEditorInternal.linesCount; ++i) { let line = this.textEditorInternal.line(i); let offset = 0; let match; do { match = regexObject.exec(line); if (match) { const matchEndIndex = match.index + Math.max(match[0].length, 1); if (match[0].length) { ranges.push(new TextUtils.TextRange.TextRange(i, offset + match.index, i, offset + matchEndIndex)); } offset += matchEndIndex; line = line.substring(matchEndIndex); } } while (match && line); } return ranges; } populateLineGutterContextMenu(_contextMenu: UI.ContextMenu.ContextMenu, _editorLineNumber: number): Promise<void> { return Promise.resolve(); } populateTextAreaContextMenu( _contextMenu: UI.ContextMenu.ContextMenu, _editorLineNumber: number, _editorColumnNumber: number): Promise<void> { return Promise.resolve(); } canEditSource(): boolean { return this.editable; } private updateSourcePosition(): void { const selections = this.textEditorInternal.selections(); if (!selections.length) { return; } if (selections.length > 1) { this.sourcePosition.setText(i18nString(UIStrings.dSelectionRegions, {PH1: selections.length})); return; } let textRange: TextUtils.TextRange.TextRange = selections[0]; if (textRange.isEmpty()) { const location = this.prettyToRawLocation(textRange.endLine, textRange.endColumn); if (this.wasmDisassemblyInternal) { const disassembly = this.wasmDisassemblyInternal; const lastBytecodeOffset = disassembly.lineNumberToBytecodeOffset(disassembly.lineNumbers - 1); const bytecodeOffsetDigits = lastBytecodeOffset.toString(16).length; const bytecodeOffset = disassembly.lineNumberToBytecodeOffset(location[0]); this.sourcePosition.setText(i18nString( UIStrings.bytecodePositionXs, {PH1: bytecodeOffset.toString(16).padStart(bytecodeOffsetDigits, '0')})); } else { if (!this.canEditSource()) { this.textEditorInternal.revealPosition(textRange.endLine, textRange.endColumn, true); } this.sourcePosition.setText(i18nString(UIStrings.lineSColumnS, {PH1: location[0] + 1, PH2: location[1] + 1})); } return; } textRange = textRange.normalize(); const selectedText = this.textEditorInternal.text(textRange); if (textRange.startLine === textRange.endLine) { this.sourcePosition.setText(i18nString(UIStrings.dCharactersSelected, {PH1: selectedText.length})); } else { this.sourcePosition.setText(i18nString( UIStrings.dLinesDCharactersSelected, {PH1: textRange.endLine - textRange.startLine + 1, PH2: selectedText.length})); } } } export interface LineDecorator { decorate(uiSourceCode: Workspace.UISourceCode.UISourceCode, textEditor: SourcesTextEditor, type: string): void; } export interface Transformer { editorLocationToUILocation(lineNumber: number, columnNumber?: number): { lineNumber: number, columnNumber?: number|undefined, }; uiLocationToEditorLocation(lineNumber: number, columnNumber?: number): { lineNumber: number, columnNumber: number, }; } const registeredLineDecorators: LineDecoratorRegistration[] = []; export function registerLineDecorator(registration: LineDecoratorRegistration): void { registeredLineDecorators.push(registration); } export function getRegisteredLineDecorators(): LineDecoratorRegistration[] { return registeredLineDecorators; } // TODO(crbug.com/1167717): Make this a const enum again // eslint-disable-next-line rulesdir/const_enum export enum DecoratorType { PERFORMANCE = 'performance', MEMORY = 'memory', COVERAGE = 'coverage', } export interface LineDecoratorRegistration { lineDecorator: () => LineDecorator; decoratorType: DecoratorType; }
the_stack
const throttle = require('lodash.throttle') //the export exists to indicate that the file is a module for typescript to allow the code to use global object export {}; //define variable types for typscript here declare global { interface devTools { renderers: { size?: number }; // onCommitFiberRoot(any?); } interface Window { __REACT_DEVTOOLS_GLOBAL_HOOK__: devTools; } interface Component { name: any; state?: any; children?: any; atoms?: any; } } function patcher() { // grabs the React DevTools from the browser const devTools:any = window.__REACT_DEVTOOLS_GLOBAL_HOOK__; // if conditions to check if devTools is running or the user application is react if (!devTools) { sendToContentScript('React DevTools is not activated, please activate React DevTools!') } if (devTools.renderers && devTools.renderers.size < 1) { sendToContentScript('The page is not using React or if it is using React please trigger a state change!') } // adding/patching functionality to capture fiberTree data to the onCommitFiberRoot method in devTools devTools.onCommitFiberRoot = (function (original) { function newFunc(...args:any) { const fiberDOM = args[1]; console.log(fiberDOM); const rootNode = fiberDOM.current.stateNode.current; //create a new array that will be sent to the frontend after being populated with necessary data const treeArr: any[] = []; try { //this function collects the data for the component tree and stores atom names and state data recurseThrottle(rootNode.child, treeArr); //this function below gets the atom value data for the right panel in UI treeArr.push(getAtomValues(treeArr[0], 'atomValues')); //this function gets the link between selectors and atom for the selector/atom tree treeArr.push(getSelectorAtomLink(treeArr[0], 'nodeToNodeSubscriptions')) //if the data is populated correctly, the array will be sent to the content_script file in the backend console.log('treearr sent to frontend', treeArr) if (treeArr.length > 0) sendToContentScript(treeArr); } catch (err) { console.log('Error at onCommitFiberRoot:', err) sendToContentScript('Error: something went wrong with our application, please submit the issue on https://github.com/oslabs-beta/TotalRecoilJS') } return original(...args); } return newFunc; // Below syntax devTools.onCommitFiberRoot runs immediately after adding our new functionality to devTools.onCommitFiberRoot (and the input is the original function of onCommitFiberRoot) })(devTools.onCommitFiberRoot) } //throttling the recusrive function getComponentData to run only once in 300 milliseconds, to improve performance as changes are made in the user application const recurseThrottle = throttle(getComponentData, 300); //recursive function (getComponentData) below traverses through the fiber tree and collects certain component,state, and atom data function getComponentData(node: any, arr: any[]) { const component: Component = {name: ''}; if (getName(node, component, arr) === -1) return; getState(node, component) getAtom(component) arr.push(component) //getchildren calls getComponentData (name, state, atom), pushes into nested "children" array getChildren(node, component, arr) } //this function will get the same of the React components function getName(node: any, component: any, arr: Array<any>) { if (!node.type || !node.type.name) { // if this is an HTML tag just keep recursing without saving the name if (node.child) getComponentData(node.child, arr); if (node.sibling) getComponentData(node.sibling, arr); return -1; } else { component.name = node.type.name; } } //this functions gets all the data related to state in React fiber (and the data stored here is used later in other functions) function getState(node: any, component: any) { //checking for 3 conditions (if state exists, if its a linkedlist with state, if its not a linkedlist with state) //check if state exists in the node, if not just return and exit out of the function if (!node.memoizedState) return; // check if the state is stored as a linkedlist if (node.memoizedState.memoizedState !== undefined) { //check if you're at the end of the linked list chain (.next = null) if (node.memoizedState.next === null) { component.state = cleanState(node.memoizedState.memoizedState) return; } // initialize array because state is a linkedlist so you can store multiple states in the array component.state = []; linkedListRecurse(node.memoizedState, component.state); return; } // if the state is not stored as a linkedlist, then run the clean state function component.state = cleanState(node.memoizedState) function linkedListRecurse(node: any, treeArr: any[]) { treeArr.push(cleanState(node.memoizedState)) if (node.next && node.memoizedState !== node.next.memoizedState) { linkedListRecurse(node.next, treeArr) } } } //this function traverses through component.state property collected in the function getState and stores atom names function getAtom(component: Component) { // if component has no state there is not atom for it so just exit from the function; if (!component.state) { return; } // Make a new empty Set const atomArr = new Set(); // this will loop through component.state to get the atom data for (let i = 0; i < component.state.length; i++) { if (component.state[i]['current'] instanceof Set || component.state[i]['current'] instanceof Map) { // this code will give us the value from the existing set/map in component.state to add to our newly created set const it = component.state[i]['current'].values(); let first = it.next(); atomArr.add(first.value); } //below code will convert the data in the create set to an array in component.atoms property, take out any duplicates, and delete the propert if no atoms exists for the component component.atoms = Array.from(atomArr); if (component.atoms.length === 0) { delete component.atoms; } else { for (const el of component.atoms) { if (typeof el !== 'string') { let index = component.atoms.indexOf(el); component.atoms.splice(index, 1); } } } } } //this is will get all the children and sibling components linked to the current component node and then run the recursive function getComponentData again on each child/sibling node function getChildren(node: any, component: Component, arr: any[]) { const children: any[] = []; //check if the node has a child, if so then run the getComponentData on that child node(s) if (node.child) { getComponentData(node.child, children); } // check if the node has a sibling, if so then run the getComponentData on that sibling node(s) if (node.sibling) getComponentData(node.sibling, arr); //if no more child or sibling nodes then return the children array if (children.length > 0) component.children = children; } //this function populates atom values in the second position of the array that is sent to the front end function getAtomValues(obj: object, prop: string) { const arr: any = []; //this function populates the array with the data as map object that is found in tree function recursivelyFindProp(o: any, keyToBeFound: string) { if (typeof o !== 'object' || !o) { return; } Object.keys(o).forEach(function (key) { if (key === keyToBeFound) { arr.push(o[key]) } else { if (typeof o[key] === 'object') { recursivelyFindProp(o[key], keyToBeFound); } } }); } //it recurses throught nested objects and arary to find the key 'atomValues' where the atom value data is stored (the atom values are in a map object) recursivelyFindProp(obj, prop); //the skeleton structure of how the data object will look stored in the array to send to the frontend interface Result { atomVal: any } const result: Result = { atomVal: {} } //converting map objects where the atom value is found into the result object with a key value pair for (let i = 0; i < arr.length; i++) { let mapData = arr[i] if (mapData) { for (let [key, value] of mapData) { result.atomVal[key] = value.contents; } } } return result; } //this function creates and stores the data for the selector/atom tree and stores in the 3rd position in the array sent to the frontend function getSelectorAtomLink(obj: any, prop: string) { let arr: any[] = []; function recursivelyFindProp(o: any, keyToBeFound: string) { if (typeof o !== 'object' || !o) { return; } Object.keys(o).forEach(function (key) { if (key === keyToBeFound) { arr.push(o[key]) } else { if (typeof o[key] === 'object') { recursivelyFindProp(o[key], keyToBeFound); } } }); } //this function recursively finds the key 'nodeToNodeSubscriptions' which has the data for atom to selector connections recursivelyFindProp(obj, prop); //skeleton structure of how the data will be stored in the array interface SelectorTree { name: string; children: any[]; } const result: SelectorTree = { name: 'Selector Tree', children: [] } interface NonSelectorAtoms { name: string; children: any[]; } const tempObj: NonSelectorAtoms = {name: 'nonSelectorAtoms', children: []} result.children.push(tempObj) //converting map data into object data to be stored const newArr = arr.filter((item, index) => arr.indexOf(item) === index) for (let i = 0; i < newArr.length; i++) { let mapData = newArr[i] if (mapData) { for (let [key, value] of mapData) { let tempArr = [...value] for (let el of tempArr) { let tempObj: SelectorTree = { name: '', children: [] } tempObj.name = el; interface TreeValObj { name: string; value: number; } const treeValObj = { name: key, value: 100 } tempObj.children.push(treeValObj); result.children.push(tempObj); } } } } let atomsAndSelectors: any = []; //finds all the atoms with selector connetions and compares if there are any atom names that exist in the component tree that do not show up in the 'nodeToComponentSubscriptions' because those are the atoms with no selectors function getNonSelectorAtoms(result: any, obj: any) { //below function finds the atom/selector data found in 'nodeToComponentSubscriptions' key findNested(obj, 'nodeToComponentSubscriptions') if(atomsAndSelectors.length > 0) { let atomsAndSelectorsArr = Array.from(atomsAndSelectors[0].keys()); for (const el of atomsAndSelectorsArr) { if (!doesNestedValueExist(result, el)) { result.children[0].children.push({name: el, value: 100}); } } } } //checks if a value exits in a nested object function doesNestedValueExist(obj: any, text: any): boolean { let exists = false; let keys = Object.keys(obj); for(let i = 0; i < keys.length; i++) { let key = keys[i]; let type = typeof obj[key]; if(type === 'object') { exists = doesNestedValueExist(obj[key], text); } else if(type === 'string') { exists = obj[key].indexOf(text) > -1; } if(exists) { break; } } return exists; }; //returns the data that exists for the key value that is in keyToBeFound input in a nested object function findNested(o: any, keyToBeFound: string) { if (typeof o !== 'object' || !o) { return; } Object.keys(o).forEach(function (key) { if (key === keyToBeFound) { atomsAndSelectors.push(o[key]); } else { if (typeof o[key] === 'object') { findNested(o[key], keyToBeFound); } } }); } //this function recursively finds atoms that have no selectors getNonSelectorAtoms(result, obj) return result; } //this function cleans the state data for component.state property (this function is run inside getState function) function cleanState(stateNode: any, depth = 0) { let result: any; if (depth > 10) return "Max recursion depth reached!" //checking if the stateNode is not an object or function, if it is not either return the stateNode if (typeof stateNode !== 'object' && typeof stateNode !== 'function') return stateNode; if (stateNode === null) { return null; } if (typeof stateNode === 'object') { //when using useRecoilValue atoms are saved as set - checking for atom data if (stateNode instanceof Set) { return stateNode; } if (stateNode instanceof Map) { return stateNode; } if (stateNode.$$typeof && typeof stateNode.$$typeof === 'symbol') { return stateNode.type && typeof stateNode.type !== 'string' ? `<${stateNode.type.name} />` : 'React component'; } if (Array.isArray(stateNode)) { result = []; stateNode.forEach((el, index) => { if (el !== null) { result[index] = cleanState(el, depth + 1) } else { result[index] = el; } }) } else { result = {}; Object.keys(stateNode).forEach((key) => { result[key] = cleanState(stateNode[key], depth + 1) }); } return result; } if (typeof stateNode === 'function') { return `function: ${stateNode.name}()`; } } //the function that sends the array with the necessary tree data to the frontend function sendToContentScript(obj: any) { const tree = JSON.parse(JSON.stringify(obj)); window.postMessage({ tree }, '*'); } //the patcher function is invoked one time when the app first runs to modify the onCommitFiberRoot function in React devTools to extract React Fiber patcher();
the_stack
import { AggregationAttrs, AVAILABLE_TABLES, getHiddenStackHelperColumns, getParentStackWhereFilter, getStackColumn, getStackDepthColumn, PivotAttrs, } from './pivot_table_common'; export function getPivotAlias(pivot: PivotAttrs): string { return `${pivot.tableName} ${pivot.columnName}`; } export function getHiddenPivotAlias(pivot: PivotAttrs) { return getPivotAlias(pivot) + ' (hidden)'; } export function getAggregationAlias(aggregation: AggregationAttrs): string { return `${aggregation.tableName} ${aggregation.columnName} (${ aggregation.aggregation})`; } export function getSqlPivotAlias(pivot: PivotAttrs): string { return `"${getPivotAlias(pivot)}"`; } export function getSqlHiddenPivotAlias(pivot: PivotAttrs): string { return `"${getHiddenPivotAlias(pivot)}"`; } export function getSqlAggregationAlias(aggregation: AggregationAttrs): string { return `"${getAggregationAlias(aggregation)}"`; } export function getAggregationOverStackAlias(aggregation: AggregationAttrs): string { return `${getAggregationAlias(aggregation)} (stack)`; } export function getSqlAggregationOverStackAlias(aggregation: AggregationAttrs): string { return `"${getAggregationOverStackAlias(aggregation)}"`; } export function getTotalAggregationAlias(aggregation: AggregationAttrs): string { return `${getAggregationAlias(aggregation)} (total)`; } export function getSqlTotalAggregationAlias(aggregation: AggregationAttrs): string { return `"${getTotalAggregationAlias(aggregation)}"`; } // Returns an array of pivot aliases along with any additional pivot aliases. export function getSqlAliasedPivotColumns(pivots: PivotAttrs[]): string[] { const pivotCols = []; for (const pivot of pivots) { pivotCols.push(getSqlPivotAlias(pivot)); if (pivot.isStackPivot) { pivotCols.push(...getHiddenStackHelperColumns(pivot).map( column => `"${column.columnAlias}"`)); } } return pivotCols; } export function getAliasedPivotColumns(pivots: PivotAttrs[]) { const pivotCols: Array<{pivotAttrs: PivotAttrs, columnAlias: string}> = []; for (const pivot of pivots) { pivotCols.push({pivotAttrs: pivot, columnAlias: getPivotAlias(pivot)}); if (pivot.isStackPivot) { pivotCols.push(...getHiddenStackHelperColumns(pivot)); } } return pivotCols; } // Returns an array of aggregation aliases along with total aggregations if // necessary. function getSqlAliasedAggregationsColumns( aggregations: AggregationAttrs[], hasPivotsSelected: boolean, isStackQuery: boolean): string[] { const aggCols = aggregations.map(aggregation => getSqlAggregationAlias(aggregation)); if (hasPivotsSelected) { aggCols.push(...aggregations.map( aggregation => getSqlTotalAggregationAlias(aggregation))); } if (isStackQuery) { aggCols.push(...aggregations.map( aggregation => getSqlAggregationOverStackAlias(aggregation))); } return aggCols; } export class PivotTableQueryGenerator { // Generates a query that selects all pivots and aggregations and joins any // tables needed by them together. All pivots are renamed into the format // tableName columnName and all aggregations are renamed into // tableName columnName (aggregation) (see getPivotAlias or // getAggregationAlias). private generateJoinQuery( pivots: PivotAttrs[], aggregations: AggregationAttrs[], whereFilters: string[], joinTables: string[]): string { let joinQuery = 'SELECT\n'; const pivotCols = []; for (const pivot of pivots) { if (pivot.isStackPivot) { pivotCols.push( `${pivot.tableName}.name AS ` + `${getSqlPivotAlias(pivot)}`); pivotCols.push(...getHiddenStackHelperColumns(pivot).map( column => `${column.pivotAttrs.tableName}.${ column.pivotAttrs.columnName} AS "${column.columnAlias}"`)); } else { pivotCols.push( `${pivot.tableName}.${pivot.columnName} AS ` + `${getSqlPivotAlias(pivot)}`); } } const aggCols = []; for (const aggregation of aggregations) { aggCols.push( `${aggregation.tableName}.${aggregation.columnName} AS ` + `${getSqlAggregationAlias(aggregation)}`); } joinQuery += pivotCols.concat(aggCols).join(',\n '); joinQuery += '\n'; joinQuery += 'FROM\n'; joinQuery += joinTables.join(',\n '); joinQuery += '\n'; joinQuery += 'WHERE\n'; joinQuery += whereFilters.join(' AND\n '); joinQuery += '\n'; return joinQuery; } // Partitions the aggregations from the subquery generateJoinQuery over // all sets of appended pivots ({pivot1}, {pivot1, pivot2}, etc). private generateAggregationQuery( pivots: PivotAttrs[], aggregations: AggregationAttrs[], whereFilters: string[], joinTables: string[], isStackQuery: boolean): string { // No need for this query if there are no aggregations. if (aggregations.length === 0) { return this.generateJoinQuery( pivots, aggregations, whereFilters, joinTables); } let aggQuery = 'SELECT\n'; const pivotCols = getSqlAliasedPivotColumns(pivots); let partitionByPivotCols = pivotCols; if (pivots.length > 0 && pivots[0].isStackPivot) { partitionByPivotCols = []; partitionByPivotCols.push( getSqlHiddenPivotAlias(getStackColumn(pivots[0]))); partitionByPivotCols.push(...getSqlAliasedPivotColumns(pivots.slice(1))); } const aggCols = []; for (const aggregation of aggregations) { const aggColPrefix = `${aggregation.aggregation}(${getSqlAggregationAlias(aggregation)})`; if (pivots.length === 0) { // Don't partition over pivots if there are no pivots. aggCols.push( `${aggColPrefix} AS ${getSqlAggregationAlias(aggregation)}`); continue; } // Add total aggregations column. aggCols.push( `${aggColPrefix} OVER () AS ` + `${getSqlTotalAggregationAlias(aggregation)}`); // Add aggregation over stack column. if (isStackQuery) { aggCols.push( `${aggColPrefix} OVER (PARTITION BY ` + `${partitionByPivotCols[0]}) AS ` + `${getSqlAggregationOverStackAlias(aggregation)}`); } aggCols.push( `${aggColPrefix} OVER (PARTITION BY ` + `${partitionByPivotCols.join(', ')}) AS ` + `${getSqlAggregationAlias(aggregation)}`); } aggQuery += pivotCols.concat(aggCols).join(',\n '); aggQuery += '\n'; aggQuery += 'FROM (\n'; aggQuery += this.generateJoinQuery(pivots, aggregations, whereFilters, joinTables); aggQuery += ')\n'; return aggQuery; } // Takes a list of pivots and aggregations and generates a query that // extracts all pivots and aggregation partitions and groups by all // columns and orders by each aggregation as requested. private generateQueryImpl( pivots: PivotAttrs[], aggregations: AggregationAttrs[], whereFilters: string[], joinTables: string[], isStackQuery: boolean, orderBy: boolean): string { // No need to generate query if there is no selected pivots or // aggregations. if (pivots.length === 0 && aggregations.length === 0) { return ''; } let query = '\nSELECT\n'; const pivotCols = getSqlAliasedPivotColumns(pivots); const aggCols = getSqlAliasedAggregationsColumns( aggregations, /* has_pivots_selected = */ pivots.length > 0, isStackQuery); query += pivotCols.concat(aggCols).join(',\n '); query += '\n'; query += 'FROM (\n'; query += this.generateAggregationQuery( pivots, aggregations, whereFilters, joinTables, isStackQuery); query += ')\n'; query += 'GROUP BY '; // Grouping by each pivot, additional pivots, and aggregations. const aggregationsGroupBy = aggregations.map(aggregation => getSqlAggregationAlias(aggregation)); query += pivotCols.concat(aggregationsGroupBy).join(', '); query += '\n'; const pivotsOrderBy = []; // Sort by depth first if generating a stack query, to ensure that the // parents appear first before their children and allow us to nest the // results into an expandable structure. if (orderBy && isStackQuery) { pivotsOrderBy.push( `${getSqlHiddenPivotAlias(getStackDepthColumn(pivots[0]))} ASC`); } // For each aggregation we order by either 'DESC' or 'ASC' as // requested (DESC by default). const orderString = (aggregation: AggregationAttrs) => `${getSqlAggregationAlias(aggregation)} ` + `${aggregation.order}`; const aggregationsOrderBy = aggregations.map(aggregation => orderString(aggregation)); if (orderBy && pivotsOrderBy.length + aggregationsOrderBy.length > 0) { query += 'ORDER BY '; query += pivotsOrderBy.concat(aggregationsOrderBy).join(', '); query += '\n'; } return query; } generateQuery( pivots: PivotAttrs[], aggregations: AggregationAttrs[], whereFilters: string[], joinTables: string[]) { return this.generateQueryImpl( pivots, aggregations, whereFilters, joinTables, /* is_stack_query = */ false, /* order_by = */ true); } generateStackQuery( pivots: PivotAttrs[], aggregations: AggregationAttrs[], whereFilters: string[], joinTables: string[], stackId: string) { const stackQuery = this.generateQueryImpl( pivots, aggregations, whereFilters, joinTables, /* is_stack_query = */ true, /* order_by = */ true); // Query the next column rows for the parent row. if (pivots.length > 1) { const stackPivot = pivots[0]; const currStackQuery = this.generateQueryImpl( pivots, aggregations, whereFilters.concat(getParentStackWhereFilter(stackPivot, stackId)), AVAILABLE_TABLES, /* is_stack_query = */ true, /* order_by = */ false); return `${currStackQuery} UNION ALL ${stackQuery}`; } return stackQuery; } }
the_stack
import { computed, reactive, ref, toRefs, watch } from 'vue' import { createPinia, defineStore, DefineStoreOptions, setActivePinia, StateTree, } from '../src' function defineOptions< O extends Omit<DefineStoreOptions<string, StateTree, any, any>, 'id'> >(options: O): O { return options } describe('HMR', () => { const baseOptions = defineOptions({ state: () => ({ n: 0, arr: [], nestedArr: { arr: [], }, nested: { a: 'a', }, }), actions: { increment(amount = 1) { // @ts-ignore this.n += amount }, }, getters: { double: (state: any) => state.n * 2, }, }) beforeEach(() => { setActivePinia(createPinia()) }) describe('Setup store', () => { const baseSetup = () => { const state = reactive({ n: 0, arr: [], nestedArr: { arr: [], }, nested: { a: 'a', }, }) function increment(amount = 1) { state.n += amount } const double = computed(() => state.n * 2) return { ...toRefs(state), increment, double } } describe('state', () => { it('adds new state properties', () => { const useStore = defineStore('id', baseSetup) const store: any = useStore() store.n++ // simulate a hmr defineStore('id', () => { const state = reactive({ newOne: 'hey', n: 0, }) function increment(amount = 1) { state.n += amount } const double = computed(() => state.n * 2) return { ...toRefs(state), increment, double } })(null, store) expect(store.$state).toEqual({ n: 1, newOne: 'hey' }) expect(store.n).toBe(1) expect(store.newOne).toBe('hey') defineStore('id', () => { const state = reactive({ other: 'new', n: 0, }) function increment(amount = 1) { state.n += amount } const double = computed(() => state.n * 2) return { ...toRefs(state), increment, double } })(null, store) expect(store.$state).toEqual({ n: 1, other: 'new' }) expect(store.n).toBe(1) expect(store).not.toHaveProperty('newOne') expect(store.other).toBe('new') }) it('keeps state reactive', () => { const useStore = defineStore('id', baseSetup) const store: any = useStore() const directSpy = jest.fn() const $stateSpy = jest.fn() watch(() => store.n, directSpy, { flush: 'sync' }) watch(() => store.$state.n, $stateSpy, { flush: 'sync' }) // simulate a hmr defineStore('id', () => { const state = reactive({ newOne: 'hey', n: 0, }) function increment(amount = 1) { state.n += amount } const double = computed(() => state.n * 2) return { ...toRefs(state), increment, double } })(null, store) expect(directSpy).toHaveBeenCalledTimes(0) expect($stateSpy).toHaveBeenCalledTimes(0) store.n++ expect(directSpy).toHaveBeenCalledTimes(1) expect($stateSpy).toHaveBeenCalledTimes(1) store.$state.n++ expect(directSpy).toHaveBeenCalledTimes(2) expect($stateSpy).toHaveBeenCalledTimes(2) defineStore('id', () => { const state = reactive({ other: 'new', n: 0, }) function increment(amount = 1) { state.n += amount } const double = computed(() => state.n * 2) return { ...toRefs(state), increment, double } })(null, store) store.n++ expect(directSpy).toHaveBeenCalledTimes(3) expect($stateSpy).toHaveBeenCalledTimes(3) store.$state.n++ expect(directSpy).toHaveBeenCalledTimes(4) expect($stateSpy).toHaveBeenCalledTimes(4) }) it.todo('handles nested objects updates') }) describe('actions', () => { it('adds new actions', () => { const useStore = defineStore('id', baseSetup) const store: any = useStore() // simulate a hmr defineStore('id', () => { const data = baseSetup() function decrement() { data.n.value-- } return { ...data, decrement } })(null, store) store.increment() expect(store.n).toBe(1) expect(store.$state.n).toBe(1) store.decrement() expect(store.n).toBe(0) expect(store.$state.n).toBe(0) defineStore('id', baseSetup)(null, store) store.increment() expect(store.n).toBe(1) expect(store.$state.n).toBe(1) expect(store).not.toHaveProperty('decrement') }) }) describe('getters', () => { it('adds new getters properties', () => { const useStore = defineStore('id', baseSetup) const store: any = useStore() expect(store.double).toBe(0) // simulate a hmr defineStore('id', () => { const data = baseSetup() const triple = computed(() => data.n.value * 3) return { ...data, triple } })(null, store) store.n = 3 expect(store.double).toBe(6) expect(store.triple).toBe(9) defineStore('id', baseSetup)(null, store) store.n = 4 expect(store.double).toBe(8) expect(store).not.toHaveProperty('triple') }) it('keeps getters reactive', () => { const useStore = defineStore('id', baseSetup) const store: any = useStore() const spy = jest.fn() watch( () => { return store.double }, spy, { flush: 'sync' } ) // simulate a hmr defineStore('id', () => { const data = baseSetup() data.n.value = 2 // @ts-expect-error: not defined data.newThing = ref(true) return data })(null, store) // n isn't changed expect(spy).toHaveBeenCalledTimes(0) store.n++ // expect(store.double).toBe(6) expect(spy).toHaveBeenCalledTimes(1) defineStore('id', baseSetup)(null, store) store.n++ // expect(store.double).toBe(8) expect(spy).toHaveBeenCalledTimes(2) }) }) }) describe('Options store', () => { describe('state', () => { it('adds new state properties', () => { const useStore = defineStore('id', baseOptions) const store: any = useStore() store.n++ // simulate a hmr defineStore('id', { ...baseOptions, state: () => ({ newOne: 'hey', n: 0 }), })(null, store) expect(store.$state).toEqual({ n: 1, newOne: 'hey' }) expect(store.n).toBe(1) expect(store.newOne).toBe('hey') defineStore('id', { ...baseOptions, state: () => ({ other: 'new', n: 0 }), })(null, store) expect(store.$state).toEqual({ n: 1, other: 'new' }) expect(store.n).toBe(1) expect(store).not.toHaveProperty('newOne') expect(store.other).toBe('new') }) it('patches nested objects', () => { const useStore = defineStore('id', baseOptions) const store: any = useStore() // simulate a hmr defineStore('id', { ...baseOptions, state: () => ({ nested: { a: 'b', b: 'b' } }), })(null, store) expect(store.$state).toEqual({ nested: { a: 'a', b: 'b' } }) defineStore('id', { ...baseOptions, state: () => ({ nested: { b: 'c' } }), })(null, store) // removes the nested a expect(store.$state).toEqual({ nested: { b: 'b' } }) }) it('skips arrays', () => { const useStore = defineStore('id', baseOptions) const store: any = useStore() // simulate a hmr defineStore('id', { ...baseOptions, state: () => ({ arr: [2] }), })(null, store) expect(store.$state).toEqual({ arr: [] }) defineStore('id', { ...baseOptions, state: () => ({ arr: [1] }), })(null, store) expect(store.$state).toEqual({ arr: [] }) }) it('skips nested arrays', () => { const useStore = defineStore('id', baseOptions) const store: any = useStore() // simulate a hmr defineStore('id', { ...baseOptions, state: () => ({ nestedArr: { arr: [2] } }), })(null, store) expect(store.$state).toEqual({ nestedArr: { arr: [] } }) defineStore('id', { ...baseOptions, state: () => ({ nestedArr: { arr: [1] } }), })(null, store) expect(store.$state).toEqual({ nestedArr: { arr: [] } }) }) it('keeps state reactive', () => { const useStore = defineStore('id', baseOptions) const store: any = useStore() const directSpy = jest.fn() const $stateSpy = jest.fn() watch(() => store.n, directSpy, { flush: 'sync' }) watch(() => store.$state.n, $stateSpy, { flush: 'sync' }) // simulate a hmr defineStore('id', { ...baseOptions, state: () => ({ newOne: 'hey', n: 0 }), })(null, store) expect(directSpy).toHaveBeenCalledTimes(0) expect($stateSpy).toHaveBeenCalledTimes(0) store.n++ expect(directSpy).toHaveBeenCalledTimes(1) expect($stateSpy).toHaveBeenCalledTimes(1) store.$state.n++ expect(directSpy).toHaveBeenCalledTimes(2) expect($stateSpy).toHaveBeenCalledTimes(2) defineStore('id', { ...baseOptions, state: () => ({ other: 'new', n: 0 }), })(null, store) store.n++ expect(directSpy).toHaveBeenCalledTimes(3) expect($stateSpy).toHaveBeenCalledTimes(3) store.$state.n++ expect(directSpy).toHaveBeenCalledTimes(4) expect($stateSpy).toHaveBeenCalledTimes(4) }) it.todo('handles nested objects updates') }) describe('actions', () => { it('adds new actions', () => { const useStore = defineStore('id', baseOptions) const store: any = useStore() // simulate a hmr defineStore('id', { ...baseOptions, actions: { ...baseOptions.actions, decrement() { this.n-- }, }, })(null, store) store.increment() expect(store.n).toBe(1) expect(store.$state.n).toBe(1) store.decrement() expect(store.n).toBe(0) expect(store.$state.n).toBe(0) defineStore('id', baseOptions)(null, store) store.increment() expect(store.n).toBe(1) expect(store.$state.n).toBe(1) expect(store).not.toHaveProperty('decrement') }) }) describe('getters', () => { it('adds new getters properties', () => { const useStore = defineStore('id', baseOptions) const store: any = useStore() expect(store.double).toBe(0) // simulate a hmr defineStore('id', { ...baseOptions, getters: { ...baseOptions.getters, triple: (state) => state.n * 3, }, })(null, store) store.n = 3 expect(store.double).toBe(6) expect(store.triple).toBe(9) defineStore('id', baseOptions)(null, store) store.n = 4 expect(store.double).toBe(8) expect(store).not.toHaveProperty('triple') }) it('keeps getters reactive', () => { const useStore = defineStore('id', baseOptions) const store: any = useStore() const spy = jest.fn() watch( () => { return store.double }, spy, { flush: 'sync' } ) // simulate a hmr defineStore('id', { ...baseOptions, state: () => ({ n: 2, newThing: true }), })(null, store) // n isn't changed expect(spy).toHaveBeenCalledTimes(0) store.n++ // expect(store.double).toBe(6) expect(spy).toHaveBeenCalledTimes(1) defineStore('id', baseOptions)(null, store) store.n++ // expect(store.double).toBe(8) expect(spy).toHaveBeenCalledTimes(2) }) }) }) })
the_stack
import { createApiPipelineWithUrl, ApiInvokeOptions } from 'farrow-api-client' /** * {@label AddPetInput} */ export type AddPetInput = { /** * @remarks Pet object that needs to be added to the store */ body: Pet } /** * {@label Pet} */ export type Pet = { id: number category: Category name: string photoUrls: string[] tags: Tag[] /** * @remarks pet status in the store */ status: 'available' | 'pending' | 'Sold' } /** * {@label Category} */ export type Category = { id: number name: string } /** * {@label Tag} */ export type Tag = { id: number name: string } /** * {@label InvalidInput} */ export type InvalidInput = { type: 'InvalidInput' } /** * {@label AddPetOutput} */ export type AddPetOutput = { type: 'AddPetOutput' pet: Pet } /** * {@label UpdatePetInput} */ export type UpdatePetInput = { /** * @remarks Pet object that needs to be added to the store */ body: Pet } /** * {@label InvalidIDSupplied} */ export type InvalidIDSupplied = { type: 'InvalidIDSupplied' } /** * {@label PetNotFound} */ export type PetNotFound = { type: 'PetNotFound' } /** * {@label ValidationException} */ export type ValidationException = { type: 'ValidationException' } /** * {@label UpdatePetOutput} */ export type UpdatePetOutput = { type: 'UpdatePetOutput' pet: Pet } /** * {@label DeletePetInput} */ export type DeletePetInput = { /** * @remarks ID of pet to delete */ petId: number } /** * {@label DeletePetOutput} */ export type DeletePetOutput = { /** * @remarks ID of pet which was deleted */ petId: number } /** * {@label FindPetByStatusInput} */ export type FindPetByStatusInput = { /** * @remarks Status values that need to be considered for filter */ status: ('available' | 'pending' | 'Sold')[] } /** * {@label InvalidPetStatus} */ export type InvalidPetStatus = { type: 'InvalidPetStatus' } /** * {@label FindPetByStatusOutput} */ export type FindPetByStatusOutput = { type: 'FindPetByStatusOutput' pets: Pet[] } /** * {@label InvalidPetTagValue} */ export type InvalidPetTagValue = { type: 'InvalidPetTagValue' } /** * {@label GetPetByIdInput} */ export type GetPetByIdInput = { /** * @remarks ID of pet to return */ petId: number } /** * {@label GetPetByIdOutput} */ export type GetPetByIdOutput = { pet: Pet } /** * {@label PlaceOrderInput} */ export type PlaceOrderInput = { /** * @remarks order placed for purchasing the pet */ body: Order } /** * {@label Order} */ export type Order = { id: number petId: number quantity: number shipDate: number /** * @remarks Order Status */ status: 'placed' | 'approved' | 'delivered' complete: boolean } /** * {@label InvalidOrder} */ export type InvalidOrder = { type: 'InvalidOrder' } /** * {@label PlaceOrderOutput} */ export type PlaceOrderOutput = { order: Order } /** * {@label GetOrderByIdInput} */ export type GetOrderByIdInput = { /** * @remarks ID of pet that needs to be fetched */ orderId: number } /** * {@label OrderNotFound} */ export type OrderNotFound = { type: 'OrderNotFound' } /** * {@label GetOrderByIdOutput} */ export type GetOrderByIdOutput = { type: 'GetOrderByIdOutput' order: Order } /** * {@label DeleteOrderInput} */ export type DeleteOrderInput = { /** * @remarks ID of the order that needs to be deleted */ orderId: number } /** * {@label DeleteOrderOutput} */ export type DeleteOrderOutput = { type: 'DeleteOrderOutput' /** * @remarks ID of the order that was deleted */ orderId: number } /** * {@label GetInventoryOutput} */ export type GetInventoryOutput = { inventory: Record<string, number> } /** * {@label CreateUsersWithArrayInput} */ export type CreateUsersWithArrayInput = { /** * @remarks List of user object */ body: User[] } /** * {@label User} */ export type User = { id: number userName: string firstName: string lastName: string email: string password: string phone: string /** * @remarks User Status */ userStatus: number } /** * {@label CreateUsersWithArrayOutput} */ export type CreateUsersWithArrayOutput = { users: User[] } /** * {@label GetUserByNameInput} */ export type GetUserByNameInput = { /** * @remarks The name that needs to be fetched. Use user1 for testing. */ username: string } /** * {@label InvalidUserSupplied} */ export type InvalidUserSupplied = { type: 'InvalidUserSupplied' } /** * {@label UserNotFound} */ export type UserNotFound = { type: 'UserNotFound' } /** * {@label GetUserByNameOutput} */ export type GetUserByNameOutput = { type: 'GetUserByNameOutput' user: User } /** * {@label UpdateUserInput} */ export type UpdateUserInput = { /** * @remarks name that need to be updated */ username: string /** * @remarks Updated user object */ body: User } /** * {@label UpdateUserOutput} */ export type UpdateUserOutput = { type: 'UpdateUserOutput' user: User } /** * {@label DeleteUserInput} */ export type DeleteUserInput = { /** * @remarks The name that needs to be deleted */ username: string } /** * {@label DeleteUserOutput} */ export type DeleteUserOutput = { type: 'DeleteUserOutput' /** * @remarks The name that needs to be deleted */ username: string } /** * {@label LoginUserInput} */ export type LoginUserInput = { /** * @remarks The user name for login */ username: string /** * @remarks The password for login in clear text */ password: string } /** * {@label InvalidUsernameSupplied} */ export type InvalidUsernameSupplied = { type: 'InvalidUsernameSupplied' } /** * {@label InvalidPasswordSupplied} */ export type InvalidPasswordSupplied = { type: 'InvalidPasswordSupplied' } /** * {@label LoginUserOutput} */ export type LoginUserOutput = { /** * @remarks login user */ user: User } /** * {@label CreateUserInput} */ export type CreateUserInput = { /** * @remarks Created user object */ body: User } /** * {@label CreateUserOutput} */ export type CreateUserOutput = { type: 'CreateUserOutput' user: User } export const url = 'http://localhost:3002/service/pet-store' export const apiPipeline = createApiPipelineWithUrl(url) export const api = { pet: { /** * @remarks Add a new pet to the store */ addPet: (input: AddPetInput, options?: ApiInvokeOptions) => apiPipeline.invoke({ type: 'Single', path: ['pet', 'addPet'], input }, options) as Promise< InvalidInput | AddPetOutput >, /** * @remarks Update an existing pet */ updatePet: (input: UpdatePetInput, options?: ApiInvokeOptions) => apiPipeline.invoke({ type: 'Single', path: ['pet', 'updatePet'], input }, options) as Promise< InvalidIDSupplied | PetNotFound | ValidationException | UpdatePetOutput >, /** * @remarks Deletes a pet */ deletePet: (input: DeletePetInput, options?: ApiInvokeOptions) => apiPipeline.invoke({ type: 'Single', path: ['pet', 'deletePet'], input }, options) as Promise< InvalidIDSupplied | PetNotFound | DeletePetOutput >, /** * @remarks Finds Pets by status * * Multiple status values can be provided with comma separated strings */ findPetByStatus: (input: FindPetByStatusInput, options?: ApiInvokeOptions) => apiPipeline.invoke({ type: 'Single', path: ['pet', 'findPetByStatus'], input }, options) as Promise< InvalidPetStatus | FindPetByStatusOutput >, /** * @remarks Finds Pets by tags * * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. */ findPetsByTags: (input: FindPetByStatusInput, options?: ApiInvokeOptions) => apiPipeline.invoke({ type: 'Single', path: ['pet', 'findPetsByTags'], input }, options) as Promise< InvalidPetTagValue | FindPetByStatusOutput >, /** * @remarks Find pet by ID * * Returns a single pet */ getPetById: (input: GetPetByIdInput, options?: ApiInvokeOptions) => apiPipeline.invoke({ type: 'Single', path: ['pet', 'getPetById'], input }, options) as Promise< InvalidIDSupplied | PetNotFound | GetPetByIdOutput >, }, store: { /** * @remarks Place an order for a pet */ placeOrder: (input: PlaceOrderInput, options?: ApiInvokeOptions) => apiPipeline.invoke({ type: 'Single', path: ['store', 'placeOrder'], input }, options) as Promise< InvalidOrder | PlaceOrderOutput >, /** * @remarks Find purchase order by ID * * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions */ getOrderById: (input: GetOrderByIdInput, options?: ApiInvokeOptions) => apiPipeline.invoke({ type: 'Single', path: ['store', 'getOrderById'], input }, options) as Promise< InvalidIDSupplied | OrderNotFound | GetOrderByIdOutput >, /** * @remarks Delete purchase order by ID * * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors */ deleteOrder: (input: DeleteOrderInput, options?: ApiInvokeOptions) => apiPipeline.invoke({ type: 'Single', path: ['store', 'deleteOrder'], input }, options) as Promise< InvalidIDSupplied | OrderNotFound | DeleteOrderOutput >, /** * @remarks Returns pet inventories by status * * Returns a map of status codes to quantities */ getInventory: (input: {}, options?: ApiInvokeOptions) => apiPipeline.invoke( { type: 'Single', path: ['store', 'getInventory'], input }, options, ) as Promise<GetInventoryOutput>, }, user: { /** * @remarks Creates list of users with given input array */ createUsersWithArray: (input: CreateUsersWithArrayInput, options?: ApiInvokeOptions) => apiPipeline.invoke( { type: 'Single', path: ['user', 'createUsersWithArray'], input }, options, ) as Promise<CreateUsersWithArrayOutput>, /** * @remarks Get user by user name */ getUserByName: (input: GetUserByNameInput, options?: ApiInvokeOptions) => apiPipeline.invoke({ type: 'Single', path: ['user', 'getUserByName'], input }, options) as Promise< InvalidUserSupplied | UserNotFound | GetUserByNameOutput >, /** * @remarks Updated user * * This can only be done by the logged in user. */ updateUser: (input: UpdateUserInput, options?: ApiInvokeOptions) => apiPipeline.invoke({ type: 'Single', path: ['user', 'updateUser'], input }, options) as Promise< InvalidUserSupplied | UserNotFound | UpdateUserOutput >, /** * @remarks Delete user * * This can only be done by the logged in user. */ deleteUser: (input: DeleteUserInput, options?: ApiInvokeOptions) => apiPipeline.invoke({ type: 'Single', path: ['user', 'deleteUser'], input }, options) as Promise<DeleteUserOutput>, /** * @remarks Logs user into the system */ loginUser: (input: LoginUserInput, options?: ApiInvokeOptions) => apiPipeline.invoke({ type: 'Single', path: ['user', 'loginUser'], input }, options) as Promise< InvalidUsernameSupplied | InvalidPasswordSupplied | LoginUserOutput >, /** * @remarks Logs out current logged in user session */ logoutUser: (input: {}, options?: ApiInvokeOptions) => apiPipeline.invoke({ type: 'Single', path: ['user', 'logoutUser'], input }, options) as Promise<{ username: string }>, /** * @remarks Create user * * This can only be done by the logged in user. * @param input - user input * @returns user output */ createUser: (input: CreateUserInput, options?: ApiInvokeOptions) => apiPipeline.invoke({ type: 'Single', path: ['user', 'createUser'], input }, options) as Promise<CreateUserOutput>, }, }
the_stack
// TypeScript Version: 2.2 import * as braces from 'braces'; declare namespace micromatch { interface Item { glob: string; regex: RegExp; input: string; output: string; } interface Options { /** * Allow glob patterns without slashes to match a file path based on its basename. Same behavior as [minimatch](https://github.com/isaacs/minimatch) option `matchBase`. * * @default false * * @example * ```js * mm(['a/b.js', 'a/c.md'], '*.js'); * //=> [] * * mm(['a/b.js', 'a/c.md'], '*.js', {matchBase: true}); * //=> ['a/b.js'] * ``` */ basename?: boolean; /** * Enabled by default, this option enforces bash-like behavior with stars immediately following a bracket expression. * Bash bracket expressions are similar to regex character classes, but unlike regex, a star following a bracket expression **does not repeat the bracketed characters**. * Instead, the star is treated the same as an other star. * * @default true * * @example * ```js * var files = ['abc', 'ajz']; * console.log(mm(files, '[a-c]*')); * //=> ['abc', 'ajz'] * * console.log(mm(files, '[a-c]*', {bash: false})); * ``` */ bash?: boolean; /** * Return regex matches in supporting methods. * * @default undefined */ capture?: boolean; /** * Allows glob to match any part of the given string(s). * * @default undefined */ contains?: boolean; /** * Current working directory. Used by `picomatch.split()` * * @default process.cwd() */ cwd?: string; /** * Debug regular expressions when an error is thrown. * * @default undefined */ debug?: boolean; /** * Match dotfiles. Otherwise dotfiles are ignored unless a `.` is explicitly defined in the pattern. * * @default false */ dot?: boolean; /** * Custom function for expanding ranges in brace patterns, such as `{a..z}`. * The function receives the range values as two arguments, and it must return a string to be used in the generated regex. * It's recommended that returned strings be wrapped in parentheses. This option is overridden by the expandBrace option. * * @default undefined */ expandRange?: (left: string, right: string, options: Options) => string; /** * Similar to the `--failglob` behavior in Bash, throws an error when no matches are found. * * @default false */ failglob?: boolean; /** * To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to false. * * @default true */ fastpaths?: boolean; /** * Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. * * @default undefined */ flags?: boolean; /** * Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. * * @default undefined */ format?: (returnedString: string) => string; /** * One or more glob patterns for excluding strings that should not be matched from the result. * * @default undefined */ ignore?: string | ReadonlyArray<string>; /** * Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. * * @default false */ keepQuotes?: boolean; /** * When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. * * @default undefined */ literalBrackets?: boolean; /** * Support regex positive and negative lookbehinds. Note that you must be using Node 8.1.10 or higher to enable regex lookbehinds. * * @default true */ lookbehinds?: boolean; /** * Alias for `basename`. * * @default false */ matchBase?: boolean; /** * Limit the max length of the input string. An error is thrown if the input string is longer than this value. * * @default 65536 */ maxLength?: number; /** * Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. * * @default false */ nobrace?: boolean; /** * Disable matching with regex brackets. * * @default undefined */ nobracket?: boolean; /** * Perform case-insensitive matching. Equivalent to the regex `i` flag. * Note that this option is ignored when the `flags` option is defined. * * @default false */ nocase?: boolean; /** * Alias for `noextglob` * * @default false */ noext?: boolean; /** * Disable support for matching with extglobs (like `+(a|b)`) * * @default false */ noextglob?: boolean; /** * Disable matching with globstars (`**`). * * @default undefined */ noglobstar?: boolean; /** * Disallow negation (`!`) patterns, and treat leading `!` as a literal character to match. * * @default undefined */ nonegate?: boolean; /** * Disable support for regex quantifiers (like `a{1,2}`) and treat them as brace patterns to be expanded. * * @default false */ noquantifiers?: boolean; /** * Function to be called on ignored items. * * @default undefined */ onIgnore?: (item: Item) => void; /** * Function to be called on matched items. * * @default undefined */ onMatch?: (item: Item) => void; /** * Function to be called on all items, regardless of whether or not they are matched or ignored. * * @default undefined */ onResult?: (item: Item) => void; /** * Support POSIX character classes ("posix brackets"). * * @default false */ posix?: boolean; /** * String to prepend to the generated regex used for matching. * * @default undefined */ prepend?: boolean; /** * Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). * * @default false */ regex?: boolean; /** * Throw an error if brackets, braces, or parens are imbalanced. * * @default undefined */ strictBrackets?: boolean; /** * When true, picomatch won't match trailing slashes with single stars. * * @default undefined */ strictSlashes?: boolean; /** * Remove backslashes from returned matches. * * @default undefined * * @example * In this example we want to match a literal `*`: * * ```js * mm.match(['abc', 'a\\*c'], 'a\\*c'); * //=> ['a\\*c'] * * mm.match(['abc', 'a\\*c'], 'a\\*c', {unescape: true}); * //=> ['a*c'] * ``` */ unescape?: boolean; /** * Convert all slashes in file paths to forward slashes. This does not convert slashes in the glob pattern itself * * @default undefined */ windows?: boolean; } interface ScanOptions extends Options { /** * When `true`, the returned object will include an array of `tokens` (objects), representing each path "segment" in the scanned glob pattern. * * @default false */ tokens?: boolean; /** * When `true`, the returned object will include an array of strings representing each path "segment" in the scanned glob pattern. * This is automatically enabled when `options.tokens` is `true`. * * @default false */ parts?: boolean; } interface ScanInfo { prefix: string; input: string; start: number; base: string; glob: string; isBrace: boolean; isBracket: boolean; isGlob: boolean; isExtglob: boolean; isGlobstar: boolean; negated: boolean; } interface ScanInfoToken { value: string; depth: number; isGlob: boolean; backslashes?: boolean; isBrace?: boolean; isBracket?: boolean; isExtglob?: boolean; isGlobstar?: boolean; isPrefix?: boolean; negated?: boolean; } interface ScanInfoWithParts extends ScanInfo { slashes: number[]; parts: string[]; } interface ScanInfoWithTokens extends ScanInfoWithParts { maxDepth: number; tokens: ScanInfoToken[]; } } interface Micromatch { /** * The main function takes a list of strings and one or more glob patterns to use for matching. * * @param list A list of strings to match * @param patterns One or more glob patterns to use for matching. * @param options See available options for changing how matches are performed * @returns Returns an array of matches * * @example * ```js * var mm = require('micromatch'); * mm(list, patterns[, options]); * * console.log(mm(['a.js', 'a.txt'], ['*.js'])); * //=> [ 'a.js' ] * ``` */ (list: ReadonlyArray<string>, patterns: string | ReadonlyArray<string>, options?: micromatch.Options): string[]; /** * Similar to the main function, but `pattern` must be a string. * * @param list Array of strings to match * @param pattern Glob pattern to use for matching. * @param options See available options for changing how matches are performed * @returns Returns an array of matches * * @example * ```js * var mm = require('micromatch'); * mm.match(list, pattern[, options]); * * console.log(mm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a')); * //=> ['a.a', 'a.aa'] * ``` */ match(list: ReadonlyArray<string>, pattern: string, options?: micromatch.Options): string[]; /** * Returns true if the specified `string` matches the given glob `pattern`. * * @param string String to match * @param pattern Glob pattern to use for matching. * @param options See available options for changing how matches are performed * @returns Returns true if the string matches the glob pattern. * * @example * ```js * var mm = require('micromatch'); * mm.isMatch(string, pattern[, options]); * * console.log(mm.isMatch('a.a', '*.a')); * //=> true * console.log(mm.isMatch('a.b', '*.a')); * //=> false * ``` */ isMatch(string: string, pattern: string | ReadonlyArray<string>, options?: micromatch.Options): boolean; /** * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. * * @param list The string or array of strings to test. Returns as soon as the first match is found. * @param patterns One or more glob patterns to use for matching. * @param options See available options for changing how matches are performed * @returns Returns true if any patterns match `str` * * @example * ```js * var mm = require('micromatch'); * mm.some(list, patterns[, options]); * * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); * // true * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); * // false * ``` */ some( list: string | ReadonlyArray<string>, patterns: string | ReadonlyArray<string>, options?: micromatch.Options, ): boolean; /** * Returns true if every string in the given `list` matches any of the given glob `patterns`. * * @param list The string or array of strings to test. * @param patterns One or more glob patterns to use for matching. * @param options See available options for changing how matches are performed * @returns Returns true if any patterns match `str` * * @example * ```js * var mm = require('micromatch'); * mm.every(list, patterns[, options]); * * console.log(mm.every('foo.js', ['foo.js'])); * // true * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); * // true * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); * // false * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); * // false * ``` */ every( list: string | ReadonlyArray<string>, patterns: string | ReadonlyArray<string>, options?: micromatch.Options, ): boolean; /** * Returns true if **any** of the given glob `patterns` match the specified `string`. * * @param str The string to test. * @param patterns One or more glob patterns to use for matching. * @param options See available options for changing how matches are performed * @returns Returns true if any patterns match `str` * * @example * ```js * var mm = require('micromatch'); * mm.any(string, patterns[, options]); * * console.log(mm.any('a.a', ['b.*', '*.a'])); * //=> true * console.log(mm.any('a.a', 'b.*')); * //=> false * ``` */ any( str: string | ReadonlyArray<string>, patterns: string | ReadonlyArray<string>, options?: micromatch.Options, ): boolean; /** * Returns true if **all** of the given `patterns` match the specified string. * * @param str The string to test. * @param patterns One or more glob patterns to use for matching. * @param options See available options for changing how matches are performed * @returns Returns true if any patterns match `str` * * @example * ```js * var mm = require('micromatch'); * mm.all(string, patterns[, options]); * * console.log(mm.all('foo.js', ['foo.js'])); * // true * * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); * // false * * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); * // true * * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); * // true * ``` */ all( str: string | ReadonlyArray<string>, patterns: string | ReadonlyArray<string>, options?: micromatch.Options, ): boolean; /** * Returns a list of strings that _**do not match any**_ of the given `patterns`. * * @param list Array of strings to match. * @param patterns One or more glob pattern to use for matching. * @param options See available options for changing how matches are performed * @returns Returns an array of strings that **do not match** the given patterns. * * @example * ```js * var mm = require('micromatch'); * mm.not(list, patterns[, options]); * * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); * //=> ['b.b', 'c.c'] * ``` */ not(list: ReadonlyArray<string>, patterns: string | ReadonlyArray<string>, options?: micromatch.Options): string[]; /** * Returns true if the given `string` contains the given pattern. Similar to [.isMatch](#isMatch) but the pattern can match any part of the string. * * @param str The string to match. * @param patterns Glob pattern to use for matching. * @param options See available options for changing how matches are performed * @returns Returns true if the patter matches any part of `str`. * * @example * ```js * var mm = require('micromatch'); * mm.contains(string, pattern[, options]); * * console.log(mm.contains('aa/bb/cc', '*b')); * //=> true * console.log(mm.contains('aa/bb/cc', '*d')); * //=> false * ``` */ contains(str: string, patterns: string | ReadonlyArray<string>, options?: micromatch.Options): boolean; /** * Filter the keys of the given object with the given `glob` pattern and `options`. Does not attempt to match nested keys. * If you need this feature, use [glob-object](https://github.com/jonschlinkert/glob-object) instead. * * @param object The object with keys to filter. * @param patterns One or more glob patterns to use for matching. * @param options See available options for changing how matches are performed * @returns Returns an object with only keys that match the given patterns. * * @example * ```js * var mm = require('micromatch'); * mm.matchKeys(object, patterns[, options]); * * var obj = { aa: 'a', ab: 'b', ac: 'c' }; * console.log(mm.matchKeys(obj, '*b')); * //=> { ab: 'b' } * ``` */ matchKeys<T>(object: T, patterns: string | ReadonlyArray<string>, options?: micromatch.Options): Partial<T>; /** * Returns a memoized matcher function from the given glob `pattern` and `options`. The returned function takes a string to match as its only argument and returns true if the string is a match. * * @param pattern Glob pattern * @param options See available options for changing how matches are performed. * @returns Returns a matcher function. * * @example * ```js * var mm = require('micromatch'); * mm.matcher(pattern[, options]); * * var isMatch = mm.matcher('*.!(*a)'); * console.log(isMatch('a.a')); * //=> false * console.log(isMatch('a.b')); * //=> true * ``` */ matcher(pattern: string, options?: micromatch.Options): (str: string) => boolean; /** * Returns an array of matches captured by `pattern` in `string, or`null` if the pattern did not match. * * @param pattern Glob pattern to use for matching. * @param string String to match * @param options See available options for changing how matches are performed * @returns Returns an array of captures if the string matches the glob pattern, otherwise `null`. * * @example * ```js * var mm = require('micromatch'); * mm.capture(pattern, string[, options]); * * console.log(mm.capture('test/*.js', 'test/foo.js')); * //=> ['foo'] * console.log(mm.capture('test/*.js', 'foo/bar.css')); * //=> null * ``` */ capture(pattern: string, string: string, options?: micromatch.Options): string[] | null; /** * Create a regular expression from the given glob `pattern`. * * @param pattern A glob pattern to convert to regex. * @param options See available options for changing how matches are performed. * @returns Returns a regex created from the given pattern. * * @example * ```js * var mm = require('micromatch'); * mm.makeRe(pattern[, options]); * * console.log(mm.makeRe('*.js')); * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ * ``` */ makeRe(pattern: string, options?: micromatch.Options): RegExp; /** * Expand the given brace `pattern`. * * @param pattern String with brace pattern to expand. * @param options Any options to change how expansion is performed. See the [braces](https://github.com/micromatch/braces) library for all available options. * * @example * ```js * var mm = require('micromatch'); * console.log(mm.braces('foo/{a,b}/bar')); * //=> ['foo/(a|b)/bar'] * * console.log(mm.braces('foo/{a,b}/bar', {expand: true})); * //=> ['foo/(a|b)/bar'] * ``` */ braces(pattern: string, options?: braces.Options): string[]; /** * Parse a glob pattern to create the source string for a regular expression. * * @returns Returns an AST * * @example * ```js * var mm = require('micromatch'); * mm.parse(pattern[, options]); * * var ast = mm.parse('a/{b,c}/d'); * console.log(ast); * // { type: 'root', * // errors: [], * // input: 'a/{b,c}/d', * // nodes: * // [ { type: 'bos', val: '' }, * // { type: 'text', val: 'a/' }, * // { type: 'brace', * // nodes: * // [ { type: 'brace.open', val: '{' }, * // { type: 'text', val: 'b,c' }, * // { type: 'brace.close', val: '}' } ] }, * // { type: 'text', val: '/d' }, * // { type: 'eos', val: '' } ] } * ``` */ parse(glob: string, options?: micromatch.Options): object; /** * Scan a glob pattern to separate the pattern into segments. */ scan(pattern: string, options: { parts: true } & micromatch.ScanOptions): micromatch.ScanInfoWithParts; scan(pattern: string, options: { tokens: true } & micromatch.ScanOptions): micromatch.ScanInfoWithTokens; scan(pattern: string, options?: micromatch.ScanOptions): micromatch.ScanInfo; } export as namespace micromatch; declare const micromatch: Micromatch; export = micromatch;
the_stack
import axios, { AxiosRequestConfig } from 'axios' import sdk, { Device, DeviceInformation, ScryptedDeviceBase, OnOff, DeviceProvider, ScryptedDeviceType, ThermostatMode, Thermometer, HumiditySensor, TemperatureSetting, Settings, Setting, ScryptedInterface, Refresh, TemperatureUnit, HumidityCommand, HumidityMode, HumiditySetting } from '@scrypted/sdk'; const { deviceManager, log } = sdk; const API_RETRY = 2; // Convert Fahrenheit to Celsius, round to 2 decimal places function convertFtoC(f: number) { let c = (5/9) * (f - 32) return Math.round(c*100)/100 } // Convert Celsius to Fahrenheit, round to 1 decimal place function convertCtoF(c: number) { let f = (c * 1.8) + 32 return Math.round(f*10)/10 } function ecobeeToThermostatMode(mode: string) { // Values: auto, auxHeatOnly, cool, heat, off switch(mode) { case "cool": return ThermostatMode.Cool; case "heat": return ThermostatMode.Heat; case "auto": return ThermostatMode.Auto; case "off": return ThermostatMode.Off; } } function thermostatModeToEcobee(mode: ThermostatMode) { // Values: auto, auxHeatOnly, cool, heat, off switch(mode) { case ThermostatMode.Cool: return "cool"; case ThermostatMode.Heat: return "heat"; case ThermostatMode.Auto: return "auto"; case ThermostatMode.Off: return "off"; } } function humModeFromEcobee(mode: string): HumidityMode { // Values: auto, manual, off switch(mode) { case 'auto': return HumidityMode.Auto; case "manual": return HumidityMode.Humidify; } return HumidityMode.Off } class EcobeeThermostat extends ScryptedDeviceBase implements HumiditySensor, Thermometer, TemperatureSetting, Refresh, OnOff, HumiditySetting, Settings { device: any; revisionList: string[]; provider: EcobeeController; on: boolean; constructor(nativeId: string, provider: EcobeeController, info: DeviceInformation) { super(nativeId); this.provider = provider; this.revisionList = null; this.info = info; this.temperatureUnit = TemperatureUnit.F const modes: ThermostatMode[] = [ThermostatMode.Cool, ThermostatMode.Heat, ThermostatMode.Auto, ThermostatMode.Off]; this.thermostatAvailableModes = modes; let humModes: HumidityMode[] = [HumidityMode.Auto, HumidityMode.Humidify, HumidityMode.Off]; this.humiditySetting = { mode: HumidityMode.Off, availableModes: humModes, } setImmediate(() => this.refresh("constructor", false)); } async getSettings(): Promise<Setting[]> { return [ { title: 'Additional Devices', key: 'additional_devices', value: this.storage.getItem("additional_devices"), choices: ['Fan', 'Humidifier'], description: 'Display additional devices for components', multiple: true, } ] } async putSetting(key: string, value: string): Promise<void> { this.storage.setItem(key, value.toString()); } /* * Get the recommended refresh/poll frequency in seconds for this device. */ async getRefreshFrequency(): Promise<number> { return 15; } /* refresh(): Request from Scrypted to refresh data from device * Poll from API '/thermostatSummary' endpoint for timestamp of last changes and compare to last check * Updates equipmentStatus on each call */ async refresh(refreshInterface: string, userInitiated: boolean): Promise<void> { this.console.log(`${refreshInterface} requested refresh\n ${new Date()}`) const json = { selection: { selectionType: "registered", selectionMatch: this.nativeId, includeEquipmentStatus: true, } } const data = await this.provider.req('get', 'thermostatSummary', json) // Update equipmentStatus, trigger reload if changes detected this._updateEquipmentStatus(data.statusList[0].split(":")[1]); if (this._updateRevisionList(data.revisionList[0])) await this.reload() } /* * Set characteristics based on equipmentStatus from API * * Possible eqipmentStatus values: * heatPump, heatPump[2-3], compCool[1-2], auxHeat[1-3], * fan, humidifier, dehumidifier, ventilator, economizer, * compHotWater, auxHotWater */ _updateEquipmentStatus(equipmentStatus: string): void { equipmentStatus = equipmentStatus.toLowerCase() this.console.log(` Current status: ${equipmentStatus}`); if (equipmentStatus.includes("heat")) // values: heatPump, heatPump[2-3], auxHeat[1-3] this.thermostatActiveMode = ThermostatMode.Heat; else if (equipmentStatus.includes("cool")) // values: compCool[1-2] this.thermostatActiveMode = ThermostatMode.Cool; else this.thermostatActiveMode = ThermostatMode.Off; // fan status if (equipmentStatus.includes('fan')) { this.on = true; } else { this.on = false; } // humidifier status let activeMode = HumidityMode.Off if (equipmentStatus.includes('humidifier')) { activeMode = HumidityMode.Humidify } this.humiditySetting = Object.assign(this.humiditySetting, { activeMode }); } /* revisionListChanged(): Compare a new revision list to the stored list, return true if changed * */ _updateRevisionList(listStr: string): boolean { const listItems = ["tId", "tName", "connected", "thermostat", "alerts", "runtime", "interval"]; const oldList = this.revisionList; this.revisionList = listStr.split(':'); if (!oldList) return true; // Compare each element, skip first 3 for (let i = 3; i < listItems.length; i++) { if (this.revisionList[i] !== oldList[i]) { this.console.log(` Changes detected: ${listItems[i]}`) return true; } } this.console.log(" Changes detected: none"); return false; } /* reload(): Reload all thermostat data from API '/thermostat' endpoint * */ async reload(): Promise<void> { const json = { selection: { selectionType: "registered", selectionMatch: this.nativeId, includeSettings: true, includeRuntime: true, includeEquipmentStatus: true, } } const data = (await this.provider.req('get', 'thermostat', json)).thermostatList[0]; // Set runtime values this.temperature = convertFtoC(Number(data.runtime.actualTemperature)/10) this.humidity = Number(data.runtime.actualHumidity); // Set current equipment status values this._updateEquipmentStatus(data.equipmentStatus); // update based on mode this.thermostatMode = ecobeeToThermostatMode(data.settings.hvacMode); this.thermostatSetpointHigh = convertFtoC(Number(data.runtime.desiredCool)/10) this.thermostatSetpointLow = convertFtoC(Number(data.runtime.desiredHeat)/10) switch(data.settings.hvacMode) { case 'cool': this.thermostatSetpoint = convertFtoC(Number(data.runtime.desiredCool)/10) break; case 'heat': this.thermostatSetpoint = convertFtoC(Number(data.runtime.desiredHeat)/10) break; } // update humidifier based on mode this.humiditySetting = Object.assign(this.humiditySetting, { mode: humModeFromEcobee(data.settings.humidifierMode), humidifierSetpoint: Number(data.settings.humidity), }); } async setHumidity(humidity: HumidityCommand): Promise<void> { this.console.log(`setHumidity ${humidity.mode} ${humidity.humidifierSetpoint}: not yet supported`); } async setThermostatMode(mode: ThermostatMode): Promise<void> { this.console.log(`setThermostatMode ${mode}`) const data = { selection: { selectionType:"registered", selectionMatch: this.nativeId, }, thermostat: { settings:{ hvacMode: thermostatModeToEcobee(mode) } } } const resp = await this.provider.req('post', 'thermostat', undefined, data); if (resp.status.code == 0) { this.console.log("setThermostatMode success") await this.reload(); return; } this.console.log(`setThermostatMode failed: ${resp}`) } async setThermostatSetpoint(degrees: number): Promise<void> { const degF = convertCtoF(degrees); this.console.log(`setThermostatSetpoint ${degrees}C/${degF}F`) if (this.thermostatMode === ThermostatMode.Auto) { this.console.log(`setThermostatSetpoint not running in auto mode`) return; } const data = { selection: { selectionType:"registered", selectionMatch: this.nativeId, }, functions: [ { type:"setHold", params:{ holdType: "nextTransition", heatHoldTemp: degF*10, coolHoldTemp: degF*10, } } ] } const resp = await this.provider.req('post', 'thermostat', undefined, data) if (resp.status.code == 0) { this.console.log("setThermostatSetpoint success") await this.reload(); return; } this.console.log(`setThermostatSetpoint failed: ${resp}`) } async setThermostatSetpointHigh(high: number): Promise<void> { const degFLow = convertCtoF(this.thermostatSetpointLow); const degFHigh = convertCtoF(high); this.console.log(`setThermostatSetpointHigh ${high}C/${degFHigh}F`) const data = { selection: { selectionType:"registered", selectionMatch: this.nativeId, }, functions: [ { type:"setHold", params:{ holdType: "nextTransition", heatHoldTemp: degFLow*10, coolHoldTemp: degFHigh*10, } } ] } const resp = await this.provider.req('post', 'thermostat', undefined, data) if (resp.status.code == 0) { this.console.log("setThermostatSetpointHigh success") await this.reload(); return; } this.console.log(`setThermostatSetpointHigh failed: ${resp}`) } async setThermostatSetpointLow(low: number): Promise<void> { const degFLow = convertCtoF(low); const degFHigh = convertCtoF(this.thermostatSetpointHigh); this.console.log(`setThermostatSetpointLow ${low}C/${degFLow}F`) const data = { selection: { selectionType:"registered", selectionMatch: this.nativeId, }, functions: [ { type:"setHold", params:{ holdType: "nextTransition", heatHoldTemp: degFLow*10, coolHoldTemp: degFHigh*10, } } ] } const resp = await this.provider.req('post', 'thermostat', undefined, data) if (resp.status.code == 0) { this.console.log("setThermostatSetpointLow success") await this.reload(); return; } this.console.log(`setThermostatSetpointLow failed: ${resp}`) } async turnOff(): Promise<void> { this.console.log(`fanOff: setting fan to auto`) const data = { selection: { selectionType: "registered", selectionMatch: this.nativeId, }, functions: [ { type: "setHold", params: { coolHoldTemp: 900, heatHoldTemp: 550, holdType: "nextTransition", fan: "auto", isTemperatureAbsolute: "false", isTemperatureRelative: "false", } } ] } const resp = await this.provider.req('post', 'thermostat', undefined, data); if (resp.status.code == 0) { this.console.log("fanOff success") await this.reload(); return; } this.console.log(`fanOff failed: ${resp}`) } async turnOn(): Promise<void> { this.console.log(`fanOn: setting fan to on`) const data = { selection: { selectionType: "registered", selectionMatch: this.nativeId, }, functions: [ { type:"setHold", params: { coolHoldTemp: 900, heatHoldTemp: 550, holdType: "nextTransition", fan: "on", isTemperatureAbsolute: "false", isTemperatureRelative: "false", } } ] } const resp = await this.provider.req('post', 'thermostat', undefined, data); if (resp.status.code == 0) { this.console.log("fanOn success") await this.reload(); return; } this.console.log(`fanOn failed: ${resp}`) } } class EcobeeController extends ScryptedDeviceBase implements DeviceProvider, Settings { devices = new Map<string, any>(); access_token: string; constructor() { super() this.log.clearAlerts(); if (!this.storage.getItem("api_base")) this.storage.setItem("api_base", "api.ecobee.com"); this.initialize(); } async initialize(): Promise<void> { // If no clientId, request clientId to start authentication process if (!this.storage.getItem("client_id")) { this.log.a("You must specify a client ID.") this.console.log("Enter a client ID for this app from the Ecobee developer portal. Then, collect the PIN and enter in Ecobee 'My Apps'. Restart this app to complete.") return; } if (!this.storage.getItem("refresh_token")) // If no refresh_token, try to get token await this.getToken(); else if (!this.access_token) await this.refreshToken(); this.discoverDevices(); } async getSettings(): Promise<Setting[]> { return [ { group: "API", title: "API Base URL", key: "api_base", description: "Customize the API base URL", value: this.storage.getItem("api_base"), }, { group: "API", title: "API Client ID", key: "client_id", description: "Your Client ID from the Ecboee developer portal", value: this.storage.getItem("client_id"), } ] } async putSetting(key: string, value: string): Promise<void> { this.storage.setItem(key, value.toString()); // Try to get a code when a client ID is saved if (key === "client_id") { await this.getCode(); } } // Get a code from Ecobee API for user verification async getCode() { // GET https://api.ecobee.com/authorize?response_type=ecobeePin&client_id=APP_KEY&scope=SCOPE const authUrl = `https://${this.storage.getItem("api_base")}/authorize` const authParams = { response_type:'ecobeePin', scope: "smartWrite", client_id: this.storage.getItem("client_id"), } let authData = (await axios.get(authUrl, { params: authParams, })).data this.log.clearAlerts(); this.log.a(`Got code ${authData.ecobeePin}. Enter this in 'My Apps' Ecobee portal. Then restart this app.`) this.storage.setItem("ecobee_code", authData.code); } // Trade the validated code for an access token async getToken() { // POST https://api.ecobee.com/token?grant_type=ecobeePin&code=AUTHORIZATION_TOKEN&client_id=APP_KEY&ecobee_type=jwt const tokenUrl = `https://${this.storage.getItem("api_base")}/token` const tokenParams = { grant_type:'ecobeePin', code: this.storage.getItem("ecobee_code"), client_id: this.storage.getItem("client_id"), ecobee_type: "jwt", }; let tokenData = (await axios.post(tokenUrl, null, { params: tokenParams })).data; this.access_token = tokenData.access_token; this.storage.setItem("refresh_token", tokenData.refresh_token); console.log(`Stored access/refresh token`) } // Refresh the tokens async refreshToken() { // POST https://api.ecobee.com/token?grant_type=refresh_token&refresh_token=REFRESH_TOKEN&client_id=APP_KEY&ecobee_type=jwt const tokenUrl = `https://${this.storage.getItem("api_base")}/token` const tokenParams = { grant_type:'refresh_token', refresh_token: this.storage.getItem("refresh_token"), client_id: this.storage.getItem("client_id"), ecobee_type: "jwt", }; let tokenData = (await axios.post(tokenUrl, null, { params: tokenParams })).data; this.access_token = tokenData.access_token; this.storage.setItem("refresh_token", tokenData.refresh_token); console.log(`Refreshed access/refresh token`) } // Generic API request async req( method: string, endpoint: string, json?: any, data?: any, attempt?: number, ): Promise<any> { if (attempt > API_RETRY) { throw new Error(` request to ${method}:${endpoint} failed after ${attempt} retries`); } // Configure API request const config: AxiosRequestConfig = { method, baseURL: `https://${this.storage.getItem("api_base")}/api/1/`, url: endpoint, headers: { Authorization: `Bearer ${this.access_token}`, }, data, timeout: 10000, } if (json) config.params = { json }; // Make API request, recursively retry after token refresh try { return (await axios.request(config)).data; } catch (e) { this.console.log(`req failed ${e}`) // refresh token and retry request await this.refreshToken(); return await this.req(method, endpoint, json, data, attempt++); } } async discoverDevices(): Promise<void> { // Get a list of all accessible devices const json = { selection: { selectionType: "registered", selectionMatch: "", includeSettings: true, } } const apiDevices = (await this.req('get', 'thermostat', json)).thermostatList; this.console.log(`Discovered ${apiDevices.length} devices.`); // Create a list of devices found from the API const devices: Device[] = []; for (let apiDevice of apiDevices) { this.console.log(` Discovered ${apiDevice.brand} ${apiDevice.modelNumber} ${apiDevice.name} (${apiDevice.identifier})`); const interfaces: ScryptedInterface[] = [ ScryptedInterface.Thermometer, ScryptedInterface.TemperatureSetting, ScryptedInterface.Refresh, ScryptedInterface.HumiditySensor, ScryptedInterface.OnOff, ScryptedInterface.Settings, ] if (apiDevice.settings.hasHumidifier) interfaces.push(ScryptedInterface.HumiditySetting); const device: Device = { nativeId: apiDevice.identifier, name: `${apiDevice.modelNumber} thermostat`, type: ScryptedDeviceType.Thermostat, info: { model: apiDevice.brand, manufacturer: apiDevice.modelNumber, serialNumber: apiDevice.identifier, }, interfaces, } devices.push(device); } // Sync full device list await deviceManager.onDevicesChanged({ devices, }); for (let device of devices) { let providerDevice = this.devices.get(device.nativeId); if (!providerDevice) { providerDevice = new EcobeeThermostat(device.nativeId, this, device.info) this.devices.set(device.nativeId, providerDevice) } } } getDevice(nativeId: string) { return this.devices.get(nativeId); } } export default new EcobeeController();
the_stack
'use strict' import * as Debug from 'debug' import { EventEmitter2 } from 'eventemitter2' import EWMA from './EWMA' import Histogram from './metrics/histogram' const fclone = (data: Object) => JSON.parse(JSON.stringify(data)) const log = Debug('axm:features:tracing:aggregator') export interface Span { name: string labels: any kind: string startTime: number min: number max: number median: number } export interface Variance { spans: Span[] count: number min: number max: number median: number p95: number } export interface Route { path: string meta: { min: number max: number count: number meter: number median: number p95: number } variances: Variance[] } export interface Trace { routes: Route[], meta: { trace_count: number http_meter: number, db_meter: number, http_percentiles: { median: number, p95: number, p99: number }, db_percentiles: any } } export interface TraceCache { routes: any meta: { trace_count: number http_meter: EWMA db_meter: EWMA histogram: Histogram db_histograms: any } } export class TransactionAggregator extends EventEmitter2 { private spanTypes: string[] = ['redis', 'mysql', 'pg', 'mongo', 'outbound_http'] private cache: TraceCache = { routes: {}, meta: { trace_count: 0, http_meter: new EWMA(), db_meter: new EWMA(), histogram: new Histogram({ measurement: 'median' }), db_histograms: {} } } private privacyRegex: RegExp = /":(?!\[|{)\\"[^"]*\\"|":(["'])(?:(?=(\\?))\2.)*?\1|":(?!\[|{)[^,}\]]*|":\[[^{]*]/g private worker: NodeJS.Timer | undefined init (sendInterval: number = 30000) { this.worker = setInterval(_ => { let data = this.prepareAggregationforShipping() this.emit('packet', { data }) }, sendInterval) } destroy () { if (this.worker !== undefined) { clearInterval(this.worker) } this.cache.routes = {} } getAggregation () { return this.cache } validateData (packet) { if (!packet) { log('Packet malformated', packet) return false } if (!packet.spans || !packet.spans[0]) { log('Trace without spans: %s', Object.keys(packet.data)) return false } if (!packet.spans[0].labels) { log('Trace spans without labels: %s', Object.keys(packet.spans)) return false } return true } /** * Main method to aggregate and compute stats for traces * * @param {Object} packet */ aggregate (packet) { if (this.validateData(packet) === false) return false // Get http path of current span let path = packet.spans[0].labels['http/path'] // Cleanup spans if (process.env.PM2_APM_CENSOR_SPAMS !== '0') { this.censorSpans(packet.spans) } // remove spans with startTime == endTime packet.spans = packet.spans.filter((span) => { return span.endTime !== span.startTime }) // compute duration of child spans packet.spans.forEach((span) => { span.mean = Math.round(new Date(span.endTime).getTime() - new Date(span.startTime).getTime()) delete span.endTime }) // Update app meta (mean_latency, http_meter, db_meter, trace_count) packet.spans.forEach((span) => { if (!span.name || !span.kind) return false if (span.kind === 'RPC_SERVER') { this.cache.meta.histogram.update(span.mean) return this.cache.meta.http_meter.update(1) } // Override outbount http queries for processing if (span.labels && span.labels['http/method'] && span.labels['http/status_code']) { span.labels['service'] = span.name span.name = 'outbound_http' } for (let i = 0; i < this.spanTypes.length; i++) { if (span.name.indexOf(this.spanTypes[i]) > -1) { this.cache.meta.db_meter.update(1) if (!this.cache.meta.db_histograms[this.spanTypes[i]]) { this.cache.meta.db_histograms[this.spanTypes[i]] = new Histogram({ measurement: 'mean' }) } this.cache.meta.db_histograms[this.spanTypes[i]].update(span.mean) break } } }) this.cache.meta.trace_count++ /** * Handle traces aggregation */ if (path[0] === '/' && path !== '/') { path = path.substr(1, path.length - 1) } let matched = this.matchPath(path, this.cache.routes) if (!matched) { this.cache.routes[path] = [] this.mergeTrace(this.cache.routes[path], packet) } else { this.mergeTrace(this.cache.routes[matched], packet) } return this.cache } /** * Merge new trace and compute mean, min, max, count * * @param {Object} aggregated previous aggregated route * @param {Object} trace */ mergeTrace (aggregated, trace) { if (!aggregated || !trace) return // if the trace doesn't any spans stop aggregation here if (trace.spans.length === 0) return // create data structure if needed if (!aggregated.variances) aggregated.variances = [] if (!aggregated.meta) { aggregated.meta = { histogram: new Histogram({ measurement: 'median' }), meter: new EWMA() } } aggregated.meta.histogram.update(trace.spans[0].mean) aggregated.meta.meter.update() const merge = (variance) => { // no variance found so its a new one if (variance == null) { delete trace.projectId delete trace.traceId trace.histogram = new Histogram({ measurement: 'median' }) trace.histogram.update(trace.spans[0].mean) trace.spans.forEach((span) => { span.histogram = new Histogram({ measurement: 'median' }) span.histogram.update(span.mean) delete span.mean }) // parse strackrace // this.parseStacktrace(trace.spans) aggregated.variances.push(trace) } else { // variance found, merge spans variance.histogram.update(trace.spans[0].mean) // update duration of spans to be mean this.updateSpanDuration(variance.spans, trace.spans) // delete stacktrace before merging trace.spans.forEach((span) => { delete span.labels.stacktrace }) } } // for every variance, check spans same variance for (let i = 0; i < aggregated.variances.length; i++) { if (this.compareList(aggregated.variances[i].spans, trace.spans)) { return merge(aggregated.variances[i]) } } // else its a new variance return merge(null) } /** * Parkour simultaneously both spans list to update value of the first one using value of the second one * The first should be variance already aggregated for which we want to merge the second one * The second one is a new trace, so we need to re-compute mean/min/max time for each spans */ updateSpanDuration (spans, newSpans) { for (let i = 0; i < spans.length; i++) { if (!newSpans[i]) continue spans[i].histogram.update(newSpans[i].mean) } } /** * Compare two spans list by going down on each span and comparing child and attribute */ compareList (one: any[], two: any[]) { if (one.length !== two.length) return false for (let i = 0; i < one.length; i++) { if (one[i].name !== two[i].name) return false if (one[i].kind !== two[i].kind) return false if (!one[i].labels && two[i].labels) return false if (one[i].labels && !two[i].labels) return false if (one[i].labels.length !== two[i].labels.length) return false } return true } /** * Will return the route if we found an already matched route */ matchPath (path, routes) { // empty route is / without the fist slash if (!path || !routes) return false if (path === '/') return routes[path] ? path : null // remove the last slash if exist if (path[path.length - 1] === '/') { path = path.substr(0, path.length - 1) } // split to get array of segment path = path.split('/') // if the path has only one segment, we just need to compare the key if (path.length === 1) return routes[path[0]] ? routes[path[0]] : null // check in routes already stored for match let keys = Object.keys(routes) for (let i = 0; i < keys.length; i++) { let route = keys[i] let segments = route.split('/') if (segments.length !== path.length) continue for (let j = path.length - 1; j >= 0; j--) { // different segment, try to find if new route or not if (path[j] !== segments[j]) { // if the aggregator already have matched that segment with a wildcard and the next segment is the same if (this.isIdentifier(path[j]) && segments[j] === '*' && path[j - 1] === segments[j - 1]) { return segments.join('/') // case a let in url match, so we continue because they must be other let in url } else if (path[j - 1] !== undefined && path[j - 1] === segments[j - 1] && this.isIdentifier(path[j]) && this.isIdentifier(segments[j])) { segments[j] = '*' // update routes in cache routes[segments.join('/')] = routes[route] delete routes[keys[i]] return segments.join('/') } else { break } } // if finish to iterate over segment of path, we must be on the same route if (j === 0) return segments.join('/') } } } /** * Normalize aggregation */ prepareAggregationforShipping () { let routes = this.cache.routes const normalized: Trace = { routes: [], meta: { trace_count: this.cache.meta.trace_count, http_meter: Math.round(this.cache.meta.http_meter.rate(1000) * 100) / 100, db_meter: Math.round(this.cache.meta.db_meter.rate(1000) * 100) / 100, http_percentiles: { median: this.cache.meta.histogram.percentiles([0.5])[0.5], p95: this.cache.meta.histogram.percentiles([0.95])[0.95], p99: this.cache.meta.histogram.percentiles([0.99])[0.99] }, db_percentiles: {} } } // compute percentiles for each db spans if they exist this.spanTypes.forEach((name) => { let histogram = this.cache.meta.db_histograms[name] if (!histogram) return normalized.meta.db_percentiles[name] = histogram.percentiles([0.5])[0.5] }) Object.keys(routes).forEach((path) => { let data = routes[path] // hard check for invalid data if (!data.variances || data.variances.length === 0) return // get top 5 variances of the same route const variances = data.variances.sort((a, b) => { return b.count - a.count }).slice(0, 5) // create a copy without reference to stored one let routeCopy: Route = { path: path === '/' ? '/' : '/' + path, meta: { min: data.meta.histogram.getMin(), max: data.meta.histogram.getMax(), count: data.meta.histogram.getCount(), meter: Math.round(data.meta.meter.rate(1000) * 100) / 100, median: data.meta.histogram.percentiles([0.5])[0.5], p95: data.meta.histogram.percentiles([0.95])[0.95] }, variances: [] } variances.forEach((variance) => { // hard check for invalid data if (!variance.spans || variance.spans.length === 0) return // deep copy of variances data let tmp: Variance = { spans: [], count: variance.histogram.getCount(), min: variance.histogram.getMin(), max: variance.histogram.getMax(), median: variance.histogram.percentiles([0.5])[0.5], p95: variance.histogram.percentiles([0.95])[0.95] } // get data for each span variance.spans.forEach((oldSpan) => { const span: Span = fclone({ name: oldSpan.name, labels: oldSpan.labels, kind: oldSpan.kind, startTime: oldSpan.startTime, min: oldSpan.histogram ? oldSpan.histogram.getMin() : undefined, max: oldSpan.histogram ? oldSpan.histogram.getMax() : undefined, median: oldSpan.histogram ? oldSpan.histogram.percentiles([0.5])[0.5] : undefined }) tmp.spans.push(span) }) // push serialized into normalized data routeCopy.variances.push(tmp) }) // push the route into normalized data normalized.routes.push(routeCopy) }) log(`sending formatted trace to remote endpoint`) return normalized } /** * Check if the string can be a id of some sort * * @param {String} id */ isIdentifier (id) { id = typeof (id) !== 'string' ? id + '' : id // uuid v1/v4 with/without dash if (id.match(/[0-9a-f]{8}-[0-9a-f]{4}-[14][0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{12}[14][0-9a-f]{19}/i)) { return true // if number } else if (id.match(/\d+/)) { return true // if suit of nbr/letters } else if (id.match(/[0-9]+[a-z]+|[a-z]+[0-9]+/)) { return true // if match pattern with multiple char spaced by . - _ @ } else if (id.match(/((?:[0-9a-zA-Z]+[@\-_.][0-9a-zA-Z]+|[0-9a-zA-Z]+[@\-_.]|[@\-_.][0-9a-zA-Z]+)+)/)) { return true } return false } /** * Cleanup trace data * - delete result(s) * - replace labels value with a question mark * * @param {Object} spans list of span for a trace */ censorSpans (spans) { if (!spans) return log('spans is null') spans.forEach((span) => { if (!span.labels) return delete span.labels.results delete span.labels.result delete span.spanId delete span.parentSpanId delete span.labels.values delete span.labels.stacktrace Object.keys(span.labels).forEach((key) => { if (typeof (span.labels[key]) === 'string' && key !== 'stacktrace') { span.labels[key] = span.labels[key].replace(this.privacyRegex, '\": \"?\"') // eslint-disable-line } }) }) } }
the_stack
import { component } from 'vuets' import { copyp, defp, extractMsg, bit_clear_and_set } from 'coreds/lib/util' import { PojoState, HasState } from 'coreds/lib/types' import { diffFieldTo } from 'coreds/lib/diff' import { bindFocus, debounce, Keys } from 'coreds-ui/lib/dom_util' import { nextTick } from 'vue' import { user } from '../../g/user/' const $ = user.BookmarkEntry, M = user.BookmarkEntry.M interface Config { url: string title: string notes: string } /*function $validateUrl() {} function $validateTitle() {} function $validateNotes() {}*/ const MAX_TAGS = 4, SUGGEST_TAGS_LIMIT = 12 interface Entry extends HasState { '6': string // title '7': string // notes tags: user.BookmarkTag.M[] // suggest fields suggest_tags: user.BookmarkTag.M[] tag_idx: number tag_name: string } interface M { original: Entry } function mapId(item: user.BookmarkTag.M): number { return item[user.BookmarkTag.M.$.id] } function handleKeyEvent(e: KeyboardEvent, pojo: Entry, self: Home, fn_name: string): boolean { let suggest_tags: user.BookmarkTag.M[], tag: user.BookmarkTag.M, idx: number switch (e.which) { case Keys.ESCAPE: pojo.suggest_tags = [] break case Keys.DOWN: idx = pojo.tag_idx suggest_tags = pojo.suggest_tags if (++idx === suggest_tags.length) break if (idx !== 0) { tag = suggest_tags[idx - 1] } tag = suggest_tags[idx] // selected idx pojo.tag_idx = idx break case Keys.UP: idx = pojo.tag_idx if (idx === 0) break suggest_tags = pojo.suggest_tags if (idx === -1) { // select last idx = suggest_tags.length - 1 tag = suggest_tags[idx] // selected idx pojo.tag_idx = idx break } tag = suggest_tags[--idx] // selected idx pojo.tag_idx = idx break case Keys.ENTER: idx = pojo.tag_idx if (idx !== -1) self[fn_name](pojo.suggest_tags[idx]) break default: return true } e.preventDefault() e.stopPropagation() return false } export class Home { config: Config initialized = false unique = false url = '' pnew = { '6': '', '7': '', tags: [], suggest_tags: [], tag_idx: -1, tag_name: '', state: 0, msg: '' } as Entry pnew$$focus_tag: any pnew$$F: any pupdate = { '6': '', '7': '', tags: [], suggest_tags: [], tag_idx: -1, tag_name: '', state: 0, msg: '' } as Entry pupdate$$focus_tag: any pupdate$$F: any pnew_tag = { name: '', state: 0, msg: '' } pnew_tag$$F: any pnew_tag$$focus: any m: M static created(self: Home) { defp(self, 'm', { original: null }) self.config = self['$root'].config self.pnew$$F = Home.send$$F.bind(self.pnew) self.pnew$$focus_tag = bindFocus('pnew-tag') self.pupdate$$F = Home.send$$F.bind(self.pupdate) self.pupdate$$focus_tag = bindFocus('pupdate-tag') self.pnew_tag$$F = Home.send$$F.bind(self.pnew_tag) self.pnew_tag$$focus = bindFocus('tag-new') } static mounted(self: Home) { self.url = self.config.url self.checkUnique$$() } static send$$F(this: HasState, err) { this.state = bit_clear_and_set(this.state, PojoState.LOADING, PojoState.ERROR) this.msg = extractMsg(err) } prepare(pojo: HasState) { pojo.state = bit_clear_and_set(pojo.state, PojoState.MASK_STATUS, PojoState.LOADING) pojo.msg = '' } success(pojo: HasState, msg?: string) { if (msg) { pojo.state = bit_clear_and_set(pojo.state, PojoState.LOADING, PojoState.SUCCESS) pojo.msg = msg } else { pojo.state ^= PojoState.LOADING } } static watch(self: Home, update: boolean) { self['$watch'](function () { return update ? self.pupdate.tag_name : self.pnew.tag_name }, debounce(function (val) { self.fetchTag(val, update) }, 300)) } checkUnique$$() { // PS $.$URL({"1": this.url, "4": {"1": false, "2": 1}}).then((data) => { this.initialized = true let array: Entry[] = data['1'] if (!array || !array.length) { let config = this.config, pnew = this.pnew this.unique = true pnew[$.$.title] = config.title pnew[$.$.notes] = config.notes Home.watch(this, false) nextTick(this.pnew$$focus_tag) return } let original = array[0], pupdate = this.pupdate, tags = original[M.$.tags], tagCount = tags.length this.m.original = original pupdate[$.$.title] = original[$.$.title] pupdate[$.$.notes] = original[$.$.notes] pupdate.tags = tags Home.watch(this, true) if (tagCount < MAX_TAGS) nextTick(this.pupdate$$focus_tag) }).then(undefined, (err) => { // probably down? this.initialized = true let config = this.config, pnew = this.pnew this.unique = true pnew[$.$.title] = config.title pnew[$.$.notes] = config.notes }) } pupdate$$str(e, field: number) { let pupdate = this.pupdate, original = this.m.original, mc = {}, req if (!diffFieldTo(mc, $.$d, original, pupdate, field)) return req = { '1': original['1'], '2': mc } this.prepare(pupdate) $.ForUser.updateBookmarkEntry(req).then(() => { let pupdate = this.pupdate, original = this.m.original, fk = String(field) original[fk] = pupdate[fk] this.success(pupdate, 'Updated') }).then(undefined, this.pupdate$$F) } fetchTag(val: string, update: boolean) { let pojo = update ? this.pupdate : this.pnew, suggest_tags = pojo.suggest_tags if (suggest_tags.length) pojo.suggest_tags = [] if (!val) return this.prepare(pojo) user.BookmarkTag.$NAME({"1": val, "4": {"1": false, "2": SUGGEST_TAGS_LIMIT}}, true).then((data) => { let array = data['1'] as any[] pojo.suggest_tags = array || [] pojo.tag_idx = -1 this.success(pojo) nextTick(update ? this.pupdate$$focus_tag : this.pnew$$focus_tag) }).then(undefined, update ? this.pupdate$$F : this.pnew$$F) } pnew$$() { let pnew = this.pnew, p = {} as user.BookmarkEntry p[$.$.url] = this.url copyp(p, $.$.title, pnew) copyp(p, $.$.notes, pnew) this.prepare(pnew) $.ForUser.create($.PNew.$new(p, pnew.tags.map(mapId))).then((data) => { window.close() }).then(undefined, this.pnew$$F) } addTag(tag: user.BookmarkTag.M) { let id = mapId(tag), pnew = this.pnew, tags = pnew.tags, i = 0, len = tags.length pnew.suggest_tags = [] pnew.tag_name = '' for (; i < len; i++) { if (id === mapId(tags[i])) { // dup nextTick(this.pnew$$focus_tag) return } } tags.push(tag) if (tags.length < MAX_TAGS) nextTick(this.pnew$$focus_tag) } rmTag(tag: user.BookmarkTag.M, update?: boolean) { let id = mapId(tag), pojo = update ? this.pupdate : this.pnew, tags = pojo.tags, i = 0, len = tags.length for (; i < len; i++) { if (id === mapId(tags[i])) { if (!update) tags.splice(i, 1) break } } if (!update) { nextTick(this.pnew$$focus_tag) return } if (i === len) { // not found nextTick(this.pupdate$$focus_tag) return } this.prepare(pojo) $.ForUser.updateTag(user.UpdateTag.$new(this.m.original['1'] as string, id, true)).then((data) => { tags.splice(i, 1) this.success(this.pupdate, 'Updated') nextTick(this.pupdate$$focus_tag) }).then(undefined, this.pupdate$$F) nextTick(this.pupdate$$focus_tag) } insertTag(tag: user.BookmarkTag.M) { let id = mapId(tag), pupdate = this.pupdate, tags = pupdate.tags, i = 0, len = tags.length pupdate.suggest_tags = [] pupdate.tag_name = '' for (; i < len; i++) { if (id === mapId(tags[i])) { // dup nextTick(this.pupdate$$focus_tag) return } } this.prepare(pupdate) $.ForUser.updateTag(user.UpdateTag.$new(this.m.original['1'] as string, id, false)).then((data) => { tags.splice(data['1'], 0, tag) this.success(this.pupdate, 'Updated') nextTick(this.pupdate$$focus_tag) }).then(undefined, this.pupdate$$F) nextTick(this.pupdate$$focus_tag) } pnew$$keyup(e: KeyboardEvent): boolean { return handleKeyEvent(e, this.pnew, this, 'addTag') } pupdate$$keyup(e: KeyboardEvent): boolean { return handleKeyEvent(e, this.pupdate, this, 'insertTag') } newTag(e) { let pnew_tag = this.pnew_tag, name = pnew_tag.name if (!name) return this.prepare(pnew_tag) user.BookmarkTag.ForUser.create({ "3": name }).then((data) => { this.success(pnew_tag, `${pnew_tag.name} added.`) // clear pnew_tag.name = '' nextTick(this.pnew_tag$$focus) }).then(undefined, this.pnew_tag$$F) } } export default component({ created(this: Home) { Home.created(this) }, mounted(this: Home) { Home.mounted(this) }, template: /**/` <div> <template v-if="initialized"> <div class="mdl input"> <input class="url" :value="url" placeholder="Url" disabled /> </div> <div v-if="unique"> <div class="mdl input"> <input v-model.lazy.trim="pnew['${$.$.title}']" placeholder="Title" :disabled="!!(pnew.state & ${PojoState.LOADING})" /> </div> <div class="mdl input"> <input v-model.lazy.trim="pnew['${$.$.notes}']" placeholder="Notes" :disabled="!!(pnew.state & ${PojoState.LOADING})" /> </div> <div class="msg" :class="{ error: ${PojoState.ERROR} === (pnew.state & ${PojoState.MASK_STATUS}) }" v-show="pnew.msg">{{pnew.msg}}<button class="b" @click.prevent="pnew.msg = null">x</button></div> <div class="mdl input"> <input id="pnew-tag" placeholder="Tag(s)" @keyup="pnew$$keyup($event)" v-model.trim="pnew.tag_name" :disabled="!!(pnew.state & ${PojoState.LOADING}) || pnew.tags.length === ${MAX_TAGS}" /> </div> <div class="dropdown" :class="{ active: pnew.suggest_tags.length }"> <ul class="dropdown-menu mfluid"> <li v-for="(tag, idx) of pnew.suggest_tags" :class="{ current: idx === pnew.tag_idx }"> <a @click.prevent="addTag(tag)">{{ tag['${user.BookmarkTag.M.$.name}'] }}</a> </li> </ul> </div> <div class="right-floated"> <button class="pv primary" @click.prevent="pnew$$" :disabled="!!(pnew.state & ${PojoState.LOADING}) || (!!pnew.tag_name && !pnew.tags.length)"><b>Submit</b></button> </div> <ul class="tags"> <li v-for="tag of pnew.tags"> <a> {{ tag['${user.BookmarkTag.M.$.name}'] }} <button class="b" @click.prevent="rmTag(tag, false)">x</button> </a> </li> </ul> </div> <div v-if="!unique"> <div class="mdl input"> <input v-model.lazy.trim="pupdate['${$.$.title}']" @change="pupdate$$str($event, ${$.$.title})" :disabled="!!(pupdate.state & ${PojoState.LOADING})" placeholder="Title" /> </div> <div class="mdl input"> <input v-model.lazy.trim="pupdate['${$.$.notes}']" @change="pupdate$$str($event, ${$.$.notes})" :disabled="!!(pupdate.state & ${PojoState.LOADING})" placeholder="Notes" /> </div> <div class="msg" :class="{ error: ${PojoState.ERROR} === (pupdate.state & ${PojoState.MASK_STATUS}) }" v-show="pupdate.msg">{{pupdate.msg}}<button class="b" @click.prevent="pupdate.msg = null">x</button></div> <div class="mdl input"> <input id="pupdate-tag" placeholder="Tag(s)" @keyup="pupdate$$keyup($event)" v-model.trim="pupdate.tag_name" :disabled="!!(pupdate.state & ${PojoState.LOADING}) || pupdate.tags.length === ${MAX_TAGS}" /> </div> <div class="dropdown" :class="{ active: pupdate.suggest_tags.length }"> <ul class="dropdown-menu mfluid"> <li v-for="(tag, idx) of pupdate.suggest_tags" :class="{ current: idx === pupdate.tag_idx }"> <a @click.prevent="insertTag(tag)">{{ tag['${user.BookmarkTag.M.$.name}'] }}</a> </li> </ul> </div> <ul class="tags"> <li v-for="tag of pupdate.tags"> <a> {{ tag['${user.BookmarkTag.M.$.name}'] }} <button class="b" @click.prevent="rmTag(tag, true)" :disabled="!!(pupdate.state & ${PojoState.LOADING})">x</button> </a> </li> </ul> </div> <div id="bk-tag"> <div class="mdl input"> <input id="tag-new" placeholder="Create new tag" v-model.trim="pnew_tag.name" @change="newTag($event)" :disabled="!!(pnew_tag.state & ${PojoState.LOADING})" /> </div> <div class="msg" :class="{ error: ${PojoState.ERROR} === (pnew_tag.state & ${PojoState.MASK_STATUS}) }" v-show="pnew_tag.msg">{{pnew_tag.msg}}<button class="b" @click.prevent="pnew_tag.msg = null">x</button></div> </div> </template> </div>`/**/ }, Home)
the_stack
import {equal as assertEqual, notEqual as assertNotEqual} from 'assert'; import {exposeClosureState, injectIntoHead, parseHTML} from '../src/lib/transformations'; import {DEFAULT_AGENT_URL, DEFAULT_BABEL_POLYFILL_URL} from '../src/lib/mitmproxy_interceptor'; import {readFileSync} from 'fs'; const AGENT_SOURCE = readFileSync(require.resolve('../src/lib/bleak_agent'), "utf8"); /** * An XMLHttpRequest mock, passed to the BLeak agent so it can support programs with eval. * Mirrors the behavior of the proxy when the /eval URL is requested. */ class XHRShim { public responseText: string = null; public open() {} public setRequestHeader() {} public send(data: string) { const d: { scope: string, source: string, strictMode: boolean } = JSON.parse(data); this.responseText = exposeClosureState(`eval-${Math.random()}.js`, d.source, DEFAULT_AGENT_URL, DEFAULT_BABEL_POLYFILL_URL, d.scope, d.strictMode); } } describe('Transformations', function() { describe('injectIntoHead', function() { const headTagTypes = [ [`<head>`, `</head>`, 'is in lowercase'], [`<HEAD>`, `</HEAD>`, 'is in uppercase'], [`<heAd>`, `</heAd>`, 'is in a mix of lower and uppercase'], [``, ``, 'is missing'] ]; const rawInjection = `<script>hello</script>`; const injection = parseHTML(rawInjection); headTagTypes.forEach((headTag) => { it(`should work when the head tag ${headTag[2]}`, function() { const source = `<!DOCTYPE html><html>${headTag[0]}${headTag[1]}</html>`; const output = `<!DOCTYPE html><html>${headTag[0]}${rawInjection}${headTag[1]}</html>`; assertEqual(injectIntoHead("test.html", source, injection), output); }); }); }); describe(`Inline JavaScript`, function() { it(`should rewrite inline JavaScript`, function() { const source = `<html><head><script type="text/javascript"> function foo() { } </script></head></html>`; const expected = `<html><head><script type="text/javascript">NO</script></head></html>`; assertEqual(injectIntoHead("test.html", source, [], () => "NO"), expected); }); }); describe('exposeClosureState', function() { function instrumentModule<T>(source: string): T { const newSource = exposeClosureState("main.js", `(function(exports) { ${source} })(exports);`); // Super basic CommonJS shim. const exp: any = {}; new Function('exports', 'XMLHttpRequest', AGENT_SOURCE + "\n" + newSource)(exp, XHRShim); return exp; } it('works with function declarations', function() { const module = instrumentModule<{decl: Function}>(` var a = 'hello'; var b = 'hello'; function decl(){ if (false) { decl(); } return a; } exports.decl = decl; `); assertEqual(module.decl.__scope__['a'], 'hello'); assertEqual(module.decl.__scope__['decl'], module.decl); // b isn't closed over. assertEqual(module.decl.__scope__['b'], undefined); module.decl.__scope__['a'] = 'no'; assertEqual(module.decl.__scope__['a'], 'no'); const arr = [1,2,3]; module.decl.__scope__['a'] = arr; assertEqual(module.decl(), arr); }); it('works with function expressions', function() { const module = instrumentModule<{decl: Function}>(` var a = 'hello'; exports.decl = function(){ if (exports) {} return a; }; `); assertEqual(module.decl.__scope__['a'], 'hello'); assertEqual(module.decl.__scope__['exports'].decl, module.decl); }); it(`works with named function expressions`, function() { const module = instrumentModule<{decl: Function}>(` var a = 'hello'; exports.decl = function decl2(){ return a; }; `); assertEqual(module.decl.__scope__['a'], 'hello'); }); it(`works with multiple functions in the same block and multiple variables`, function() { const module = instrumentModule<{decl: Function, decl2: Function}>(` var a='hello'; var b=3; exports.decl=function(){ return a + b; }; exports.decl2=function(){ return a + b; }; `); assertEqual(module.decl.__scope__['a'], 'hello'); assertEqual(module.decl2.__scope__['a'], 'hello'); assertEqual(module.decl.__scope__['b'], 3); assertEqual(module.decl.__scope__['b'], 3); }); it(`works with nested functions`, function() { const module = instrumentModule<{decl: Function, notDecl: Function}>(` var a = 'hello'; function decl(){ return a; } function notDecl(){ var decl = function decl(){}; return decl; } exports.decl = decl; exports.notDecl = notDecl; `); assertEqual(module.decl.__scope__['a'], 'hello'); assertEqual(module.notDecl.__scope__['a'], 'hello'); assertEqual(module.notDecl().__scope__['a'], 'hello'); }); it(`works with nested function declarations`, function() { const module = instrumentModule<{decl: Function, notDecl: Function}>(` var a = 'hello'; function decl(){ return a; } function notDecl(){ function decl(){} return decl; } exports.decl = decl; exports.notDecl = notDecl; `) assertEqual(module.decl.__scope__['a'], 'hello'); assertEqual(module.notDecl.__scope__['a'], 'hello'); assertEqual(module.notDecl().__scope__['a'], 'hello'); }); it(`works with functions in a list`, function() { const module = instrumentModule<{obj: {decl: Function, decl2: Function}}>(` var a = 'hello'; exports.obj = { decl: function() { return a; }, decl2: function() { return 3 } }; `); assertEqual(module.obj.decl.__scope__['a'], 'hello'); assertEqual(module.obj.decl2.__scope__['a'], 'hello'); }); it(`works with initializer lists in for loops`, function() { const module = instrumentModule<{obj: {decl: Function}}>(` exports.obj = { decl: function(a, b) { for (var i = 0, j = 0; i < b.length; i++) { j++; a += j; } return a; } }; `); assertEqual(module.obj.decl(0, [0,1,2]), 6); }); it(`works with initializers in for of loops`, function() { const module = instrumentModule<{obj: {decl: Function}}>(` exports.obj = { decl: function(a, b) { for (var prop of b) { if (b.hasOwnProperty(prop)) { a += parseInt(prop, 10); } } // Make sure prop doesn't escape. return function() { return [prop, a]; }; } }; `); assertEqual(module.obj.decl(0, [0,1,2])()[1], 3); }); it(`works with initializers in for in loops`, function() { const module = instrumentModule<{obj: {decl: Function}}>(` exports.b = [0,1,2]; exports.obj = { decl: function(a) { for (var prop in exports.b) a += prop; prop = "hello"; // Make sure prop escapes. return function() { return prop; }; } }; `); assertEqual(module.obj.decl("")(), "hello"); }); it(`works with catch clauses`, function() { const module = instrumentModule<{obj: {decl: Function}}>(` var err, e; exports.obj = { decl: function() { try { throw new Error("Hello"); } catch (e) { err = e; } } }; `); module.obj.decl(); assertEqual(module.obj.decl.__scope__['err'].message, "Hello"); }); it(`works with object literals`, function() { const module = instrumentModule<{obj: {decl: Function}}>(` var e = 5; exports.obj = { decl: function() { return { e: e }; } }; `); assertEqual(module.obj.decl().e, 5); }); it(`works with computed properties`, function() { const module = instrumentModule<{obj: {decl: Function}}>(` var e = 0; exports.obj = { decl: function() { return arguments[e]; } }; `); assertEqual(module.obj.decl(100), 100); }); it(`works with named function expressions`, function() { const module = instrumentModule<{obj: {decl: Function}}>(` var e = 0; exports.obj = { decl: function() { return function e(i) { return i === 0 ? 5 : e(i - 1); }; } }; `); assertEqual(module.obj.decl()(3), 5); }); it(`does not change value of this`, function() { const module = instrumentModule<{obj: {decl: Function}}>(` var e = function() { return this; }; exports.obj = { decl: function() { return e(); } }; `); assertEqual(module.obj.decl(), global); }); it(`keeps strict mode declaration`, function() { const module = instrumentModule<{obj: {decl: Function}}>(` var e = function() { "use strict"; return this; }; exports.obj = { decl: function() { return e(); } }; `); assertEqual(module.obj.decl(), undefined); }); it(`updates arguments`, function() { const module = instrumentModule<{obj: {decl: Function}}>(` exports.obj = { decl: function(e) { e = 4; return arguments[0]; } }; `); assertEqual(module.obj.decl(100), 4); }); it(`works on functions illegally defined in blocks`, function() { const module = instrumentModule<{obj: {decl: Function}}>(` exports.obj = { decl: function() { if (1) { function Z() { var a = 4; return function() { return a; }; } return Z; } } }; `); assertEqual(module.obj.decl()()(), 4); }); it(`works on functions illegally defined in switch cases`, function() { const module = instrumentModule<{obj: {decl: Function}}>(` exports.obj = { decl: function(s) { switch (s) { case 1: function Z() { var a = 4; return function() { return a; }; } return Z; } } }; `); assertEqual(module.obj.decl(1)()(), 4); }); it(`works on function expressions with names`, function() { const module = instrumentModule<{obj: Function}>(` exports.obj = function s() { s = 4; return s; }; `); assertEqual(module.obj(), module.obj); }); it(`makes proxy objects equal to original objects`, function() { const module = instrumentModule<{obj: Function, cmp: (a: any) => boolean}>(` global.a = {}; exports.obj = function () { return a; }; exports.cmp = function(b) { return a === b; }; `); const a = module.obj(); (<Window> <any> global).$$$INSTRUMENT_PATHS$$$([{ id: 1, isGrowing: true, indexOrName: "a", type: PathSegmentType.PROPERTY, children: [] }]); assertNotEqual(module.obj(), a, `Proxy for global variable 'a' is properly installed`); assertEqual(module.cmp(a), true, `a === Proxy(a)`); assertEqual(module.cmp(module.obj()), true, `Proxy(a) === Proxy(a)`); }); it(`works with null array entry`, function() { const module = instrumentModule<{obj: (number | null)[]}>(`exports.obj = [,1,2];`); assertEqual(module.obj[0], null); }); it(`works with computed properties`, function() { const module = instrumentModule<{fcn: () => number}>(` var a = "hello"; var obj = { hello: 3 }; exports.fcn = function() { return obj[a]; };`); assertEqual(module.fcn(), 3); assertEqual(module.fcn.__scope__.a, "hello"); }); it(`works with arguments that do not escape`, function() { const module = instrumentModule<{fcn: (a: number) => number}>(` exports.fcn = function(a) { return a };`); assertEqual(module.fcn(3), 3); }); it(`works with arguments that escape`, function() { const module = instrumentModule<{fcn: (a: number) => () => number}>(` exports.fcn = function(a) { return function() { return a; }; };`); assertEqual(module.fcn(3)(), 3); }); it(`moves all heap objects when eval is used`, function() { const module = instrumentModule<{fcn: (a: string) => any}>(` var secret = 3; exports.fcn = function(a) { return eval(a); };`); assertEqual(module.fcn("secret"), 3); assertEqual(module.fcn.__scope__.secret, 3); assertEqual(module.fcn("a"), "a"); }); it(`appropriately overwrites variables when eval is used`, function() { const module = instrumentModule<{fcn: (a: string) => any}>(` global.secret = 3; exports.fcn = function(a) { return eval(a); };`); assertEqual(module.fcn.__scope__.secret, 3); assertEqual((<any> global).secret, 3); (<any> global).secret = 4; assertEqual(module.fcn.__scope__.secret, 4); module.fcn("secret = 6"); assertEqual(module.fcn.__scope__.secret, 6); assertEqual((<any> global).secret, 6); }); it(`works with with()`, function() { const module = instrumentModule<{fcn: () => any, assign: (v: any) => any}>(` var l = 3; var o = { l: 5 }; exports.fcn = function() { with(o) { return l; } }; exports.assign = function(v) { with(o) { l = v; return l; } };`); assertEqual(module.fcn(), 5); assertEqual(module.assign(7), 7); assertEqual(module.fcn(), 7); }); it(`works when variables are incorrectly reinitialized`, function() { const module = instrumentModule<{fcn: () => any, assign: (v: any) => any}>(` var l; l = 4; var l; exports.fcn = function() { return l; };`); assertEqual(module.fcn(), 4); }); it(`works when arguments are incorrectly reinitialized`, function() { const module = instrumentModule<{fcn: (v: any) => any, assign: (v: any) => any}>(` exports.fcn = function(l) { var l; // Make sure l gets captured. return (function() { return l; })(); };`); assertEqual(module.fcn(4), 4); }); it(`works with indirect evals`, function() { const module = instrumentModule<{fcn: (v: any) => any, assign: (v: any) => any}>(` var indirectEval = eval; exports.fcn = function(l) { var l = 4; indirectEval("var l = 5"); // Make sure l gets captured. return (function() { return l; })(); };`); assertEqual(module.fcn(4), 4); assertEqual((global as any).l, 5); }); it(`works with eval that defines global functions`, function() { const module = instrumentModule<{fcn: () => any, assign: (v: any) => any}>(` var indirectEval = eval; exports.fcn = function() { indirectEval("function foo() { return 4; } function bar() { return arguments[0]; }"); };`); module.fcn(); assertEqual((global as any).foo(), 4); assertEqual((global as any).bar(5), 5); }); it(`works with named functions that have overriding local variables`, function() { const module = instrumentModule<{fcn: () => any, assign: (v: any) => any}>(` exports.fcn = function foo() { var foo = 3; // Close over to make sure it gets captured. return function() { return foo; }; };`); assertEqual(module.fcn()(), 3); }); it(`works with local variables named Object`, function() { const module = instrumentModule<{fcn: () => any, assign: (v: any) => any}>(` exports.fcn = function foo() { // Define a variable named Object (does not escape) var Object = undefined; // Close over at least one variable to create a scope object.. var foo = 3; // Hoist. function rv() { return foo; } return rv; };`); assertEqual(module.fcn()(), 3); }); // instrument a global variable and get stack traces // with() with undefined / null / zeroish values. // growing paths: set up such that it has two separate custom setters! // growing window? // cycle of growing objects?? // getters/setters // template literal // arrow functions, with `this` as the leaking object. arrow has only ref. // multiple object patterns that reference each other, e.g.: // var {a, b, c} = foo, {d=a} = bar; // a leak in a getter, e.g. { get foo() { var a; return function() { } }} // or actually more like { get foo() { bar[random] = 3; }} // ==> Shows up as `get foo`!! Instrument both `foo` and `get foo`. }); // NEED A SWITCH CASE VERSION where it's not within a block!!! });
the_stack
import { mat3, mat4, vec3 } from 'gl-matrix'; import { auxiliaries } from 'webgl-operate'; import { Camera, Canvas, Context, DefaultFramebuffer, EventProvider, ForwardSceneRenderPass, Framebuffer, Geometry, GLTFAlphaMode, GLTFLoader, GLTFPbrMaterial, GLTFPrimitive, Invalidate, Material, Navigation, Program, Renderer, Texture2D, TextureCube, Wizard, } from 'webgl-operate'; import { Demo } from '../demo'; // tslint:disable:max-classes-per-file /** * @todo comment */ export class GltfRenderer extends Renderer { protected _loader: GLTFLoader; protected _navigation: Navigation; protected _forwardPass: ForwardSceneRenderPass; protected _camera: Camera; protected _texture: Texture2D; protected _framebuffer: Framebuffer; protected _program: Program; protected _emptyTexture: Texture2D; protected _specularEnvironment: TextureCube; protected _brdfLUT: Texture2D; protected _uViewProjection: WebGLUniformLocation; protected _uModel: WebGLUniformLocation; protected _uNormalMatrix: WebGLUniformLocation; protected _uBaseColor: WebGLUniformLocation; protected _uBaseColorTexCoord: WebGLUniformLocation; protected _uMetallicRoughness: WebGLUniformLocation; protected _uMetallicRoughnessTexCoord: WebGLUniformLocation; protected _uNormal: WebGLUniformLocation; protected _uNormalTexCoord: WebGLUniformLocation; protected _uEmissive: WebGLUniformLocation; protected _uEmissiveTexCoord: WebGLUniformLocation; protected _uOcclusion: WebGLUniformLocation; protected _uOcclusionTexCoord: WebGLUniformLocation; protected _uEye: WebGLUniformLocation; protected _uGeometryFlags: WebGLUniformLocation; protected _uPbrFlags: WebGLUniformLocation; protected _uBaseColorFactor: WebGLUniformLocation; protected _uMetallicFactor: WebGLUniformLocation; protected _uRoughnessFactor: WebGLUniformLocation; protected _uEmissiveFactor: WebGLUniformLocation; protected _uNormalScale: WebGLUniformLocation; protected _uBlendMode: WebGLUniformLocation; protected _uBlendCutoff: WebGLUniformLocation; protected _uSpecularEnvironment: WebGLUniformLocation; protected _uBRDFLookupTable: WebGLUniformLocation; /** * Initializes and sets up rendering passes, navigation, loads a font face and links shaders with program. * @param context - valid context to create the object for. * @param identifier - meaningful name for identification of this instance. * @param mouseEventProvider - required for mouse interaction * @returns - whether initialization was successful */ protected onInitialize(context: Context, callback: Invalidate, eventProvider: EventProvider): boolean { const gl = this._context.gl; this._loader = new GLTFLoader(this._context); this._emptyTexture = new Texture2D(this._context, 'EmptyTexture'); this._emptyTexture.initialize(1, 1, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE); this._framebuffer = new DefaultFramebuffer(this._context, 'DefaultFBO'); this._framebuffer.initialize(); this._program = this._loader.pbrProgram; this._uViewProjection = this._program.uniform('u_viewProjection'); this._uModel = this._program.uniform('u_model'); this._uNormalMatrix = this._program.uniform('u_normalMatrix'); this._uBaseColor = this._program.uniform('u_baseColor'); this._uBaseColorTexCoord = this._program.uniform('u_baseColorTexCoord'); this._uMetallicRoughness = this._program.uniform('u_metallicRoughness'); this._uMetallicRoughnessTexCoord = this._program.uniform('u_metallicRoughnessTexCoord'); this._uNormal = this._program.uniform('u_normal'); this._uNormalTexCoord = this._program.uniform('u_normalTexCoord'); this._uEmissive = this._program.uniform('u_emissive'); this._uEmissiveTexCoord = this._program.uniform('u_emissiveTexCoord'); this._uOcclusion = this._program.uniform('u_occlusion'); this._uOcclusionTexCoord = this._program.uniform('u_occlusionTexCoord'); this._uEye = this._program.uniform('u_eye'); this._uGeometryFlags = this._program.uniform('u_geometryFlags'); this._uPbrFlags = this._program.uniform('u_pbrFlags'); this._uBaseColorFactor = this._program.uniform('u_baseColorFactor'); this._uMetallicFactor = this._program.uniform('u_metallicFactor'); this._uRoughnessFactor = this._program.uniform('u_roughnessFactor'); this._uEmissiveFactor = this._program.uniform('u_emissiveFactor'); this._uNormalScale = this._program.uniform('u_normalScale'); this._uBlendMode = this._program.uniform('u_blendMode'); this._uBlendCutoff = this._program.uniform('u_blendCutoff'); this._uSpecularEnvironment = this._program.uniform('u_specularEnvironment'); this._uBRDFLookupTable = this._program.uniform('u_brdfLUT'); /* Create and configure camera. */ if (this._camera === undefined) { this._camera = new Camera(); this._camera.center = vec3.fromValues(0.0, 0.0, 0.0); this._camera.up = vec3.fromValues(0.0, 1.0, 0.0); this._camera.eye = vec3.fromValues(0.0, 3.0, 1.0); this._camera.near = 0.1; this._camera.far = 32.0; } /* Create and configure navigation */ this._navigation = new Navigation(callback, eventProvider); this._navigation.camera = this._camera; /* Create and configure forward pass. */ this._forwardPass = new ForwardSceneRenderPass(context); this._forwardPass.initialize(); this._forwardPass.camera = this._camera; this._forwardPass.target = this._framebuffer; this._forwardPass.program = this._program; this._forwardPass.updateModelTransform = (matrix: mat4) => { gl.uniformMatrix4fv(this._uModel, false, matrix); const normalMatrix = mat3.create(); mat3.normalFromMat4(normalMatrix, matrix); gl.uniformMatrix3fv(this._uNormalMatrix, false, normalMatrix); }; this._forwardPass.updateViewProjectionTransform = (matrix: mat4) => { gl.uniformMatrix4fv(this._uViewProjection, false, matrix); }; this._forwardPass.bindGeometry = (geometry: Geometry) => { const primitive = geometry as GLTFPrimitive; gl.uniform1i(this._uGeometryFlags, primitive.flags); }; this._forwardPass.bindMaterial = (material: Material) => { const pbrMaterial = material as GLTFPbrMaterial; auxiliaries.assert(pbrMaterial !== undefined, `Material ${material.name} is not a PBR material.`); /** * Base color texture */ if (pbrMaterial.baseColorTexture !== undefined) { pbrMaterial.baseColorTexture.bind(gl.TEXTURE0); gl.uniform1i(this._uBaseColorTexCoord, pbrMaterial.baseColorTexCoord); } else { this._emptyTexture.bind(gl.TEXTURE0); } /** * Metallic Roughness texture */ if (pbrMaterial.metallicRoughnessTexture !== undefined) { pbrMaterial.metallicRoughnessTexture.bind(gl.TEXTURE1); gl.uniform1i(this._uMetallicRoughnessTexCoord, pbrMaterial.metallicRoughnessTexCoord); } else { this._emptyTexture.bind(gl.TEXTURE1); } /** * Normal texture */ if (pbrMaterial.normalTexture !== undefined) { pbrMaterial.normalTexture.bind(gl.TEXTURE2); gl.uniform1i(this._uNormalTexCoord, pbrMaterial.normalTexCoord); } else { this._emptyTexture.bind(gl.TEXTURE2); } /** * Occlusion texture */ if (pbrMaterial.occlusionTexture !== undefined) { pbrMaterial.occlusionTexture.bind(gl.TEXTURE3); gl.uniform1i(this._uOcclusionTexCoord, pbrMaterial.occlusionTexCoord); } else { this._emptyTexture.bind(gl.TEXTURE3); } /** * Emission texture */ if (pbrMaterial.emissiveTexture !== undefined) { pbrMaterial.emissiveTexture.bind(gl.TEXTURE4); gl.uniform1i(this._uEmissiveTexCoord, pbrMaterial.emissiveTexCoord); } else { this._emptyTexture.bind(gl.TEXTURE4); } /** * Factors */ gl.uniform4fv(this._uBaseColorFactor, pbrMaterial.baseColorFactor); gl.uniform3fv(this._uEmissiveFactor, pbrMaterial.emissiveFactor); gl.uniform1f(this._uMetallicFactor, pbrMaterial.metallicFactor); gl.uniform1f(this._uRoughnessFactor, pbrMaterial.roughnessFactor); gl.uniform1f(this._uNormalScale, pbrMaterial.normalScale); gl.uniform1i(this._uPbrFlags, pbrMaterial.flags); /** * Handle alpha modes */ if (pbrMaterial.alphaMode === GLTFAlphaMode.OPAQUE) { gl.disable(gl.BLEND); gl.uniform1i(this._uBlendMode, 0); } else if (pbrMaterial.alphaMode === GLTFAlphaMode.MASK) { gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.uniform1i(this._uBlendMode, 1); gl.uniform1f(this._uBlendCutoff, pbrMaterial.alphaCutoff); } else if (pbrMaterial.alphaMode === GLTFAlphaMode.BLEND) { gl.enable(gl.BLEND); // We premultiply in the shader gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.uniform1i(this._uBlendMode, 2); } else { auxiliaries.log(auxiliaries.LogLevel.Warning, 'Unknown blend mode encountered.'); } }; this.loadAsset(); this.loadEnvironmentMap(); const assetSelect = window.document.getElementById('asset-select')! as HTMLSelectElement; assetSelect.onchange = (_) => { this.loadAsset(); }; return true; } /** * Uninitializes Buffers, Textures, and Program. */ protected onUninitialize(): void { super.uninitialize(); // TODO: make sure that all meshes and programs inside of the scene get cleaned // this._mesh.uninitialize(); // this._meshProgram.uninitialize(); } protected onDiscarded(): void { this._altered.alter('frameSize'); this._altered.alter('canvasSize'); this._altered.alter('clearColor'); } /** * This is invoked in order to check if rendering of a frame is required by means of implementation specific * evaluation (e.g., lazy non continuous rendering). Regardless of the return value a new frame (preparation, * frame, swap) might be invoked anyway, e.g., when update is forced or canvas or context properties have * changed or the renderer was invalidated @see{@link invalidate}. * Updates the navigaten and the AntiAliasingKernel. * @returns whether to redraw */ protected onUpdate(): boolean { if (this._altered.frameSize) { this._camera.viewport = [this._frameSize[0], this._frameSize[1]]; } if (this._altered.canvasSize) { this._camera.aspect = this._canvasSize[0] / this._canvasSize[1]; } if (this._altered.clearColor) { this._forwardPass.clearColor = this._clearColor; } this._navigation.update(); this._forwardPass.update(); return this._altered.any || this._camera.altered; } /** * This is invoked in order to prepare rendering of one or more frames, regarding multi-frame rendering and * camera-updates. */ protected onPrepare(): void { this._forwardPass.prepare(); this._altered.reset(); this._camera.altered = false; } protected onFrame(frameNumber: number): void { if (this.isLoading) { return; } this.bindUniforms(); const gl = this._context.gl; // TODO: proper handling of transparent materials in the loader gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); this._forwardPass.frame(); } protected onSwap(): void { } protected bindUniforms(): void { const gl = this._context.gl; this._program.bind(); gl.uniform3fv(this._uEye, this._camera.eye); gl.uniform1i(this._uBaseColor, 0); gl.uniform1i(this._uMetallicRoughness, 1); gl.uniform1i(this._uNormal, 2); gl.uniform1i(this._uOcclusion, 3); gl.uniform1i(this._uEmissive, 4); gl.uniform1i(this._uSpecularEnvironment, 5); gl.uniform1i(this._uBRDFLookupTable, 6); this._specularEnvironment.bind(gl.TEXTURE5); this._brdfLUT.bind(gl.TEXTURE6); this._program.unbind(); } /** * Load asset from URI specified by the HTML select */ protected loadAsset(): void { const assetSelect = window.document.getElementById('asset-select')! as HTMLSelectElement; this.startLoading(); const uri = assetSelect.value; this._forwardPass.scene = undefined; this._loader.uninitialize(); this._loader.loadAsset(uri) .then(() => { this._forwardPass.scene = this._loader.defaultScene; this.finishLoading(); this._invalidate(true); }); } /** * Setup environment lighting */ protected loadEnvironmentMap(): void { const gl = this._context.gl; this._brdfLUT = new Texture2D(this._context, 'BRDFLookUpTable'); this._brdfLUT.initialize(1, 1, gl.RG16F, gl.RG, gl.FLOAT); this._brdfLUT.wrap(gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE); this._brdfLUT.filter(gl.LINEAR, gl.LINEAR); this._brdfLUT.fetch('/examples/data/imagebasedlighting/brdfLUT.png'); const internalFormatAndType = Wizard.queryInternalTextureFormat( this._context, gl.RGBA, Wizard.Precision.byte); this._specularEnvironment = new TextureCube(this._context, 'Cubemap'); this._specularEnvironment.initialize(512, internalFormatAndType[0], gl.RGBA, internalFormatAndType[1]); const MIPMAP_LEVELS = 9; this._specularEnvironment.filter(gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR); this._specularEnvironment.levels(0, MIPMAP_LEVELS - 1); for (let mipLevel = 0; mipLevel < MIPMAP_LEVELS; ++mipLevel) { this._specularEnvironment.fetch({ positiveX: `/examples/data/imagebasedlighting/preprocessed-map-px-${mipLevel}.png`, negativeX: `/examples/data/imagebasedlighting/preprocessed-map-nx-${mipLevel}.png`, positiveY: `/examples/data/imagebasedlighting/preprocessed-map-py-${mipLevel}.png`, negativeY: `/examples/data/imagebasedlighting/preprocessed-map-ny-${mipLevel}.png`, positiveZ: `/examples/data/imagebasedlighting/preprocessed-map-pz-${mipLevel}.png`, negativeZ: `/examples/data/imagebasedlighting/preprocessed-map-nz-${mipLevel}.png`, }, false, mipLevel); } } } export class GltfDemo extends Demo { private _canvas: Canvas; private _renderer: GltfRenderer; onInitialize(element: HTMLCanvasElement | string): boolean { this._canvas = new Canvas(element, { antialias: true }); this._canvas.controller.multiFrameNumber = 1; this._canvas.framePrecision = Wizard.Precision.byte; this._canvas.frameScale = [1.0, 1.0]; this._renderer = new GltfRenderer(); this._canvas.renderer = this._renderer; return true; } onUninitialize(): void { this._canvas.dispose(); (this._renderer as Renderer).uninitialize(); } get canvas(): Canvas { return this._canvas; } get renderer(): GltfRenderer { return this._renderer; } }
the_stack
import { h, render, Fragment } from "preact"; import { useState, useEffect, useRef, useCallback, useMemo } from "preact/hooks"; import { Os, Storage, Notification, RegularFont, GoogleFont, Theme, NotesObject, NotesOrder, Sync, Message, MessageType, } from "shared/storage/schema"; import { setTheme as setThemeCore } from "themes/set-theme"; import __Notification from "notes/components/Notification"; import __Sidebar from "notes/components/Sidebar"; import __Content from "notes/components/Content"; import __CommandPalette, { CommandPaletteProps } from "notes/components/CommandPalette"; import __Toolbar from "notes/components/Toolbar"; import range from "notes/range"; import __ContextMenu, { ContextMenuProps } from "notes/components/ContextMenu"; import __RenameNoteModal, { RenameNoteModalProps } from "notes/components/modals/RenameNoteModal"; import __DeleteNoteModal, { DeleteNoteModalProps } from "notes/components/modals/DeleteNoteModal"; import __NewNoteModal, { NewNoteModalProps } from "notes/components/modals/NewNoteModal"; import __Overlay from "notes/components/Overlay"; import renameNote from "notes/state/rename-note"; import deleteNote from "notes/state/delete-note"; import createNote from "notes/state/create-note"; import { saveNote, setLocked } from "notes/content/save"; import { sendMessage } from "messages"; import notesHistory from "notes/history"; import keyboardShortcuts, { KeyboardShortcut } from "notes/keyboard-shortcuts"; import { useKeyboardShortcut } from "notes/hooks/use-keyboard-shortcut"; import { Command, commands } from "notes/commands"; import { exportNote } from "notes/export"; import { notesToSidebarNotes } from "notes/adapters"; const getFocusOverride = (): boolean => new URL(window.location.href).searchParams.get("focus") === ""; const getActiveFromUrl = (): string => new URL(window.location.href).searchParams.get("note") || ""; // Bookmark const getFirstAvailableNote = (notes: NotesObject): string => Object.keys(notes).sort().shift() || ""; let autoSyncIntervalId: number | undefined; interface NotesProps { notes: NotesObject active: string } const Notes = (): h.JSX.Element => { const [os, setOs] = useState<Os | undefined>(undefined); const [tabId, setTabId] = useState<number | undefined>(undefined); const [notification, setNotification] = useState<Notification | undefined>(undefined); const [font, setFont] = useState<RegularFont | GoogleFont | undefined>(undefined); const [size, setSize] = useState<number>(0); const [sidebar, setSidebar] = useState<boolean>(false); const [sidebarWidth, setSidebarWidth] = useState<string | undefined>(undefined); const [toolbar, setToolbar] = useState<boolean>(false); const [theme, setTheme] = useState<Theme | undefined>(undefined); const [customTheme, setCustomTheme] = useState<string>(""); const [notesProps, setNotesProps] = useState<NotesProps>({ notes: {}, active: "", }); const notesRef = useRef<NotesObject>(); notesRef.current = notesProps.notes; const [order, setOrder] = useState<string[] | undefined>(undefined); const [initialContent, setInitialContent] = useState<string>(""); const [notesOrder, setNotesOrder] = useState<NotesOrder | undefined>(undefined); const [focus, setFocus] = useState<boolean>(false); const [tab, setTab] = useState<boolean>(false); const [tabSize, setTabSize] = useState<number>(-1); const [sync, setSync] = useState<Sync | undefined>(undefined); const syncRef = useRef<Sync | undefined>(undefined); syncRef.current = sync; const [autoSync, setAutoSync] = useState<boolean>(false); const lastEditRef = useRef<string>(""); const [initialized, setInitialized] = useState<boolean>(false); const [contextMenuProps, setContextMenuProps] = useState<ContextMenuProps | null>(null); const [renameNoteModalProps, setRenameNoteModalProps] = useState<RenameNoteModalProps | null>(null); const [deleteNoteModalProps, setDeleteNoteModalProps] = useState<DeleteNoteModalProps | null>(null); const [newNoteModalProps, setNewNoteModalProps] = useState<NewNoteModalProps | null>(null); const [commandPaletteProps, setCommandPaletteProps] = useState<CommandPaletteProps | null>(null); useEffect(() => { chrome.runtime.getPlatformInfo((platformInfo) => setOs(platformInfo.os === "mac" ? "mac" : "other")); chrome.tabs.getCurrent((tab) => tab && setTabId(tab.id)); }, []); useEffect(() => { if (!tabId) { return; } chrome.storage.local.get([ // Notifications "notification", // Appearance "font", "size", "sidebar", "sidebarWidth", "toolbar", "theme", "customTheme", // Notes "notes", "order", "active", // Options "notesOrder", "focus", "autoSync", "tab", "tabSize", // Sync "sync", "autoSync", "lastEdit", ], items => { const local = items as Storage; // Notifications setNotification(local.notification); // Appearance setFont(local.font); setSize(local.size); setSidebar(local.sidebar); setSidebarWidth(local.sidebarWidth); setToolbar(local.toolbar); setTheme(local.theme); setCustomTheme(local.customTheme); // Notes const activeFromUrl = getActiveFromUrl(); const activeCandidates: string[] = [activeFromUrl, local.active as string, getFirstAvailableNote(local.notes)]; // ordered by importance const active: string = activeCandidates.find((candidate) => candidate && candidate in local.notes) || ""; setNotesProps({ notes: local.notes, active, }); if (active !== activeFromUrl) { notesHistory.replace(active); } setOrder(local.order); // Options setNotesOrder(local.notesOrder); setFocus(getFocusOverride() || local.focus); setTab(local.tab); setTabSize(local.tabSize); // Sync setSync(local.sync); setAutoSync(local.autoSync); lastEditRef.current = local.lastEdit; // Initialized setInitialized(true); }); chrome.storage.onChanged.addListener((changes, areaName) => { if (areaName !== "local") { return; } if (changes["font"]) { setFont(changes["font"].newValue); } if (changes["size"]) { setSize(changes["size"].newValue); } if (changes["theme"]) { setTheme(changes["theme"].newValue); } if (changes["customTheme"]) { setCustomTheme(changes["customTheme"].newValue); } if (changes["notes"]) { const oldNotes: NotesObject = changes["notes"].oldValue; const newNotes: NotesObject = changes["notes"].newValue; const oldSet = new Set(Object.keys(oldNotes)); const newSet = new Set(Object.keys(newNotes)); // RENAME if (newSet.size === oldSet.size) { const diff = new Set([...newSet].filter(x => !oldSet.has(x))); if (diff.size === 1) { const renamedNoteName = diff.values().next().value as string; setNotesProps((prev) => { const newActive = prev.active in newNotes ? prev.active // active is NOT renamed => keep unchanged : renamedNoteName; // active is renamed => update it if (newActive !== prev.active) { notesHistory.replace(newActive); // active is renamed => replace history } return { notes: newNotes, active: newActive, }; }); return; // RENAME condition was met } } // DELETE if (oldSet.size > newSet.size) { setNotesProps((prev) => { const newActive = prev.active in newNotes ? prev.active // active is NOT deleted => keep unchanged : getFirstAvailableNote(newNotes); // active is deleted => use first available if (newActive !== prev.active) { notesHistory.replace(newActive); // active is deleted => replace history } return { notes: newNotes, active: newActive, }; }); return; // DELETE condition was met } // NEW or UPDATE setNotesProps((prev) => { const diff = newSet.size > oldSet.size ? new Set([...newSet].filter(x => !oldSet.has(x))) : undefined; const newNoteName = (changes["active"] && changes["active"].newValue as string) || ((diff && diff.size === 1) ? diff.values().next().value as string : ""); // Auto-active new note const newActive = newNoteName || prev.active; // Update note content if updated from background const setBy: string | undefined = changes["setBy"] && changes["setBy"].newValue; if ( (setBy && !setBy.startsWith(`${tabId}-`)) && // expecting "worker-*" or "sync-*" (newActive in oldNotes) && (newActive in newNotes) && (newNotes[newActive].content !== oldNotes[newActive].content) && (newNotes[newActive].modifiedTime > oldNotes[newActive].modifiedTime) ) { setInitialContent(newNotes[newActive].content); } if (!(newActive in oldNotes)) { notesHistory.push(newActive); } return { notes: newNotes, active: newActive, }; }); } if (changes["order"]) { setOrder(changes["order"].newValue); } if (changes["notesOrder"]) { setNotesOrder(changes["notesOrder"].newValue); } if (changes["focus"]) { setFocus(getFocusOverride() || changes["focus"].newValue); } if (changes["tab"]) { setTab(changes["tab"].newValue); } if (changes["tabSize"]) { setTabSize(changes["tabSize"].newValue); } if (changes["sync"]) { setSync(changes["sync"].newValue); document.body.classList.remove("syncing"); } if (changes["autoSync"]) { setAutoSync(changes["autoSync"].newValue); } if (changes["lastEdit"]) { lastEditRef.current = changes["lastEdit"].newValue; } }); chrome.runtime.onMessage.addListener((message: Message) => { if (message.type === MessageType.SYNC_START) { document.body.classList.add("syncing"); return; } if (message.type === MessageType.SYNC_DONE || message.type === MessageType.SYNC_FAIL) { document.body.classList.remove("syncing"); return; } }); notesHistory.attach((noteName) => { setNotesProps((prev) => noteName in prev.notes ? { ...prev, active: noteName } : prev); }); }, [tabId]); // Font useEffect(() => { if (!font) { return; } const href = (font as GoogleFont).href; if (href) { (document.getElementById("google-fonts") as HTMLLinkElement).href = href; } document.body.style.fontFamily = font.fontFamily; }, [font]); // Size useEffect(() => { document.body.style.fontSize = Number.isInteger(size) ? `${size}%` : ""; }, [size]); // Sidebar useEffect(() => { document.body.classList.toggle("with-sidebar", sidebar); }, [sidebar]); // Sidebar width useEffect(() => { document.body.style.left = sidebarWidth ?? ""; }, [sidebarWidth]); // Theme useEffect(() => { // setThemeCore injects one of: // - light.css // - dark.css // - customTheme string theme && setThemeCore(document, { theme, customTheme: customTheme }); }, [theme, customTheme]); // Focus useEffect(() => { document.body.classList.toggle("focus", focus); }, [focus]); // Hide context menu on click anywhere useEffect(() => { document.addEventListener("click", (event) => { if ((event.target as Element).closest("#context-menu") === null) { setContextMenuProps(null); } }); }, []); // Activate note useEffect(() => { const note = notesProps.notes[notesProps.active]; setInitialContent(note ? note.content : ""); document.title = note ? notesProps.active : "My Notes"; }, [notesProps.active]); // Toolbar useEffect(() => { document.body.classList.toggle("with-toolbar", toolbar); }, [toolbar]); // Keyboard shortcuts useEffect(() => { if (!os) { return; } keyboardShortcuts.register(os); keyboardShortcuts.subscribe(KeyboardShortcut.OnEscape, () => { setContextMenuProps(null); setCommandPaletteProps((prev) => { if (prev) { range.restore(); } return null; }); }); keyboardShortcuts.subscribe(KeyboardShortcut.OnOpenOptions, chrome.runtime.openOptionsPage); keyboardShortcuts.subscribe(KeyboardShortcut.OnToggleFocusMode, () => { if (getFocusOverride()) { return; } chrome.storage.local.get(["focus"], local => { chrome.storage.local.set({ focus: !local.focus }); }); }); keyboardShortcuts.subscribe(KeyboardShortcut.OnToggleSidebar, () => { if (getFocusOverride()) { return; } chrome.storage.local.get(["focus"], local => { if (!local.focus) { // toggle only if not in focus mode const hasSidebar = document.body.classList.toggle("with-sidebar"); chrome.storage.local.set({ sidebar: hasSidebar }); } }); }); keyboardShortcuts.subscribe(KeyboardShortcut.OnToggleToolbar, () => { if (getFocusOverride()) { return; } chrome.storage.local.get(["focus"], local => { if (!local.focus) { // toggle only if not in focus mode const hasToolbar = document.body.classList.toggle("with-toolbar"); chrome.storage.local.set({ toolbar: hasToolbar }); } }); }); keyboardShortcuts.subscribe(KeyboardShortcut.OnSync, () => sendMessage(MessageType.SYNC)); }, [os]); useEffect(() => { window.addEventListener("blur", () => { document.body.classList.remove("with-control"); }); }, []); const onNewNote = useCallback((empty?: boolean) => { setNewNoteModalProps({ validate: (newNoteName: string) => newNoteName.length > 0 && !(newNoteName in notesProps.notes), onCancel: empty ? undefined : () => setNewNoteModalProps(null), onConfirm: (newNoteName) => { setNewNoteModalProps(null); createNote(newNoteName); }, }); }, [notesProps]); const handleOnActivateNote = useCallback((noteName: string) => { if (notesProps.active === noteName || !(noteName in notesProps.notes)) { return; } setNotesProps((prev) => ({ ...prev, active: noteName })); notesHistory.push(noteName); chrome.storage.local.set({ active: noteName }); }, [notesProps]); // Command Palette const commandPaletteCommands = useMemo((): Command[] => [ commands.InsertCurrentDate, commands.InsertCurrentTime, commands.InsertCurrentDateAndTime, ], []); // Repeat last executed command const [lastExecutedCommand, setLastExecutedCommand] = useState<Command | undefined>(undefined); const [setHandlerOnRepeatLastExecutedCommand] = useKeyboardShortcut(KeyboardShortcut.OnRepeatLastExecutedCommand); useEffect(() => setHandlerOnRepeatLastExecutedCommand(lastExecutedCommand?.execute), [lastExecutedCommand]); // Command Palette const [setHandlerOnToggleCommandPalette] = useKeyboardShortcut(KeyboardShortcut.OnToggleCommandPalette); useEffect(() => { // Detach when there are no notes if (!Object.keys(notesProps.notes).length) { setHandlerOnToggleCommandPalette(undefined); setCommandPaletteProps(null); return; } // Start preparing props for Command Palette const currentNoteLocked: boolean = notesProps.active in notesProps.notes && notesProps.notes[notesProps.active].locked === true; const commands = currentNoteLocked ? [] : commandPaletteCommands.map((command) => command.name); // no commands if the current note is locked // Props for Command Palette const props: CommandPaletteProps = { notes: notesProps.notes, commands, onActivateNote: (noteName: string) => { setCommandPaletteProps(null); range.restore(() => handleOnActivateNote(noteName)); }, onExecuteCommand: (commandName: string) => { const foundCommand = commandPaletteCommands.find((command) => command.name === commandName); if (foundCommand) { setCommandPaletteProps(null); range.restore(() => { foundCommand.execute(); setLastExecutedCommand(foundCommand); }); } }, }; // Update event to show Command Palette and props to use setHandlerOnToggleCommandPalette(() => { setCommandPaletteProps((prev) => { if (prev) { range.restore(); return null; } range.save(); return props; }); }); // Update props for already visible Command Palette setCommandPaletteProps((prev) => !prev ? prev : props); }, [os, notesProps, handleOnActivateNote, commandPaletteCommands]); // Automatically show modal to create a new note if there are 0 notes useEffect(() => { if (!initialized || !tabId || Object.keys(notesProps.notes).length > 0) { setNewNoteModalProps(null); return; } onNewNote(true); }, [initialized, tabId, notesProps, onNewNote]); // Auto Sync useEffect(() => { if (!initialized || !autoSync || !syncRef.current) { window.clearInterval(autoSyncIntervalId); autoSyncIntervalId = undefined; return; } if (autoSyncIntervalId) { return; // interval is already set } window.setTimeout(() => sendMessage(MessageType.SYNC), 100); // Auto Sync on start autoSyncIntervalId = window.setInterval(() => { if (!syncRef.current || lastEditRef.current <= (syncRef.current.lastSync ?? "")) { return; } sendMessage(MessageType.SYNC); }, 6000); // and then Auto Sync every 6 seconds }, [initialized, autoSync]); return ( <Fragment> {notification && ( <__Notification notification={notification} onClose={() => { setNotification(undefined); chrome.storage.local.remove("notification"); }} /> )} {notesOrder && order && ( <__Sidebar os={os} notes={notesToSidebarNotes(notesProps.notes, notesOrder, order)} active={notesProps.active} width={sidebarWidth} onActivateNote={handleOnActivateNote} onNoteContextMenu={(noteName, x, y) => setContextMenuProps({ noteName, x, y, onRename: (noteName) => { setContextMenuProps(null); setRenameNoteModalProps({ noteName, validate: (newNoteName: string) => newNoteName.length > 0 && newNoteName !== noteName && !(newNoteName in notesProps.notes), onCancel: () => setRenameNoteModalProps(null), onConfirm: (newNoteName) => { setRenameNoteModalProps(null); renameNote(noteName, newNoteName); }, }); }, onDelete: (noteName) => { setContextMenuProps(null); setDeleteNoteModalProps({ noteName, onCancel: () => setDeleteNoteModalProps(null), onConfirm: () => { setDeleteNoteModalProps(null); deleteNote(noteName); }, }); }, locked: notesProps.notes[noteName].locked ?? false, onToggleLocked: (noteName) => { setContextMenuProps(null); tabId && notesRef.current && setLocked(noteName, !(notesProps.notes[noteName].locked ?? false), tabId, notesRef.current); }, onExport: (noteName) => { setContextMenuProps(null); exportNote(noteName); }, })} onNewNote={() => onNewNote()} canChangeOrder={notesOrder === NotesOrder.Custom} onChangeOrder={(newOrder) => chrome.storage.local.set({ order: newOrder })} sync={sync} /> )} <div id="content-container"> {notesProps.active && ( <__Content active={notesProps.active} locked={notesProps.notes[notesProps.active].locked ?? false} initialContent={initialContent} onEdit={(active, content) => { tabId && notesRef.current && saveNote(active, content, tabId, notesRef.current); }} indentOnTab={tab} tabSize={tabSize} /> )} {commandPaletteProps && ( <__CommandPalette {...commandPaletteProps} /> )} </div> {os && notesProps.active && notesProps.active in notesProps.notes && ( <__Toolbar os={os} note={notesProps.notes[notesProps.active]} /> )} {contextMenuProps && ( <__ContextMenu {...contextMenuProps} /> )} {renameNoteModalProps && ( <Fragment> <__RenameNoteModal {...renameNoteModalProps} /> <__Overlay type="to-rename" /> </Fragment> )} {deleteNoteModalProps && ( <Fragment> <__DeleteNoteModal {...deleteNoteModalProps} /> <__Overlay type="to-delete" /> </Fragment> )} {newNoteModalProps && ( <Fragment> <__NewNoteModal {...newNoteModalProps} /> <__Overlay type="to-create" /> </Fragment> )} <div id="tooltip-container"></div> </Fragment> ); }; render(<Notes />, document.body);
the_stack
import {SimpleChanges} from '@angular/core'; import * as _moment from 'moment'; import {DlDateTimePickerModel} from './dl-date-time-picker-model'; import {DlModelProvider} from './dl-model-provider'; /** * Work around for moment namespace conflict when used with webpack and rollup. * See https://github.com/dherges/ng-packagr/issues/163 * * Depending on whether rollup is used, moment needs to be imported differently. * Since Moment.js doesn't have a default export, we normally need to import using * the `* as`syntax. * * rollup creates a synthetic default module and we thus need to import it using * the `default as` syntax. * * @internal **/ const moment = _moment; /** * Default implementation for the `day` view. */ export class DlDayModelProvider implements DlModelProvider { /** * Receives input changes detected by Angular. * * @param changes * the input changes detected by Angular. */ onChanges( // @ts-ignore changes: SimpleChanges ): void {} /** * Returns the `day` model for the specified moment in `local` time with the * `active` day set to the first day of the month. * * The `day` model represents a month (42 days) as six rows with seven columns * and each cell representing one-day increments. * * The `day` always starts at midnight. * * Each cell represents a one-day increment at midnight. * * @param milliseconds * the moment in time from which the minute model will be created. * @param selectedMilliseconds * the current value of the date/time picker. * @returns * the model representing the specified moment in time. */ getModel(milliseconds: number, selectedMilliseconds: number): DlDateTimePickerModel { const startOfMonth = moment(milliseconds).startOf('month'); const endOfMonth = moment(milliseconds).endOf('month'); const startOfView = moment(startOfMonth).subtract(Math.abs(startOfMonth.weekday()), 'days'); const rowNumbers = [0, 1, 2, 3, 4, 5]; const columnNumbers = [0, 1, 2, 3, 4, 5, 6]; const previousMonth = moment(startOfMonth).subtract(1, 'month'); const nextMonth = moment(startOfMonth).add(1, 'month'); const activeValue = moment(milliseconds).startOf('day').valueOf(); const selectedValue = selectedMilliseconds === null || selectedMilliseconds === undefined ? selectedMilliseconds : moment(selectedMilliseconds).startOf('day').valueOf(); return { viewName: 'day', viewLabel: startOfMonth.format('MMM YYYY'), activeDate: activeValue, leftButton: { value: previousMonth.valueOf(), ariaLabel: `Go to ${previousMonth.format('MMM YYYY')}`, classes: {}, }, upButton: { value: startOfMonth.valueOf(), ariaLabel: `Go to month view`, classes: {}, }, rightButton: { value: nextMonth.valueOf(), ariaLabel: `Go to ${nextMonth.format('MMM YYYY')}`, classes: {}, }, rowLabels: columnNumbers.map((column) => moment().weekday(column).format('dd')), rows: rowNumbers.map(rowOfDays) }; function rowOfDays(rowNumber) { const currentMoment = moment(); const cells = columnNumbers.map((columnNumber) => { const dayMoment = moment(startOfView).add((rowNumber * columnNumbers.length) + columnNumber, 'days'); return { display: dayMoment.format('D'), ariaLabel: dayMoment.format('ll'), value: dayMoment.valueOf(), classes: { 'dl-abdtp-active': activeValue === dayMoment.valueOf(), 'dl-abdtp-future': dayMoment.isAfter(endOfMonth), 'dl-abdtp-past': dayMoment.isBefore(startOfMonth), 'dl-abdtp-selected': selectedValue === dayMoment.valueOf(), 'dl-abdtp-now': dayMoment.isSame(currentMoment, 'day'), } }; }); return {cells}; } } /** * Move the active `day` one row `down` from the specified moment in time. * * Moving `down` can result in the `active` day being part of a different month than * the specified `fromMilliseconds`, in this case the month represented by the model * will change to show the correct hour. * * @param fromMilliseconds * the moment in time from which the next `day` model `down` will be constructed. * @param selectedMilliseconds * the current value of the date/time picker. * @returns * model containing an `active` `day` one row `down` from the specified moment in time. */ goDown(fromMilliseconds: number, selectedMilliseconds: number): DlDateTimePickerModel { return this.getModel(moment(fromMilliseconds).add(7, 'days').valueOf(), selectedMilliseconds); } /** * Move the active `day` one row `up` from the specified moment in time. * * Moving `up` can result in the `active` day being part of a different month than * the specified `fromMilliseconds`, in this case the month represented by the model * will change to show the correct hour. * * @param fromMilliseconds * the moment in time from which the next `day` model `up` will be constructed. * @param selectedMilliseconds * the current value of the date/time picker. * @returns * model containing an `active` `day` one row `up` from the specified moment in time. */ goUp(fromMilliseconds: number, selectedMilliseconds: number): DlDateTimePickerModel { return this.getModel(moment(fromMilliseconds).subtract(7, 'days').valueOf(), selectedMilliseconds); } /** * Move the `active` day one cell `left` in the current `day` view. * * Moving `left` can result in the `active` day being part of a different month than * the specified `fromMilliseconds`, in this case the month represented by the model * will change to show the correct year. * * @param fromMilliseconds * the moment in time from which the `day` model to the `left` will be constructed. * @param selectedMilliseconds * the current value of the date/time picker. * @returns * model containing an `active` `day` one cell to the `left` of the specified moment in time. */ goLeft(fromMilliseconds: number, selectedMilliseconds: number): DlDateTimePickerModel { return this.getModel(moment(fromMilliseconds).subtract(1, 'day').valueOf(), selectedMilliseconds); } /** * Move the `active` day one cell `right` in the current `day` view. * * Moving `right` can result in the `active` day being part of a different month than * the specified `fromMilliseconds`, in this case the month represented by the model * will change to show the correct year. * * @param fromMilliseconds * the moment in time from which the `day` model to the `right` will be constructed. * @param selectedMilliseconds * the current value of the date/time picker. * @returns * model containing an `active` `day` one cell to the `right` of the specified moment in time. */ goRight(fromMilliseconds: number, selectedMilliseconds: number): DlDateTimePickerModel { return this.getModel(moment(fromMilliseconds).add(1, 'day').valueOf(), selectedMilliseconds); } /** * Move the active `day` one month `down` from the specified moment in time. * * Paging `down` will result in the `active` day being part of a different month than * the specified `fromMilliseconds`. As a result, the month represented by the model * will change to show the correct year. * * @param fromMilliseconds * the moment in time from which the next `day` model page `down` will be constructed. * @param selectedMilliseconds * the current value of the date/time picker. * @returns * model containing an `active` `day` one month `down` from the specified moment in time. */ pageDown(fromMilliseconds: number, selectedMilliseconds: number): DlDateTimePickerModel { return this.getModel(moment(fromMilliseconds).add(1, 'month').valueOf(), selectedMilliseconds); } /** * Move the active `day` one month `up` from the specified moment in time. * * Paging `up` will result in the `active` day being part of a different month than * the specified `fromMilliseconds`. As a result, the month represented by the model * will change to show the correct year. * * @param fromMilliseconds * the moment in time from which the next `day` model page `up` will be constructed. * @param selectedMilliseconds * the current value of the date/time picker. * @returns * model containing an `active` `day` one month `up` from the specified moment in time. */ pageUp(fromMilliseconds: number, selectedMilliseconds: number): DlDateTimePickerModel { return this.getModel(moment(fromMilliseconds).subtract(1, 'month').valueOf(), selectedMilliseconds); } /** * Move the `active` `day` to the last day of the month. * * The view or time range will not change unless the `fromMilliseconds` value * is in a different day than the displayed decade. * * @param fromMilliseconds * the moment in time from which the last day of the month will be calculated. * @param selectedMilliseconds * the current value of the date/time picker. * @returns * a model with the last cell in the view as the active `day`. */ goEnd(fromMilliseconds: number, selectedMilliseconds: number): DlDateTimePickerModel { return this.getModel(moment(fromMilliseconds) .endOf('month').startOf('day').valueOf(), selectedMilliseconds); } /** * Move the `active` `day` to the first day of the month. * * The view or time range will not change unless the `fromMilliseconds` value * is in a different day than the displayed decade. * * @param fromMilliseconds * the moment in time from which the first day of the month will be calculated. * @param selectedMilliseconds * the current value of the date/time picker. * @returns * a model with the first cell in the view as the active `day`. */ goHome(fromMilliseconds: number, selectedMilliseconds: number): DlDateTimePickerModel { return this.getModel(moment(fromMilliseconds).startOf('month').valueOf(), selectedMilliseconds); } }
the_stack
import {getSystemPath, normalize, virtualFs} from '@angular-devkit/core'; import {TempScopedNodeJsSyncHost} from '@angular-devkit/core/node/testing'; import {HostTree} from '@angular-devkit/schematics'; import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing'; import * as shx from 'shelljs'; describe('TestBed teardown migration', () => { let runner: SchematicTestRunner; let host: TempScopedNodeJsSyncHost; let tree: UnitTestTree; let tmpDirPath: string; let previousWorkingDir: string; beforeEach(() => { runner = new SchematicTestRunner('test', require.resolve('../migrations.json')); host = new TempScopedNodeJsSyncHost(); tree = new UnitTestTree(new HostTree(host)); writeFile('/tsconfig.json', JSON.stringify({ compilerOptions: { lib: ['es2015'], strictNullChecks: true, }, })); writeFile('/angular.json', JSON.stringify({ version: 1, projects: {t: {architect: {build: {options: {tsConfig: './tsconfig.json'}}}}} })); // We need to declare the Angular symbols we're testing for, otherwise type checking won't work. // Note that the declarations here are a little more convoluted than they need to be. It's // because they've been copied over directly from `node_modules/@angular/core/testing.d.ts`, // except for removing some methods that are irrelevant to these tests. writeFile('/node_modules/@angular/core/testing.d.ts', ` export declare const getTestBed: () => TestBed; export declare interface TestBed { initTestEnvironment(ngModule: any, platform: any, options?: any): void; configureTestingModule(moduleDef: any): void; } export declare const TestBed: TestBedStatic; export declare interface TestBedStatic { new (...args: any[]): TestBed; initTestEnvironment(ngModule: any, platform: any, options?: any): TestBed; configureTestingModule(moduleDef: any): TestBedStatic; } export declare function withModule(moduleDef: any, fn: Function): () => any; `); previousWorkingDir = shx.pwd(); tmpDirPath = getSystemPath(host.root); // Switch into the temporary directory path. This allows us to run // the schematic against our custom unit test tree. shx.cd(tmpDirPath); }); afterEach(() => { shx.cd(previousWorkingDir); shx.rm('-r', tmpDirPath); }); it('should migrate calls to initTestEnvironment', async () => { writeFile('/index.ts', ` import { TestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); `); await runMigration(); expect(stripWhitespace(tree.readContent('/index.ts'))).toContain(stripWhitespace(` TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { teardown: { destroyAfterEach: false } }); `)); }); it('should migrate calls to initTestEnvironment going through getTestBed()', async () => { writeFile('/index.ts', ` import { getTestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); `); await runMigration(); expect(stripWhitespace(tree.readContent('/index.ts'))).toContain(stripWhitespace(` getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { teardown: { destroyAfterEach: false } }); `)); }); it('should migrate calls to initTestEnvironment going through a variable', async () => { writeFile('/index.ts', ` import { getTestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; const tb = getTestBed(); tb.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); `); await runMigration(); expect(stripWhitespace(tree.readContent('/index.ts'))).toContain(stripWhitespace(` tb.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { teardown: { destroyAfterEach: false } }); `)); }); it('should migrate not calls to initTestEnvironment that already specify a teardown behavior', async () => { writeFile('/index.ts', ` import { TestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { teardown: {destroyAfterEach: true} }); `); await runMigration(); expect(stripWhitespace(tree.readContent('/index.ts'))).toContain(stripWhitespace(` TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { teardown: {destroyAfterEach: true} }); `)); }); it('should migrate calls to initTestEnvironment that pass in aotSummaries as an arrow function', async () => { writeFile('/index.ts', ` import { TestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; class Foo {} TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), () => [Foo]); `); await runMigration(); expect(stripWhitespace(tree.readContent('/index.ts'))).toContain(stripWhitespace(` TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { aotSummaries: () => [Foo], teardown: { destroyAfterEach: false } }); `)); }); it('should migrate calls to initTestEnvironment that pass in aotSummaries as an anonymous function', async () => { writeFile('/index.ts', ` import { TestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; class Foo {} TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), function() { return [Foo]; }); `); await runMigration(); expect(stripWhitespace(tree.readContent('/index.ts'))).toContain(stripWhitespace(` TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { aotSummaries: function() { return [Foo]; }, teardown: { destroyAfterEach: false } }); `)); }); it('should migrate calls to initTestEnvironment that pass in aotSummaries via an object literal', async () => { writeFile('/index.ts', ` import { TestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; class Foo {} TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { aotSummaries: () => [Foo] }); `); await runMigration(); expect(stripWhitespace(tree.readContent('/index.ts'))).toContain(stripWhitespace(` TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { aotSummaries: () => [Foo], teardown: { destroyAfterEach: false } }); `)); }); it('should migrate initTestEnvironment calls across multiple files', async () => { writeFile('/test-init.ts', ` import { TestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); `); writeFile('/other-test-init.ts', ` import { getTestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); `); await runMigration(); expect(stripWhitespace(tree.readContent('/test-init.ts'))).toContain(stripWhitespace(` TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { teardown: { destroyAfterEach: false } }); `)); expect(stripWhitespace(tree.readContent('/other-test-init.ts'))).toContain(stripWhitespace(` getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { teardown: { destroyAfterEach: false } }); `)); }); it('should not migrate calls to initTestEnvironment that pass in a variable', async () => { writeFile('/index.ts', ` import { TestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; const config = {aotSummaries: () => []}; TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), config); `); await runMigration(); const content = stripWhitespace(tree.readContent('/index.ts')); expect(content).toContain(stripWhitespace(`const config = {aotSummaries: () => []};`)); expect(content).toContain(stripWhitespace(` TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), config); `)); }); it('should not migrate invalid initTestEnvironment calls', async () => { writeFile('/index.ts', ` import { TestBed } from '@angular/core/testing'; TestBed.initTestEnvironment(); `); await runMigration(); expect(stripWhitespace(tree.readContent('/index.ts'))) .toContain(stripWhitespace(`TestBed.initTestEnvironment();`)); }); it('should not migrate calls to initTestEnvironment not coming from Angular', async () => { writeFile('/index.ts', ` import { TestBed } from '@not-angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); `); await runMigration(); expect(stripWhitespace(tree.readContent('/index.ts'))) .toContain(stripWhitespace( `TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting());`)); }); it('should migrate calls to initTestEnvironment when TestBed is aliased', async () => { writeFile('/index.ts', ` import { TestBed as AliasOfTestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; AliasOfTestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); `); await runMigration(); expect(stripWhitespace(tree.readContent('/index.ts'))).toContain(stripWhitespace(` AliasOfTestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { teardown: { destroyAfterEach: false } }); `)); }); it('should migrate withModule calls', async () => { writeFile('/index.spec.ts', ` import { Component } from '@angular/core'; import { withModule, TestBed } from '@angular/core/testing'; @Component({template: ''}) class Comp {} it('should work', withModule({ declarations: [Comp], }, () => { TestBed.createComponent(Comp); })); `); await runMigration(); expect(stripWhitespace(tree.readContent('/index.spec.ts'))).toContain(stripWhitespace(` it('should work', withModule({ declarations: [Comp], teardown: {destroyAfterEach: false} }, () => { TestBed.createComponent(Comp); })); `)); }); it('should not migrate withModule calls that already pass in the teardown flag', async () => { writeFile('/index.spec.ts', ` import { Component } from '@angular/core'; import { withModule, TestBed } from '@angular/core/testing'; @Component({template: ''}) class Comp {} it('should work', withModule({ teardown: {destroyAfterEach: true}, declarations: [Comp], }, () => { TestBed.createComponent(Comp); })); `); await runMigration(); expect(stripWhitespace(tree.readContent('/index.spec.ts'))).toContain(stripWhitespace(` it('should work', withModule({ teardown: {destroyAfterEach: true}, declarations: [Comp], }, () => { TestBed.createComponent(Comp); })); `)); }); it('should not migrate withModule calls that do not come from Angular', async () => { writeFile('/index.spec.ts', ` import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; function withModule(...args: any[]) {} @Component({template: ''}) class Comp {} it('should work', withModule({ declarations: [Comp], }, () => { TestBed.createComponent(Comp); })); `); await runMigration(); expect(stripWhitespace(tree.readContent('/index.spec.ts'))).toContain(stripWhitespace(` it('should work', withModule({ declarations: [Comp], }, () => { TestBed.createComponent(Comp); })); `)); }); it('should migrate aliased withModule calls', async () => { writeFile('/index.spec.ts', ` import { Component } from '@angular/core'; import { withModule as aliasOfWithModule, TestBed } from '@angular/core/testing'; @Component({template: ''}) class Comp {} it('should work', aliasOfWithModule({ declarations: [Comp], }, () => { TestBed.createComponent(Comp); })); `); await runMigration(); expect(stripWhitespace(tree.readContent('/index.spec.ts'))).toContain(stripWhitespace(` it('should work', aliasOfWithModule({ declarations: [Comp], teardown: {destroyAfterEach: false} }, () => { TestBed.createComponent(Comp); })); `)); }); it('should migrate configureTestingModule calls', async () => { writeFile('/index.spec.ts', ` import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; @Component({template: ''}) class Comp {} it('should work', () => { TestBed.configureTestingModule({ declarations: [Comp] }); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); }); `); await runMigration(); expect(stripWhitespace(tree.readContent('/index.spec.ts'))).toContain(stripWhitespace(` TestBed.configureTestingModule({ declarations: [Comp], teardown: {destroyAfterEach: false} }); `)); }); it('should migrate multiple configureTestingModule calls within the same file', async () => { writeFile('/index.spec.ts', ` import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; @Component({template: ''}) class Comp {} @Component({template: ''}) class BetterComp {} it('should work', () => { TestBed.configureTestingModule({ declarations: [Comp] }); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); }); it('should work better', () => { TestBed.configureTestingModule({ declarations: [BetterComp] }); const fixture = TestBed.createComponent(BetterComp); fixture.detectChanges(); }); `); await runMigration(); const content = stripWhitespace(tree.readContent('/index.spec.ts')); expect(content).toContain(stripWhitespace(` TestBed.configureTestingModule({ declarations: [Comp], teardown: {destroyAfterEach: false} }); `)); expect(content).toContain(stripWhitespace(` TestBed.configureTestingModule({ declarations: [BetterComp], teardown: {destroyAfterEach: false} }); `)); }); it('should migrate configureTestingModule calls through getTestBed()', async () => { writeFile('/index.spec.ts', ` import { Component } from '@angular/core'; import { getTestBed } from '@angular/core/testing'; @Component({template: ''}) class Comp {} it('should work', () => { getTestBed().configureTestingModule({ declarations: [Comp] }); const fixture = getTestBed().createComponent(Comp); fixture.detectChanges(); }); `); await runMigration(); expect(stripWhitespace(tree.readContent('/index.spec.ts'))).toContain(stripWhitespace(` getTestBed().configureTestingModule({ declarations: [Comp], teardown: {destroyAfterEach: false} }); `)); }); it('should not migrate configureTestingModule calls that already pass in the teardown flag', async () => { writeFile('/index.spec.ts', ` import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; @Component({template: ''}) class Comp {} it('should work', () => { TestBed.configureTestingModule({ teardown: {destroyAfterEach: true}, declarations: [Comp] }); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); }); `); await runMigration(); expect(stripWhitespace(tree.readContent('/index.spec.ts'))).toContain(stripWhitespace(` TestBed.configureTestingModule({ teardown: {destroyAfterEach: true}, declarations: [Comp] }); `)); }); it('should not migrate configureTestingModule or withModule calls if initTestEnvironment was migrated in another file', async () => { writeFile('/test-init.ts', ` import { TestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); `); writeFile('/comp.spec.ts', ` import { Component } from '@angular/core'; import { TestBed, withModule } from '@angular/core/testing'; @Component({template: ''}) class Comp {} it('should work', () => { TestBed.configureTestingModule({ declarations: [Comp] }); const fixture = TestBed.createComponent(Comp); fixture.detectChanges(); }); it('should also work', withModule({ declarations: [Comp], }, () => { TestBed.createComponent(Comp); })); `); await runMigration(); expect(stripWhitespace(tree.readContent('/test-init.ts'))).toContain(stripWhitespace(` TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { teardown: { destroyAfterEach: false } }); `)); expect(stripWhitespace(tree.readContent('/comp.spec.ts'))).toContain(stripWhitespace(` TestBed.configureTestingModule({ declarations: [Comp] }); `)); expect(stripWhitespace(tree.readContent('/comp.spec.ts'))).toContain(stripWhitespace(` it('should also work', withModule({ declarations: [Comp], }, () => { TestBed.createComponent(Comp); })); `)); }); it('should not duplicate comments on initTestEnvironment calls', async () => { writeFile('/index.ts', ` import { TestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; // Hello TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting()); `); await runMigration(); expect(stripWhitespace(tree.readContent('/index.ts'))).toContain(stripWhitespace(` import { TestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; // Hello TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), { teardown: { destroyAfterEach: false } }); `)); }); function writeFile(filePath: string, contents: string) { host.sync.write(normalize(filePath), virtualFs.stringToFileBuffer(contents)); } function runMigration() { return runner.runSchematicAsync('migration-v13-testbed-teardown', {}, tree).toPromise(); } function stripWhitespace(contents: string) { return contents.replace(/\s/g, ''); } });
the_stack
import * as os from 'os'; import * as fs from 'fs'; import * as path from 'path'; import * as assert from 'assert'; import * as vscode from 'vscode'; import { MonitorView } from '../../MonitorView'; import { Settings } from "../../Settings"; import * as SharedConstants from '../../SharedConstants'; import axios from 'axios'; suite('MonitorView Test Suite', () => { const testTimeoutInMs = 60000; test('Shows the WebView', async () => { // Arrange const webViewState = { myKey: new Date().toISOString() }; const context: any = { globalState: { get: () => webViewState } }; const backend: any = { getBackend: () => Promise.resolve(), storageConnectionStrings: [ Settings().storageEmulatorConnectionString ], binariesFolder: path.join(__dirname, '..', '..', '..', '..', 'durablefunctionsmonitor.dotnetbackend') }; Object.defineProperty(vscode.workspace, 'rootPath', { get: () => backend.binariesFolder }); const functionGraphList: any = {}; const monitorView = new MonitorView(context, backend, 'my-hub', functionGraphList, () => { }); var iAmReadyMessageSent = false; // Act await monitorView.show(); // Assert const webViewPanel: vscode.WebviewPanel = (monitorView as any)._webViewPanel; (monitorView as any).handleMessageFromWebView = (webView: vscode.Webview, request: any, messageToWebView: any) => { if (webView === webViewPanel.webview && request.method === 'IAmReady') { iAmReadyMessageSent = true; } }; // Waiting for the webView to send a message await new Promise<void>((resolve) => setTimeout(resolve, 1500)); assert.strictEqual(monitorView.isVisible, true); assert.strictEqual(iAmReadyMessageSent, true); const html = webViewPanel.webview.html; // Checking embedded constants const stateFromVsCodeScript = `<script>var OrchestrationIdFromVsCode="",StateFromVsCode=${JSON.stringify(webViewState)}</script>`; assert.strictEqual(html.includes(stateFromVsCodeScript), true); const dfmClientConfigScriptIncluded = html.match(`<script>var DfmClientConfig={'theme':'[^']+','showTimeAs':'UTC'}</script>`); assert.strictEqual(!!dfmClientConfigScriptIncluded, true); const dfmViewModeScript = `<script>var DfmViewMode=0</script>`; assert.strictEqual(html.includes(dfmViewModeScript), true); const isFunctionGraphAvailableScript = `<script>var IsFunctionGraphAvailable=1</script>`; assert.strictEqual(html.includes(isFunctionGraphAvailableScript), true); // Checking links const linkToManifestJson = webViewPanel.webview.asWebviewUri(vscode.Uri.file(path.join(backend.binariesFolder, 'DfmStatics', 'manifest.json'))); assert.strictEqual(html.includes(`href="${linkToManifestJson}"`), true); const linkToFavicon = webViewPanel.webview.asWebviewUri(vscode.Uri.file(path.join(backend.binariesFolder, 'DfmStatics', 'favicon.png'))); assert.strictEqual(html.includes(`href="${linkToFavicon}"`), true); const cssFolder = path.join(backend.binariesFolder, 'DfmStatics', 'static', 'css'); for (const fileName of await fs.promises.readdir(cssFolder)) { if (path.extname(fileName).toLowerCase() === '.css') { const linkToCss = webViewPanel.webview.asWebviewUri(vscode.Uri.file(path.join(cssFolder, fileName))); assert.strictEqual(html.includes(`href="${linkToCss}"`), true); } } const jsFolder = path.join(backend.binariesFolder, 'DfmStatics', 'static', 'js'); for (const fileName of await fs.promises.readdir(jsFolder)) { if ( !fileName.startsWith('runtime-main.') && path.extname(fileName).toLowerCase() === '.js') { const linkToJs = webViewPanel.webview.asWebviewUri(vscode.Uri.file(path.join(jsFolder, fileName))); assert.strictEqual(html.includes(`src="${linkToJs}"`), true); } } var webViewPanelDisposed = false; (webViewPanel as any).dispose = () => { webViewPanelDisposed = true; } monitorView.cleanup(); assert.strictEqual(webViewPanelDisposed, true); }).timeout(testTimeoutInMs); test('Handles IAmReady', async () => { // Arrange const context: any = {}; const backend: any = {}; const functionGraphList: any = {}; const msgToWebView = 'just-a-message'; var msgWasSent = false; const webView: any = { postMessage: (msg: any) => { if (msg === msgToWebView) { msgWasSent = true; } } }; const request: any = { method: 'IAmReady' }; const monitorView = new MonitorView(context, backend, 'my-hub', functionGraphList, () => { }); // Act (monitorView as any).handleMessageFromWebView(webView, request, msgToWebView); // Assert assert.strictEqual(msgWasSent, true); }); test('Handles PersistState', async () => { // Arrange const globalStateName = 'durableFunctionsMonitorWebViewState'; const globalState = { someOtherField: new Date() }; const stateFieldKey = 'my-field-key'; const stateFieldValue = 'my-field-value'; var stateWasUpdated = false; const context: any = { globalState: { get: (name: string) => { assert.strictEqual(name, globalStateName); return globalState; }, update: (name: string, value: any) => { assert.strictEqual(name, globalStateName); assert.strictEqual(value.someOtherField, globalState.someOtherField); assert.strictEqual(value[stateFieldKey], stateFieldValue); stateWasUpdated = true; } } }; const backend: any = {}; const functionGraphList: any = {}; const webView: any = {}; const request: any = { method: 'PersistState', key: stateFieldKey, data: stateFieldValue }; const monitorView = new MonitorView(context, backend, 'my-hub', functionGraphList, () => { }); // Act (monitorView as any).handleMessageFromWebView(webView, request); // Assert assert.strictEqual(stateWasUpdated, true); }); test('Handles OpenInNewWindow', async () => { // Arrange const globalState = {}; const context: any = { globalState: { get: () => globalState } }; const backend: any = { getBackend: () => Promise.resolve(), storageConnectionStrings: [ Settings().storageEmulatorConnectionString ], binariesFolder: path.join(__dirname, '..', '..', '..', '..', 'durablefunctionsmonitor.dotnetbackend') }; const functionGraphList: any = { traverseFunctions: () => Promise.resolve({ functions: {}, proxies: {} }) }; const webView: any = {}; const orchestrationId = new Date().toISOString(); const request: any = { method: 'OpenInNewWindow', url: orchestrationId }; const monitorView = new MonitorView(context, backend, 'my-hub', functionGraphList, () => { }); // Act (monitorView as any).handleMessageFromWebView(webView, request); // Assert const childWebViewPanels: vscode.WebviewPanel[] = (monitorView as any)._childWebViewPanels; assert.strictEqual(childWebViewPanels.length, 1); const viewPanel = childWebViewPanels[0]; assert.strictEqual(viewPanel.title, `Instance '${orchestrationId}'`); const html = viewPanel.webview.html; const stateFromVsCodeScript = `<script>var OrchestrationIdFromVsCode="${orchestrationId}",StateFromVsCode={}</script>`; assert.strictEqual(html.includes(stateFromVsCodeScript), true); }).timeout(testTimeoutInMs); test('Handles SaveAs', async () => { // Arrange const context: any = {}; const backend: any = {}; const functionGraphList: any = { traverseFunctions: () => Promise.resolve({ functions: {}, proxies: {} }) }; const webView: any = {}; const svgFileName = `dfm-test-svg-${new Date().valueOf().toString()}.svg`; const svgFilePath = path.join(os.tmpdir(), svgFileName); const request: any = { method: 'SaveAs', data: `<svg id="${svgFileName}"></svg>` }; const monitorView = new MonitorView(context, backend, 'my-hub', functionGraphList, () => { }); (vscode.window as any).showSaveDialog = (options: vscode.SaveDialogOptions) => { const filters = options.filters!; assert.strictEqual(filters['SVG Images'].length, 1); assert.strictEqual(filters['SVG Images'][0], 'svg'); return Promise.resolve({ fsPath: svgFilePath }); }; // Act (monitorView as any).handleMessageFromWebView(webView, request); await new Promise<void>((resolve) => setTimeout(resolve, 100)); // Assert const svg = await fs.promises.readFile(svgFilePath, { encoding: 'utf8' }); await fs.promises.rm(svgFilePath); assert.strictEqual(svg, request.data); }).timeout(testTimeoutInMs); test('Handles GotoFunctionCode', async () => { // Arrange const context: any = {}; const backend: any = {}; const webView: any = {}; const functionGraphList: any = {}; const request: any = { method: 'GotoFunctionCode', url: 'my-func-1' }; const backendFolder = path.join(__dirname, '..', '..', '..', '..', 'durablefunctionsmonitor.dotnetbackend'); Object.defineProperty(vscode.workspace, 'rootPath', { get: () => backendFolder }); const monitorView = new MonitorView(context, backend, 'my-hub', functionGraphList, () => { }); (monitorView as any)._functionsAndProxies[request.url] = { filePath: path.join(backendFolder, 'Functions', 'About.cs'), pos: 67 }; // Act (monitorView as any).handleMessageFromWebView(webView, request); await new Promise<void>((resolve) => setTimeout(resolve, 1000)); // Assert const projectPath = (monitorView as any)._functionProjectPath; assert.strictEqual(backendFolder, projectPath); assert.strictEqual(1, vscode.window.activeTextEditor!.selection.start.line); assert.strictEqual(26, vscode.window.activeTextEditor!.selection.start.character); }).timeout(testTimeoutInMs); test('Handles GET /function-map', async () => { // Arrange const context: any = {}; const backend: any = {}; const request: any = { method: 'GET', url: '/function-map', id: new Date().toISOString() }; const functions = { 'my-func-1': {}, 'my-func-2': {}, } const proxies = { 'my-proxy-1': {}, 'my-proxy-2': {} } var responseMessagePosted = false; const webView: any = { postMessage: (msg: any) => { assert.strictEqual(msg.id, request.id); assert.strictEqual(msg.data.functions, functions); assert.strictEqual(msg.data.proxies, proxies); responseMessagePosted = true; } }; const backendFolder = path.join(__dirname, '..', '..', '..', '..', 'durablefunctionsmonitor.dotnetbackend'); Object.defineProperty(vscode.workspace, 'rootPath', { get: () => backendFolder }); const functionGraphList: any = { traverseFunctions: (projectPath: string) => { assert.strictEqual(projectPath, backendFolder); return Promise.resolve({ functions, proxies }); } }; const monitorView = new MonitorView(context, backend, 'my-hub', functionGraphList, () => { }); // Act (monitorView as any).handleMessageFromWebView(webView, request); await new Promise<void>((resolve) => setTimeout(resolve, 100)); // Assert assert.strictEqual(responseMessagePosted, true); const projectPath = (monitorView as any)._functionProjectPath; assert.strictEqual(backendFolder, projectPath); const functionsAndProxies = (monitorView as any)._functionsAndProxies; assert.strictEqual(functionsAndProxies['my-func-1'], functions['my-func-1']); }).timeout(testTimeoutInMs); test('Handles HTTP requests', async () => { // Arrange const context: any = {}; const functionGraphList: any = {}; const backend: any = { backendUrl: 'http://localhost:12345', backendCommunicationNonce: `nonce-${new Date().valueOf()}` }; const hubName = 'my-hub-4321'; const monitorView = new MonitorView(context, backend, hubName, functionGraphList, () => { }); const request: any = { id: new Date().toISOString(), method: 'OPTIONS', url: '/some/other/path', data: { fieldOne: 'value1' } }; const responseData: any = { fieldTwo: 'value2' }; var responseMessagePosted = false; const webView: any = { postMessage: (msg: any) => { assert.strictEqual(msg.id, request.id); assert.strictEqual(msg.data, responseData); responseMessagePosted = true; } }; (axios as any).request = (r: any) => { assert.strictEqual(r.method, request.method); assert.strictEqual(r.url, `${backend.backendUrl}/--${hubName}${request.url}`); assert.strictEqual(r.data, request.data); assert.strictEqual(r.headers[SharedConstants.NonceHeaderName], backend.backendCommunicationNonce); return Promise.resolve({ data: responseData }); }; // Act (monitorView as any).handleMessageFromWebView(webView, request); await new Promise<void>((resolve) => setTimeout(resolve, 100)); // Assert assert.strictEqual(responseMessagePosted, true); }).timeout(testTimeoutInMs); test('Deletes Task Hub', async () => { // Arrange const context: any = {}; const functionGraphList: any = {}; const backend: any = { backendUrl: 'http://localhost:12345', backendCommunicationNonce: `nonce-${new Date().valueOf()}` }; const hubName = 'my-hub-6789'; const monitorView = new MonitorView(context, backend, hubName, functionGraphList, () => { }); (axios as any).post = (url: string, data: any, config: any) => { assert.strictEqual(url, `${backend.backendUrl}/--${hubName}/delete-task-hub`); assert.strictEqual(config.headers[SharedConstants.NonceHeaderName], backend.backendCommunicationNonce); return Promise.resolve(); }; var webViewPanelDisposed = false; (monitorView as any)._webViewPanel = { dispose: () => { webViewPanelDisposed = true; } } // Act await monitorView.deleteTaskHub(); // Assert assert.strictEqual(webViewPanelDisposed, true); }).timeout(testTimeoutInMs); });
the_stack
import { buildThunks, PatchQueryResultThunk, UpdateQueryResultThunk } from './buildThunks'; import { ActionCreatorWithPayload, AnyAction, Middleware, Reducer, ThunkAction, ThunkDispatch } from '@reduxjs/toolkit'; import { EndpointDefinitions, QueryArgFrom, QueryDefinition, MutationDefinition, AssertTagTypes, isQueryDefinition, isMutationDefinition, FullTagDescription, } from '../endpointDefinitions'; import { CombinedState, QueryKeys, RootState } from './apiState'; import './buildSelectors'; import { Api, Module } from '../apiTypes'; import { onFocus, onFocusLost, onOnline, onOffline } from './setupListeners'; import { buildSlice } from './buildSlice'; import { buildMiddleware } from './buildMiddleware'; import { buildSelectors } from './buildSelectors'; import { buildInitiate } from './buildInitiate'; import { assertCast, Id, safeAssign } from '../tsHelpers'; import { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'; import { SliceActions } from './buildSlice'; import { BaseQueryFn } from '../baseQueryTypes'; /** * `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_ * - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value * * @overloadSummary * `force` * - If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query will be run even if it exists in the cache. */ export type PrefetchOptions = | { ifOlderThan?: false | number; } | { force?: boolean }; export const coreModuleName = Symbol(); export type CoreModule = typeof coreModuleName; declare module '../apiTypes' { export interface ApiModules< // eslint-disable-next-line @typescript-eslint/no-unused-vars BaseQuery extends BaseQueryFn, Definitions extends EndpointDefinitions, ReducerPath extends string, TagTypes extends string > { [coreModuleName]: { /** * This api's reducer should be mounted at `store[api.reducerPath]`. * * @example * ```ts * configureStore({ * reducer: { * [api.reducerPath]: api.reducer, * }, * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware), * }) * ``` */ reducerPath: ReducerPath; /** * Internal actions not part of the public API. Note: These are subject to change at any given time. */ internalActions: InternalActions; /** * A standard redux reducer that enables core functionality. Make sure it's included in your store. * * @example * ```ts * configureStore({ * reducer: { * [api.reducerPath]: api.reducer, * }, * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware), * }) * ``` */ reducer: Reducer<CombinedState<Definitions, TagTypes, ReducerPath>, AnyAction>; /** * This is a standard redux middleware and is responsible for things like polling, garbage collection and a handful of other things. Make sure it's included in your store. * * @example * ```ts * configureStore({ * reducer: { * [api.reducerPath]: api.reducer, * }, * middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware), * }) * ``` */ middleware: Middleware<{}, RootState<Definitions, string, ReducerPath>, ThunkDispatch<any, any, AnyAction>>; /** * TODO */ util: { /** * TODO */ prefetch<EndpointName extends QueryKeys<EndpointDefinitions>>( endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, options: PrefetchOptions ): ThunkAction<void, any, any, AnyAction>; /* @deprecated */ prefetchThunk<EndpointName extends QueryKeys<EndpointDefinitions>>( endpointName: EndpointName, arg: QueryArgFrom<Definitions[EndpointName]>, options: PrefetchOptions ): ThunkAction<void, any, any, AnyAction>; /** * TODO */ updateQueryResult: UpdateQueryResultThunk<Definitions, RootState<Definitions, string, ReducerPath>>; /** * TODO */ patchQueryResult: PatchQueryResultThunk<Definitions, RootState<Definitions, string, ReducerPath>>; /** * TODO */ resetApiState: SliceActions['resetApiState']; /** * TODO */ invalidateTags: ActionCreatorWithPayload<Array<TagTypes | FullTagDescription<TagTypes>>, string>; /** @deprecated renamed to `invalidateTags` */ invalidateEntities: ActionCreatorWithPayload<Array<TagTypes | FullTagDescription<TagTypes>>, string>; }; /** * Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`. */ endpoints: { [K in keyof Definitions]: Definitions[K] extends QueryDefinition<any, any, any, any, any> ? Id<ApiEndpointQuery<Definitions[K], Definitions>> : Definitions[K] extends MutationDefinition<any, any, any, any, any> ? Id<ApiEndpointMutation<Definitions[K], Definitions>> : never; }; }; } } export interface ApiEndpointQuery< // eslint-disable-next-line @typescript-eslint/no-unused-vars Definition extends QueryDefinition<any, any, any, any, any>, // eslint-disable-next-line @typescript-eslint/no-unused-vars Definitions extends EndpointDefinitions > {} // eslint-disable-next-line @typescript-eslint/no-unused-vars export interface ApiEndpointMutation< // eslint-disable-next-line @typescript-eslint/no-unused-vars Definition extends MutationDefinition<any, any, any, any, any>, // eslint-disable-next-line @typescript-eslint/no-unused-vars Definitions extends EndpointDefinitions > {} export type ListenerActions = { /** * Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior * @link https://rtk-query-docs.netlify.app/api/setupListeners */ onOnline: typeof onOnline; onOffline: typeof onOffline; /** * Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior * @link https://rtk-query-docs.netlify.app/api/setupListeners */ onFocus: typeof onFocus; onFocusLost: typeof onFocusLost; }; export type InternalActions = SliceActions & ListenerActions; /** * Creates a module containing the basic redux logic for use with `buildCreateApi`. * * @example * ```ts * const createBaseApi = buildCreateApi(coreModule()); * ``` */ export const coreModule = (): Module<CoreModule> => ({ name: coreModuleName, init( api, { baseQuery, tagTypes, reducerPath, serializeQueryArgs, keepUnusedDataFor, refetchOnMountOrArgChange, refetchOnFocus, refetchOnReconnect, }, context ) { assertCast<InternalSerializeQueryArgs<any>>(serializeQueryArgs); const assertTagType: AssertTagTypes = (tag) => { if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') { if (!tagTypes.includes(tag.type as any)) { console.error(`Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!`); } } return tag; }; Object.assign(api, { reducerPath, endpoints: {}, internalActions: { onOnline, onOffline, onFocus, onFocusLost, }, util: {}, }); const { queryThunk, mutationThunk, patchQueryResult, updateQueryResult, prefetch, buildMatchThunkActions, } = buildThunks({ baseQuery, reducerPath, context, api, serializeQueryArgs, }); const { reducer, actions: sliceActions } = buildSlice({ context, queryThunk, mutationThunk, reducerPath, assertTagType, config: { refetchOnFocus, refetchOnReconnect, refetchOnMountOrArgChange, keepUnusedDataFor, reducerPath }, }); safeAssign(api.util, { patchQueryResult, updateQueryResult, prefetch, resetApiState: sliceActions.resetApiState, }); safeAssign(api.internalActions, sliceActions); const { middleware, actions: middlewareActions } = buildMiddleware({ reducerPath, context, queryThunk, mutationThunk, api, assertTagType, }); safeAssign(api.util, middlewareActions); safeAssign(api, { reducer: reducer as any, middleware }); const { buildQuerySelector, buildMutationSelector } = buildSelectors({ serializeQueryArgs: serializeQueryArgs as any, reducerPath, }); const { buildInitiateQuery, buildInitiateMutation } = buildInitiate({ queryThunk, mutationThunk, api, serializeQueryArgs: serializeQueryArgs as any, }); // remove in final release Object.defineProperty(api.util, 'invalidateEntities', { get() { if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') { console.warn( '`api.util.invalidateEntities` has been renamed to `api.util.invalidateTags`, please change your code accordingly' ); } return api.util.invalidateTags; }, }); Object.defineProperty(api.util, 'prefetchThunk', { get() { if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') { console.warn( '`api.util.prefetchThunk` has been renamed to `api.util.prefetch`, please change your code accordingly' ); } return api.util.prefetch; }, }); return { name: coreModuleName, injectEndpoint(endpointName, definition) { const anyApi = (api as any) as Api<any, Record<string, any>, string, string, CoreModule>; anyApi.endpoints[endpointName] ??= {} as any; if (isQueryDefinition(definition)) { safeAssign( anyApi.endpoints[endpointName], { select: buildQuerySelector(endpointName, definition), initiate: buildInitiateQuery(endpointName, definition), }, buildMatchThunkActions(queryThunk, endpointName) ); } else if (isMutationDefinition(definition)) { safeAssign( anyApi.endpoints[endpointName], { select: buildMutationSelector(), initiate: buildInitiateMutation(endpointName, definition), }, buildMatchThunkActions(mutationThunk, endpointName) ); } }, }; }, });
the_stack
import * as chai from 'chai'; import * as fs from 'fs'; import { DeclarationGenerator } from '../../src/generator/declarationGenerator'; import { TypingGenerator } from '../../src/generator/typingGenerator'; const expect = chai.expect; describe('SObject Javacript type declaration generator', () => { let typePath = ''; const declGenerator = new DeclarationGenerator(); afterEach(() => { if (typePath) { try { fs.unlinkSync(typePath); } catch (e) { console.log(e); } typePath = ''; } }); it('Should generate a declaration file as read-only', async () => { const fieldsHeader = '{ "name": "Custom__c", "fields": [ '; const closeHeader = ' ], "childRelationships": [] }'; const sobject1 = `${fieldsHeader}${closeHeader}`; const objDef = declGenerator.generateSObjectDefinition( JSON.parse(sobject1) ); const sobjectFolder = process.cwd(); const gen = new TypingGenerator(); typePath = gen.generateType(sobjectFolder, objDef); expect(fs.existsSync(typePath)); const stat = fs.lstatSync(typePath); const expectedMode = parseInt('100444', 8); expect(stat.mode).to.equal(expectedMode); }); it('Should generate a declaration file with all types of fields that can be in custom SObjects', async () => { const fieldsHeader = '{ "name": "Custom__c", "fields": [ '; const closeHeader = ' ], "childRelationships": [] }'; const fields: string[] = [ '{"name": "StringField", "type": "string", "referenceTo": []}', '{"name": "DoubleField", "type" : "double", "referenceTo": []}', '{"name": "BooleanField", "type" : "boolean", "referenceTo": []}', '{"name": "CurrencyField", "type" : "currency", "referenceTo": []}', '{"name": "DateField", "type" : "date", "referenceTo": []}', '{"name": "DatetimeField", "type" : "datetime", "referenceTo": []}', '{"name": "EmailField", "type" : "email", "referenceTo": []}', '{"name": "LocationField", "type" : "location", "referenceTo": []}', '{"name": "PercentField", "type" : "percent", "referenceTo": []}', '{"name": "PicklistField", "type" : "picklist", "referenceTo": []}', '{"name": "MultipicklistField", "type" : "multipicklist", "referenceTo": []}', '{"name": "TextareaField", "type" : "textarea", "referenceTo": []}', '{"name": "EncryptedField", "type" : "encryptedstring", "referenceTo": []}', '{"name": "UrlField", "type" : "url", "referenceTo": []}', '{"name": "IdField", "type" : "id", "referenceTo": []}' ]; const fieldsString = fields.join(','); const sobject1 = `${fieldsHeader}${fieldsString}${closeHeader}`; const objDef = declGenerator.generateSObjectDefinition( JSON.parse(sobject1) ); const sobjectFolder = process.cwd(); const gen = new TypingGenerator(); typePath = gen.generateType(sobjectFolder, objDef); expect(fs.existsSync(typePath)); const typeText = fs.readFileSync(typePath, 'utf8'); expect(typeText).to.include('@salesforce/schema/Custom__c.StringField'); expect(typeText).to.include('const StringField:string;'); expect(typeText).to.include('export default StringField;'); expect(typeText).to.include('@salesforce/schema/Custom__c.DoubleField'); expect(typeText).to.include('const DoubleField:number;'); expect(typeText).to.include('export default DoubleField;'); expect(typeText).to.include('@salesforce/schema/Custom__c.BooleanField'); expect(typeText).to.include('const BooleanField:boolean;'); expect(typeText).to.include('export default BooleanField;'); expect(typeText).to.include('@salesforce/schema/Custom__c.CurrencyField'); expect(typeText).to.include('const CurrencyField:number;'); expect(typeText).to.include('export default CurrencyField;'); expect(typeText).to.include('@salesforce/schema/Custom__c.DateField'); expect(typeText).to.include('const DateField:any;'); expect(typeText).to.include('export default DateField;'); expect(typeText).to.include('@salesforce/schema/Custom__c.DatetimeField'); expect(typeText).to.include('const DatetimeField:any;'); expect(typeText).to.include('export default DatetimeField;'); expect(typeText).to.include('@salesforce/schema/Custom__c.EmailField'); expect(typeText).to.include('const EmailField:string;'); expect(typeText).to.include('export default EmailField;'); expect(typeText).to.include('@salesforce/schema/Custom__c.LocationField'); expect(typeText).to.include('const LocationField:any;'); expect(typeText).to.include('export default LocationField;'); expect(typeText).to.include('@salesforce/schema/Custom__c.PercentField'); expect(typeText).to.include('const PercentField:number;'); expect(typeText).to.include('export default PercentField;'); expect(typeText).to.include('@salesforce/schema/Custom__c.PicklistField'); expect(typeText).to.include('const PicklistField:string;'); expect(typeText).to.include('export default PicklistField;'); expect(typeText).to.include( '@salesforce/schema/Custom__c.MultipicklistField' ); expect(typeText).to.include('const MultipicklistField:string;'); expect(typeText).to.include('export default MultipicklistField;'); expect(typeText).to.include('@salesforce/schema/Custom__c.TextareaField'); expect(typeText).to.include('const TextareaField:string;'); expect(typeText).to.include('export default TextareaField;'); expect(typeText).to.include('@salesforce/schema/Custom__c.EncryptedField'); expect(typeText).to.include('const EncryptedField:string;'); expect(typeText).to.include('export default EncryptedField;'); expect(typeText).to.include('@salesforce/schema/Custom__c.UrlField'); expect(typeText).to.include('const UrlField:string;'); expect(typeText).to.include('export default UrlField;'); expect(typeText).to.include('@salesforce/schema/Custom__c.IdField'); expect(typeText).to.include('const IdField:any;'); expect(typeText).to.include('export default IdField;'); }); it('Should generate a declaration file with all types of fields that show only in standard SObjects', async () => { const fieldsHeader = '{ "name": "Custom__c", "fields": [ '; const closeHeader = ' ], "childRelationships": [] }'; const fields: string[] = [ '{"name": "BaseField", "type": "base64", "referenceTo": []}', '{"name": "AddressField", "type" : "address", "referenceTo": []}', '{"name": "IntField", "type" : "int", "referenceTo": []}', '{"name": "AnytypeField", "type" : "anyType", "referenceTo": []}', '{"name": "ComboboxField", "type" : "combobox", "referenceTo": []}' ]; const fieldsString = fields.join(','); const sobject1 = `${fieldsHeader}${fieldsString}${closeHeader}`; const objDef = declGenerator.generateSObjectDefinition( JSON.parse(sobject1) ); const sobjectFolder = process.cwd(); const gen = new TypingGenerator(); typePath = gen.generateType(sobjectFolder, objDef); expect(fs.existsSync(typePath)); const typeText = fs.readFileSync(typePath, 'utf8'); expect(typeText).to.include('const BaseField:any;'); expect(typeText).to.include('const AddressField:any;'); expect(typeText).to.include('const IntField:number;'); expect(typeText).to.include('const AnytypeField:any;'); expect(typeText).to.include('const ComboboxField:string;'); }); it('Should create a declaration file with a field and relationship', async () => { const field1 = '{"name": "StringField", "type": "string", "referenceTo": []}'; const relation1 = '{"name": "Account__c", "referenceTo": ["Account"], "relationshipName": "Account__r"}'; const sobject1: string = '{ "name": "Custom__c", "fields": [ ' + field1 + ',' + relation1 + ' ], "childRelationships": [] }'; const objDef = declGenerator.generateSObjectDefinition( JSON.parse(sobject1) ); const sobjectFolder = process.cwd(); const gen = new TypingGenerator(); typePath = gen.generateType(sobjectFolder, objDef); expect(fs.existsSync(typePath)); const typeText = fs.readFileSync(typePath, 'utf8'); expect(typeText).to.include('@salesforce/schema/Custom__c.StringField'); expect(typeText).to.include('const StringField:string;'); expect(typeText).to.include('export default StringField;'); expect(typeText).to.include('@salesforce/schema/Custom__c.Account__r'); expect(typeText).to.include('const Account__r:any;'); expect(typeText).to.include('export default Account__r;'); expect(typeText).to.include('@salesforce/schema/Custom__c.Account__c'); expect(typeText).to.include('const Account__c:any;'); expect(typeText).to.include('export default Account__c;'); }); it('Should create a String field type for an external lookup relationship', async () => { const field1 = '{"name": "ExtRef__c", "type": "reference", "referenceTo": [], "relationshipName": null, "extraTypeInfo": "externallookup"}'; const header = '{ "name": "Custom__c", "childRelationships": []'; const fieldHeader = '"fields": ['; const sobject1 = `${header},${fieldHeader}${field1}]}`; const objDef = declGenerator.generateSObjectDefinition( JSON.parse(sobject1) ); const sobjectFolder = process.cwd(); const gen = new TypingGenerator(); typePath = gen.generateType(sobjectFolder, objDef); expect(fs.existsSync(typePath)); const typeText = fs.readFileSync(typePath, 'utf8'); expect(typeText).to.include('@salesforce/schema/Custom__c.ExtRef__c"'); expect(typeText).to.include('const ExtRef__c:string;'); expect(typeText).to.include('export default ExtRef__c;'); }); it('Should create a valid declaration file for a metadata object with EntityDefinition relationship target', async () => { const header = '{ "name": "Custom__mdt", "childRelationships": [], "fields": ['; const field1 = '{"name": "MDRef__c", "type": "reference", "referenceTo": [], "relationshipName": null, "extraTypeInfo": "externallookup"}'; const field2 = '{"name": "StringField", "type": "string", "referenceTo": []}'; const sobject1 = `${header}${field1},${field2}]}`; const objDef = declGenerator.generateSObjectDefinition( JSON.parse(sobject1) ); const sobjectFolder = process.cwd(); const gen = new TypingGenerator(); typePath = gen.generateType(sobjectFolder, objDef); expect(fs.existsSync(typePath)); const typeText = fs.readFileSync(typePath, 'utf8'); expect(typeText).to.include('@salesforce/schema/Custom__mdt.MDRef__c"'); expect(typeText).to.include('const MDRef__c:string;'); expect(typeText).to.include('export default MDRef__c;'); }); it('Should create a valid declaration file for a metadata object with a __mdt target', async () => { const header = '{ "name": "Custom__mdt", "childRelationships": [], "fields": ['; const field1 = '{"name": "MDRef__r", "type": "reference", "referenceTo": ["XX_mdt"], "relationshipName": null}'; const field2 = '{"name": "StringField", "type": "string", "referenceTo": []}'; const sobject1 = `${header}${field1},${field2}]}`; const objDef = declGenerator.generateSObjectDefinition( JSON.parse(sobject1) ); const sobjectFolder = process.cwd(); const gen = new TypingGenerator(); typePath = gen.generateType(sobjectFolder, objDef); expect(fs.existsSync(typePath)); const typeText = fs.readFileSync(typePath, 'utf8'); expect(typeText).to.include('@salesforce/schema/Custom__mdt.MDRef__r'); expect(typeText).to.include('const MDRef__r:any;'); expect(typeText).to.include('export default MDRef__r;'); }); it('Should create a valid declaration file for a platform event object', async () => { const fieldsHeader = '{ "name": "PE1__e", "fields": [ '; const closeHeader = ' ], "childRelationships": [] }'; const fields: string[] = [ '{"name": "StringField", "type": "string", "referenceTo": []}', '{"name": "DoubleField", "type" : "double", "referenceTo": []}' ]; const fieldsString = fields.join(','); const sobject1 = `${fieldsHeader}${fieldsString}${closeHeader}`; const objDef = declGenerator.generateSObjectDefinition( JSON.parse(sobject1) ); const sobjectFolder = process.cwd(); const gen = new TypingGenerator(); typePath = gen.generateType(sobjectFolder, objDef); expect(fs.existsSync(typePath)); const typeText = fs.readFileSync(typePath, 'utf8'); expect(typeText).to.include( 'declare module "@salesforce/schema/PE1__e.StringField" ' ); expect(typeText).to.include('const StringField:string;'); expect(typeText).to.include('export default StringField;'); expect(typeText).to.include( 'declare module "@salesforce/schema/PE1__e.DoubleField"' ); expect(typeText).to.include('const DoubleField:number;'); expect(typeText).to.include('export default DoubleField;'); }); });
the_stack
import { compatibleAsync, safeExec } from 'rx-util' const LastUpdateKey = 'LastUpdate' const LastValueKey = 'LastValue' /** * 在固定时间周期内只执行函数一次 * @param {Function} fn 执行的函数 * @param {Number} time 时间周期 * @returns {Function} 包装后的函数 */ function onceOfCycle(fn: (...args: any[]) => any, time: number) { const get = window.GM_getValue.bind(window) const set = window.GM_setValue.bind(window) return new Proxy(fn, { apply(_, _this, args) { const now = Date.now() const last: number | string = get(LastUpdateKey) if ( ![null, undefined, 'null', 'undefined'].includes(last as string) && now - (last as number) < time ) { return safeExec(() => JSON.parse(get(LastValueKey)), 1) } return compatibleAsync(Reflect.apply(_, _this, args), (res) => { set(LastUpdateKey, now) set(LastValueKey, JSON.stringify(res)) return res }) }, }) } //endregion type ClearEventEnum = | 'copy' | 'cut' | 'paste' | 'select' | 'selectstart' | 'contextmenu' | 'dragstart' | 'mousedown' /** * 解除限制 */ class UnblockLimit { private static eventTypes: readonly ClearEventEnum[] = [ 'copy', 'cut', 'paste', 'select', 'selectstart', 'contextmenu', 'dragstart', 'mousedown', ] private static keyEventTypes: readonly (keyof WindowEventMap)[] = [ 'keydown', 'keypress', 'keyup', ] /** * 监听 event 的添加 * 注:必须及早运行 */ static watchEventListener() { const documentAddEventListener = document.addEventListener const eventTargetAddEventListener = EventTarget.prototype.addEventListener const proxyHandler: ProxyHandler<Document['addEventListener']> = { apply( target: Document['addEventListener'], thisArg: any, [type, listener, useCapture]: [ type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean, ], ): any { const $addEventListener = target instanceof Document ? documentAddEventListener : eventTargetAddEventListener // 在这里阻止会更合适一点 if (UnblockLimit.eventTypes.includes(type as any)) { console.log('拦截 addEventListener: ', type, this) return } Reflect.apply($addEventListener, thisArg, [type, listener, useCapture]) }, } document.addEventListener = new Proxy( documentAddEventListener, proxyHandler, ) EventTarget.prototype.addEventListener = new Proxy( eventTargetAddEventListener, proxyHandler, ) } // 代理网页添加的键盘快捷键,阻止自定义 C-C/C-V/C-X 这三个快捷键 static proxyKeyEventListener() { const documentAddEventListener = document.addEventListener const eventTargetAddEventListener = EventTarget.prototype.addEventListener const keyProxyHandler: ProxyHandler<(ev: KeyboardEvent) => void> = { apply( target: (ev: KeyboardEvent) => void, thisArg: any, argArray: [KeyboardEvent], ): any { const ev = argArray[0] const proxyKey = ['c', 'x', 'v', 'a'] const proxyAssistKey = ['Control', 'Alt'] if ( (ev.ctrlKey && proxyKey.includes(ev.key)) || proxyAssistKey.includes(ev.key) ) { console.log('已阻止: ', ev.ctrlKey, ev.altKey, ev.key) return } if (ev.altKey) { return } Reflect.apply(target, thisArg, argArray) }, } const proxyHandler: ProxyHandler<Document['addEventListener']> = { apply( target: Document['addEventListener'], thisArg: any, [type, listener, useCapture]: [ type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean, ], ): any { const $addEventListener = target instanceof Document ? documentAddEventListener : eventTargetAddEventListener Reflect.apply($addEventListener, thisArg, [ type, UnblockLimit.keyEventTypes.includes(type as any) ? new Proxy(listener as Function, keyProxyHandler) : listener, useCapture, ]) }, } document.addEventListener = new Proxy( documentAddEventListener, proxyHandler, ) EventTarget.prototype.addEventListener = new Proxy( eventTargetAddEventListener, proxyHandler, ) } // 清理使用 onXXX 添加到事件 static clearJsOnXXXEvent() { const emptyFunc = () => {} function modifyPrototype( prototype: HTMLElement | Document, type: ClearEventEnum, ) { Object.defineProperty(prototype, `on${type}`, { get() { return emptyFunc }, set() { return true }, }) } UnblockLimit.eventTypes.forEach((type) => { modifyPrototype(HTMLElement.prototype, type) modifyPrototype(document, type) }) } // 清理或还原DOM节点的onXXX 属性 static clearDomOnXXXEvent() { function _innerClear() { UnblockLimit.eventTypes.forEach((type) => { document .querySelectorAll(`[on${type}]`) .forEach((el) => el.setAttribute(`on${type}`, 'return true')) }) } setInterval(_innerClear, 3000) } // 清理掉网页添加的全局防止复制/选择的 CSS static clearCSS() { GM_addStyle( `html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video, html body * { -webkit-user-select: text !important; -moz-user-select: text !important; user-select: text !important; } ::-moz-selection { color: #111 !important; background: #05d3f9 !important; } ::selection { color: #111 !important; background: #05d3f9 !important; } `, ) } } /** * 屏蔽配置项类型 */ type BlockConfig = | string | { type: 'domain' | 'link' | 'linkPrefix' | 'regex' url: string } //更新屏蔽列表 class BlockHost { static fetchHostList() { return new Promise<BlockConfig[]>((resolve, reject) => { GM_xmlhttpRequest({ method: 'GET', url: 'https://userjs.rxliuli.com/blockList.json', headers: { 'Cache-Control': 'no-cache', }, onload(res) { const list = JSON.parse(res.responseText) resolve(list) console.info('更新配置成功: ', list) }, onerror(e) { reject(e) console.error('更新配置失败: ', e) }, }) }) } static updateHostList(hostList: BlockConfig[]) { hostList .filter((config) => GM_getValue(JSON.stringify(config)) === undefined) .forEach((domain) => { console.log('更新了屏蔽域名: ', domain) GM_setValue(JSON.stringify(domain), true) }) } // 更新支持的网站列表 static updateBlockHostList = onceOfCycle(async () => { BlockHost.updateHostList(await BlockHost.fetchHostList()) }, 1000 * 60 * 60 * 24) static findKey() { return GM_listValues() .filter((config) => GM_getValue(config)) .find((configStr) => { const config = safeExec(() => JSON.parse(configStr) as BlockConfig, { type: 'domain', url: configStr, })! return this.match(new URL(location.href), config) }) } private static match( href: URL, config: | string | { type: 'domain' | 'link' | 'linkPrefix' | 'regex'; url: string }, ) { if (typeof config === 'string') { return href.host.includes(config) } else { const { type, url } = config switch (type) { case 'domain': return href.host === url case 'link': return href.href === url case 'linkPrefix': return href.href.startsWith(url) case 'regex': return new RegExp(url).test(href.href) } } } } //注册菜单 class MenuHandler { static register() { const findKey = BlockHost.findKey() const key = findKey || JSON.stringify({ type: 'domain', url: location.host, }) console.log('key: ', key) GM_registerMenuCommand(findKey ? '恢复默认' : '解除限制', () => { GM_setValue(key, !GM_getValue(key)) console.log('isBlock: ', key, GM_getValue(key)) location.reload() }) } } /** * 屏蔽列表配置 API,用以在指定 API 进行高级配置 */ class ConfigBlockApi { private listKey() { return GM_listValues().filter( (key) => ![LastUpdateKey, LastValueKey].includes(key), ) } list() { return this.listKey().map((config) => ({ ...safeExec(() => JSON.parse(config as string), { type: 'domain', url: config, } as BlockConfig), enable: GM_getValue(config), key: config, })) } switch(key: string) { console.log('ConfigBlockApi.switch: ', key) GM_setValue(key, !GM_getValue(key)) } remove(key: string) { console.log('ConfigBlockApi.remove: ', key) GM_deleteValue(key) } add(config: BlockConfig) { console.log('ConfigBlockApi.add: ', config) GM_setValue(JSON.stringify(config), true) } clear() { const delKeyList = this.listKey() console.log('ConfigBlockApi.clear: ', delKeyList) delKeyList.forEach(GM_deleteValue) } async update() { await BlockHost.updateHostList(await BlockHost.fetchHostList()) } } //启动类 class Application { start() { MenuHandler.register() if (BlockHost.findKey()) { UnblockLimit.watchEventListener() UnblockLimit.proxyKeyEventListener() UnblockLimit.clearJsOnXXXEvent() } BlockHost.updateBlockHostList() window.addEventListener('load', function () { if (BlockHost.findKey()) { UnblockLimit.clearDomOnXXXEvent() UnblockLimit.clearCSS() } }) if ( location.href.startsWith('https://userjs.rxliuli.com/') || location.hostname === '127.0.0.1' ) { Reflect.set( unsafeWindow, 'com.rxliuli.UnblockWebRestrictions.configBlockApi', new ConfigBlockApi(), ) } } } new Application().start()
the_stack
import { Client, ClientOptions } from '@src/core' import { asyncSome, NonOptional } from '@src/utils' import { ChannelsCachingPolicy, EmojisCachingPolicy, GlobalCachingPolicy, GuildsCachingPolicy, GuildMembersCachingPolicy, MessagesCachingPolicy, OverwritesCachingPolicy, PermissionOverwriteTypes, PresencesCachingPolicy, RolesCachingPolicy, StickerFormatTypes, StickersCachingPolicy, StickerTypes, UsersCachingPolicy } from '@src/constants' import { ActivityEmoji, AnyEmoji, GuildEmoji, GuildMember, Message, Presence, ReactionEmoji, Role, Sticker, User } from '@src/api' import { PermissionOverwrite } from '@src/api/entities/overwrites/PermissionOverwrite' export class CachingPoliciesProcessor { public client: Client private options: NonOptional<ClientOptions, 'cache'>['cache'] // client cache options constructor(client: Client) { this.client = client this.options = this.client.options?.cache ?? {} } async global(entity: any): Promise<boolean | undefined> { if (this.options.global) { const results: any[] /* [ boolean | undefined, boolean ] */ = [] results.push(await this.options.global.custom?.(entity) ?? undefined) results.push( await asyncSome(this.options.global.policies, policy => { switch (policy) { case GlobalCachingPolicy.NONE: return false case GlobalCachingPolicy.ALL: default: return true } }) ) // when results[0] is undefined - return results[1], else return results[0] return results[0] ?? results[1] } } async channels(channel: any): Promise<boolean> { let result = true if (this.options.channels) { const results: any[] /* [ boolean | undefined, boolean ] */ = [] results.push(await this.options.channels.custom?.(channel) ?? undefined) results.push( await asyncSome(this.options.channels.policies, policy => { switch (policy) { case ChannelsCachingPolicy.CATEGORY: return channel.type === 'category' case ChannelsCachingPolicy.DM: return channel.type === 'dm' case ChannelsCachingPolicy.NEWS: return channel.type === 'news' case ChannelsCachingPolicy.NEWS_THREAD: return channel.type === 'newsThread' case ChannelsCachingPolicy.TEXT: return channel.type === 'text' case ChannelsCachingPolicy.STORE: return channel.type === 'store' case ChannelsCachingPolicy.VOICE: return channel.type === 'voice' case ChannelsCachingPolicy.STAGE_VOICE: return channel.type === 'stageVoice' case ChannelsCachingPolicy.PUBLIC_THREAD: return channel.type === 'publicThread' case ChannelsCachingPolicy.PRIVATE_THREAD: return channel.type === 'privateThread' case ChannelsCachingPolicy.NONE: return false case ChannelsCachingPolicy.ALL: default: return true } }) ) result = results[0] ?? results[1] } return result } async emojis(emoji: AnyEmoji): Promise<boolean> { let result = true if (this.options.emojis) { const results: any[] /* [ boolean | undefined, boolean ] */ = [] results.push(await this.options.emojis.custom?.(emoji) ?? undefined) results.push( await asyncSome(this.options.emojis.policies, policy => { switch (policy) { case EmojisCachingPolicy.NONE: return false case EmojisCachingPolicy.GUILD: return emoji instanceof GuildEmoji case EmojisCachingPolicy.ACTIVITY: return emoji instanceof ActivityEmoji case EmojisCachingPolicy.REACTION: return emoji instanceof ReactionEmoji case EmojisCachingPolicy.STATIC: case EmojisCachingPolicy.ANIMATED: return !!emoji.animated case EmojisCachingPolicy.ALL: default: return true } }) ) result = results[0] ?? results[1] } return result } async stickers(sticker: Sticker): Promise<boolean> { let result = true if (this.options.stickers) { const results: any[] /* [ boolean | undefined, boolean ] */ = [] results.push(await this.options.stickers.custom?.(sticker) ?? undefined) results.push( await asyncSome(this.options.stickers.policies, policy => { switch (policy) { case StickersCachingPolicy.NONE: return false case StickersCachingPolicy.STANDARD: return sticker.type === StickerTypes.STANDARD case StickersCachingPolicy.GUILD: return sticker.type === StickerTypes.GUILD case StickersCachingPolicy.PNG: return sticker.formatType === StickerFormatTypes.PNG case StickersCachingPolicy.APNG: return sticker.formatType === StickerFormatTypes.APNG case StickersCachingPolicy.LOTTIE: return sticker.formatType === StickerFormatTypes.LOTTIE case StickersCachingPolicy.ALL: default: return true } }) ) result = results[0] ?? results[1] } return result } async guilds(guild: any): Promise<boolean> { let result = true if (this.options.guilds) { const results: any[] /* [ boolean | undefined, boolean ] */ = [] results.push(await this.options.guilds.custom?.(guild) ?? undefined) results.push( await asyncSome(this.options.guilds.policies, policy => { switch (policy) { case GuildsCachingPolicy.NONE: return false case GuildsCachingPolicy.ALL: default: return true } }) ) result = results[0] ?? results[1] } return result } async members(member: GuildMember): Promise<boolean> { let result = true if (this.options.members) { const results: any[] /* [ boolean | undefined, boolean ] */ = [], presence = await member.presence() results.push(await this.options.members.custom?.(member) ?? undefined) results.push( await asyncSome(this.options.members.policies, policy => { switch (policy) { case GuildMembersCachingPolicy.ONLINE: return presence?.status === 'online' case GuildMembersCachingPolicy.DND: return presence?.status === 'dnd' case GuildMembersCachingPolicy.IDLE: return presence?.status === 'idle' case GuildMembersCachingPolicy.OFFLINE: return presence?.status === 'offline' case GuildMembersCachingPolicy.OWNER: return member.guildOwner case GuildMembersCachingPolicy.PENDING: return !!member.pending case GuildMembersCachingPolicy.VOICE: // TODO return false case GuildMembersCachingPolicy.RECENT_MESSAGE: // TODO return false case GuildMembersCachingPolicy.NONE: return false case GuildMembersCachingPolicy.ALL: default: return true } }) ) result = results[0] ?? results[1] } return result } async messages(message: Message): Promise<boolean> { let result = true if (this.options.messages) { const results: any[] /* [ boolean | undefined, boolean ] */ = [] results.push(await this.options.messages.custom?.(message) ?? undefined) results.push( await asyncSome(this.options.messages.policies, async policy => { const author = await message.author() switch (policy) { case MessagesCachingPolicy.BOTS: return !!author?.bot case MessagesCachingPolicy.USERS: return !author?.bot case MessagesCachingPolicy.NONE: return false case MessagesCachingPolicy.ALL: default: return true } }) ) result = results[0] ?? results[1] } return result } async presences(presence: Presence): Promise<boolean> { // TODO let result = true if (this.options.presences) { const results: any[] /* [ boolean | undefined, boolean ] */ = [] results.push(await this.options.presences.custom?.(presence) ?? undefined) results.push( await asyncSome(this.options.presences.policies, policy => { switch (policy) { case PresencesCachingPolicy.NONE: return false case PresencesCachingPolicy.ONLINE: return presence.status === 'online' case PresencesCachingPolicy.IDLE: return presence.status === 'idle' case PresencesCachingPolicy.DND: return presence.status === 'dnd' case PresencesCachingPolicy.OFFLINE: return presence.status === 'offline' case PresencesCachingPolicy.ALL: default: return true } }) ) result = results[0] ?? results[1] } return result } async overwrites(overwrite: PermissionOverwrite): Promise<boolean> { let result = true if (this.options.overwrites) { const results: any[] /* [ boolean | undefined, boolean ] */ = [] results.push(await this.options.overwrites.custom?.(overwrite) ?? undefined) results.push( await asyncSome(this.options.overwrites.policies, policy => { switch (policy) { case OverwritesCachingPolicy.NONE: return false case OverwritesCachingPolicy.MEMBERS: return overwrite.type === PermissionOverwriteTypes.MEMBER case OverwritesCachingPolicy.ROLES: return overwrite.type === PermissionOverwriteTypes.ROLE case OverwritesCachingPolicy.ALL: default: return true } }) ) result = results[0] ?? results[1] } return result } async roles(role: Role): Promise<boolean> { let result = true if (this.options.roles) { const results: any[] /* [ boolean | undefined, boolean ] */ = [] results.push(await this.options.roles.custom?.(role) ?? undefined) results.push( await asyncSome(this.options.roles.policies, policy => { switch (policy) { case RolesCachingPolicy.EVERYONE: return role.id === role.guildId case RolesCachingPolicy.MANAGED: return role.managed case RolesCachingPolicy.NONE: return false case RolesCachingPolicy.ALL: default: return true } }) ) result = results[0] ?? results[1] } return result } async users(user: User): Promise<boolean> { let result = true if (this.options.users) { const results: any[] /* [ boolean | undefined, boolean ] */ = [] results.push(await this.options.users.custom?.(user) ?? undefined) results.push( await asyncSome(this.options.users.policies, policy => { switch (policy) { case UsersCachingPolicy.NONE: return false case UsersCachingPolicy.ALL: default: return true } }) ) result = results[0] ?? results[1] } return result } }
the_stack