text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { SearchParameters } from 'algoliasearch-helper'; import type { ConnectorDescription, ConnectedProps, } from '../../core/createConnector'; import type { QueryRulesProps } from '../connectQueryRules'; import connectReal from '../connectQueryRules'; jest.mock( '../../core/createConnector', () => (connector: ConnectorDescription) => connector ); // our mock implementation is diverging from the regular createConnector, // so we redefine it as `any` here, since we have no more information // @TODO: refactor these tests to work better with TS const connect: any = connectReal; describe('connectQueryRules', () => { const defaultProps: QueryRulesProps = { transformItems: (items) => items, trackedFilters: {}, transformRuleContexts: (ruleContexts) => ruleContexts, }; describe('single index', () => { const indexName = 'index'; const contextValue: any = { mainTargetedIndex: indexName }; const defaultPropsSingleIndex = { ...defaultProps, contextValue, }; describe('default', () => { it('without userData provides the correct props to the component', () => { const props: ConnectedProps<QueryRulesProps> = defaultPropsSingleIndex; const searchState = {}; const searchResults = { results: { [indexName]: { userData: undefined } }, }; expect( connect.getProvidedProps(props, searchState, searchResults) ).toEqual({ items: [], canRefine: false, }); }); it('with userData provides the correct props to the component', () => { const props: ConnectedProps<QueryRulesProps> = defaultPropsSingleIndex; const searchState = {}; const searchResults = { results: { [indexName]: { userData: [{ banner: 'image.png' }] }, }, }; expect( connect.getProvidedProps(props, searchState, searchResults) ).toEqual({ items: [{ banner: 'image.png' }], canRefine: true, }); }); }); describe('transformItems', () => { it('transforms items before passing the props to the component', () => { const transformItemsSpy = jest.fn(() => [ { banner: 'image-transformed.png' }, ]); const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsSingleIndex, transformItems: transformItemsSpy, }; const searchState = {}; const searchResults = { results: { [indexName]: { userData: [{ banner: 'image.png' }] }, }, }; expect( connect.getProvidedProps(props, searchState, searchResults) ).toEqual({ items: [{ banner: 'image-transformed.png' }], canRefine: true, }); expect(transformItemsSpy).toHaveBeenCalledTimes(1); expect(transformItemsSpy).toHaveBeenCalledWith([ { banner: 'image.png' }, ]); }); }); describe('trackedFilters', () => { it('does not set ruleContexts without search state and trackedFilters', () => { const props: ConnectedProps<QueryRulesProps> = defaultPropsSingleIndex; const searchState = {}; const searchParameters = connect.getSearchParameters( new SearchParameters(), props, searchState ); expect(searchParameters.ruleContexts).toEqual(undefined); }); it('does not set ruleContexts with search state but without tracked filters', () => { const props: ConnectedProps<QueryRulesProps> = defaultPropsSingleIndex; const searchState = { range: { price: { min: 20, max: 3000, }, }, }; const searchParameters = connect.getSearchParameters( new SearchParameters(), props, searchState ); expect(searchParameters.ruleContexts).toEqual(undefined); }); it('does not reset initial ruleContexts with trackedFilters', () => { const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsSingleIndex, trackedFilters: { price: (values) => values, }, }; const searchState = {}; const searchParameters = connect.getSearchParameters( SearchParameters.make({ ruleContexts: ['initial-rule'], }), props, searchState ); expect(searchParameters.ruleContexts).toEqual(['initial-rule']); }); it('does not throw an error with search state that contains `undefined` value', () => { const props: QueryRulesProps = { ...defaultProps, trackedFilters: { price: (values) => values, }, }; const searchState = { refinementList: undefined, }; expect(() => { connect.getSearchParameters( SearchParameters.make({}), props, searchState ); }).not.toThrow(); }); it('sets ruleContexts based on range', () => { const priceSpy = jest.fn((values) => values); const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsSingleIndex, trackedFilters: { price: priceSpy, }, }; const searchState = { range: { price: { min: 20, max: 3000, }, }, }; const searchParameters = connect.getSearchParameters( new SearchParameters(), props, searchState ); expect(priceSpy).toHaveBeenCalledTimes(1); expect(priceSpy).toHaveBeenCalledWith([20, 3000]); expect(searchParameters.ruleContexts).toEqual([ 'ais-price-20', 'ais-price-3000', ]); }); it('sets ruleContexts based on refinementList', () => { const fruitSpy = jest.fn((values) => values); const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsSingleIndex, trackedFilters: { fruit: fruitSpy, }, }; const searchState = { refinementList: { fruit: ['lemon', 'orange'], }, }; const searchParameters = connect.getSearchParameters( new SearchParameters(), props, searchState ); expect(fruitSpy).toHaveBeenCalledTimes(1); expect(fruitSpy).toHaveBeenCalledWith(['lemon', 'orange']); expect(searchParameters.ruleContexts).toEqual([ 'ais-fruit-lemon', 'ais-fruit-orange', ]); }); it('sets ruleContexts based on hierarchicalMenu', () => { const productsSpy = jest.fn((values) => values); const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsSingleIndex, trackedFilters: { products: productsSpy, }, }; const searchState = { hierarchicalMenu: { products: 'Laptops > Surface', }, }; const searchParameters = connect.getSearchParameters( new SearchParameters(), props, searchState ); expect(productsSpy).toHaveBeenCalledTimes(1); expect(productsSpy).toHaveBeenCalledWith(['Laptops > Surface']); expect(searchParameters.ruleContexts).toEqual([ 'ais-products-Laptops_Surface', ]); }); it('sets ruleContexts based on menu', () => { const brandsSpy = jest.fn((values) => values); const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsSingleIndex, trackedFilters: { brands: brandsSpy, }, }; const searchState = { menu: { brands: 'Sony', }, }; const searchParameters = connect.getSearchParameters( new SearchParameters(), props, searchState ); expect(brandsSpy).toHaveBeenCalledTimes(1); expect(brandsSpy).toHaveBeenCalledWith(['Sony']); expect(searchParameters.ruleContexts).toEqual(['ais-brands-Sony']); }); it('sets ruleContexts based on multiRange', () => { const rankSpy = jest.fn((values) => values); const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsSingleIndex, trackedFilters: { rank: rankSpy, }, }; const searchState = { multiRange: { rank: '2:5', }, }; const searchParameters = connect.getSearchParameters( new SearchParameters(), props, searchState ); expect(rankSpy).toHaveBeenCalledTimes(1); expect(rankSpy).toHaveBeenCalledWith(['2', '5']); expect(searchParameters.ruleContexts).toEqual([ 'ais-rank-2', 'ais-rank-5', ]); }); it('sets ruleContexts based on toggle', () => { const freeShippingSpy = jest.fn((values) => values); const availableInStockSpy = jest.fn((values) => values); const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsSingleIndex, trackedFilters: { freeShipping: freeShippingSpy, availableInStock: availableInStockSpy, }, }; const searchState = { toggle: { freeShipping: true, availableInStock: false, }, }; const searchParameters = connect.getSearchParameters( new SearchParameters(), props, searchState ); expect(freeShippingSpy).toHaveBeenCalledTimes(1); expect(freeShippingSpy).toHaveBeenCalledWith([true]); expect(availableInStockSpy).toHaveBeenCalledTimes(1); expect(availableInStockSpy).toHaveBeenCalledWith([false]); expect(searchParameters.ruleContexts).toEqual([ 'ais-freeShipping-true', 'ais-availableInStock-false', ]); }); it('escapes all rule contexts before passing them to search parameters', () => { const brandSpy = jest.fn((values) => values); const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsSingleIndex, trackedFilters: { brand: brandSpy, }, }; const searchState = { refinementList: { brand: ['Insignia™', '© Apple'], }, }; const searchParameters = connect.getSearchParameters( new SearchParameters(), props, searchState ); expect(brandSpy).toHaveBeenCalledTimes(1); expect(brandSpy).toHaveBeenCalledWith(['Insignia™', '© Apple']); expect(searchParameters.ruleContexts).toEqual([ 'ais-brand-Insignia_', 'ais-brand-_Apple', ]); }); it('slices and warns in development when more than 10 rule contexts are applied', () => { // We need to simulate being in development mode and to mock the global console object // in this test to assert that development warnings are displayed correctly. const originalNodeEnv = process.env.NODE_ENV; process.env.NODE_ENV = 'development'; const warnSpy = jest .spyOn(console, 'warn') .mockImplementation(() => {}); const brandFacetRefinements = [ 'Insignia', 'Canon', 'Dynex', 'LG', 'Metra', 'Sony', 'HP', 'Apple', 'Samsung', 'Speck', 'PNY', ]; expect(brandFacetRefinements).toHaveLength(11); const brandSpy = jest.fn((values) => values); const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsSingleIndex, trackedFilters: { brand: brandSpy, }, }; const searchState = { refinementList: { brand: brandFacetRefinements, }, }; const searchParameters = connect.getSearchParameters( new SearchParameters(), props, searchState ); expect(warnSpy).toHaveBeenCalledTimes(1); expect(warnSpy) .toHaveBeenCalledWith(`The maximum number of \`ruleContexts\` is 10. They have been sliced to that limit. Consider using \`transformRuleContexts\` to minimize the number of rules sent to Algolia.`); expect(brandSpy).toHaveBeenCalledTimes(1); expect(brandSpy).toHaveBeenCalledWith([ 'Insignia', 'Canon', 'Dynex', 'LG', 'Metra', 'Sony', 'HP', 'Apple', 'Samsung', 'Speck', 'PNY', ]); expect(searchParameters.ruleContexts).toEqual([ 'ais-brand-Insignia', 'ais-brand-Canon', 'ais-brand-Dynex', 'ais-brand-LG', 'ais-brand-Metra', 'ais-brand-Sony', 'ais-brand-HP', 'ais-brand-Apple', 'ais-brand-Samsung', 'ais-brand-Speck', ]); process.env.NODE_ENV = originalNodeEnv; warnSpy.mockRestore(); }); }); describe('transformRuleContexts', () => { it('transform rule contexts before adding them to search parameters', () => { const priceSpy = jest.fn((values) => values); const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsSingleIndex, trackedFilters: { price: priceSpy, }, transformRuleContexts: (rules) => rules.map((rule) => rule.replace('ais-', 'transformed-')), }; const searchState = { range: { price: { min: 20, max: 3000, }, }, }; const searchParameters = connect.getSearchParameters( new SearchParameters(), props, searchState ); expect(priceSpy).toHaveBeenCalledTimes(1); expect(priceSpy).toHaveBeenCalledWith([20, 3000]); expect(searchParameters.ruleContexts).toEqual([ 'transformed-price-20', 'transformed-price-3000', ]); }); }); }); describe('multi index', () => { const firstIndexName = 'firstIndex'; const secondIndexName = 'secondIndex'; const contextValue: any = { mainTargetedIndex: firstIndexName }; const indexContextValue: any = { targetedIndex: secondIndexName }; const defaultPropsMultiIndex = { ...defaultProps, contextValue, indexContextValue, }; it('without userData provides the correct props to the component', () => { const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsMultiIndex, }; const searchState = {}; const searchResults = { results: { [secondIndexName]: { userData: undefined } }, }; expect( connect.getProvidedProps(props, searchState, searchResults) ).toEqual({ items: [], canRefine: false, }); }); it('with userData provides the correct props to the component', () => { const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsMultiIndex, }; const searchState = {}; const searchResults = { results: { [secondIndexName]: { userData: [{ banner: 'image.png' }] }, }, }; expect( connect.getProvidedProps(props, searchState, searchResults) ).toEqual({ items: [{ banner: 'image.png' }], canRefine: true, }); }); describe('transformItems', () => { it('transforms items before passing the props to the component', () => { const transformItemsSpy = jest.fn(() => [ { banner: 'image-transformed.png' }, ]); const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsMultiIndex, transformItems: transformItemsSpy, }; const searchState = {}; const searchResults = { results: { [secondIndexName]: { userData: [{ banner: 'image.png' }] }, }, }; expect( connect.getProvidedProps(props, searchState, searchResults) ).toEqual({ items: [{ banner: 'image-transformed.png' }], canRefine: true, }); expect(transformItemsSpy).toHaveBeenCalledTimes(1); expect(transformItemsSpy).toHaveBeenCalledWith([ { banner: 'image.png' }, ]); }); }); describe('trackedFilters', () => { it('does not set ruleContexts without search state and trackedFilters', () => { const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsMultiIndex, }; const searchState = {}; const searchParameters = connect.getSearchParameters( new SearchParameters(), props, searchState ); expect(searchParameters.ruleContexts).toEqual(undefined); }); it('does not set ruleContexts with search state but without tracked filters', () => { const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsMultiIndex, }; const searchState = { indices: { [secondIndexName]: { range: { price: { min: 20, max: 3000, }, }, }, }, }; const searchParameters = connect.getSearchParameters( new SearchParameters(), props, searchState ); expect(searchParameters.ruleContexts).toEqual(undefined); }); it('sets ruleContexts based on range', () => { const priceSpy = jest.fn((values) => values); const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsMultiIndex, trackedFilters: { price: priceSpy, }, }; const searchState = { indices: { [secondIndexName]: { range: { price: { min: 20, max: 3000, }, }, }, }, }; const searchParameters = connect.getSearchParameters( new SearchParameters(), props, searchState ); expect(priceSpy).toHaveBeenCalledTimes(1); expect(priceSpy).toHaveBeenCalledWith([20, 3000]); expect(searchParameters.ruleContexts).toEqual([ 'ais-price-20', 'ais-price-3000', ]); }); it('sets empty ruleContexts without search state', () => { const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsMultiIndex, trackedFilters: { price: (values) => values, }, }; const searchState = {}; const searchParameters = connect.getSearchParameters( new SearchParameters(), props, searchState ); expect(searchParameters.ruleContexts).toEqual([]); }); }); describe('transformRuleContexts', () => { it('transform rule contexts before adding them to search parameters', () => { const priceSpy = jest.fn((values) => values); const props: ConnectedProps<QueryRulesProps> = { ...defaultPropsMultiIndex, trackedFilters: { price: priceSpy, }, transformRuleContexts: (rules) => rules.map((rule) => rule.replace('ais-', 'transformed-')), }; const searchState = { indices: { [secondIndexName]: { range: { price: { min: 20, max: 3000, }, }, }, }, }; const searchParameters = connect.getSearchParameters( new SearchParameters(), props, searchState ); expect(priceSpy).toHaveBeenCalledTimes(1); expect(priceSpy).toHaveBeenCalledWith([20, 3000]); expect(searchParameters.ruleContexts).toEqual([ 'transformed-price-20', 'transformed-price-3000', ]); }); }); }); });
the_stack
import { getGeneralTriggerFinalOptions, getThirdPartyTrigger, getGlobalThirdPartyTrigger, isPromise, log, getWebhookByRequest, Cursor, getLocalTrigger, filter as filterFn, getStringFunctionResult, ITriggerInternalResult, AnyObject, ITriggerClassTypeConstructable, ITriggerResult, ITriggerResultObject, IInternalRunTrigger, IWebhookRequestPayload, ITrigger, getTriggerConstructorParams, ITriggerInternalOptions, getTriggerManageCache, } from "actionsflow-core"; import Triggers from "./triggers"; const MAX_CACHE_KEYS_COUNT = 5000; const allTriggers = Triggers as Record<string, ITriggerClassTypeConstructable>; export const run = async ({ trigger, event, workflow, cwd, dest, }: ITriggerInternalOptions): Promise<ITriggerInternalResult> => { log.debug("Trigger event: ", event); const originLogLevel = log.getLevel(); const finalResult: ITriggerInternalResult = { items: [], outcome: "success", conclusion: "success", }; const Trigger = trigger.class; if (Trigger) { const triggerCacheManager = getTriggerManageCache({ name: trigger.name, workflowRelativePath: workflow.relativePath, }); const triggerConstructorParams = await getTriggerConstructorParams({ name: trigger.name, workflow: workflow, options: trigger.options, }); finalResult.helpers = triggerConstructorParams.helpers; const triggerInstance = new Trigger(triggerConstructorParams); let triggerResult: ITriggerResult | undefined; if (triggerInstance) { const triggerGeneralOptions = getGeneralTriggerFinalOptions( triggerInstance, trigger.options, event, { cwd, dest, } ); const { shouldDeduplicate, limit, filter, filterOutputs, format, sort, skip, skipFirst, force, logLevel, filterScript, sortScript, } = triggerGeneralOptions; if (logLevel) { log.setLevel(logLevel); } log.debug( `Start to run trigger [${trigger.name}] of workflow [${workflow.relativePath}]` ); try { if (event.type === "webhook" && triggerInstance.webhooks) { // webhook event should call webhook method // lookup specific webhook event // call webhooks const webhook = getWebhookByRequest({ webhooks: triggerInstance.webhooks, request: event.request as IWebhookRequestPayload, workflow, trigger: { name: trigger.name, options: trigger.options }, }); if (webhook) { log.debug("detect webhook", webhook); // check if specific getItemKey at Webhook if (webhook.getItemKey) { triggerGeneralOptions.getItemKey = webhook.getItemKey.bind( triggerInstance ); } const webhookHandlerResult = webhook.handler.bind(triggerInstance)( webhook.request ); if (isPromise(webhookHandlerResult)) { triggerResult = (await webhookHandlerResult) as ITriggerResult; } else { triggerResult = webhookHandlerResult as ITriggerResult; } } else { // skip throw new Error( `No webhook path matched request path, skip [${trigger.name}] trigger building` ); } } else if (triggerInstance.run) { const runHandler = triggerInstance.run.bind(triggerInstance)(); if (isPromise(runHandler)) { triggerResult = (await runHandler) as ITriggerResult; } else { triggerResult = runHandler as ITriggerResult; } } else { // skipped, no method for the event type finalResult.outcome = "skipped"; finalResult.conclusion = "skipped"; triggerResult = []; } if (triggerResult) { let triggerResultFormat: ITriggerResultObject = { items: [], }; let deduplicationKeys: string[] = []; const { getItemKey } = triggerGeneralOptions; if (Array.isArray(triggerResult)) { triggerResultFormat.items = triggerResult; } else { triggerResultFormat = triggerResult as ITriggerResultObject; } let items = triggerResultFormat.items; if (!Array.isArray(items)) { throw new Error( `trigger [${ trigger.name }] returns an invalid results: ${JSON.stringify( triggerResult, null, 2 )}` ); } if (items.length > 0) { // filter outputs if (filterOutputs) { const filterOutpusCursor = filterFn(items, {}, filterOutputs); items = filterOutpusCursor.all(); } // format outputs if (format) { items = items.map((item) => { try { const newItem = getStringFunctionResult(format, { require: require, item, helpers: triggerConstructorParams.helpers, }) as Record<string, unknown>; return newItem; } catch (error) { throw new Error( `An error occurred in the ${workflow.relativePath} [${ trigger.name }] format function: ${error.toString()}` ); } }); } let cursor: Cursor | undefined; // filter if (filter) { cursor = filterFn(items, filter); } // filterScript if (filterScript) { items = items.filter((item, index) => { try { const filterResult = getStringFunctionResult(filterScript, { require: require, item, index, items, helpers: triggerConstructorParams.helpers, }) as Record<string, unknown>; return filterResult; } catch (error) { throw new Error( `An error occurred in the ${workflow.relativePath} [${ trigger.name }] filterScript function: ${error.toString()}` ); } }); } if (sort) { if (!cursor) { cursor = filterFn(items, {}); } cursor = cursor.sort(sort); } if (sortScript) { items.sort((a, b) => { try { const sortResult = getStringFunctionResult(sortScript, { require: require, a, b, items, helpers: triggerConstructorParams.helpers, }) as number; return sortResult; } catch (error) { throw new Error( `An error occurred in the ${workflow.relativePath} [${ trigger.name }] sortScript function: ${error.toString()}` ); } }); } if (cursor) { items = cursor.all(); } if (skip && skip > 0) { items = items.slice(skip, items.length); } if (limit && limit > 0) { items = items.slice(0, limit); } // duplicate if (shouldDeduplicate === true && getItemKey) { // deduplicate // get cache deduplicationKeys = (await triggerCacheManager.get("deduplicationKeys")) || []; log.debug( `Get ${deduplicationKeys.length} cached deduplicationKeys` ); const itemsKeyMaps = new Map(); items.forEach((item) => { itemsKeyMaps.set(getItemKey(item), item); }); items = [...itemsKeyMaps.values()]; if (!force) { items = items.filter((result) => { const key = getItemKey(result); if ((deduplicationKeys as string[]).includes(key)) { return false; } else { return true; } }); } // set deduplicate key // if save to cache // items should use raw items if (items.length > 0) { deduplicationKeys = (deduplicationKeys as string[]).concat( items .map((item: AnyObject) => getItemKey(item)) .filter((item) => { if (deduplicationKeys.includes(item)) { return false; } else { return true; } }) ); // deduplicate, just in case deduplicationKeys = [...new Set(deduplicationKeys)]; deduplicationKeys = (deduplicationKeys as string[]).slice( -MAX_CACHE_KEYS_COUNT ); // set cache await triggerCacheManager.set( "deduplicationKeys", deduplicationKeys ); log.debug( `Save ${deduplicationKeys.length} deduplicationKeys to cache` ); } else { log.debug("no items update, do not need to update cache"); } } } // save first run status await triggerCacheManager.set("firstRunAt", Date.now()); if ( !( skipFirst && triggerConstructorParams.context.isFirstRun === true ) || force ) { finalResult.items = items; } } else { log.debug("no items update, do not need to update cache"); } log.setLevel(originLogLevel); } catch (e) { log.setLevel(originLogLevel); throw e; } } else { throw new Error(`Trigger [${trigger.name}] construct error`); } } log.debug( `End to run trigger [${trigger.name}] of workflow [${workflow.relativePath}] with ${finalResult.items.length} items` ); return finalResult; }; export const runSettled = async ( options: ITriggerInternalOptions ): Promise<PromiseSettledResult<ITriggerInternalResult>> => { try { const value = await run(options); return { status: "fulfilled", value, }; } catch (e) { return { status: "rejected", reason: e, }; } }; export const resolveTrigger = ( name: string ): ITriggerClassTypeConstructable | undefined => { // check thirdparty support let trigger: ITriggerClassTypeConstructable | undefined; // first get local trigger trigger = getLocalTrigger(name); if (trigger) { log.debug(`Use local trigger [${name}]`); } // then, get third party trigger if (!trigger) { trigger = getThirdPartyTrigger(name); if (trigger) { log.debug(`Use third party trigger [${name}]`); } } // last, get official trigger if (!trigger) { trigger = allTriggers[name]; if (trigger) { log.debug(`Use official trigger [${name}]`); } } // last last, get global trigger if (!trigger) { trigger = getGlobalThirdPartyTrigger(name); if (trigger) { log.debug(`Use global third party trigger [${name}]`); } } return trigger; }; export const getSupportedTriggers = ( rawTriggers: ITrigger[] ): IInternalRunTrigger[] => { const triggers = []; for (let index = 0; index < rawTriggers.length; index++) { const trigger = rawTriggers[index]; const name = trigger.name; const triggerOptions = trigger.options || {}; // is active if (triggerOptions.config && triggerOptions.config.active === false) { continue; } // check thirdparty support const triggerClass = resolveTrigger(name); if (!triggerClass) { log.warn( `can not found the trigger [${name}]. Did you forget to install the third party trigger? Try \`npm i @actionsflow/trigger-${name}\` if it exists. ` ); } if (triggerClass) { // valid event triggers.push({ ...trigger, class: triggerClass, }); } } return triggers; };
the_stack
import { buildPipelinesRelation, buildTopicsMap, buildTopicsRelation, PipelineRelationMap, PipelinesMap, TopicRelationMap, TopicsMap } from '@/services/data/pipeline/pipeline-relations'; import {listConnectedSpacesForExport} from '@/services/data/tuples/connected-space'; import {ConnectedSpace} from '@/services/data/tuples/connected-space-types'; import {DataSource} from '@/services/data/tuples/data-source-types'; import {ExternalWriter} from '@/services/data/tuples/external-writer-types'; import {Pipeline} from '@/services/data/tuples/pipeline-types'; import {listSpacesForExport} from '@/services/data/tuples/space'; import {Space} from '@/services/data/tuples/space-types'; import {Topic} from '@/services/data/tuples/topic-types'; import {AdminCacheData} from '@/services/local-persist/types'; import {Button} from '@/widgets/basic/button'; import {ICON_EXPORT} from '@/widgets/basic/constants'; import {PageHeaderButton} from '@/widgets/basic/page-header-buttons'; import {ButtonInk} from '@/widgets/basic/types'; import {downloadAsZip} from '@/widgets/basic/utils'; import {DialogFooter, DialogLabel} from '@/widgets/dialog/widgets'; import {useEventBus} from '@/widgets/events/event-bus'; import {EventTypes} from '@/widgets/events/types'; import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'; import dayjs from 'dayjs'; import React, {useState} from 'react'; // noinspection ES6PreferShortImport import {useAdminCacheEventBus} from '../../../cache/cache-event-bus'; // noinspection ES6PreferShortImport import {AdminCacheEventTypes} from '../../../cache/cache-event-bus-types'; import {useCatalogEventBus} from '../catalog-event-bus'; import {CatalogEventTypes} from '../catalog-event-bus-types'; import {generateMarkdown} from '../markdown'; import {DataSourcesMap, ExternalWritersMap} from '../markdown/types'; import {AssembledPipelinesGraphics} from '../types'; import {TopicPickerTable} from './topic-picker-table'; import {SpaceCandidate, TopicCandidate} from './types'; import {isSpaceCandidate, isTopicCandidate} from './utils'; import {PICKER_DIALOG_HEIGHT, PickerDialogBody} from './widgets'; const findPipelinesWriteMe = (topics: Array<Topic>, topicRelations: TopicRelationMap): Array<Pipeline> => { return topics.reduce((found, topic) => { const {writeMe} = topicRelations[topic.topicId]; return [...new Set([...writeMe, ...found])]; }, [] as Array<Pipeline>); }; const findTopicsOnMe = (pipelines: Array<Pipeline>, pipelineRelation: PipelineRelationMap): Array<Topic> => { return pipelines.reduce((found, pipeline) => { const {trigger, incoming, outgoing} = pipelineRelation[pipeline.pipelineId]; if (trigger?.topic) { return [...new Set([trigger.topic!, ...incoming.map(({topic}) => topic), ...outgoing.map(({topic}) => topic), ...found])]; } else { return [...new Set([...incoming.map(({topic}) => topic), ...outgoing.map(({topic}) => topic), ...found])]; } }, [] as Array<Topic>); }; const findByTopics = (options: { topics: Array<Topic>; finalTopicMap: TopicsMap; finalPipelineMap: PipelinesMap topicRelations: TopicRelationMap; pipelineRelations: PipelineRelationMap }) => { const {topics, finalTopicMap, finalPipelineMap, topicRelations, pipelineRelations} = options; topics.forEach(topic => { if (!finalTopicMap[topic.topicId]) { finalTopicMap[topic.topicId] = topic; } }); const writeMe = findPipelinesWriteMe(topics, topicRelations); if (writeMe.length !== 0) { const relatedPipelines = writeMe.filter(pipeline => { if (!finalPipelineMap[pipeline.pipelineId]) { finalPipelineMap[pipeline.pipelineId] = pipeline; return true; } else { return false; } }); const relatedTopics = findTopicsOnMe(relatedPipelines, pipelineRelations).filter(topic => { return !finalTopicMap[topic.topicId]; }); if (relatedTopics.length !== 0) { findByTopics({topics: relatedTopics, finalTopicMap, finalPipelineMap, topicRelations, pipelineRelations}); } } }; const PipelinesDownload = (props: { pipelines: Array<Pipeline>; topics: Array<Topic>; graphics: AssembledPipelinesGraphics; dataSources: Array<DataSource>; externalWriters: Array<ExternalWriter>; spaces: Array<Space>; connectedSpaces: Array<ConnectedSpace>; askSvg: (topics: Array<Topic>) => Promise<string> }) => { const {pipelines, topics, graphics, dataSources, externalWriters, spaces, connectedSpaces, askSvg} = props; const {fire} = useEventBus(); const [candidates] = useState(() => { const inGraphicsTopics = graphics.topics.map(t => t.topic); const selectedTopics = topics.map(topic => ({topic, picked: inGraphicsTopics.includes(topic)})); const selectedSpaces = spaces.map(space => { return { space, // eslint-disable-next-line picked: (space.topicIds || []).every(topicId => selectedTopics.some(({topic}) => topic.topicId == topicId)) }; }); return [...selectedTopics, ...selectedSpaces]; }); const onDownloadClicked = async () => { const selectedTopics = candidates.filter<TopicCandidate>(isTopicCandidate).filter(c => c.picked).map(({topic}) => topic); const selectedSpaces = candidates.filter<SpaceCandidate>(isSpaceCandidate).filter(c => c.picked).map(({space}) => space); // eslint-disable-next-line const selectedConnectedSpaces = connectedSpaces.filter(connectedSpace => selectedSpaces.some(space => space.spaceId == connectedSpace.spaceId)); // use these topics to find upstream const topicsMap = buildTopicsMap(topics); const pipelineRelations = buildPipelinesRelation(pipelines, topicsMap); const topicRelations = buildTopicsRelation(topics, pipelineRelations); const finalTopicMap: TopicsMap = selectedTopics.reduce((map, topic) => { map[topic.topicId] = topic; return map; }, {} as TopicsMap); const finalPipelineMap: PipelinesMap = {}; findByTopics({topics: selectedTopics, finalTopicMap, finalPipelineMap, topicRelations, pipelineRelations}); const selectedSvg = await askSvg(selectedTopics); const allTopics = Object.values(finalTopicMap); const allSvg = allTopics.length === selectedTopics.length ? '' : await askSvg(Object.values(finalTopicMap)); const markdown = await generateMarkdown({ topicsMap: finalTopicMap, pipelinesMap: finalPipelineMap, dataSourcesMap: dataSources.reduce((map, dataSource) => { map[dataSource.dataSourceId] = dataSource; return map; }, {} as DataSourcesMap), externalWritersMap: externalWriters.reduce((map, writer) => { map[writer.writerId] = writer; return map; }, {} as ExternalWritersMap), topicRelations, pipelineRelations, spaces: selectedSpaces, connectedSpaces: selectedConnectedSpaces, selectedSvg, allSvg }); await downloadAsZip({ [`${graphics.name || 'Noname Pipelines Group'}.md`]: markdown }, `export-${graphics.name || 'Noname Pipelines Group'}-${dayjs().format('YYYYMMDD')}.zip`); fire(EventTypes.HIDE_DIALOG); }; const onCancelClicked = () => { fire(EventTypes.HIDE_DIALOG); }; return <> <PickerDialogBody> <DialogLabel>Pick topics/spaces to export, related pipelines will be included as well.</DialogLabel> <TopicPickerTable candidates={candidates}/> </PickerDialogBody> <DialogFooter> <Button ink={ButtonInk.PRIMARY} onClick={onDownloadClicked}>Export</Button> <Button ink={ButtonInk.WAIVE} onClick={onCancelClicked}>Cancel</Button> </DialogFooter> </>; }; export const HeaderExportButton = (props: { graphics: AssembledPipelinesGraphics }) => { const {graphics} = props; const {fire: fireGlobal} = useEventBus(); const {once} = useCatalogEventBus(); const {fire: fireCache} = useAdminCacheEventBus(); const askSvg = async (topics: Array<Topic>) => { return new Promise<string>(resolve => { once(CatalogEventTypes.REPLY_GRAPHICS_SVG, (html: string) => { resolve(html); }).fire(CatalogEventTypes.ASK_GRAPHICS_SVG, topics); }); }; const onExportClicked = () => { fireCache(AdminCacheEventTypes.ASK_DATA, (data?: AdminCacheData) => { const {pipelines, topics, dataSources, externalWriters} = data!; fireGlobal(EventTypes.INVOKE_REMOTE_REQUEST, async () => { const [spaces, connectedSpaces] = await Promise.all([listSpacesForExport(), listConnectedSpacesForExport()]); // drop spaces has no topic const availableSpaces = spaces.filter(space => space.topicIds != null && space.topicIds.length !== 0); // drop connected spaces is not template, has no subject, and not belongs to available spaces const availableConnectedSpaces = connectedSpaces.filter(connectedSpace => connectedSpace.isTemplate) .filter(connectedSpace => connectedSpace.subjects != null && connectedSpace.subjects.length !== 0) // eslint-disable-next-line .filter(connectedSpace => availableSpaces.some(space => space.spaceId == connectedSpace.spaceId)); return {spaces: availableSpaces, connectedSpaces: availableConnectedSpaces}; }, ({spaces, connectedSpaces}: { spaces: Array<Space>, connectedSpaces: Array<ConnectedSpace> }) => { fireGlobal(EventTypes.SHOW_DIALOG, <PipelinesDownload pipelines={pipelines} topics={topics} graphics={graphics} dataSources={dataSources} externalWriters={externalWriters} spaces={spaces} connectedSpaces={connectedSpaces} askSvg={askSvg}/>, { marginTop: '10vh', marginLeft: '20%', width: '60%', height: PICKER_DIALOG_HEIGHT }); }, () => { fireGlobal(EventTypes.SHOW_DIALOG, <PipelinesDownload pipelines={pipelines} topics={topics} graphics={graphics} dataSources={dataSources} externalWriters={externalWriters} spaces={[]} connectedSpaces={[]} askSvg={askSvg}/>, { marginTop: '10vh', marginLeft: '20%', width: '60%', height: PICKER_DIALOG_HEIGHT }); }); }); }; return <PageHeaderButton tooltip="Export" onClick={onExportClicked}> <FontAwesomeIcon icon={ICON_EXPORT}/> </PageHeaderButton>; };
the_stack
interface NodeMessage { topic?: string; payload?: any; _msgid?: string; [other: string]: any; //permit other properties } /** @type {NodeMessage} the `msg` object */ declare var msg: NodeMessage; /** @type {string} the id of the incoming `msg` (alias of msg._msgid) */ declare const __msgid__:string; /** * @typedef NodeStatus * @type {object} * @property {string} [fill] The fill property can be: red, green, yellow, blue or grey. * @property {string} [shape] The shape property can be: ring or dot. * @property {string} [text] The text to display */ interface NodeStatus { /** The fill property can be: red, green, yellow, blue or grey */ fill?: string, /** The shape property can be: ring or dot */ shape?: string, /** The text to display */ text?: string|boolean|number } declare class node { /** * Send 1 or more messages asynchronously * @param {object | object[]} msg The msg object * @param {Boolean} [clone=true] Flag to indicate the `msg` should be cloned. Default = `true` * @see node-red documentation [writing-functions: sending messages asynchronously](https://nodered.org/docs/user-guide/writing-functions#sending-messages-asynchronously) */ static send(msg:object|object[], clone?:Boolean): void; /** Inform runtime this instance has completed its operation */ static done(); /** Send an error to the console and debug side bar. Include `msg` in the 2nd parameter to trigger the catch node. */ static error(err:string|Error, msg?:object); /** Log a warn message to the console and debug sidebar */ static warn(warning:string|object); /** Log an info message to the console (not sent to sidebar)' */ static log(info:string|object); /** Sets the status icon and text underneath the node. * @param {NodeStatus} status - The status object `{fill, shape, text}` * @see node-red documentation [writing-functions: adding-status](https://nodered.org/docs/user-guide/writing-functions#adding-status) */ static status(status:NodeStatus); /** Sets the status text underneath the node. * @param {string} status - The status to display * @see node-red documentation [writing-functions: adding-status](https://nodered.org/docs/user-guide/writing-functions#adding-status) */ static status(status:string|boolean|number); /** the id of this node */ public readonly id:string; /** the name of this node */ public readonly name:string; /** the number of outputs of this node */ public readonly outputCount:number; } declare class context { /** * Get one or multiple values from context (synchronous). * @param name - Name of context variable */ static get(name: string | string[]); /** * Get one or multiple values from context (asynchronous). * @param name - Name (or array of names) to get from context * @param {function} callback - (optional) Callback function (`(err,value) => {}`) */ static get(name: string | string[], callback: Function); /** * Get one or multiple values from context (synchronous). * @param name - Name (or array of names) to get from context * @param store - Name of context store */ static get(name: string | string[], store: string); /** * Get one or multiple values from context (asynchronous). * @param name - Name (or array of names) to get from context * @param store - Name of context store * @param {function} callback - (optional) Callback function (`(err,value) => {}`) */ static get(name: string | string[], store: string, callback: Function); /** * Set one or multiple values in context (synchronous). * @param name - Name (or array of names) to set in context * @param value - The value (or array of values) to store in context. If the value(s) are null/undefined, the context item(s) will be removed. */ static set(name: string | string[], value?: any | any[]); /** * Set one or multiple values in context (asynchronous). * @param name - Name (or array of names) to set in context * @param value - The value (or array of values) to store in context. If the value(s) are null/undefined, the context item(s) will be removed. * @param callback - (optional) Callback function (`(err) => {}`) */ static set(name: string | string[], value?: any | any[], callback?: Function); /** * Set one or multiple values in context (synchronous). * @param name - Name (or array of names) to set in context * @param value - The value (or array of values) to store in context. If the value(s) are null/undefined, the context item(s) will be removed. * @param store - (optional) Name of context store */ static set(name: string | string[], value?: any | any[], store?: string); /** * Set one or multiple values in context (asynchronous). * @param name - Name (or array of names) to set in context * @param value - The value (or array of values) to store in context. If the value(s) are null/undefined, the context item(s) will be removed. * @param store - (optional) Name of context store * @param callback - (optional) Callback function (`(err) => {}`) */ static set(name: string | string[], value?: any | any[], store?: string, callback?: Function); /** Get an array of the keys in the context store */ static keys(): Array<string>; /** Get an array of the keys in the context store */ static keys(store: string): Array<string>; /** Get an array of the keys in the context store */ static keys(callback: Function); /** Get an array of the keys in the context store */ static keys(store: string, callback: Function); } declare class flow { /** * Get one or multiple values from context (synchronous). * @param name - Name of context variable */ static get(name: string | string[]); /** * Get one or multiple values from context (asynchronous). * @param name - Name (or array of names) to get from context * @param {function} callback - (optional) Callback function (`(err,value) => {}`) */ static get(name: string | string[], callback: Function); /** * Get one or multiple values from context (synchronous). * @param name - Name (or array of names) to get from context * @param store - Name of context store */ static get(name: string | string[], store: string); /** * Get one or multiple values from context (asynchronous). * @param name - Name (or array of names) to get from context * @param store - Name of context store * @param {function} callback - (optional) Callback function (`(err,value) => {}`) */ static get(name: string | string[], store: string, callback: Function); /** * Set one or multiple values in context (synchronous). * @param name - Name (or array of names) to set in context * @param value - The value (or array of values) to store in context. If the value(s) are null/undefined, the context item(s) will be removed. */ static set(name: string | string[], value?: any | any[]); /** * Set one or multiple values in context (asynchronous). * @param name - Name (or array of names) to set in context * @param value - The value (or array of values) to store in context. If the value(s) are null/undefined, the context item(s) will be removed. * @param callback - (optional) Callback function (`(err) => {}`) */ static set(name: string | string[], value?: any | any[], callback?: Function); /** * Set one or multiple values in context (synchronous). * @param name - Name (or array of names) to set in context * @param value - The value (or array of values) to store in context. If the value(s) are null/undefined, the context item(s) will be removed. * @param store - (optional) Name of context store */ static set(name: string | string[], value?: any | any[], store?: string); /** * Set one or multiple values in context (asynchronous). * @param name - Name (or array of names) to set in context * @param value - The value (or array of values) to store in context. If the value(s) are null/undefined, the context item(s) will be removed. * @param store - (optional) Name of context store * @param callback - (optional) Callback function (`(err) => {}`) */ static set(name: string | string[], value?: any | any[], store?: string, callback?: Function); /** Get an array of the keys in the context store */ static keys(): Array<string>; /** Get an array of the keys in the context store */ static keys(store: string): Array<string>; /** Get an array of the keys in the context store */ static keys(callback: Function); /** Get an array of the keys in the context store */ static keys(store: string, callback: Function); } // @ts-ignore declare class global { /** * Get one or multiple values from context (synchronous). * @param name - Name of context variable */ static get(name: string | string[]); /** * Get one or multiple values from context (asynchronous). * @param name - Name (or array of names) to get from context * @param {function} callback - (optional) Callback function (`(err,value) => {}`) */ static get(name: string | string[], callback: Function); /** * Get one or multiple values from context (synchronous). * @param name - Name (or array of names) to get from context * @param store - Name of context store */ static get(name: string | string[], store: string); /** * Get one or multiple values from context (asynchronous). * @param name - Name (or array of names) to get from context * @param store - Name of context store * @param {function} callback - (optional) Callback function (`(err,value) => {}`) */ static get(name: string | string[], store: string, callback: Function); /** * Set one or multiple values in context (synchronous). * @param name - Name (or array of names) to set in context * @param value - The value (or array of values) to store in context. If the value(s) are null/undefined, the context item(s) will be removed. */ static set(name: string | string[], value?: any | any[]); /** * Set one or multiple values in context (asynchronous). * @param name - Name (or array of names) to set in context * @param value - The value (or array of values) to store in context. If the value(s) are null/undefined, the context item(s) will be removed. * @param callback - (optional) Callback function (`(err) => {}`) */ static set(name: string | string[], value?: any | any[], callback?: Function); /** * Set one or multiple values in context (synchronous). * @param name - Name (or array of names) to set in context * @param value - The value (or array of values) to store in context. If the value(s) are null/undefined, the context item(s) will be removed. * @param store - (optional) Name of context store */ static set(name: string | string[], value?: any | any[], store?: string); /** * Set one or multiple values in context (asynchronous). * @param name - Name (or array of names) to set in context * @param value - The value (or array of values) to store in context. If the value(s) are null/undefined, the context item(s) will be removed. * @param store - (optional) Name of context store * @param callback - (optional) Callback function (`(err) => {}`) */ static set(name: string | string[], value?: any | any[], store?: string, callback?: Function); /** Get an array of the keys in the context store */ static keys(): Array<string>; /** Get an array of the keys in the context store */ static keys(store: string): Array<string>; /** Get an array of the keys in the context store */ static keys(callback: Function); /** Get an array of the keys in the context store */ static keys(store: string, callback: Function); } declare class env { /** Get an environment variable value */ static get(name:string); }
the_stack
import * as d3 from 'd3' import {SimpleEventHandler} from "../etc/SimpleEventHandler"; import {WordLine, WordLineHoverEvent} from "../vis/WordLine" import {AttentionVis, AttentionVisData} from "../vis/AttentionVis"; import {WordProjector, WordProjectorClickedEvent} from "../vis/WordProjector"; import {S2SApi, TrainDataIndexResponse} from "../api/S2SApi"; import {PanelManager} from "./PanelManager"; import { StateDesc, StateProjector, StateProjectorClickEvent, StateProjectorHoverEvent } from "../vis/StateProjector"; import {isEqual, range, indexOf, min, flatten, max} from 'lodash'; import {StatePictograms, StatePictogramsHovered} from "../vis/StatePictograms"; import {BeamTreeData, BeamTree} from "../vis/BeamTree"; import ModalDialog from "../etc/ModalDialog"; import {Translation} from "../api/Translation"; enum ComparisonMode { none, enc_diff, dec_dff } enum WordClickMode { word, attn } type ComparisonFeedBack = { in: any, compare: any, neighbors: any }; export class PanelController { private readonly eventHandler: SimpleEventHandler; private pm: PanelManager; private _current = { beamIndex: 0, inWordPos: [], outWordPos: [], inWords: [], outWords: [], allNeighbors: {}, projectedNeighbor: null, sentence: null, translations: <Translation[]>[null, null], comparison: <ComparisonMode> ComparisonMode.none, wordClickMode: WordClickMode.word, attnChange: { selected: <number>-1, changes: <{ [key: number]: number }>{}//<{ [key: number]: { [key: number]: number } }>{} } }; constructor() { this.eventHandler = new SimpleEventHandler(<Element> d3.select('body').node()); this.pm = new PanelManager(this.eventHandler); this._init(); this._bindEvents(); } _init() { } selectProjection(key) { // TODO: remove duck typing for encoder and src/tgt this.pm.setVisibilityNeighborPanels(true); this._current.projectedNeighbor = key; let labels = this._current.translations.map( translation => { if (translation == null) return []; // else: if (key.startsWith('enc')) return translation.encoderWords; else return translation.decoderWords[0]; } ); const getNeighborsFor = { 'encoder': (trans: Translation) => trans.encoder.map(d => d.neighbors.map(dd => dd[0])), 'decoder': (trans: Translation) => trans.decoder[0].map(d => d.neighbors.map(dd => dd[0])), 'context': (trans: Translation) => trans.decoder[0].map(d => d.neighbor_context.map(dd => dd[0])), }; let moreNeighbors = null; if (key in getNeighborsFor) { const getNeighbors = getNeighborsFor[key]; moreNeighbors = this._current.translations.map(translation => { if (translation == null) return []; // else: return getNeighbors(translation) } ); } this.pm.vis.projectors.update({ states: this._current.allNeighbors[key], loc: key.startsWith('enc') ? 'src' : 'tgt', labels, moreNeighbors }); this.pm.vis.statePicto.update(null); } updateProjectorData(allNeighbors) { const cur = this._current; cur.allNeighbors = allNeighbors; if (allNeighbors) { const allNeighborKeys = Object.keys(allNeighbors); if (!cur.projectedNeighbor) cur.projectedNeighbor = (allNeighborKeys.indexOf('decoder') > -1) ? 'decoder' : allNeighborKeys[0]; this.pm.panels.projectorSelect.style('display', null); this.pm.panels.loadProjectButton.style('display', 'none'); this.pm.vis.statePicto.unhideView(); this.pm.vis.projectors.unhideView(); this.pm.updateProjectionSelectField(allNeighborKeys, cur.projectedNeighbor); this.selectProjection(cur.projectedNeighbor); } else { this.pm.panels.projectorSelect.style('display', 'none'); this.pm.panels.loadProjectButton.style('display', null); this.pm.vis.statePicto.hideView(); this.pm.vis.projectors.hideView(); } } clearCompare() { this._current.translations[1] = null; this._current.comparison = ComparisonMode.none; } update(translation: Translation, main = this.pm.vis.left, extra = this.pm.vis.zero, isCompare = false) { const cur = this._current; //=== translation object with convenience functions // const translation = new Translation(raw_data); translation.filterAttention(.75); //=== update words: const enc = main.encoder_words; const dec = main.decoder_words; enc.update({wordRows: [translation.encoderWords]}); dec.update({wordRows: [translation.decoderWords[cur.beamIndex]]}); //=== update attention using measures from word lists: const attentionData: AttentionVisData = { inWidths: enc.rows[0].map(t => t.width), outWidths: dec.rows[cur.beamIndex].map(t => t.width), inPos: enc.positions[0], outPos: dec.positions[cur.beamIndex], edgeWeights: translation.attnFiltered[cur.beamIndex] }; const attn = main.attention; attn.update(attentionData); // main.encoder_states.update({ // row: translation.encoderNeighbors // }); // main.decoder_states.update({ // row: translation.decoderNeighbors[cur.beamIndex] // }); // main.context.update({ // row: translation.contextNeighbors[cur.beamIndex] // }); if (isCompare) { cur.translations[1] = translation; main.sideIndicator.classed('side_compare', true) .text('compare'); } else { cur.translations[0] = translation; main.sideIndicator.classed('side_pivot', true) .text('pivot'); // if (main == this.pm.vis.left) { this._current.sentence = translation.inputSentence; this.updateProjectorData(translation.allNeighbors); const winnerBeam = translation.decoderWords[cur.beamIndex]; const btWords: string[][][] = translation.beam_trace_words; // console.log(raw_data.beam_trace_words, "--- "); const allNodes: { [key: string]: BeamTree } = {}; //TODO: This is a terrible hack :) const withStartToken = btWords[0][0][0] === '<s>'; const root: BeamTree = { name: btWords[0][0][0], children: [] }; allNodes[btWords[0][0][0]] = root; for (const depthList of btWords.slice(withStartToken ? 1 : 0)) { for (const subBeam of depthList) { const [nodeName] = subBeam.slice(-1); const rootName = subBeam.slice(0, -1).join('||'); const nodeID = subBeam.join('||'); let topBeam = null; if (withStartToken) { topBeam = isEqual(subBeam.slice(1), winnerBeam.slice(0, subBeam.length - 1)); } else { topBeam = isEqual(subBeam.slice(0), winnerBeam.slice(0, subBeam.length)); } const node: BeamTree = { name: nodeName, children: [], topBeam }; if (!(nodeID in allNodes)) { allNodes[rootName].children.push(node); allNodes[nodeID] = node; } } } this.pm.vis.beamView.update({root, maxDepth: btWords.length}) } if ('beam' in main) { let beamWords: string[][] = []; let beamColors: string[][] = []; let beamValues: number[][] = []; const top_predict = translation.decoderWords[0]; // console.log(top_predict, "--- top_predict"); for (const j in range(translation.beam[0].length)) { const ro: string[] = []; const roCol: string[] = []; const bv: number[] = []; for (const i in translation.beam) { const w = translation.beam[i][j].word; ro.push(w); if (w === top_predict[i]) { roCol.push('#ccc2a3') } else { roCol.push(null) } bv.push(translation.beam[i][j].score) } beamWords.push(ro); beamColors.push(roCol); beamValues.push(bv); } const valBound = d3.extent(flatten(beamValues)); const cScale = d3.scaleLinear<string>().domain(valBound) .range(['#fff', '#999']); const wordFill = beamValues.map(row => row.map(value => cScale(value))) const bwScale = d3.scaleLinear().domain(valBound).range([1, main.beam.options.box_width - 10]); const boxWidth = beamValues.map(row => row.map(value => bwScale(value))) main.beam.update({ wordRows: beamWords, boxWidth, wordFill: beamColors }) } // main.encoder_extra.forEach(e => e.update(translation)); // main.decoder_extra.forEach(e => e.update(translation)); //=== setup column if (extra) { //=== helper function to const extentScores = (scores) => { const ex = <[number, number]>d3.extent(scores); if (ex[0] * ex[1] > 0) { if (ex[0] > 0) ex[0] = ex[1]; ex[1] = 0; } return ex; }; extra.decoder_words.update({ extent: extentScores(translation.scores), values: [translation.scores[cur.beamIndex]] }); // extra.decoder_extra.forEach(d => { // if ('updateOptions' in d) { // d.updateOptions({options: {xScale: extra.decoder_words.xScale}}); // d.update(translation); // } // // }) } } cleanPanels() { this.pm.closeAllRight(); this.pm.removeMediumPanel(); } updateAndShowWordProjector(data, loc) { this.pm.setVisibilityNeighborPanels(false); const wp = this.pm.getWordProjector(); console.log(data, "--- WP_data"); wp.options.loc = loc; wp.update(data); } updateAndShowWordList(data) { const wl = this.pm.getWordList(); wl.update(data); } updateProjectInfo(info) { if (!info.has_neighbors) { this.pm.panels.loadProjectButton.style('display', 'none'); } if (info.pre_cached && info.pre_cached.length>0){ this.pm.panels.loadProjectButton.remove(); this.pm.panels.loadProjectButton = d3.select('#alternativeProjectText'); this.pm.panels.loadProjectButton.style('display', 'block'); const ex = info.pre_cached.map((d)=> `<div style="padding-top: 3pt;"><a href='index.html?in=${d.in}' style="font-weight: bold;">${d.in}</a></div>`).join('\n') this.pm.panels.loadProjectButton.html('<hr> Enjoy playing with the Translation View above. ' + 'For the demo, we only support ' + 'Neighbor View for the following examples:<br>'+ex+'<hr>') } } _bindEvents() { const vis = this.pm.vis; const determinePanelType = caller => { if ((caller === vis.left.encoder_words)) //includes(vis.left.encoder_extra, caller) return { vType: AttentionVis.VERTEX_TYPE.src, col: vis.left }; else if ((caller === vis.middle.encoder_words)) return { vType: AttentionVis.VERTEX_TYPE.src, col: vis.middle }; else if ((caller === vis.middle.decoder_words)) return { vType: AttentionVis.VERTEX_TYPE.tgt, col: vis.middle }; else return { vType: AttentionVis.VERTEX_TYPE.tgt, col: vis.left }; }; const updateComparisonView = (d: ComparisonFeedBack) => { const {main, extra} = this.pm.getMediumPanel(); // console.log(d, "--- d"); this.update(new Translation(d.compare), main, null, true); this.updateProjectorData(d.neighbors); } const actionWordHovered = (d: WordLineHoverEvent) => { // console.log(d,"--- d"); // return if decoder word is fixed if (this._current.wordClickMode === WordClickMode.attn && this._current.attnChange.selected > -1) return; d.caller.actionHighlightWord(d.row, d.col, d.hovered); const {vType, col} = determinePanelType(d.caller); let transID = 0; if (col != this.pm.vis.left) { col.attention.actionHighlightEdges(d.col, vType, d.hovered); transID = 1; } this.pm.vis.left.attention.actionHighlightEdges(d.col, vType, d.hovered); const proj = this.pm.vis.projectors; const pictos = this.pm.vis.statePicto; if (proj.current.hidden === false) { if (vType === AttentionVis.VERTEX_TYPE.src && proj.loc === 'src') { proj.actionHoverPivot(transID, d.col, d.hovered); pictos.actionHighlightSegment(transID, d.col, d.hovered); } else if (vType === AttentionVis.VERTEX_TYPE.tgt && proj.loc === 'tgt') { proj.actionHoverPivot(transID, d.col, d.hovered); pictos.actionHighlightSegment(transID, d.col, d.hovered); } } }; this.eventHandler.bind(WordLine.events.wordHovered, actionWordHovered); const openWordCloud = ({input, loc, limit, allWords, replaceIndex}) => { this.cleanPanels(); S2SApi.closeWords({input, loc, limit}) .then(data => { const word_data = JSON.parse(data); // this.updateAndShowWordProjector(word_data); // if (loc === 'src') { // const pivot = allWords.join(' '); // // const compare = word_data.word.map(wd => { // return allWords.map((aw, wi) => // (wi === replaceIndex) ? wd : aw).join(' '); // }) // // S2SApi.compareTranslation({pivot, compare}) // .then(data => { // word_data["compare"] = JSON.parse(data)["compare"]; // // this.updateAndShowWordList(word_data); // this.updateAndShowWordProjector(word_data); // }) // // } else { // this.updateAndShowWordList(word_data); if (loc === 'src') { word_data.compare = word_data.word.map(wd => { return { orig: allWords.map((aw, wi) => (wi === replaceIndex) ? wd : aw).join(' ') }; }) // word_data.compare = {orig: } } else { word_data.compare = word_data.word.map(wd => { return { orig: allWords.map((aw, wi) => (wi === replaceIndex) ? wd : (wi < replaceIndex) ? aw : '').join(' ').trim() }; }) } this.updateAndShowWordProjector(word_data, loc); // } }) .catch(error => console.log(error, "--- error")); } this.eventHandler.bind(WordLine.events.wordSelected, (d: WordLineHoverEvent, e) => { if (d.caller === vis.left.encoder_words || d.caller === vis.left.decoder_words) { let loc = 'src'; let vType = AttentionVis.VERTEX_TYPE.src; if (d.caller === vis.left.decoder_words) { loc = 'tgt'; vType = AttentionVis.VERTEX_TYPE.tgt; } if (this._current.wordClickMode === WordClickMode.word) { d.caller.actionHighlightWord(d.row, d.col, d.hovered, true, 'selected'); openWordCloud({ input: d.word.word.text, loc, limit: 20, allWords: d.caller.firstRowPlainWords, replaceIndex: d.col }) } else if (this._current.wordClickMode === WordClickMode.attn) { const aChg = this._current.attnChange; if (loc === 'tgt') { if (aChg.selected != d.col) { aChg.selected = d.col; d.caller.actionHighlightWord(d.row, d.col, true, true, 'selected'); this.pm.vis.left.attention .actionHighlightEdges(d.col, vType, true, 'highlight'); } else { aChg.selected = -1; d.caller.actionHighlightWord(d.row, d.col, false, true, 'selected'); this.pm.vis.left.attention .actionHighlightEdges(d.col, vType, false, 'highlight'); } } if (loc === 'src') { if (aChg.selected > -1) { const a = this._current.translations[0] .setAttn(aChg.selected, d.col); aChg.changes[aChg.selected] = indexOf(a, max(a)); this.pm.panels.wordMode.attnApplyBtn.style('display', null); console.log(a, aChg.selected, d.col, "--- a, aChg.selected, d.col"); this.update(this._current.translations[0]); this.pm.vis.left.decoder_words.actionHighlightWord(0, aChg.selected, true, true, 'selected'); this.pm.vis.left.attention .actionHighlightEdges(aChg.selected, AttentionVis.VERTEX_TYPE.tgt, true, 'highlight'); } else { alert('Please select a decoder word first. ' + 'Then you can increase respective weights by clicking on encoder'); } } } } else if (d.caller === vis.left.beam) { const partialDec = this._current.translations[0] .decoderWords[0].slice(0, d.col).join(' ') + ' ' + d.word.word.text; this.pm.closeAllRight(); S2SApi.translate( { input: this._current.translations[0].inputSentence, partial: [partialDec], neighbors: [] }).then(data => { data = JSON.parse(data); console.log(data, "--- data"); this.update(new Translation(data)); actionWordHovered(d); }) // .map((w, i) => (i === d.col) ? d.word.word.text : w) } }); this.pm.panels.wordMode.attnApplyBtn.on('click', () => { this.pm.panels.wordMode.attnApplyBtn.style('display', 'none'); const minIndex = min(Object.keys(this._current.attnChange.changes).map(d => +d)); const partialDec = this._current.translations[0] .decoderWords[0].slice(0, minIndex).join(' ') S2SApi.translate( { input: this._current.translations[0].inputSentence, partial: [partialDec], neighbors: [], force_attn: this._current.attnChange.changes }).then(data => { data = JSON.parse(data); console.log(data, "--- data"); this.update(new Translation(data)); }) }); this.eventHandler.bind(WordProjector.events.wordClicked, (d: WordProjectorClickedEvent) => { d.caller.highlightWord(d.word, true, true, 'selected'); const loc = d.caller.options.loc; if (loc === 'src') { S2SApi.translate_compare({ input: this._current.sentence, compare: d.sentence, neighbors: [] }).then(data => { // TODO: ENC / DEC difference !!! this._current.comparison = ComparisonMode.enc_diff; data = <ComparisonFeedBack>JSON.parse(data); updateComparisonView(data) }) } else { S2SApi.translate({ input: this._current.sentence, // compare: d.sentence, partial: [d.sentence], neighbors: [] }).then(data => { // TODO: ENC / DEC difference !!! this._current.comparison = ComparisonMode.none; data = new Translation(JSON.parse(data)); this.update(data) }) } }); this.eventHandler.bind(StateProjector.events.clicked, (d: StateProjectorClickEvent) => { d.caller.actionSelectPoints(d.pointIDs); S2SApi.trainDataIndices(d.neighborIDs, d.loc).then(data => { const raw_data = <TrainDataIndexResponse> JSON.parse(data); this.pm.getInfoPanel().update({ translations: raw_data.res.map(d => ({ src: d.src_words, tgt: d.tgt_words })), highlights: { loc: raw_data.loc, indices: raw_data.res.map(d => d.tokenId) } }); }) }) const projectHovered = (loc: string, transID: number, wordID: number, hovered: boolean) => { const panels = [this.pm.vis.left, this.pm.vis.middle]; let vType = AttentionVis.VERTEX_TYPE.src; const visRoot = panels[transID]; if (loc === 'src') { visRoot.encoder_words.actionHighlightWord(0, wordID, hovered) } else { vType = AttentionVis.VERTEX_TYPE.tgt; visRoot.decoder_words.actionHighlightWord(0, wordID, hovered) } for (const tID in range(transID + 1)) { const visRoot = panels[tID]; visRoot.attention.actionHighlightEdges(wordID, vType, hovered); } // shouldn't happen when views are hidden: this.pm.vis.projectors.actionHoverPivot(transID, wordID, hovered); this.pm.vis.statePicto.actionHighlightSegment(transID, wordID, hovered) } this.eventHandler.bind(StateProjector.events.hovered, (d: StateProjectorHoverEvent) => { projectHovered(d.loc, d.transID, d.wordID, d.hovered); }); this.eventHandler.bind(StatePictograms.events.segmentHovered, (d: StatePictogramsHovered) => { const seg = d.segment; projectHovered(seg.loc, seg.transID, seg.wordID, d.hovered); this.pm.vis.projectors .actionHoverRegion([{ x: seg.x, y: seg.y, h: seg.oh, w: seg.ow }], d.hovered) } ) this.pm.panels.loadProjectButton.on('click', () => { this.pm.panels.loadProjectSpinner.style('display', 'inline'); if (this._current.comparison === ComparisonMode.enc_diff) { // then we are in compare mode S2SApi.translate_compare({ input: this._current.translations[0].inputSentence, compare: this._current.translations[1].inputSentence }).then(data => { // TODO: ENC / DEC difference !!! this.cleanPanels(); this._current.comparison = ComparisonMode.enc_diff; data = <ComparisonFeedBack>JSON.parse(data); this.pm.panels.loadProjectSpinner.style('display', 'none'); this.update(new Translation(data.in)); updateComparisonView(data) }) } else if (this._current.comparison === ComparisonMode.none) { // here in single mode S2SApi.translate({input: this._current.sentence}) .then((data: string) => { this.cleanPanels(); const raw_data = JSON.parse(data); console.log(raw_data, "--- raw_data"); this.pm.panels.loadProjectSpinner.style('display', 'none'); this.update(new Translation(raw_data)); }) } }) this.pm.panels.projectorSelect .on('change', () => { const v = this.pm.panels.projectorSelect.property('value'); this.selectProjection(v); }); const ec = this.pm.panels.enterComparison; ec.btn.on('click', () => { const t = this._current.translations[0]; ModalDialog.open(ec.dialog, this.eventHandler, 400); ec.enc.property('value', t.inputSentence); ec.dec.property('value', t.decoderWords[0].join(' ')); }) ec.encBtn.on('click', () => { const inSentence = ec.enc.property('value').trim(); S2SApi.translate_compare({ input: this._current.sentence, compare: inSentence, neighbors: [] }).then(data => { // TODO: ENC / DEC difference !!! this._current.comparison = ComparisonMode.enc_diff; data = <ComparisonFeedBack>JSON.parse(data); updateComparisonView(data) }) ModalDialog.close(ec.dialog); }) ec.decBtn.on('click', () => { const inSentence = (<string> ec.dec.property('value')).trim(); S2SApi.translate( { input: this._current.translations[0].inputSentence, partial: [inSentence], neighbors: [] }).then(data => { this._current.comparison = ComparisonMode.enc_diff; data = JSON.parse(data); // TODO: make nice and work with updateCOmparisonVoew const {main, extra} = this.pm.getMediumPanel(); this.update(new Translation(data), main, null, true); // this.updateProjectorData(data.neighbors); }) ModalDialog.close(ec.dialog); }) this.pm.panels.swapBtn.on('click', () => { if (!this._current.translations[1]) return; const comp = this._current.translations[1]; const pivot = this._current.translations[0]; this.update(comp); const {main, extra} = this.pm.getMediumPanel(); this.update(pivot, main, null, true); }); this.pm.panels.wordMode.attnBtn.on('click', () => { this.pm.panels.wordMode.attnBtn.classed('selected', true); this.pm.panels.wordMode.wordBtn.classed('selected', false); this._current.wordClickMode = WordClickMode.attn }); this.pm.panels.wordMode.wordBtn.on('click', () => { this.pm.panels.wordMode.attnBtn.classed('selected', false); this.pm.panels.wordMode.wordBtn.classed('selected', true); this._current.wordClickMode = WordClickMode.word }); } }
the_stack
import * as path from "path"; import * as shell from "shelljs"; import * as _ from "lodash"; import * as constants from "../constants"; import * as semver from "semver"; import * as projectServiceBaseLib from "./platform-project-service-base"; import { DeviceAndroidDebugBridge } from "../common/mobile/android/device-android-debug-bridge"; import { Configurations, LiveSyncPaths } from "../common/constants"; import { hook } from "../common/helpers"; import { performanceLog } from ".././common/decorators"; import { IProjectData, IProjectDataService, IValidatePlatformOutput, } from "../definitions/project"; import { IPlatformData, IBuildOutputOptions, IPlatformEnvironmentRequirements, IValidBuildOutputData, } from "../definitions/platform"; import { IAndroidToolsInfo, IAndroidResourcesMigrationService, IOptions, IDependencyData, } from "../declarations"; import { IAndroidBuildData } from "../definitions/build"; import { IPluginData } from "../definitions/plugins"; import { IErrors, IFileSystem, IAnalyticsService, IDictionary, IRelease, ISpawnResult, } from "../common/declarations"; import { IAndroidPluginBuildService, IPluginBuildOptions, } from "../definitions/android-plugin-migrator"; import { IFilesHashService } from "../definitions/files-hash-service"; import { IGradleCommandService, IGradleBuildService, } from "../definitions/gradle"; import { IInjector } from "../common/definitions/yok"; import { injector } from "../common/yok"; import { INotConfiguredEnvOptions } from "../common/definitions/commands"; export class AndroidProjectService extends projectServiceBaseLib.PlatformProjectServiceBase { private static VALUES_DIRNAME = "values"; private static VALUES_VERSION_DIRNAME_PREFIX = AndroidProjectService.VALUES_DIRNAME + "-v"; private static ANDROID_PLATFORM_NAME = "android"; private static MIN_RUNTIME_VERSION_WITH_GRADLE = "1.5.0"; constructor( private $androidToolsInfo: IAndroidToolsInfo, private $errors: IErrors, $fs: IFileSystem, private $logger: ILogger, $projectDataService: IProjectDataService, private $injector: IInjector, private $devicePlatformsConstants: Mobile.IDevicePlatformsConstants, private $androidPluginBuildService: IAndroidPluginBuildService, private $platformEnvironmentRequirements: IPlatformEnvironmentRequirements, private $androidResourcesMigrationService: IAndroidResourcesMigrationService, private $filesHashService: IFilesHashService, private $gradleCommandService: IGradleCommandService, private $gradleBuildService: IGradleBuildService, private $analyticsService: IAnalyticsService ) { super($fs, $projectDataService); } private _platformData: IPlatformData = null; public getPlatformData(projectData: IProjectData): IPlatformData { if (!projectData && !this._platformData) { throw new Error( "First call of getPlatformData without providing projectData." ); } if (projectData && projectData.platformsDir) { const projectRoot = path.join( projectData.platformsDir, AndroidProjectService.ANDROID_PLATFORM_NAME ); const appDestinationDirectoryArr = [ projectRoot, constants.APP_FOLDER_NAME, constants.SRC_DIR, constants.MAIN_DIR, constants.ASSETS_DIR, ]; const configurationsDirectoryArr = [ projectRoot, constants.APP_FOLDER_NAME, constants.SRC_DIR, constants.MAIN_DIR, constants.MANIFEST_FILE_NAME, ]; const deviceBuildOutputArr = [ projectRoot, constants.APP_FOLDER_NAME, constants.BUILD_DIR, constants.OUTPUTS_DIR, constants.APK_DIR, ]; const packageName = this.getProjectNameFromId(projectData); const runtimePackage = this.$projectDataService.getRuntimePackage( projectData.projectDir, constants.PlatformTypes.android ); this._platformData = { frameworkPackageName: runtimePackage.name, normalizedPlatformName: "Android", platformNameLowerCase: "android", appDestinationDirectoryPath: path.join(...appDestinationDirectoryArr), platformProjectService: <any>this, projectRoot: projectRoot, getBuildOutputPath: (buildOptions: IBuildOutputOptions) => { if (buildOptions.androidBundle) { return path.join( projectRoot, constants.APP_FOLDER_NAME, constants.BUILD_DIR, constants.OUTPUTS_DIR, constants.BUNDLE_DIR ); } return path.join(...deviceBuildOutputArr); }, getValidBuildOutputData: ( buildOptions: IBuildOutputOptions ): IValidBuildOutputData => { const buildMode = buildOptions.release ? Configurations.Release.toLowerCase() : Configurations.Debug.toLowerCase(); if (buildOptions.androidBundle) { return { packageNames: [ `${constants.APP_FOLDER_NAME}${constants.AAB_EXTENSION_NAME}`, `${constants.APP_FOLDER_NAME}-${buildMode}${constants.AAB_EXTENSION_NAME}`, ], }; } return { packageNames: [ `${packageName}-${buildMode}${constants.APK_EXTENSION_NAME}`, `${projectData.projectName}-${buildMode}${constants.APK_EXTENSION_NAME}`, `${projectData.projectName}${constants.APK_EXTENSION_NAME}`, `${constants.APP_FOLDER_NAME}-${buildMode}${constants.APK_EXTENSION_NAME}`, ], regexes: [ new RegExp( `${constants.APP_FOLDER_NAME}-.*-(${Configurations.Debug}|${Configurations.Release})${constants.APK_EXTENSION_NAME}`, "i" ), new RegExp( `${packageName}-.*-(${Configurations.Debug}|${Configurations.Release})${constants.APK_EXTENSION_NAME}`, "i" ), ], }; }, configurationFileName: constants.MANIFEST_FILE_NAME, configurationFilePath: path.join(...configurationsDirectoryArr), relativeToFrameworkConfigurationFilePath: path.join( constants.SRC_DIR, constants.MAIN_DIR, constants.MANIFEST_FILE_NAME ), fastLivesyncFileExtensions: [".jpg", ".gif", ".png", ".bmp", ".webp"], // http://developer.android.com/guide/appendix/media-formats.html }; } return this._platformData; } public getCurrentPlatformVersion( platformData: IPlatformData, projectData: IProjectData ): string { const currentPlatformData: IDictionary<any> = this.$projectDataService.getRuntimePackage( projectData.projectDir, <constants.PlatformTypes>platformData.platformNameLowerCase ); return currentPlatformData && currentPlatformData[constants.VERSION_STRING]; } public async validateOptions(): Promise<boolean> { return true; } public getAppResourcesDestinationDirectoryPath( projectData: IProjectData ): string { const appResourcesDirStructureHasMigrated = this.$androidResourcesMigrationService.hasMigrated( projectData.getAppResourcesDirectoryPath() ); if (appResourcesDirStructureHasMigrated) { return this.getUpdatedAppResourcesDestinationDirPath(projectData); } else { return this.getLegacyAppResourcesDestinationDirPath(projectData); } } public async validate( projectData: IProjectData, options: IOptions, notConfiguredEnvOptions?: INotConfiguredEnvOptions ): Promise<IValidatePlatformOutput> { this.validatePackageName(projectData.projectIdentifiers.android); this.validateProjectName(projectData.projectName); const checkEnvironmentRequirementsOutput = await this.$platformEnvironmentRequirements.checkEnvironmentRequirements( { platform: this.getPlatformData(projectData).normalizedPlatformName, projectDir: projectData.projectDir, options, notConfiguredEnvOptions, } ); this.$androidToolsInfo.validateTargetSdk({ showWarningsAsErrors: true, projectDir: projectData.projectDir, }); return { checkEnvironmentRequirementsOutput, }; } public async createProject( frameworkDir: string, frameworkVersion: string, projectData: IProjectData ): Promise<void> { if ( semver.lt( frameworkVersion, AndroidProjectService.MIN_RUNTIME_VERSION_WITH_GRADLE ) ) { this.$errors.fail( `The NativeScript CLI requires Android runtime ${AndroidProjectService.MIN_RUNTIME_VERSION_WITH_GRADLE} or later to work properly.` ); } this.$fs.ensureDirectoryExists( this.getPlatformData(projectData).projectRoot ); const androidToolsInfo = this.$androidToolsInfo.getToolsInfo({ projectDir: projectData.projectDir, }); const targetSdkVersion = androidToolsInfo && androidToolsInfo.targetSdkVersion; this.$logger.trace(`Using Android SDK '${targetSdkVersion}'.`); this.copy( this.getPlatformData(projectData).projectRoot, frameworkDir, "*", "-R" ); // TODO: Check if we actually need this and if it should be targetSdk or compileSdk this.cleanResValues(targetSdkVersion, projectData); } private getResDestinationDir(projectData: IProjectData): string { const appResourcesDirStructureHasMigrated = this.$androidResourcesMigrationService.hasMigrated( projectData.getAppResourcesDirectoryPath() ); if (appResourcesDirStructureHasMigrated) { const appResourcesDestinationPath = this.getUpdatedAppResourcesDestinationDirPath( projectData ); return path.join( appResourcesDestinationPath, constants.MAIN_DIR, constants.RESOURCES_DIR ); } else { return this.getLegacyAppResourcesDestinationDirPath(projectData); } } private cleanResValues( targetSdkVersion: number, projectData: IProjectData ): void { const resDestinationDir = this.getResDestinationDir(projectData); const directoriesInResFolder = this.$fs.readDirectory(resDestinationDir); const directoriesToClean = directoriesInResFolder .map((dir) => { return { dirName: dir, sdkNum: parseInt( dir.substr( AndroidProjectService.VALUES_VERSION_DIRNAME_PREFIX.length ) ), }; }) .filter( (dir) => dir.dirName.match( AndroidProjectService.VALUES_VERSION_DIRNAME_PREFIX ) && dir.sdkNum && (!targetSdkVersion || targetSdkVersion < dir.sdkNum) ) .map((dir) => path.join(resDestinationDir, dir.dirName)); this.$logger.trace("Directories to clean:"); this.$logger.trace(directoriesToClean); _.map(directoriesToClean, (dir) => this.$fs.deleteDirectory(dir)); } public async interpolateData(projectData: IProjectData): Promise<void> { // Interpolate the apilevel and package this.interpolateConfigurationFile(projectData); const appResourcesDirectoryPath = projectData.getAppResourcesDirectoryPath(); let stringsFilePath: string; const appResourcesDestinationDirectoryPath = this.getAppResourcesDestinationDirectoryPath( projectData ); if ( this.$androidResourcesMigrationService.hasMigrated( appResourcesDirectoryPath ) ) { stringsFilePath = path.join( appResourcesDestinationDirectoryPath, constants.MAIN_DIR, constants.RESOURCES_DIR, "values", "strings.xml" ); } else { stringsFilePath = path.join( appResourcesDestinationDirectoryPath, "values", "strings.xml" ); } shell.sed("-i", /__NAME__/, projectData.projectName, stringsFilePath); shell.sed( "-i", /__TITLE_ACTIVITY__/, projectData.projectName, stringsFilePath ); const gradleSettingsFilePath = path.join( this.getPlatformData(projectData).projectRoot, "settings.gradle" ); shell.sed( "-i", /__PROJECT_NAME__/, this.getProjectNameFromId(projectData), gradleSettingsFilePath ); try { // will replace applicationId in app/App_Resources/Android/app.gradle if it has not been edited by the user const appGradleContent = this.$fs.readText(projectData.appGradlePath); if (appGradleContent.indexOf(constants.PACKAGE_PLACEHOLDER_NAME) !== -1) { //TODO: For compatibility with old templates. Once all templates are updated should delete. shell.sed( "-i", new RegExp(constants.PACKAGE_PLACEHOLDER_NAME), projectData.projectIdentifiers.android, projectData.appGradlePath ); } } catch (e) { this.$logger.trace( `Templates updated and no need for replace in app.gradle.` ); } } public interpolateConfigurationFile(projectData: IProjectData): void { const manifestPath = this.getPlatformData(projectData) .configurationFilePath; shell.sed( "-i", /__PACKAGE__/, projectData.projectIdentifiers.android, manifestPath ); } private getProjectNameFromId(projectData: IProjectData): string { let id: string; if ( projectData && projectData.projectIdentifiers && projectData.projectIdentifiers.android ) { const idParts = projectData.projectIdentifiers.android.split("."); id = idParts[idParts.length - 1]; } return id; } public afterCreateProject(projectRoot: string): void { return null; } public async updatePlatform( currentVersion: string, newVersion: string, canUpdate: boolean, projectData: IProjectData, addPlatform?: Function, removePlatforms?: (platforms: string[]) => Promise<void> ): Promise<boolean> { if ( semver.eq( newVersion, AndroidProjectService.MIN_RUNTIME_VERSION_WITH_GRADLE ) ) { const platformLowercase = this.getPlatformData( projectData ).normalizedPlatformName.toLowerCase(); await removePlatforms([platformLowercase.split("@")[0]]); await addPlatform(platformLowercase); return false; } return true; } @performanceLog() @hook("buildAndroid") public async buildProject( projectRoot: string, projectData: IProjectData, buildData: IAndroidBuildData ): Promise<void> { const platformData = this.getPlatformData(projectData); await this.$gradleBuildService.buildProject( platformData.projectRoot, buildData ); const outputPath = platformData.getBuildOutputPath(buildData); await this.$filesHashService.saveHashesForProject( this._platformData, outputPath ); await this.trackKotlinUsage(projectRoot); } public async buildForDeploy( projectRoot: string, projectData: IProjectData, buildData?: IAndroidBuildData ): Promise<void> { return this.buildProject(projectRoot, projectData, buildData); } public isPlatformPrepared( projectRoot: string, projectData: IProjectData ): boolean { return this.$fs.exists( path.join( this.getPlatformData(projectData).appDestinationDirectoryPath, constants.APP_FOLDER_NAME ) ); } public getFrameworkFilesExtensions(): string[] { return [".jar", ".dat"]; } public async prepareProject(): Promise<void> { // Intentionally left empty. } public ensureConfigurationFileInAppResources( projectData: IProjectData ): void { const appResourcesDirectoryPath = projectData.appResourcesDirectoryPath; const appResourcesDirStructureHasMigrated = this.$androidResourcesMigrationService.hasMigrated( appResourcesDirectoryPath ); let originalAndroidManifestFilePath; if (appResourcesDirStructureHasMigrated) { originalAndroidManifestFilePath = path.join( appResourcesDirectoryPath, this.$devicePlatformsConstants.Android, "src", "main", this.getPlatformData(projectData).configurationFileName ); } else { originalAndroidManifestFilePath = path.join( appResourcesDirectoryPath, this.$devicePlatformsConstants.Android, this.getPlatformData(projectData).configurationFileName ); } const manifestExists = this.$fs.exists(originalAndroidManifestFilePath); if (!manifestExists) { this.$logger.warn( "No manifest found in " + originalAndroidManifestFilePath ); return; } // Overwrite the AndroidManifest from runtime. if (!appResourcesDirStructureHasMigrated) { this.$fs.copyFile( originalAndroidManifestFilePath, this.getPlatformData(projectData).configurationFilePath ); } } public prepareAppResources(projectData: IProjectData): void { const platformData = this.getPlatformData(projectData); const projectAppResourcesPath = projectData.getAppResourcesDirectoryPath( projectData.projectDir ); const platformsAppResourcesPath = this.getAppResourcesDestinationDirectoryPath( projectData ); this.cleanUpPreparedResources(projectData); this.$fs.ensureDirectoryExists(platformsAppResourcesPath); const appResourcesDirStructureHasMigrated = this.$androidResourcesMigrationService.hasMigrated( projectAppResourcesPath ); if (appResourcesDirStructureHasMigrated) { this.$fs.copyFile( path.join( projectAppResourcesPath, platformData.normalizedPlatformName, constants.SRC_DIR, "*" ), platformsAppResourcesPath ); } else { this.$fs.copyFile( path.join( projectAppResourcesPath, platformData.normalizedPlatformName, "*" ), platformsAppResourcesPath ); // https://github.com/NativeScript/android-runtime/issues/899 // App_Resources/Android/libs is reserved to user's aars and jars, but they should not be copied as resources this.$fs.deleteDirectory(path.join(platformsAppResourcesPath, "libs")); } const androidToolsInfo = this.$androidToolsInfo.getToolsInfo({ projectDir: projectData.projectDir, }); const compileSdkVersion = androidToolsInfo && androidToolsInfo.compileSdkVersion; this.cleanResValues(compileSdkVersion, projectData); } public async preparePluginNativeCode( pluginData: IPluginData, projectData: IProjectData ): Promise<void> { // build Android plugins which contain AndroidManifest.xml and/or resources const pluginPlatformsFolderPath = this.getPluginPlatformsFolderPath( pluginData, AndroidProjectService.ANDROID_PLATFORM_NAME ); if (this.$fs.exists(pluginPlatformsFolderPath)) { const options: IPluginBuildOptions = { projectDir: projectData.projectDir, pluginName: pluginData.name, platformsAndroidDirPath: pluginPlatformsFolderPath, aarOutputDir: pluginPlatformsFolderPath, tempPluginDirPath: path.join(projectData.platformsDir, "tempPlugin"), }; if (await this.$androidPluginBuildService.buildAar(options)) { this.$logger.info(`Built aar for ${options.pluginName}`); } this.$androidPluginBuildService.migrateIncludeGradle(options); } } public async processConfigurationFilesFromAppResources(): Promise<void> { return; } public async removePluginNativeCode( pluginData: IPluginData, projectData: IProjectData ): Promise<void> { // not implemented } public async beforePrepareAllPlugins( projectData: IProjectData, dependencies?: IDependencyData[] ): Promise<void> { if (dependencies) { dependencies = this.filterUniqueDependencies(dependencies); this.provideDependenciesJson(projectData, dependencies); } } public async handleNativeDependenciesChange( projectData: IProjectData, opts: IRelease ): Promise<void> { return; } private filterUniqueDependencies( dependencies: IDependencyData[] ): IDependencyData[] { const depsDictionary = dependencies.reduce((dict, dep) => { const collision = dict[dep.name]; // in case there are multiple dependencies to the same module, the one declared in the package.json takes precedence if (!collision || collision.depth > dep.depth) { dict[dep.name] = dep; } return dict; }, <IDictionary<IDependencyData>>{}); return _.values(depsDictionary); } private provideDependenciesJson( projectData: IProjectData, dependencies: IDependencyData[] ): void { const platformDir = path.join( projectData.platformsDir, AndroidProjectService.ANDROID_PLATFORM_NAME ); const dependenciesJsonPath = path.join( platformDir, constants.DEPENDENCIES_JSON_NAME ); const nativeDependencies = dependencies .filter(AndroidProjectService.isNativeAndroidDependency) .map(({ name, directory }) => ({ name, directory: path.relative(platformDir, directory), })); const jsonContent = JSON.stringify(nativeDependencies, null, 4); this.$fs.writeFile(dependenciesJsonPath, jsonContent); } private static isNativeAndroidDependency({ nativescript, }: IDependencyData): boolean { return ( nativescript && (nativescript.android || (nativescript.platforms && nativescript.platforms.android)) ); } public async stopServices(projectRoot: string): Promise<ISpawnResult> { const result = await this.$gradleCommandService.executeCommand( ["--stop", "--quiet"], { cwd: projectRoot, message: "Gradle stop services...", stdio: "pipe", } ); return result; } public async cleanProject(projectRoot: string): Promise<void> { await this.$gradleBuildService.cleanProject(projectRoot, <any>{ release: false, }); } public async cleanDeviceTempFolder( deviceIdentifier: string, projectData: IProjectData ): Promise<void> { const adb = this.$injector.resolve(DeviceAndroidDebugBridge, { identifier: deviceIdentifier, }); const deviceRootPath = `${LiveSyncPaths.ANDROID_TMP_DIR_NAME}/${projectData.projectIdentifiers.android}`; await adb.executeShellCommand(["rm", "-rf", deviceRootPath]); } public async checkForChanges(): Promise<void> { // Nothing android specific to check yet. } public getDeploymentTarget(projectData: IProjectData): semver.SemVer { return; } private copy( projectRoot: string, frameworkDir: string, files: string, cpArg: string ): void { const paths = files.split(" ").map((p) => path.join(frameworkDir, p)); shell.cp(cpArg, paths, projectRoot); } private validatePackageName(packageName: string): void { //Make the package conform to Java package types //Enforce underscore limitation if (!/^[a-zA-Z]+(\.[a-zA-Z0-9][a-zA-Z0-9_]*)+$/.test(packageName)) { this.$errors.fail( `Package name must look like: com.company.Name. Got: ${packageName}` ); } //Class is a reserved word if (/\b[Cc]lass\b/.test(packageName)) { this.$errors.fail("class is a reserved word"); } } private validateProjectName(projectName: string): void { if (projectName === "") { this.$errors.fail("Project name cannot be empty"); } //Classes in Java don't begin with numbers if (/^[0-9]/.test(projectName)) { this.$errors.fail("Project name must not begin with a number"); } } private getLegacyAppResourcesDestinationDirPath( projectData: IProjectData ): string { const resourcePath: string[] = [ constants.APP_FOLDER_NAME, constants.SRC_DIR, constants.MAIN_DIR, constants.RESOURCES_DIR, ]; return path.join( this.getPlatformData(projectData).projectRoot, ...resourcePath ); } private getUpdatedAppResourcesDestinationDirPath( projectData: IProjectData ): string { const resourcePath: string[] = [ constants.APP_FOLDER_NAME, constants.SRC_DIR, ]; return path.join( this.getPlatformData(projectData).projectRoot, ...resourcePath ); } /** * The purpose of this method is to delete the previously prepared user resources. * The content of the `<platforms>/android/.../res` directory is based on user's resources and gradle project template from android-runtime. * During preparation of the `<path to user's App_Resources>/Android` we want to clean all the users files from previous preparation, * but keep the ones that were introduced during `platform add` of the android-runtime. * Currently the Gradle project template contains resources only in values and values-v21 directories. * So the current logic of the method is cleaning al resources from `<platforms>/android/.../res` that are not in `values.*` directories * and that exist in the `<path to user's App_Resources>/Android/.../res` directory * This means that if user has a resource file in values-v29 for example, builds the project and then deletes this resource, * it will be kept in platforms directory. Reference issue: `https://github.com/NativeScript/nativescript-cli/issues/5083` * Same is valid for files in `drawable-<resolution>` directories - in case in user's resources there's drawable-hdpi directory, * which is deleted after the first build of app, it will remain in platforms directory. */ private cleanUpPreparedResources(projectData: IProjectData): void { let resourcesDirPath = path.join( projectData.appResourcesDirectoryPath, this.getPlatformData(projectData).normalizedPlatformName ); if ( this.$androidResourcesMigrationService.hasMigrated( projectData.appResourcesDirectoryPath ) ) { resourcesDirPath = path.join( resourcesDirPath, constants.SRC_DIR, constants.MAIN_DIR, constants.RESOURCES_DIR ); } const valuesDirRegExp = /^values/; if (this.$fs.exists(resourcesDirPath)) { const resourcesDirs = this.$fs .readDirectory(resourcesDirPath) .filter((resDir) => !resDir.match(valuesDirRegExp)); const resDestinationDir = this.getResDestinationDir(projectData); _.each(resourcesDirs, (currentResource) => { this.$fs.deleteDirectory(path.join(resDestinationDir, currentResource)); }); } } private async trackKotlinUsage(projectRoot: string): Promise<void> { const buildStatistics = this.tryGetAndroidBuildStatistics(projectRoot); try { if (buildStatistics && buildStatistics.kotlinUsage) { const analyticsDelimiter = constants.AnalyticsEventLabelDelimiter; const hasUseKotlinPropertyInAppData = `hasUseKotlinPropertyInApp${analyticsDelimiter}${buildStatistics.kotlinUsage.hasUseKotlinPropertyInApp}`; const hasKotlinRuntimeClassesData = `hasKotlinRuntimeClasses${analyticsDelimiter}${buildStatistics.kotlinUsage.hasKotlinRuntimeClasses}`; await this.$analyticsService.trackEventActionInGoogleAnalytics({ action: constants.TrackActionNames.UsingKotlin, additionalData: `${hasUseKotlinPropertyInAppData}${analyticsDelimiter}${hasKotlinRuntimeClassesData}`, }); } } catch (e) { this.$logger.trace( `Failed to track android build statistics. Error is: ${e.message}` ); } } private tryGetAndroidBuildStatistics(projectRoot: string): any { const staticsFilePath = path.join( projectRoot, constants.ANDROID_ANALYTICS_DATA_DIR, constants.ANDROID_ANALYTICS_DATA_FILE ); let buildStatistics; if (this.$fs.exists(staticsFilePath)) { try { buildStatistics = this.$fs.readJson(staticsFilePath); } catch (e) { this.$logger.trace( `Unable to read android build statistics file. Error is ${e.message}` ); } } return buildStatistics; } } injector.register("androidProjectService", AndroidProjectService);
the_stack
import { DeleteObjectCommand, DeleteObjectsCommand, GetObjectCommand, ListObjectsV2Command, S3Client, } from "@aws-sdk/client-s3"; import { getSignedUrl } from "@aws-sdk/s3-request-presigner"; import { Drive } from "@prisma/client"; import { cryptoHexEncodedHash256, cryptoMd5Method, signRequest } from "@util/helpers/s3-helpers"; import { DriveFile, DriveFolder, UploadingFile } from "@util/types"; import Evaporate from "evaporate"; import mime from "mime-types"; import { nanoid } from "nanoid"; import { createContext, useContext, useEffect, useState } from "react"; import toast from "react-hot-toast"; import { ContextValue, ROOT_FOLDER } from "./useBucket"; import useUser from "./useUser"; const S3Context = createContext<ContextValue>(null); export default () => useContext(S3Context); type Props = { data: Drive & { keys: any }; fullPath?: string; }; export const S3Provider: React.FC<Props> = ({ data, fullPath, children }) => { const [s3Client, setS3Client] = useState<S3Client>( new S3Client({ region: data.keys.region, maxAttempts: 1, credentials: { accessKeyId: data.keys.accessKey, secretAccessKey: data.keys.secretKey }, }) ); const [loading, setLoading] = useState(false); const { user } = useUser(); const [currentFolder, setCurrentFolder] = useState<DriveFolder>(null); const [folders, setFolders] = useState<DriveFolder[]>(null); const [uploadingFiles, setUploadingFiles] = useState<UploadingFile[]>([]); const [files, setFiles] = useState<DriveFile[]>(null); const addFolder = (name: string) => { const path = currentFolder.fullPath !== "" ? decodeURIComponent(currentFolder.fullPath) + name + "/" : name + "/"; const newFolder: DriveFolder = { name, fullPath: path, parent: currentFolder.fullPath, createdAt: new Date().toISOString(), bucketName: data.keys.Bucket, bucketUrl: `https://${data.keys.Bucket}.s3.${data.keys.region}.amazonaws.com`, }; setFolders((folders) => [...folders, newFolder]); const localFolders = localStorage.getItem(`local_folders_${data.id}`); const folders: DriveFolder[] = localFolders ? JSON.parse(localFolders) : []; localStorage.setItem(`local_folders_${data.id}`, JSON.stringify([...folders, newFolder])); }; const removeFolder = async (folder: DriveFolder) => { // remove from local state setFolders((folders) => folders.filter((f) => f.fullPath !== folder.fullPath)); // delete from localStorage const localFolders = localStorage.getItem(`local_folders_${data.id}`); if (localFolders) { const folders = JSON.parse(localFolders); const filtered = folders.filter((f) => !f.fullPath.includes(folder.fullPath)); localStorage.setItem(`local_folders_${data.id}`, JSON.stringify(filtered)); } // recursively delete children await emptyS3Directory(s3Client, folder.bucketName, folder.fullPath); }; const addFile = async (filesToUpload: File[] | FileList) => { const evaporate = await Evaporate.create({ bucket: data.keys.Bucket, awsRegion: data.keys.region, aws_key: data.keys.accessKey, computeContentMd5: true, cryptoMd5Method, cryptoHexEncodedHash256, customAuthMethod: (_, __, stringToSign) => signRequest(stringToSign, data.keys.secretKey), logging: false, }); Array.from(filesToUpload).forEach(async (toUpload) => { const id = nanoid(); if (/[#\$\[\]\*/]/.test(toUpload.name)) { toast.error("File name cannot contain special characters (#$[]*/)."); return; } if (files?.filter((f) => f.name === toUpload.name).length > 0) { toast.error("File with same name already exists."); return; } const filePath = currentFolder === ROOT_FOLDER ? toUpload.name : `${decodeURIComponent(currentFolder.fullPath)}${toUpload.name}`; evaporate.add({ name: filePath, file: toUpload, contentType: mime.lookup(toUpload.name) || "application/octet-stream", uploadInitiated: () => { setUploadingFiles((prev) => prev.concat([ { id, name: toUpload.name, key: `${data.keys.Bucket}/${filePath}`, task: evaporate, state: "running", progress: 0, error: false, }, ]) ); }, progress: (_, stats) => { setUploadingFiles((prevUploadingFiles) => prevUploadingFiles.map((uploadFile) => { return uploadFile.id === id ? { ...uploadFile, state: "running", progress: Math.round((stats.totalUploaded / stats.fileSize) * 100), } : uploadFile; }) ); }, paused: () => { setUploadingFiles((prevUploadingFiles) => prevUploadingFiles.map((uploadFile) => { return uploadFile.id === id ? { ...uploadFile, state: "paused" } : uploadFile; }) ); }, resumed: () => { setUploadingFiles((prevUploadingFiles) => prevUploadingFiles.map((uploadFile) => { return uploadFile.id === id ? { ...uploadFile, state: "running" } : uploadFile; }) ); }, error: (_) => { setUploadingFiles((prevUploadingFiles) => { return prevUploadingFiles.map((uploadFile) => { if (uploadFile.id === id) return { ...uploadFile, error: true }; return uploadFile; }); }); }, complete: async (_xhr, file_key) => { console.log("complete", decodeURIComponent(file_key)); setUploadingFiles((prevUploadingFiles) => prevUploadingFiles.filter((uploadFile) => uploadFile.id !== id) ); const newFile: DriveFile = { fullPath: filePath, name: toUpload.name, parent: currentFolder.fullPath, size: toUpload.size.toString(), createdAt: new Date().toISOString(), contentType: mime.lookup(toUpload.name) || "application/octet-stream", bucketName: data.keys.Bucket, bucketUrl: `https://${data.keys.Bucket}.s3.${data.keys.region}.amazonaws.com`, url: await getSignedUrl( s3Client, new GetObjectCommand({ Bucket: data.keys.Bucket, Key: decodeURIComponent(file_key) }), { expiresIn: 3600 * 24 } ), }; setFiles((files) => (files ? [...files, newFile] : [newFile])); toast.success("File uploaded successfully."); }, }); }); }; const removeFile = async (file: DriveFile) => { setFiles((files) => files.filter((f) => f.fullPath !== file.fullPath)); await s3Client.send(new DeleteObjectCommand({ Bucket: data.keys.Bucket, Key: file.fullPath })); return true; }; // set currentFolder useEffect(() => { if (!user?.email) return; setFiles(null); setFolders(null); if (fullPath === "" || !fullPath) { setCurrentFolder(ROOT_FOLDER); return; } setCurrentFolder({ fullPath: fullPath + "/", name: fullPath.split("/").pop(), bucketName: data.keys.Bucket, parent: fullPath.split("/").shift() + "/", bucketUrl: `https://${data.keys.Bucket}.s3.${data.keys.region}.amazonaws.com`, }); }, [fullPath, user]); // get files and folders useEffect(() => { if (!user?.email || !currentFolder) return; setLoading(true); (async () => { try { if (!files) { let results = await s3Client.send( new ListObjectsV2Command({ Bucket: data.keys.Bucket, Prefix: currentFolder.fullPath, Delimiter: "/", }) ); if (results.Contents) { results.Contents.forEach(async (result) => { const driveFile: DriveFile = { fullPath: result.Key, name: result.Key.split("/").pop(), parent: currentFolder.fullPath, createdAt: result.LastModified.toISOString(), size: result.Size.toString(), contentType: mime.lookup(result.Key) || "", bucketName: results.Name, bucketUrl: `https://${results.Name}.s3.${data.keys.region}.amazonaws.com`, url: await getSignedUrl( s3Client, new GetObjectCommand({ Bucket: results.Name, Key: result.Key }), { expiresIn: 3600 * 24 } ), }; setFiles((files) => (files ? [...files, driveFile] : [driveFile])); }); } const localFolders = localStorage.getItem(`local_folders_${data.id}`); let localFoldersArray: DriveFolder[] = localFolders ? JSON.parse(localFolders) : []; localFoldersArray = localFoldersArray.filter( (folder) => folder.parent === currentFolder.fullPath && !results.CommonPrefixes?.find((prefix) => prefix.Prefix === folder.fullPath) ); setFolders(localFoldersArray); if (results.CommonPrefixes) { for (let i = 0; i < results.CommonPrefixes.length; i++) { const driveFolder: DriveFolder = { fullPath: results.CommonPrefixes[i].Prefix, name: results.CommonPrefixes[i].Prefix.slice(0, -1).split("/").pop(), bucketName: results.Name, parent: currentFolder.fullPath, bucketUrl: `https://${results.Name}.s3.${data.keys.region}.amazonaws.com`, }; setFolders((folders) => [...folders, driveFolder]); } } // loop to list all files. while (results.IsTruncated) { results = await s3Client.send( new ListObjectsV2Command({ Bucket: data.keys.Bucket, Prefix: currentFolder.fullPath, ContinuationToken: results.ContinuationToken, Delimiter: "/", }) ); results.Contents.forEach(async (result) => { const driveFile: DriveFile = { fullPath: result.Key, name: result.Key.split("/").pop(), parent: currentFolder.fullPath, createdAt: result.LastModified.toISOString(), size: result.Size.toString(), contentType: mime.lookup(result.Key) || "", bucketName: results.Name, bucketUrl: `https://${results.Name}.s3.${data.keys.region}.amazonaws.com`, url: await getSignedUrl( s3Client, new GetObjectCommand({ Bucket: results.Name, Key: result.Key }), { expiresIn: 3600 * 24 } ), }; setFiles((files) => (files ? [...files, driveFile] : [driveFile])); }); } } } catch (err) { console.error(err); } setLoading(false); })(); }, [currentFolder, user]); return ( <S3Context.Provider value={{ loading, currentFolder, files, folders, uploadingFiles, setUploadingFiles, addFile, addFolder, removeFile, removeFolder, }} > {children} </S3Context.Provider> ); }; async function emptyS3Directory(client: S3Client, Bucket: string, Prefix: string) { const listParams = { Bucket, Prefix }; const listedObjects = await client.send(new ListObjectsV2Command(listParams)); if (listedObjects.CommonPrefixes?.length > 0) { for (let i = 0; i < listedObjects.CommonPrefixes.length; i++) { await emptyS3Directory(client, Bucket, listedObjects.CommonPrefixes[i].Prefix); } } if (listedObjects.Contents?.length === 0) return; const deleteParams = { Bucket, Delete: { Objects: [] } }; for (let i = 0; i < listedObjects.Contents.length; i++) { deleteParams.Delete.Objects.push({ Key: listedObjects.Contents[i].Key }); } await client.send(new DeleteObjectsCommand(deleteParams)); if (listedObjects.IsTruncated) await emptyS3Directory(client, Bucket, Prefix); }
the_stack
import { GraphQLID, GraphQLString } from 'graphql'; import memorize from 'memorize-decorator'; import { ACCESS_GROUP_FIELD, FLEX_SEARCH_FULLTEXT_INDEXED_DIRECTIVE, FLEX_SEARCH_INDEXED_DIRECTIVE, FLEX_SEARCH_ORDER_ARGUMENT, ID_FIELD, ROOT_ENTITY_DIRECTIVE, SCALAR_INT, SCALAR_STRING } from '../../schema/constants'; import { GraphQLInt53 } from '../../schema/scalars/int53'; import { GraphQLLocalDate } from '../../schema/scalars/local-date'; import { compact } from '../../utils/utils'; import { FlexSearchPrimarySortClauseConfig, PermissionsConfig, RootEntityTypeConfig, TypeKind } from '../config'; import { ValidationContext, ValidationMessage } from '../validation'; import { Field, SystemFieldConfig } from './field'; import { FieldPath } from './field-path'; import { FlexSearchPrimarySortClause } from './flex-search'; import { Index } from './indices'; import { Model } from './model'; import { ObjectTypeBase } from './object-type-base'; import { OrderDirection } from './order'; import { PermissionProfile } from './permission-profile'; import { Relation, RelationSide } from './relation'; import { RolesSpecifier } from './roles-specifier'; import { ScalarType } from './scalar-type'; import { TimeToLiveType } from './time-to-live'; export class RootEntityType extends ObjectTypeBase { private readonly permissions: PermissionsConfig & {}; readonly roles: RolesSpecifier | undefined; readonly kind: TypeKind.ROOT_ENTITY = TypeKind.ROOT_ENTITY; readonly isChildEntityType: false = false; readonly isRootEntityType: true = true; readonly isEntityExtensionType: false = false; readonly isValueObjectType: false = false; readonly isBusinessObject: boolean; readonly isFlexSearchIndexed: boolean; readonly flexSearchPrimarySort: ReadonlyArray<FlexSearchPrimarySortClause>; constructor(private readonly input: RootEntityTypeConfig, model: Model) { super(input, model, systemFieldInputs); this.permissions = input.permissions || {}; this.roles = input.permissions && input.permissions.roles ? new RolesSpecifier(input.permissions.roles) : undefined; this.isBusinessObject = input.isBusinessObject || false; if (input.flexSearchIndexConfig && input.flexSearchIndexConfig.isIndexed) { this.isFlexSearchIndexed = true; this.flexSearchPrimarySort = this.completeFlexSearchPrimarySort(input.flexSearchIndexConfig.primarySort); } else { this.isFlexSearchIndexed = false; this.flexSearchPrimarySort = []; } } @memorize() get indices(): ReadonlyArray<Index> { const indexConfigs = this.input.indices ? [...this.input.indices] : []; // @key implies a unique index // (do this to the inputs so that addIdentifyingSuffixIfNeeded is called on these, too) if (this.keyField) { const keyField = this.keyField; if (!indexConfigs.some(f => f.unique === true && f.fields.length == 1 && f.fields[0] === keyField.name)) { indexConfigs.push({ unique: true, fields: [keyField.name] }); } } for (const timeToLiveType of this.timeToLiveTypes) { indexConfigs.push({ unique: false, fields: timeToLiveType.input.dateField.split('.') }); } const indices = indexConfigs.map(config => new Index(config, this)); if (this.discriminatorField !== this.keyField) { if ( !indices.some(index => index.fields.length === 1 && index.fields[0].field === this.discriminatorField) ) { // make sure there is an index on the discriminator field that can be used for sorting // arangodb already has an index on 'id', but it's a hash index which is unusable for sorting // if the discriminator field is the key field, we already added an index above. // don't use unique to avoid running into performance workarounds for unique indices (sparseness) indices.push( new Index( { fields: [this.discriminatorField.name] }, this ) ); } } // deduplicate indices return indices.filter((index, i1) => !indices.some((other, i2) => i1 < i2 && other.equals(index))); } get hasFieldsIncludedInSearch() { return ( this.fields.some(value => value.isIncludedInSearch) || this.fields.some(value => value.isFulltextIncludedInSearch) ); } @memorize() get keyField(): Field | undefined { if (!this.input.keyFieldName) { return undefined; } const field = this.getField(this.input.keyFieldName); if (!field || field.isList) { return undefined; } return field; } getKeyFieldOrThrow(): Field { if (!this.keyField) { throw new Error(`Expected "${this.name}" to have a key field`); } return this.keyField; } getKeyFieldTypeOrThrow(): ScalarType { const field = this.getKeyFieldOrThrow(); if (!field.type.isScalarType) { throw new Error(`Expected "${this.name}.${field.name}" to be of scalar type because it is a key field`); } return field.type; } /** * Gets a field that is guaranteed to be unique, to be used for absolute order */ @memorize() get discriminatorField(): Field { // later, we can return @key here when it exists and is required return this.getFieldOrThrow(ID_FIELD); } get permissionProfile(): PermissionProfile | undefined { if (this.permissions.permissionProfileName == undefined) { if (this.permissions.roles != undefined) { // if @roles is specified, this root entity explicitly does not have a permission profile return undefined; } return this.namespace.defaultPermissionProfile; } return this.namespace.getPermissionProfile(this.permissions.permissionProfileName); } /** * A list of all relations that have a field in this type * * (as opposed to the relation only existing because a different type has a relation field to this root entity) */ get explicitRelations(): ReadonlyArray<Relation> { return compact(this.fields.map(field => field.relation)); } /** * A list of all relations concerning this type, regardless of whether there is a field on this type for it */ @memorize() get relations(): ReadonlyArray<Relation> { return this.model.relations.filter(rel => rel.fromType === this || rel.toType === this); } /** * A list of all relations sides concerning this type, regardless of whether there is a field on this type for it */ @memorize() get relationSides(): ReadonlyArray<RelationSide> { return [ ...this.model.relations.filter(rel => rel.fromType === this).map(rel => rel.fromSide), ...this.model.relations.filter(rel => rel.toType === this).map(rel => rel.toSide) ]; } validate(context: ValidationContext) { super.validate(context); if (this.model.forbiddenRootEntityNames.find(value => this.name.toLowerCase() === value.toLowerCase())) { context.addMessage(ValidationMessage.error(`RootEntities cannot be named ${this.name}.`, this.nameASTNode)); } this.validateKeyField(context); this.validatePermissions(context); this.validateIndices(context); this.validateFlexSearch(context); } private validateKeyField(context: ValidationContext) { if (this.input.keyFieldName == undefined) { return; } const astNode = this.input.keyFieldASTNode || this.astNode; const field = this.getField(this.input.keyFieldName); if (!field) { context.addMessage( ValidationMessage.error( `Field "${this.input.keyFieldName}" does not exist on type "${this.name}".`, astNode ) ); return; } // support for ID is needed because id: ID @key is possible const isSupported = field.type.kind === TypeKind.ENUM || (field.type.kind === TypeKind.SCALAR && [SCALAR_INT, SCALAR_STRING, GraphQLID.name, GraphQLLocalDate.name].includes(field.type.name)); if (!isSupported) { context.addMessage( ValidationMessage.error( `Only fields of type "String", "Int", "ID", "LocalDate", and enum types can be used as key field.`, astNode ) ); } if (field.isList) { context.addMessage(ValidationMessage.error(`List fields cannot be used as key field.`, astNode)); } } private validatePermissions(context: ValidationContext) { const permissions = this.permissions; if (permissions.permissionProfileName != undefined && permissions.roles != undefined) { const message = `Permission profile and explicit role specifiers cannot be combined.`; context.addMessage( ValidationMessage.error(message, permissions.permissionProfileNameAstNode || this.nameASTNode) ); context.addMessage(ValidationMessage.error(message, permissions.roles.astNode || this.nameASTNode)); } if ( permissions.permissionProfileName != undefined && !this.namespace.getPermissionProfile(permissions.permissionProfileName) ) { context.addMessage( ValidationMessage.error( `Permission profile "${permissions.permissionProfileName}" not found.`, permissions.permissionProfileNameAstNode || this.nameASTNode ) ); } if (this.roles) { this.roles.validate(context); } const usesAccessGroup = this.permissionProfile && this.permissionProfile.permissions.some(per => !!per.restrictToAccessGroups); if (usesAccessGroup) { const accessGroupField = this.getField(ACCESS_GROUP_FIELD); if (!accessGroupField) { context.addMessage( ValidationMessage.error( `The permission profile "${permissions.permissionProfileName}" uses "restrictToAccessGroups", but this root entity does not have a "${ACCESS_GROUP_FIELD}" field.`, permissions.permissionProfileNameAstNode || this.nameASTNode ) ); } else if (!accessGroupField.type.isEnumType && accessGroupField.type.name !== GraphQLString.name) { context.addMessage( ValidationMessage.error( `This field must be of String or enum type to be used as "accessGroup" with the permission profile "${permissions.permissionProfileName}".`, accessGroupField.astNode || this.nameASTNode ) ); } } } private validateIndices(context: ValidationContext) { // validate the "raw" indices without our magic additions like adding the id field for (const indexInput of this.input.indices || []) { const index = new Index(indexInput, this); index.validate(context); } } private validateFlexSearch(context: ValidationContext) { if ( !this.isFlexSearchIndexed && this.fields.some( value => (value.isFlexSearchIndexed || value.isFlexSearchFulltextIndexed) && !value.isSystemField ) ) { context.addMessage( ValidationMessage.warn( `The type contains fields that are annotated with ${FLEX_SEARCH_INDEXED_DIRECTIVE} or ${FLEX_SEARCH_FULLTEXT_INDEXED_DIRECTIVE}, but the type itself is not marked with flexSearch = true.`, this.input.astNode!.name ) ); } // validate primarySort for (const primarySortConfig of this.flexSearchPrimarySort) { const primarySortPath = primarySortConfig.field.path.split('.'); const astNode = this.input .astNode!.directives!.find(value => value.name.value === ROOT_ENTITY_DIRECTIVE)! .arguments!.find(value => value.name.value === FLEX_SEARCH_ORDER_ARGUMENT)!; function isValidPath(fields: ReadonlyArray<Field>, path: ReadonlyArray<string>): boolean { const [head, ...tail] = path; const field = fields.find(value => value.name === head); if (field) { if (field.type.isScalarType || (field.type.isEnumType && tail.length == 0)) { return true; } else if (field.type.isObjectType && !field.isList && tail.length > 0) { return isValidPath(field.type.fields, tail); } else { return false; } } else { return false; } } if (!isValidPath(this.fields, primarySortPath)) { context.addMessage( ValidationMessage.warn( `The provided flexSearchOrder is invalid. It must be a path that evaluates to a scalar value and the full path must be annotated with ${FLEX_SEARCH_INDEXED_DIRECTIVE}.`, astNode ) ); } } } @memorize() get billingEntityConfig() { return this.model.billingEntityTypes.find(value => value.rootEntityType === this); } private completeFlexSearchPrimarySort( clauses: ReadonlyArray<FlexSearchPrimarySortClauseConfig> ): ReadonlyArray<FlexSearchPrimarySortClause> { // primary sort is only used for sorting, so make sure it's unique // - this makes querying more consistent // - this enables us to use primary sort for cursor-based pagination (which requires an absolute sort order) if (!clauses.some(clause => clause.field === this.discriminatorField.name)) { clauses = [ ...clauses, { field: this.discriminatorField.name, asc: true } ]; } return clauses.map( c => new FlexSearchPrimarySortClause( new FieldPath({ path: c.field, baseType: this }), c.asc ? OrderDirection.ASCENDING : OrderDirection.DESCENDING ) ); } @memorize() get timeToLiveTypes(): ReadonlyArray<TimeToLiveType> { return this.model.timeToLiveTypes.filter( ttlType => ttlType.rootEntityType && ttlType.rootEntityType.name === this.name ); } } const systemFieldInputs: ReadonlyArray<SystemFieldConfig> = [ { name: 'id', typeName: 'ID', isNonNull: true, description: 'An auto-generated string that identifies this root entity uniquely among others of the same type', isFlexSearchIndexed: true, isFlexSearchFulltextIndexed: false, isIncludedInSearch: false }, { name: 'createdAt', typeName: 'DateTime', isNonNull: true, description: 'The instant this object has been created', isFlexSearchIndexed: true, isFlexSearchFulltextIndexed: false, isIncludedInSearch: false }, { name: 'updatedAt', typeName: 'DateTime', isNonNull: true, description: 'The instant this object has been updated the last time (not including relation updates)', isFlexSearchIndexed: true, isFlexSearchFulltextIndexed: false, isIncludedInSearch: false } ];
the_stack
import * as React from 'react'; import './App.css'; import Toolbar from './components/toolbar/toolbar'; import Viewport from './components/viewport/viewport'; import Connection from './connection'; import { ExtensionConfiguration } from '../ext-src/extensionConfiguration'; import { resolve as getElementSourceMetadata } from 'element-to-source'; import { CDPHelper } from './utils/cdpHelper'; interface ElementSource { charNumber: number; columnNumber: number; fileName: string; lineNumber: string; } interface IState { format: 'jpeg' | 'png'; frame: object | null; url: string; isVerboseMode: boolean; isInspectEnabled: boolean; isDeviceEmulationEnabled: boolean; viewportMetadata: IViewport; history: { canGoBack: boolean; canGoForward: boolean; }; } interface IViewport { height: number | null; width: number | null; cursor: string | null; emulatedDeviceId: string | null; isLoading: boolean; isFixedSize: boolean; isFixedZoom: boolean; isResizable: boolean; loadingPercent: number; highlightNode: { nodeId: string; sourceMetadata: ElementSource | null; } | null; highlightInfo: object | null; deviceSizeRatio: number; screenZoom: number; scrollOffsetX: number; scrollOffsetY: number; } class App extends React.Component<any, IState> { private connection: Connection; private viewport: any; private cdpHelper: CDPHelper; constructor(props: any) { super(props); this.state = { frame: null, format: 'jpeg', url: 'about:blank', isVerboseMode: false, isInspectEnabled: false, isDeviceEmulationEnabled: false, history: { canGoBack: false, canGoForward: false }, viewportMetadata: { cursor: null, deviceSizeRatio: 1, height: null, width: null, highlightNode: null, highlightInfo: null, emulatedDeviceId: 'Responsive', isLoading: false, isFixedSize: false, isFixedZoom: false, isResizable: true, loadingPercent: 0.0, screenZoom: 1, scrollOffsetX: 0, scrollOffsetY: 0 } }; this.connection = new Connection(); this.onToolbarActionInvoked = this.onToolbarActionInvoked.bind(this); this.onViewportChanged = this.onViewportChanged.bind(this); this.connection.enableVerboseLogging(this.state.isVerboseMode); this.connection.on('Page.navigatedWithinDocument', (result: any) => { this.requestNavigationHistory(); }); this.connection.on('Page.frameNavigated', (result: any) => { const { frame } = result; var isMainFrame = !frame.parentId; if (isMainFrame) { this.requestNavigationHistory(); this.updateState({ ...this.state, viewportMetadata: { ...this.state.viewportMetadata, isLoading: true, loadingPercent: 0.1 } }); } }); this.connection.on('Page.loadEventFired', (result: any) => { this.updateState({ ...this.state, viewportMetadata: { ...this.state.viewportMetadata, loadingPercent: 1.0 } }); setTimeout(() => { this.updateState({ ...this.state, viewportMetadata: { ...this.state.viewportMetadata, isLoading: false, loadingPercent: 0 } }); }, 500); }); this.connection.on('Page.screencastFrame', (result: any) => { this.handleScreencastFrame(result); }); this.connection.on('Page.windowOpen', (result: any) => { this.connection.send('extension.windowOpenRequested', { url: result.url }); }); this.connection.on('Page.javascriptDialogOpening', (result: any) => { const { url, message, type } = result; this.connection.send('extension.windowDialogRequested', { url: url, message: message, type: type }); }); this.connection.on('Page.frameResized', (result: any) => { this.stopCasting(); this.startCasting(); }); this.connection.on('Overlay.nodeHighlightRequested', (result: any) => { console.log('nodeHighlightRequested', result); // this.handleInspectHighlightRequested(); }); this.connection.on('Overlay.inspectNodeRequested', (result: any) => { console.log('inspectNodeRequested', result); // this.handleInspectHighlightRequested(); }); this.connection.on('extension.appConfiguration', (payload: ExtensionConfiguration) => { if (!payload) { return; } this.updateState({ isVerboseMode: payload.isVerboseMode ? payload.isVerboseMode : false, url: payload.startUrl ? payload.startUrl : 'about:blank', format: payload.format ? payload.format : 'jpeg' }); if (payload.startUrl) { this.connection.send('Page.navigate', { url: payload.startUrl }); } }); this.connection.on('extension.viewport', (viewport: IViewport) => { this.handleViewportSizeChange(viewport); this.enableViewportDeviceEmulation('Live Share'); // TODO: Scroll the page }); // Initialize this.connection.send('Page.enable'); this.connection.send('DOM.enable'); this.connection.send('CSS.enable'); this.connection.send('Overlay.enable'); this.requestNavigationHistory(); this.startCasting(); this.cdpHelper = new CDPHelper(this.connection); } private handleScreencastFrame(result: any) { const { sessionId, data, metadata } = result; this.connection.send('Page.screencastFrameAck', { sessionId }); this.requestNodeHighlighting(); this.updateState({ ...this.state, frame: { base64Data: data, metadata: metadata }, viewportMetadata: { ...this.state.viewportMetadata, scrollOffsetX: metadata.scrollOffsetX, scrollOffsetY: metadata.scrollOffsetY } }); } public componentDidUpdate() { const { isVerboseMode } = this.state; this.connection.enableVerboseLogging(isVerboseMode); } private sendStatetoHost() { this.connection.send('extension.appStateChanged', { state: this.state }); } public render() { return ( <div className="App"> <Toolbar url={this.state.url} viewport={this.state.viewportMetadata} onActionInvoked={this.onToolbarActionInvoked} canGoBack={this.state.history.canGoBack} canGoForward={this.state.history.canGoForward} isInspectEnabled={this.state.isInspectEnabled} isDeviceEmulationEnabled={this.state.isDeviceEmulationEnabled} /> <Viewport viewport={this.state.viewportMetadata} isInspectEnabled={this.state.isInspectEnabled} isDeviceEmulationEnabled={this.state.isDeviceEmulationEnabled} frame={this.state.frame} format={this.state.format} url={this.state.url} onViewportChanged={this.onViewportChanged} ref={(c) => { this.viewport = c; }} /> </div> ); } public stopCasting() { this.connection.send('Page.stopScreencast'); } public startCasting() { var params = { quality: 80, format: this.state.format, maxWidth: 2000, maxHeight: 2000 }; if (this.state.viewportMetadata.width) { params.maxWidth = Math.floor(this.state.viewportMetadata.width * window.devicePixelRatio); } if (this.state.viewportMetadata.height) { params.maxHeight = Math.floor(this.state.viewportMetadata.height * window.devicePixelRatio); } this.connection.send('Page.startScreencast', params); } private async requestNavigationHistory() { const history: any = await this.connection.send('Page.getNavigationHistory'); if (!history) { return; } let historyIndex = history.currentIndex; let historyEntries = history.entries; let currentEntry = historyEntries[historyIndex]; let url = currentEntry.url; const pattern = /^http:\/\/(.+)/; const match = url.match(pattern); if (match) { url = match[1]; } this.updateState({ ...this.state, url: url, history: { canGoBack: historyIndex === 0, canGoForward: historyIndex === historyEntries.length - 1 } }); let panelTitle = currentEntry.title || currentEntry.url; this.connection.send('extension.updateTitle', { title: `Browser Preview (${panelTitle})` }); } private async onViewportChanged(action: string, data: any) { switch (action) { case 'inspectHighlightRequested': this.handleInspectHighlightRequested(data); break; case 'inspectElement': await this.handleInspectElementRequest(data); this.handleToggleInspect(); break; case 'hoverElementChanged': await this.handleElementChanged(data); break; case 'interaction': this.connection.send(data.action, data.params); break; case 'size': console.log('app.onViewportChanged.size', data); let newViewport = {} as any; if (data.height !== undefined && data.width !== undefined) { let height = Math.floor(data.height); let width = Math.floor(data.width); let devicePixelRatio = window.devicePixelRatio || 1; this.connection.send('Page.setDeviceMetricsOverride', { deviceScaleFactor: devicePixelRatio, mobile: false, height: height, width: width }); newViewport.height = height as number; newViewport.width = width as number; } if (data.isResizable !== undefined) { newViewport.isResizable = data.isResizable; } if (data.isFixedSize !== undefined) { newViewport.isFixedSize = data.isFixedSize; } if (data.isFixedZoom !== undefined) { newViewport.isFixedZoom = data.isFixedZoom; } if (data.emulatedDeviceId !== undefined) { newViewport.emulatedDeviceId = data.emulatedDeviceId; } if (data.screenZoom !== undefined) { newViewport.screenZoom = data.screenZoom; } await this.updateState({ ...this.state, viewportMetadata: { ...this.state.viewportMetadata, ...newViewport } }); this.viewport.calculateViewport(); break; } } private async updateState(newState: any) { return new Promise((resolve, reject) => { this.setState(newState, () => { this.sendStatetoHost(); resolve(); }); }); } private async handleInspectHighlightRequested(data: any) { let highlightNodeInfo: any = await this.connection.send('DOM.getNodeForLocation', { x: data.params.position.x, y: data.params.position.y }); if (highlightNodeInfo) { let nodeId = highlightNodeInfo.nodeId; if (!highlightNodeInfo.nodeId && highlightNodeInfo.backendNodeId) { nodeId = await this.cdpHelper.getNodeIdFromBackendId(highlightNodeInfo.backendNodeId); } this.setState({ ...this.state, viewportMetadata: { ...this.state.viewportMetadata, highlightNode: { nodeId: nodeId, sourceMetadata: null } } }); // await this.handleHighlightNodeClickType(); this.requestNodeHighlighting(); } } // private async handleHighlightNodeClickType() { // if (!this.state.viewportMetadata.highlightNode) { // return; // } // let cursor = 'not-allowed'; // let sourceMetadata = this.state.viewportMetadata.highlightNode.sourceMetadata; // if(sourceMetadata && sourceMetadata.fileName) { // cursor = 'pointer'; // } // this.setState({ // ...this.state, // viewportMetadata: { // ...this.state.viewportMetadata, // cursor: cursor // } // }); // } private async resolveHighlightNodeSourceMetadata() { if (!this.state.viewportMetadata.highlightNode) { return; } let nodeId = this.state.viewportMetadata.highlightNode.nodeId; const nodeDetails: any = await this.connection.send('DOM.resolveNode', { nodeId: nodeId }); if (nodeDetails.object) { let objectId = nodeDetails.object.objectId; let nodeProperties = await this.cdpHelper.resolveElementProperties(objectId, 3); if (nodeProperties) { let sourceMetadata = getElementSourceMetadata(nodeProperties); if (!sourceMetadata.fileName) { return; } this.setState({ ...this.state, viewportMetadata: { ...this.state.viewportMetadata, highlightNode: { ...this.state.viewportMetadata.highlightNode, sourceMetadata: { fileName: sourceMetadata.fileName, columnNumber: sourceMetadata.columnNumber, lineNumber: sourceMetadata.lineNumber, charNumber: sourceMetadata.charNumber } } } }); } } } private async handleInspectElementRequest(data: any) { if (!this.state.viewportMetadata.highlightNode) { return; } await this.resolveHighlightNodeSourceMetadata(); let nodeId = this.state.viewportMetadata.highlightNode.nodeId; // Trigger CDP request to enable DOM explorer // TODO: No sure this works. this.connection.send('Overlay.inspectNodeRequested', { nodeId: nodeId }); let sourceMetadata = this.state.viewportMetadata.highlightNode.sourceMetadata; if (sourceMetadata) { this.connection.send('extension.openFile', { fileName: sourceMetadata.fileName, lineNumber: sourceMetadata.lineNumber, columnNumber: sourceMetadata.columnNumber, charNumber: sourceMetadata.charNumber }); } } private onToolbarActionInvoked(action: string, data: any): Promise<any> { switch (action) { case 'forward': this.connection.send('Page.goForward'); break; case 'backward': this.connection.send('Page.goBackward'); break; case 'refresh': this.connection.send('Page.reload'); break; case 'inspect': this.handleToggleInspect(); break; case 'emulateDevice': this.handleToggleDeviceEmulation(); break; case 'urlChange': this.handleUrlChange(data); break; case 'readClipboard': return this.connection.send('Clipboard.readText'); case 'writeClipboard': this.handleClipboardWrite(data); break; case 'viewportSizeChange': this.handleViewportSizeChange(data); break; case 'viewportDeviceChange': this.handleViewportDeviceChange(data); break; } // return an empty promise return Promise.resolve(); } private handleToggleInspect() { if (this.state.isInspectEnabled) { // Hide browser highlight this.connection.send('Overlay.hideHighlight'); // Hide local highlight this.updateState({ isInspectEnabled: false, viewportMetadata: { ...this.state.viewportMetadata, highlightInfo: null, highlightNode: null } }); } else { this.updateState({ isInspectEnabled: true }); } } private handleUrlChange(data: any) { this.connection.send('Page.navigate', { url: data.url }); this.updateState({ ...this.state, url: data.url }); } private handleViewportSizeChange(data: any) { this.onViewportChanged('size', { width: data.width, height: data.height }); } private handleViewportDeviceChange(data: any) { let isResizable = data.device.name === 'Responsive'; let isFixedSize = data.device.name !== 'Responsive'; let isFixedZoom = data.device.name === 'Responsive'; let width = data.device.viewport ? data.device.viewport.width : undefined; let height = data.device.viewport ? data.device.viewport.height : undefined; let screenZoom = 1; this.onViewportChanged('size', { emulatedDeviceId: data.device.name, height: height, isResizable: isResizable, isFixedSize: isFixedSize, isFixedZoom: isFixedZoom, screenZoom: screenZoom, width: width }); } private handleToggleDeviceEmulation() { if (this.state.isDeviceEmulationEnabled) { this.disableViewportDeviceEmulation(); } else { this.enableViewportDeviceEmulation(); } } private disableViewportDeviceEmulation() { console.log('app.disableViewportDeviceEmulation'); this.handleViewportDeviceChange({ device: { name: 'Responsive', viewport: { width: this.state.viewportMetadata.width, height: this.state.viewportMetadata.height } } }); this.updateState({ isDeviceEmulationEnabled: false }); } private enableViewportDeviceEmulation(deviceName: string = 'Responsive') { console.log('app.enableViewportDeviceEmulation'); this.handleViewportDeviceChange({ device: { name: deviceName, viewport: { width: this.state.viewportMetadata.width, height: this.state.viewportMetadata.height } } }); this.updateState({ isDeviceEmulationEnabled: true }); } private handleClipboardWrite(data: any) { // overwrite the clipboard only if there is a valid value if (data && (data as any).value) { return this.connection.send('Clipboard.writeText', data); } } private async handleElementChanged(data: any) { const nodeInfo: any = await this.connection.send('DOM.getNodeForLocation', { x: data.params.position.x, y: data.params.position.y }); var cursor = await this.cdpHelper.getCursorForNode(nodeInfo); this.setState({ ...this.state, viewportMetadata: { ...this.state.viewportMetadata, cursor: cursor } }); } private async requestNodeHighlighting() { if (this.state.viewportMetadata.highlightNode) { let nodeId = this.state.viewportMetadata.highlightNode.nodeId; let highlightBoxModel: any = await this.connection.send('DOM.getBoxModel', { nodeId: nodeId }); // Trigger hightlight in regular browser. await this.connection.send('Overlay.highlightNode', { nodeId: nodeId, highlightConfig: { showInfo: true, showStyles: true, showRulers: true, showExtensionLines: true } }); if (highlightBoxModel && highlightBoxModel.model) { this.setState({ ...this.state, viewportMetadata: { ...this.state.viewportMetadata, highlightInfo: highlightBoxModel.model } }); } } } } export default App;
the_stack
interface JQuery { validate: any; collapse: any; } module OCM { export class LocationEditor extends OCM.AppBase { editorMapInitialised: boolean; editorMap: any; editMarker: any; positionAttribution: any; numConnectionEditors: number; isLocationEditMode: boolean; initEditors() { this.numConnectionEditors = 5; this.editorMapInitialised = false; this.editorMap = null; this.editMarker = null; this.positionAttribution = null; var editorSubmitMethod = $.proxy(this.performLocationSubmit, this); $("#editlocation-form").validate({ rules: { edit_addressinfo_title: { required: true, email: true } }, submitHandler: function (form) { editorSubmitMethod(); } }); //fetch editor reference data this.apiClient.referenceData = this.apiClient.getCachedDataObject("CoreReferenceData"); if (this.apiClient.referenceData == null) { //no cached reference data, fetch from service this.apiClient.fetchCoreReferenceData("ocm_app.populateEditor", this.getLoggedInUserInfo()); } else { //cached ref data exists, use that this.log("Using cached reference data.."); var _app = this; setTimeout(function () { _app.populateEditor(null); }, 50); //attempt to fetch fresh data later (wait 1 second) setTimeout(function () { _app.apiClient.fetchCoreReferenceData("ocm_app.populateEditor", _app.getLoggedInUserInfo()); }, 1000); } } resetEditorForm() { //init editor to default settings (<HTMLFormElement>document.getElementById("editlocation-form")).reset(); for (var n = 1; n <= this.numConnectionEditors; n++) { //reset editor dropdowns this.setDropdown("edit_connection" + n + "_connectiontype", "0"); this.setDropdown("edit_connection" + n + "_level", ""); this.setDropdown("edit_connection" + n + "_status", "0"); this.setDropdown("edit_connection" + n + "_currenttype", ""); } this.setDropdown("edit_addressinfo_countryid", 1); this.setDropdown("edit_operator", 1); this.setDropdown("edit_dataprovider", 1); this.setDropdown("edit_submissionstatus", 1); this.setDropdown("edit_statustype", 50); //operational this.positionAttribution = null; $("#editor-map").hide(); } populateEditor(refData) { this.hideProgressIndicator(); //todo:move this into OCM_Data then pass to here from callback if (refData == null) { //may be loaded from cache refData = this.apiClient.referenceData; } else { //store cached ref data if (refData != null) { this.apiClient.setCachedDataObject("CoreReferenceData", refData); this.log("Updated cached CoreReferenceData."); } } this.apiClient.referenceData = refData; this.apiClient.sortCoreReferenceData(); refData = this.apiClient.referenceData; // this.isLocationEditMode = false; //populate location editor dropdowns etc this.populateDropdown("edit_addressinfo_countryid", refData.Countries, null); this.populateDropdown("edit_usagetype", refData.UsageTypes, null); this.populateDropdown("edit_statustype", refData.StatusTypes, null); this.populateDropdown("edit_operator", refData.Operators, 1); //populate connection editor(s) for (var n = 1; n <= this.numConnectionEditors; n++) { //create editor section var $connection = ($("#edit_connection" + n)); if (!($connection.length > 0)) { //create new section using section 1 as template var templateHTML = $("#edit_connection1").html(); if (templateHTML != null) { templateHTML = templateHTML.replace("Equipment Details 1", "Equipment Details " + n); templateHTML = templateHTML.replace(/connection1/gi, "connection" + n); $connection = $("<div id=\"edit_connection" + n + "\" class='panel panel-default'>" + templateHTML + "</div>"); $("#edit-connectioneditors").append($connection); } $connection.collapse("show"); } //populate dropdowns this.populateDropdown("edit_connection" + n + "_connectiontype", refData.ConnectionTypes, null); this.populateDropdown("edit_connection" + n + "_level", refData.ChargerTypes, null, true); this.populateDropdown("edit_connection" + n + "_status", refData.StatusTypes, null); this.populateDropdown("edit_connection" + n + "_currenttype", refData.CurrentTypes, null, true); } //setup geocoding lookup of address in editor var appContext = (<any>this); appContext.setElementAction("#edit-location-lookup", function (event, ui) { //format current address as string var lookupString = ($("#edit_addressinfo_addressline1").val().length > 0 ? $("#edit_addressinfo_addressline1").val() + "," : "") + ($("#edit_addressinfo_addressline2").val().length > 0 ? $("#edit_addressinfo_addressline2").val() + "," : "") + ($("#edit_addressinfo_town").val().length > 0 ? $("#edit_addressinfo_town").val() + "," : "") + ($("#edit_addressinfo_stateorprovince").val().length > 0 ? $("#edit_addressinfo_stateorprovince").val() + "," : "") + ($("#edit_addressinfo_postcode").val().length > 0 ? $("#edit_addressinfo_postcode").val() + "," : "") + appContext.apiClient.getRefDataByID(refData.Countries, $("#edit_addressinfo_countryid").val()).Title; //attempt to geocode address appContext.geolocationManager.determineGeocodedLocation(lookupString, $.proxy(appContext.populateEditorLatLon, appContext), $.proxy((<OCM.App>appContext).determineGeocodedLocationFailed, appContext)); }); appContext.setElementAction("#editlocation-submit", function () { if (appContext.validateLocationEditor() === true) { appContext.performLocationSubmit(); } }); //populate user comment editor this.populateDropdown("comment-type", refData.UserCommentTypes, null); this.populateDropdown("checkin-type", refData.CheckinStatusTypes, null); //populate and hide non-edit mode items: submission status etc by default this.populateDropdown("edit_submissionstatus", refData.SubmissionStatusTypes, 1); this.populateDropdown("edit_dataprovider", refData.DataProviders, 1); $("#edit-submissionstatus-container").hide(); $("#edit-dataprovider-container").hide(); //avoid resetting pref selections on list change this.appState.suppressSettingsSave = true; //populate lists in filter/prefs/about page this.populateDropdown("filter-connectiontype", refData.ConnectionTypes, this.getMultiSelectionAsArray($("#filter-connectiontype"), ""), true, false, "(All)"); this.populateDropdown("filter-operator", refData.Operators, this.getMultiSelectionAsArray($("#filter-operator"), ""), true, false, "(All)"); this.populateDropdown("filter-usagetype", refData.UsageTypes, this.getMultiSelectionAsArray($("#filter-usagetype"), ""), true, false, "(All)"); this.populateDropdown("filter-statustype", refData.StatusTypes, this.getMultiSelectionAsArray($("#filter-statustype"), ""), true, false, "(All)"); this.appState.suppressSettingsSave = false //refresh of core ref data wipes settings selections, load from prefs so set them again appContext.loadSettings(); this.resetEditorForm(); if (refData.UserProfile && refData.UserProfile != null && refData.UserProfile.IsCurrentSessionTokenValid == false) { //login info is stale, logout user if (this.isUserSignedIn()) { this.log("Sign In token is stale, logging out user."); appContext.logout(false); } } } populateEditorLatLon(result: GeoPosition) { var lat = result.coords.latitude; var lng = result.coords.longitude; $("#edit_addressinfo_latitude").val(lat); $("#edit_addressinfo_longitude").val(lng); //show data attribution for lookup $("#position-attribution").html(result.attribution); this.positionAttribution = result.attribution; //refresh map view this.refreshEditorMap(); } validateLocationEditor() { var isValid = true; if (isValid == true && $("#edit_addressinfo_title").val().length < 3) { this.showMessage("Please provide a descriptive/summary title for this location"); isValid = false; } if (isValid == true && $("#edit_addressinfo_latitude").val() == "") { this.showMessage("Please provide a valid Latitude or use the lookup button."); isValid = false; } else if (isValid == true && $("#edit_addressinfo_longitude").val() == "") { this.showMessage("Please provide a valid Longitude or use the lookup button."); isValid = false; } return isValid; } performLocationSubmit() { var app = (<any>this); if (!app.appState.isSubmissionInProgress) { var refData = this.apiClient.referenceData; var item = this.apiClient.referenceData.ChargePoint; if (this.isLocationEditMode == true) item = this.viewModel.selectedPOI; //collect form values item.AddressInfo.Title = $("#edit_addressinfo_title").val(); item.AddressInfo.AddressLine1 = $("#edit_addressinfo_addressline1").val(); item.AddressInfo.AddressLine2 = $("#edit_addressinfo_addressline2").val(); item.AddressInfo.Town = $("#edit_addressinfo_town").val(); item.AddressInfo.StateOrProvince = $("#edit_addressinfo_stateorprovince").val(); item.AddressInfo.Postcode = $("#edit_addressinfo_postcode").val(); item.AddressInfo.Latitude = $("#edit_addressinfo_latitude").val(); item.AddressInfo.Longitude = $("#edit_addressinfo_longitude").val(); var country = this.apiClient.getRefDataByID(refData.Countries, $("#edit_addressinfo_countryid").val()); item.AddressInfo.Country = country; item.AddressInfo.CountryID = null; item.AddressInfo.AccessComments = $("#edit_addressinfo_accesscomments").val(); item.AddressInfo.ContactTelephone1 = $("#edit_addressinfo_contacttelephone1").val(); item.AddressInfo.ContactTelephone2 = $("#edit_addressinfo_contacttelephone2").val(); item.AddressInfo.ContactEmail = $("#edit_addressinfo_contactemail").val(); item.AddressInfo.RelatedURL = $("#edit_addressinfo_relatedurl").val(); item.NumberOfPoints = $("#edit_numberofpoints").val(); item.UsageType = this.apiClient.getRefDataByID(refData.UsageTypes, $("#edit_usagetype").val()); item.UsageTypeID = null; item.UsageCost = $("#edit_usagecost").val(); item.StatusType = this.apiClient.getRefDataByID(refData.StatusTypes, $("#edit_statustype").val()); item.StatusTypeID = null; item.GeneralComments = $("#edit_generalcomments").val(); item.OperatorInfo = this.apiClient.getRefDataByID(refData.Operators, $("#edit_operator").val()); item.OperatorID = null; if (this.isLocationEditMode != true) { item.DataProvider = null; item.DataProviderID = null; //if user is editor for this new location, set to publish on submit if (this.hasUserPermissionForPOI(item, "Edit")) { item.SubmissionStatus = this.apiClient.getRefDataByID(refData.SubmissionStatusTypes, 200); item.SubmissionStatusTypeID = null; } } else { //in edit mode use submission status from form item.SubmissionStatus = this.apiClient.getRefDataByID(refData.SubmissionStatusTypes, $("#edit_submissionstatus").val()); item.SubmissionStatusTypeID = null; /*item.DataProvider = this.ocm_data.getRefDataByID(refData.DataProviders, $("#edit_dataprovider").val()); item.DataProviderID = null;*/ } if (item.Connections == null) item.Connections = new Array(); //read settings from connection editors var numConnections = 0; for (var n = 1; n <= this.numConnectionEditors; n++) { var originalConnection = null; if (item.Connections.length >= n) { originalConnection = item.Connections[n - 1]; } var connectionInfo: OCM.ConnectionInfo = { "ID": -1, "Reference": null, "ConnectionType": this.apiClient.getRefDataByID(refData.ConnectionTypes, $("#edit_connection" + n + "_connectiontype").val()), "StatusType": this.apiClient.getRefDataByID(refData.StatusTypes, $("#edit_connection" + n + "_status").val()), "Level": this.apiClient.getRefDataByID(refData.ChargerTypes, $("#edit_connection" + n + "_level").val()), "CurrentType": this.apiClient.getRefDataByID(refData.CurrentTypes, $("#edit_connection" + n + "_currenttype").val()), "Amps": $("#edit_connection" + n + "_amps").val(), "Voltage": $("#edit_connection" + n + "_volts").val(), "PowerKW": $("#edit_connection" + n + "_powerkw").val(), "Quantity": $("#edit_connection" + n + "_quantity").val() }; //preserve original connection info not editable in this editor if (originalConnection != null) { connectionInfo.ID = originalConnection.ID; connectionInfo.Reference = originalConnection.Reference; connectionInfo.Comments = originalConnection.Comments; } //add new connection or update existing if (item.Connections.length >= n) { item.Connections[n - 1] = connectionInfo; } else { item.Connections.push(connectionInfo); } } //stored attribution metadata if any if (this.positionAttribution != null) { //add/update position attributiom if (item.MetadataValues == null) item.MetadataValues = new Array(); var attributionMetadata = this.apiClient.getMetadataValueByMetadataFieldID(item.MetadataValues, this.apiClient.ATTRIBUTION_METADATAFIELDID); if (attributionMetadata != null) { attributionMetadata.ItemValue = this.positionAttribution; } else { attributionMetadata = { MetadataFieldID: this.apiClient.ATTRIBUTION_METADATAFIELDID, ItemValue: this.positionAttribution }; item.MetadataValues.push(attributionMetadata); } } else { //clear position attribution if required var attributionMetadata = this.apiClient.getMetadataValueByMetadataFieldID(item.MetadataValues, this.apiClient.ATTRIBUTION_METADATAFIELDID); if (attributionMetadata != null) { //remove existing item from array item.MetadataValues = jQuery.grep(item.MetadataValues, function (a: any, i: number) { return a.MetadataFieldID !== app.apiClient.ATTRIBUTION_METADATAFIELDID; }); } } //show progress indicator this.showProgressIndicator(); this.appState.isSubmissionInProgress = true; //submit this.apiClient.submitLocation(item, this.getLoggedInUserInfo(), function (jqXHR, textStatus) { app.submissionCompleted(jqXHR, textStatus); //refresh POI details via API if (item.ID > 0) { app.showDetailsViewById(item.ID, true); app.navigateToLocationDetails(); } } , $.proxy(app.submissionFailed, app) ); } } showLocationEditor() { this.resetEditorForm(); //populate editor with currently selected poi if (this.viewModel.selectedPOI != null) { this.isLocationEditMode = true; var poi = this.viewModel.selectedPOI; this.positionAttribution = null; //load existing position attribution (if any) if (poi.MetadataValues != null) { var attributionMetadata = this.apiClient.getMetadataValueByMetadataFieldID(poi.MetadataValues, this.apiClient.ATTRIBUTION_METADATAFIELDID); if (attributionMetadata != null) { this.positionAttribution = attributionMetadata.ItemValue; } } $("#edit_addressinfo_title").val(poi.AddressInfo.Title); $("#edit_addressinfo_addressline1").val(poi.AddressInfo.AddressLine1); $("#edit_addressinfo_addressline2").val(poi.AddressInfo.AddressLine2); $("#edit_addressinfo_town").val(poi.AddressInfo.Town); $("#edit_addressinfo_stateorprovince").val(poi.AddressInfo.StateOrProvince); $("#edit_addressinfo_postcode").val(poi.AddressInfo.Postcode); this.setDropdown("edit_addressinfo_countryid", poi.AddressInfo.Country.ID); $("#edit_addressinfo_latitude").val(poi.AddressInfo.Latitude); $("#edit_addressinfo_longitude").val(poi.AddressInfo.Longitude); //show map based on current position this.refreshEditorMap(); $("#edit_addressinfo_accesscomments").val(poi.AddressInfo.AccessComments); $("#edit_addressinfo_contacttelephone1").val(poi.AddressInfo.ContactTelephone1); $("#edit_addressinfo_contacttelephone2").val(poi.AddressInfo.ContactTelephone2); $("#edit_addressinfo_contactemail").val(poi.AddressInfo.ContactEmail); $("#edit_addressinfo_relatedurl").val(poi.AddressInfo.RelatedURL); $("#edit_numberofpoints").val(poi.NumberOfPoints); $("#edit_usagecost").val(poi.UsageCost); $("#edit_generalcomments").val(poi.GeneralComments); this.setDropdown("edit_usagetype", poi.UsageType != null ? poi.UsageType.ID : "0"); this.setDropdown("edit_statustype", poi.StatusType != null ? poi.StatusType.ID : "50"); this.setDropdown("edit_submissionstatus", poi.SubmissionStatus != null ? poi.SubmissionStatus.ID : "1"); this.setDropdown("edit_operator", poi.OperatorInfo != null ? poi.OperatorInfo.ID : "1"); this.setDropdown("edit_dataprovider", poi.DataProvider != null ? poi.DataProvider.ID : "1"); //show edit-only mode dropdowns $("#edit-operator-container").show(); $("#edit-submissionstatus-container").show(); /*$("#edit-dataprovider-container").show();*/ //populate connection editor(s) if (poi.Connections != null) { for (var n = 1; n <= this.numConnectionEditors; n++) { var $connection = ($("#edit_connection" + n)); $connection.removeClass("panel-primary"); $connection.removeClass("panel-default"); if (poi.Connections.length >= n) { //create editor section var con = poi.Connections[n - 1]; if (con != null) { if ($connection.length > 0) { //populate connection editor this.setDropdown("edit_connection" + n + "_connectiontype", con.ConnectionType != null ? con.ConnectionType.ID : "0"); this.setDropdown("edit_connection" + n + "_level", con.Level != null ? con.Level.ID : ""); this.setDropdown("edit_connection" + n + "_status", con.StatusType != null ? con.StatusType.ID : "0"); this.setDropdown("edit_connection" + n + "_currenttype", con.CurrentType != null ? con.CurrentType.ID : ""); $("#edit_connection" + n + "_amps").val(con.Amps); $("#edit_connection" + n + "_volts").val(con.Voltage); $("#edit_connection" + n + "_quantity").val(con.Quantity); $("#edit_connection" + n + "_powerkw").val(con.PowerKW); $connection.data("_connection_id", con.ID); $connection.addClass("panel-primary"); } } } else { //null data (if present) from connection editor $connection.data("_connection_id", 0); $connection.addClass("panel-default"); } } } } } refreshEditorMap() { var lat = parseFloat($("#edit_addressinfo_latitude").val()); var lng = parseFloat($("#edit_addressinfo_longitude").val()); if (this.editorMap != null) { if (this.editorMap != null) { this.editMarker.setLatLng([lat, lng]); this.editorMap.panTo([lat, lng]); $("#editor-map").show(); } } else { this.initEditorMap(lat, lng); } } initEditorMap(currentLat, currentLng) { if (this.editorMapInitialised === false) { this.editorMapInitialised = true; var app = this; //listen for changes to lat/lng input boxes $('#edit_addressinfo_latitude, #edit_addressinfo_longitude').change(function () { if (app.editorMap != null) { //reflect new pos on map app.refreshEditorMap(); //clear attribution when manually modified app.positionAttribution = null; } }) // Create editor map view $("#editor-map").show(); this.editorMap = this.mappingManager.createMapLeaflet("editor-map-canvas", currentLat, currentLng, false, 14); var unknownPowerMarker = L.AwesomeMarkers.icon({ icon: 'bolt', color: 'darkpurple' }); this.editMarker = new (<any>L).Marker(new (<any>L).LatLng(currentLat, currentLng), { draggable: true }); this.editMarker.addTo(this.editorMap); $("#editor-map-canvas").show(); this.editMarker.on("dragend", function () { //move map to new map centre var point = app.editMarker.getLatLng(); app.editorMap.panTo(point); $("#edit_addressinfo_latitude").val(point.lat); $("#edit_addressinfo_longitude").val(point.lng); //suggest new address as well? //clear attribution when manually modified app.positionAttribution = null; }); //refresh map rendering var map = this.editorMap; setTimeout(function () { map.invalidateSize(false); }, 300); } else { var point = app.editMarker.getLatLng(); app.editorMap.panTo(point); } } hasUserPermissionForPOI(poi, permissionLevel) { var userInfo = this.getLoggedInUserInfo(); if (userInfo.Permissions != null) { if (userInfo.Permissions.indexOf("[Administrator=true]") != -1) { return true; } if (permissionLevel == "Edit") { //check if user has country level or all countries edit permission if (userInfo.Permissions.indexOf("[CountryLevel_Editor=All]") != -1) { return true; } if (poi.AddressInfo.Country != null) { if (userInfo.Permissions.indexOf("[CountryLevel_Editor=" + poi.AddressInfo.Country.ID + "]") != -1) { return true; } } } } return false; } } }
the_stack
import { createElement, L10n, isNullOrUndefined } from '@syncfusion/ej2-base'; import { RadioButton, ChangeArgs, CheckBox } from '@syncfusion/ej2-buttons'; import { DocumentEditor } from '../../document-editor'; import { DocumentHelper, ElementBox } from '../viewer'; import { FieldElementBox, CheckBoxFormField } from '../viewer/page'; import { NumericTextBox, TextBox } from '@syncfusion/ej2-inputs'; /** * Form field checkbox dialog is used to modify the value in checkbox form field. */ export class CheckBoxFormFieldDialog { private target: HTMLElement; private owner: DocumentEditor; private autoButton: RadioButton; private exactButton: RadioButton; private notCheckedButton: RadioButton; private checkedButton: RadioButton; private bookmarkInputText: HTMLInputElement; private tooltipInputText: HTMLInputElement; private checBoxEnableElement: CheckBox; private exactlyNumber: NumericTextBox; private exactNumberDiv: HTMLElement; private fieldBegin: FieldElementBox; /** * @param {DocumentHelper} owner - Specifies the document helper. * @private */ public constructor(owner: DocumentEditor) { this.owner = owner; } private get documentHelper(): DocumentHelper { return this.owner.documentHelper; } private getModuleName(): string { return 'CheckBoxFormFieldDialog'; } /* eslint-disable */ /** * @private * @param {L10n} locale - Specifies the locale. * @param {boolean} isRtl - Specifies is rtl. * @returns {void} */ private initCheckBoxDialog(localValue: L10n, isRtl?: boolean): void { this.target = createElement('div'); let dialogDiv: HTMLDivElement = createElement('div') as HTMLDivElement; let headingLabel: HTMLElement = createElement('div', { className: 'e-de-para-dlg-heading', innerHTML: localValue.getConstant('Check box size') }); let sizeParentDiv: HTMLElement = createElement('div', {className: 'e-de-container-row'}) as HTMLDivElement; let autoDiv: HTMLElement = createElement('div', { className: 'e-de-ff-radio-scnd-div' }) as HTMLDivElement; let exactDiv: HTMLElement = createElement('div', { className: 'e-de-ff-radio-scnd-div' }) as HTMLDivElement; let autoEle: HTMLElement = createElement('input', { className: 'e-de-rtl-btn-div' }); let exactEle: HTMLElement = createElement('input', { className: 'e-de-rtl-btn-div' }); this.autoButton = new RadioButton({ label: localValue.getConstant('Auto'), cssClass: 'e-small', change: this.changeBidirectional, checked: true, enableRtl: isRtl }); this.exactButton = new RadioButton({ label: localValue.getConstant('Exactly'), value: 'exact', cssClass: 'e-small', change: this.changeBidirectional, enableRtl: isRtl }); this.exactNumberDiv = createElement('div', { className: 'e-de-ff-chck-exact' }); let exactNumber: HTMLInputElement = createElement('input', { attrs: { 'type': 'text' } }) as HTMLInputElement; this.exactlyNumber = new NumericTextBox({ format: 'n', value: 10, min: 1, max: 1584, enablePersistence: false, enabled: false, cssClass: 'e-de-check-exactnumbr-width', enableRtl: isRtl }); let defaultValueLabel: HTMLElement = createElement('div', { className: 'e-de-para-dlg-heading', innerHTML: localValue.getConstant('Default value') }); let defaultcheckDiv: HTMLElement = createElement('div', { className: 'e-de-container-row' }) as HTMLDivElement; let notcheckDiv: HTMLElement = createElement('div', { className: 'e-de-ff-radio-div' }) as HTMLDivElement; let checkDiv: HTMLElement = createElement('div', { className: 'e-de-ff-radio-div' }) as HTMLDivElement; let notcheckEle: HTMLElement = createElement('input', { className: 'e-de-rtl-btn-div' }); let checkEle: HTMLElement = createElement('input', { className: 'e-de-rtl-btn-div' }); this.notCheckedButton = new RadioButton({ label: localValue.getConstant('Not checked'), enableRtl: isRtl, cssClass: 'e-small', change: this.changeBidirect }); this.checkedButton = new RadioButton({ label: localValue.getConstant('Checked'), value: 'check', enableRtl: isRtl, cssClass: 'e-small', change: this.changeBidirect, checked: true }); let fieldSettingsLabel: HTMLElement = createElement('div', { className: 'e-de-para-dlg-heading', innerHTML: localValue.getConstant('Field settings') }); let settingsTotalDiv: HTMLElement = createElement('div', { className: 'e-de-container-row' }); let totalToolTipDiv: HTMLElement = createElement('div', { className: 'e-de-subcontainer-left' }); let totalBookmarkDiv: HTMLElement = createElement('div', { className: 'e-de-subcontainer-right' }); this.tooltipInputText = createElement('input', { className: 'e-input e-bookmark-textbox-input' }) as HTMLInputElement; this.bookmarkInputText = createElement('input', { className: 'e-input e-bookmark-textbox-input' }) as HTMLInputElement; let checkBoxEnableDiv: HTMLElement = createElement('div'); let checBoxEnableEle: HTMLInputElement = createElement('input', { attrs: { type: 'checkbox' } }) as HTMLInputElement; this.checBoxEnableElement = new CheckBox({ cssClass: 'e-de-ff-dlg-check', label: localValue.getConstant('Check box enabled'), enableRtl: isRtl }); if (isRtl) { autoDiv.classList.add('e-de-rtl'); exactDiv.classList.add('e-de-rtl'); this.exactNumberDiv.classList.add('e-de-rtl'); notcheckDiv.classList.add('e-de-rtl'); checkDiv.classList.add('e-de-rtl'); totalToolTipDiv.classList.add('e-de-rtl'); totalBookmarkDiv.classList.add('e-de-rtl'); } this.target.appendChild(dialogDiv); dialogDiv.appendChild(defaultValueLabel); dialogDiv.appendChild(defaultcheckDiv); defaultcheckDiv.appendChild(notcheckDiv); notcheckDiv.appendChild(notcheckEle); this.notCheckedButton.appendTo(notcheckEle); defaultcheckDiv.appendChild(checkDiv); checkDiv.appendChild(checkEle); this.checkedButton.appendTo(checkEle); dialogDiv.appendChild(headingLabel); dialogDiv.appendChild(sizeParentDiv); sizeParentDiv.appendChild(autoDiv); autoDiv.appendChild(autoEle); this.autoButton.appendTo(autoEle); sizeParentDiv.appendChild(exactDiv); exactDiv.appendChild(exactEle); this.exactButton.appendTo(exactEle); exactDiv.appendChild(this.exactNumberDiv); this.exactNumberDiv.appendChild(exactNumber); this.exactlyNumber.appendTo(exactNumber); dialogDiv.appendChild(fieldSettingsLabel); dialogDiv.appendChild(settingsTotalDiv); settingsTotalDiv.appendChild(totalToolTipDiv); settingsTotalDiv.appendChild(totalBookmarkDiv); totalToolTipDiv.appendChild(this.tooltipInputText); totalBookmarkDiv.appendChild(this.bookmarkInputText); dialogDiv.appendChild(checkBoxEnableDiv); checkBoxEnableDiv.appendChild(checBoxEnableEle); this.checBoxEnableElement.appendTo(checBoxEnableEle); new TextBox({placeholder: localValue.getConstant('Tooltip'), floatLabelType: 'Always'}, this.tooltipInputText); new TextBox({placeholder: localValue.getConstant('Name'), floatLabelType: 'Always'}, this.bookmarkInputText); } /** * @private * @returns {void} */ public show(): void { let localObj: L10n = new L10n('documenteditor', this.documentHelper.owner.defaultLocale); localObj.setLocale(this.documentHelper.owner.locale); if (isNullOrUndefined(this.target)) { this.initCheckBoxDialog(localObj, this.documentHelper.owner.enableRtl); } this.loadCheckBoxDialog(); this.documentHelper.dialog.header = localObj.getConstant('Check Box Form Field'); this.documentHelper.dialog.position = { X: 'center', Y: 'center' }; this.documentHelper.dialog.height = 'auto'; this.documentHelper.dialog.width = '400px'; this.documentHelper.dialog.content = this.target; this.documentHelper.dialog.buttons = [{ click: this.insertCheckBoxField, buttonModel: { content: localObj.getConstant('Ok'), cssClass: 'e-flat e-table-cell-margin-okay', isPrimary: true } }, { click: this.onCancelButtonClick, buttonModel: { content: localObj.getConstant('Cancel'), cssClass: 'e-flat e-table-cell-margin-cancel' } }]; this.documentHelper.dialog.show(); } /** * @private * @returns {void} */ public loadCheckBoxDialog(): void { let inline: ElementBox = this.owner.selection.getCurrentFormField(); if (inline instanceof FieldElementBox) { this.fieldBegin = inline; let fieldData: CheckBoxFormField = this.fieldBegin.formFieldData as CheckBoxFormField; if (!fieldData.defaultValue) { this.checkedButton.checked = false; this.notCheckedButton.checked = true; } else { this.checkedButton.checked = true; this.notCheckedButton.checked = false; } if (fieldData.sizeType !== 'Auto') { this.exactButton.checked = true; this.autoButton.checked = false; this.exactlyNumber.enabled = true; } else { this.autoButton.checked = true; this.exactButton.checked = false; this.exactlyNumber.enabled = false; } if (fieldData.size) { this.exactlyNumber.value = fieldData.size; } if (fieldData.enabled) { this.checBoxEnableElement.checked = true; } else { this.checBoxEnableElement.checked = false; } if (fieldData.name && fieldData.name !== '') { (this.bookmarkInputText as HTMLInputElement).value = fieldData.name; } else { (this.bookmarkInputText as HTMLInputElement).value = ''; } if (fieldData.helpText && fieldData.helpText !== '') { (this.tooltipInputText as HTMLInputElement).value = fieldData.helpText; } else { (this.tooltipInputText as HTMLInputElement).value = ''; } } } /** * @private * @param {ChangeArgs} event - Specifies the event args. * @returns {void} */ public changeBidirectional = (event: ChangeArgs): void => { if (event.value === 'exact') { this.autoButton.checked = !this.exactButton.checked; this.exactlyNumber.enabled = true; } else { this.exactButton.checked = !this.autoButton.checked; this.exactlyNumber.enabled = false; } } /** * @private * @param {ChangeArgs} event - Specifies the event args. * @returns {void} */ public changeBidirect = (event: ChangeArgs): void => { if (event.value === 'check') { this.notCheckedButton.checked = !this.checkedButton.checked; } else { this.checkedButton.checked = !this.notCheckedButton.checked; } } /** * @private * @returns {void} */ public onCancelButtonClick = (): void => { this.documentHelper.dialog.hide(); } /** * @private * @returns {void} */ public insertCheckBoxField = (): void => { this.closeCheckBoxField(); let checkBoxField: CheckBoxFormField = new CheckBoxFormField(); checkBoxField.defaultValue = this.checkedButton.checked; checkBoxField.name = (this.bookmarkInputText as HTMLInputElement).value; checkBoxField.helpText = (this.tooltipInputText as HTMLInputElement).value; checkBoxField.checked = checkBoxField.defaultValue; checkBoxField.enabled = this.checBoxEnableElement.checked; if (this.exactButton.checked) { checkBoxField.sizeType = 'Exactly'; checkBoxField.size = this.exactlyNumber.value; } else { checkBoxField.sizeType = 'Auto'; checkBoxField.size = 11; } this.owner.editor.editFormField('CheckBox', checkBoxField); } /** * @private * @returns {void} */ private closeCheckBoxField = (): void => { this.documentHelper.dialog.hide(); this.documentHelper.dialog.element.style.pointerEvents = ''; } /** * @private * @returns {void} */ private destroy(): void { let checkBoxDialogTarget: HTMLElement = this.target; if (checkBoxDialogTarget) { if (checkBoxDialogTarget.parentElement) { checkBoxDialogTarget.parentElement.removeChild(checkBoxDialogTarget); } this.target = undefined; } this.owner = undefined; if (this.autoButton) { this.autoButton.destroy(); this.autoButton = undefined; } if (this.exactButton) { this.exactButton.destroy(); this.exactButton = undefined; } if (this.notCheckedButton) { this.notCheckedButton.destroy(); this.notCheckedButton = undefined; } if (this.checkedButton) { this.checkedButton.destroy(); this.checkedButton = undefined; } this.bookmarkInputText = undefined; this.tooltipInputText = undefined; if (this.checBoxEnableElement) { this.checBoxEnableElement.destroy(); this.checBoxEnableElement = undefined; } if (this.exactlyNumber) { this.exactlyNumber.destroy(); this.exactlyNumber = undefined; } this.exactNumberDiv = undefined; } }
the_stack
import type { Operation } from '../http/Operation'; import type { ErrorHandler } from '../http/output/error/ErrorHandler'; import { RedirectResponseDescription } from '../http/output/response/RedirectResponseDescription'; import { ResponseDescription } from '../http/output/response/ResponseDescription'; import { BasicRepresentation } from '../http/representation/BasicRepresentation'; import { getLoggerFor } from '../logging/LogUtil'; import type { HttpRequest } from '../server/HttpRequest'; import type { OperationHttpHandlerInput } from '../server/OperationHttpHandler'; import { OperationHttpHandler } from '../server/OperationHttpHandler'; import type { RepresentationConverter } from '../storage/conversion/RepresentationConverter'; import { APPLICATION_JSON } from '../util/ContentTypes'; import { BadRequestHttpError } from '../util/errors/BadRequestHttpError'; import { joinUrl, trimTrailingSlashes } from '../util/PathUtil'; import { addTemplateMetadata, cloneRepresentation } from '../util/ResourceUtil'; import { readJsonStream } from '../util/StreamUtil'; import type { ProviderFactory } from './configuration/ProviderFactory'; import type { Interaction } from './interaction/email-password/handler/InteractionHandler'; import type { InteractionRoute, TemplatedInteractionResult } from './interaction/routing/InteractionRoute'; import type { InteractionCompleter } from './interaction/util/InteractionCompleter'; // Registration is not standardized within Solid yet, so we use a custom versioned API for now const API_VERSION = '0.2'; export interface IdentityProviderHttpHandlerArgs { /** * Base URL of the server. */ baseUrl: string; /** * Relative path of the IDP entry point. */ idpPath: string; /** * Used to generate the OIDC provider. */ providerFactory: ProviderFactory; /** * All routes handling the custom IDP behaviour. */ interactionRoutes: InteractionRoute[]; /** * Used for content negotiation. */ converter: RepresentationConverter; /** * Used for POST requests that need to be handled by the OIDC library. */ interactionCompleter: InteractionCompleter; /** * Used for converting output errors. */ errorHandler: ErrorHandler; } /** * Handles all requests relevant for the entire IDP interaction, * by sending them to either a matching {@link InteractionRoute}, * or the generated Provider from the {@link ProviderFactory} if there is no match. * * The InteractionRoutes handle all requests where we need custom behaviour, * such as everything related to generating and validating an account. * The Provider handles all the default request such as the initial handshake. * * This handler handles all requests since it assumes all those requests are relevant for the IDP interaction. * A {@link RouterHandler} should be used to filter out other requests. */ export class IdentityProviderHttpHandler extends OperationHttpHandler { protected readonly logger = getLoggerFor(this); private readonly baseUrl: string; private readonly providerFactory: ProviderFactory; private readonly interactionRoutes: InteractionRoute[]; private readonly converter: RepresentationConverter; private readonly interactionCompleter: InteractionCompleter; private readonly errorHandler: ErrorHandler; private readonly controls: Record<string, string>; public constructor(args: IdentityProviderHttpHandlerArgs) { // It is important that the RequestParser does not read out the Request body stream. // Otherwise we can't pass it anymore to the OIDC library when needed. super(); // Trimming trailing slashes so the relative URL starts with a slash after slicing this off this.baseUrl = trimTrailingSlashes(joinUrl(args.baseUrl, args.idpPath)); this.providerFactory = args.providerFactory; this.interactionRoutes = args.interactionRoutes; this.converter = args.converter; this.interactionCompleter = args.interactionCompleter; this.errorHandler = args.errorHandler; this.controls = Object.assign( {}, ...this.interactionRoutes.map((route): Record<string, string> => this.getRouteControls(route)), ); } /** * Finds the matching route and resolves the operation. */ public async handle({ operation, request, response }: OperationHttpHandlerInput): Promise<ResponseDescription | undefined> { // This being defined means we're in an OIDC session let oidcInteraction: Interaction | undefined; try { const provider = await this.providerFactory.getProvider(); // This being defined means we're in an OIDC session oidcInteraction = await provider.interactionDetails(request, response); } catch { // Just a regular request } // If our own interaction handler does not support the input, it is either invalid or a request for the OIDC library const route = await this.findRoute(operation, oidcInteraction); if (!route) { const provider = await this.providerFactory.getProvider(); this.logger.debug(`Sending request to oidc-provider: ${request.url}`); // Even though the typings do not indicate this, this is a Promise that needs to be awaited. // Otherwise the `BaseHttpServerFactory` will write a 404 before the OIDC library could handle the response. // eslint-disable-next-line @typescript-eslint/await-thenable await provider.callback(request, response); return; } // Cloning input data so it can be sent back in case of errors let clone = operation.body; // IDP handlers expect JSON data if (!operation.body.isEmpty) { const args = { representation: operation.body, preferences: { type: { [APPLICATION_JSON]: 1 }}, identifier: operation.target, }; operation.body = await this.converter.handleSafe(args); clone = await cloneRepresentation(operation.body); } const result = await route.handleOperation(operation, oidcInteraction); // Reset the body so it can be reused when needed for output operation.body = clone; return this.handleInteractionResult(operation, request, result, oidcInteraction); } /** * Finds a route that supports the given request. */ private async findRoute(operation: Operation, oidcInteraction?: Interaction): Promise<InteractionRoute | undefined> { if (!operation.target.path.startsWith(this.baseUrl)) { // This is either an invalid request or a call to the .well-known configuration return; } const pathName = operation.target.path.slice(this.baseUrl.length); for (const route of this.interactionRoutes) { if (route.supportsPath(pathName, oidcInteraction?.prompt.name)) { return route; } } } /** * Creates a ResponseDescription based on the InteractionHandlerResult. * This will either be a redirect if type is "complete" or a data stream if the type is "response". */ private async handleInteractionResult(operation: Operation, request: HttpRequest, result: TemplatedInteractionResult, oidcInteraction?: Interaction): Promise<ResponseDescription> { let responseDescription: ResponseDescription | undefined; if (result.type === 'complete') { if (!oidcInteraction) { throw new BadRequestHttpError( 'This action can only be performed as part of an OIDC authentication flow.', { errorCode: 'E0002' }, ); } // Create a redirect URL with the OIDC library const location = await this.interactionCompleter.handleSafe({ ...result.details, request }); responseDescription = new RedirectResponseDescription(location); } else if (result.type === 'error') { // We want to show the errors on the original page in case of html interactions, so we can't just throw them here const preferences = { type: { [APPLICATION_JSON]: 1 }}; const response = await this.errorHandler.handleSafe({ error: result.error, preferences }); const details = await readJsonStream(response.data!); // Add the input data to the JSON response; if (!operation.body.isEmpty) { details.prefilled = await readJsonStream(operation.body.data); // Don't send passwords back delete details.prefilled.password; delete details.prefilled.confirmPassword; } responseDescription = await this.handleResponseResult(details, operation, result.templateFiles, oidcInteraction, response.statusCode); } else { // Convert the response object to a data stream responseDescription = await this.handleResponseResult(result.details ?? {}, operation, result.templateFiles, oidcInteraction); } return responseDescription; } /** * Converts an InteractionResponseResult to a ResponseDescription by first converting to a Representation * and applying necessary conversions. */ private async handleResponseResult(details: Record<string, any>, operation: Operation, templateFiles: Record<string, string>, oidcInteraction?: Interaction, statusCode = 200): Promise<ResponseDescription> { const json = { ...details, apiVersion: API_VERSION, authenticating: Boolean(oidcInteraction), controls: this.controls, }; const representation = new BasicRepresentation(JSON.stringify(json), operation.target, APPLICATION_JSON); // Template metadata is required for conversion for (const [ type, templateFile ] of Object.entries(templateFiles)) { addTemplateMetadata(representation.metadata, templateFile, type); } // Potentially convert the Representation based on the preferences const args = { representation, preferences: operation.preferences, identifier: operation.target }; const converted = await this.converter.handleSafe(args); return new ResponseDescription(statusCode, converted.metadata, converted.data); } /** * Converts the controls object of a route to one with full URLs. */ private getRouteControls(route: InteractionRoute): Record<string, string> { const entries = Object.entries(route.getControls()) .map(([ name, path ]): [ string, string ] => [ name, joinUrl(this.baseUrl, path) ]); return Object.fromEntries(entries); } }
the_stack
import * as d3ScaleChromatic from 'd3-scale-chromatic' import * as d3Scale from 'd3-scale' import { Data, Mdata, IsMdata } from '@/components/Mindmap/interface' import { BoundingBox, Layout } from './flextree' type GetSize = (text: string) => { width: number, height: number } type Processer = (d: Mdata, id: string) => void const swapWidthAndHeight = (d: Mdata) => [d.width, d.height] = [d.height, d.width] const renewDelta = (d: Mdata) => { if (d.parent) { d.dx = d.x - d.parent.x d.dy = d.y - d.parent.y } else { d.dx = 0 d.dy = 0 } } const renewId = (d: Mdata, id: string) => d.id = id const renewDepth = (d: Mdata) => { if (d.parent) { d.depth = d.parent.depth + 1 } else { d.depth = 0 } } const renewColor = (d: Mdata): void => { if (d.parent && d.parent.color) { d.color = d.parent.color } } const renewLeft = (d: Mdata) => { if (d.depth > 1 && d.parent) { d.left = d.parent.left } } const separateLeftAndRight = (d: Mdata): { left: Mdata, right: Mdata } => { const ld = Object.assign({}, d) const rd = Object.assign({}, d) if (d.collapse) { // } else { const { children } = d ld.children = [] rd.children = [] children.forEach((child) => { if (child.left) { ld.children.push(child) } else { rd.children.push(child) } if (child.parent) { child.parent = rd } }) } return { left: ld, right: rd } } /** * 遍历数据d,在此过程中会对每个数据调用指定函数,同时删除id为del的数据,不处理被折叠的数据 * @param d - 数据 * @param processers - 函数 * @param id - 新id */ const traverse = (d: Mdata, processers: Processer[], id = '0') => { processers.forEach((p) => { p(d, id) }) const { children } = d if (children) { for (let index = 0; index < children.length; ) { const child = children[index] if (child.id === 'del') { children.splice(index, 1) d.rawData.children?.splice(index, 1) } else { traverse(child, processers, `${id}-${index}`) index += 1 } } } } const getLayout = (xGap: number, yGap: number) => { const bb = new BoundingBox(yGap, xGap) return new Layout(bb) } class ImData { data: Mdata private getSize: GetSize private layout: Layout private colorScale: d3Scale.ScaleOrdinal<string, string, never> private colorNumber = 0 private gKey = 0 private rootWidth = 0 private diffY = 0 // 左树与右树的差值 constructor ( d: Data, xGap: number, yGap: number, getSize: GetSize, colorScale = d3Scale.scaleOrdinal(d3ScaleChromatic.schemePaired) ) { this.colorScale = colorScale this.getSize = getSize this.layout = getLayout(xGap, yGap) this.data = this.createMdataFromData(d, '0') this.renew() } private createMdataFromData (rawData: Data, id: string, parent: IsMdata = null): Mdata { const { name, collapse, children: rawChildren } = rawData const { width, height } = this.getSize(name) const depth = parent ? parent.depth + 1 : 0 let left = false let color = parent ? parent.color : '' if (depth === 1) { left = !!rawData.left color = this.colorScale(`${this.colorNumber += 1}`) } else if (depth !== 0 && parent) { left = parent.left } const data: Mdata = { id, name, rawData, parent, left, color, depth, x: 0, y: 0, dx: 0, dy: 0, px: 0, py: 0, width, height, children: [], _children: [], collapse: !!collapse, gKey: this.gKey += 1, } if (rawChildren) { if (!data.collapse) { rawChildren.forEach((c, j) => { data.children.push(this.createMdataFromData(c, `${id}-${j}`, data)) }) } else { rawChildren.forEach((c, j) => { data._children.push(this.createMdataFromData(c, `${id}-${j}`, data)) }) } } return data } /** * 默认更新x, y, dx, dy, left, depth * @param plugins - 需要更新其他属性时的函数 */ private renew (...plugins: Processer[]): void { traverse(this.data, [swapWidthAndHeight, renewDepth, renewLeft]) this.data = this.l(this.data) const temp: Processer[] = [swapWidthAndHeight, this.renewXY.bind(this), renewDelta] traverse(this.data, temp.concat(plugins)) } /** * 分别计算左右树,最后合并成一颗树,右树为主树 */ private l (data: Mdata): Mdata { const { left, right } = separateLeftAndRight(data) this.layout.layout(left) // 更新x,y this.layout.layout(right) this.diffY = right.x - left.x this.rootWidth = left.height right.children = data.children // children原顺序 return right } private renewXY (d: Mdata): void { [d.x, d.y] = [d.y, d.x] if (d.left) { d.x = -d.x + this.rootWidth d.y += this.diffY } } getRootWidth (): number { return this.rootWidth } setBoundingBox (xGap: number, yGap: number): void { this.layout = getLayout(xGap, yGap) this.renew() } find (id: string): IsMdata { // 根据id找到数据 const array = id.split('-').map(n => ~~n) let data = this.data for (let i = 1; i < array.length; i++) { const index = array[i] const { children } = data if (index < children.length) { data = children[index] } else { // No data matching id return null } } return data.id === id ? data : null } rename (id: string, name: string): IsMdata { // 修改名称 if (id.length > 0) { const d = this.find(id) if (d && d.name !== name) { d.name = name d.rawData.name = name // const size = this.getSize(d.name) d.width = size.width d.height = size.height this.renew() } return d } else { return null } } /** * 将b节点移动到a节点下 * @param parentId - 目标节点a * @param delId - 被移动节点b */ moveChild (parentId: string, delId: string): IsMdata { if (parentId === delId) { return null } const np = this.find(parentId) const del = this.find(delId) const delIndex = delId.split('-').pop() if (delIndex && np && del) { const delParent = del.parent delParent?.children?.splice(~~delIndex, 1) delParent?.rawData.children?.splice(~~delIndex, 1) del.parent = np del.gKey = this.gKey += 1 del.depth = del.parent.depth + 1 if (del.depth === 1) { del.color = this.colorScale(`${this.colorNumber += 1}`) } else { del.left = del.parent.left } if (np.collapse) { np._children.push(del) } else { np.children.push(del) } np.rawData.children ? np.rawData.children.push(del.rawData) : np.rawData.children = [del.rawData] this.renew(renewId, renewColor) } return del } moveSibling (id: string, referenceId: string, after = 0): IsMdata { // 同层调换顺序 const idArr = id.split('-') const refArr = referenceId.split('-') let index: number | string | undefined = idArr.pop() let refIndex: number | string | undefined = refArr.pop() if (id === referenceId || idArr.length !== refArr.length || !index || !refIndex) { return null } const d = this.find(id) const r = this.find(referenceId) if (r && d && d.parent) { index = parseInt(index, 10) refIndex = parseInt(refIndex, 10) if (index < refIndex) { refIndex -= 1 } // 删除时可能会改变插入的序号 const { children } = d.parent const { children: rawChildren } = d.parent.rawData if (children && rawChildren) { children.splice(index, 1) children.splice(refIndex + after, 0, d) rawChildren.splice(index, 1) rawChildren.splice(refIndex + after, 0, d.rawData) if (d.depth === 1) { d.left = r.left } this.renew(renewId) return d } } return null } add (id: string, variable: string | Data): IsMdata { const p = this.find(id) if (p) { if (p.collapse) { this.expand(id) } if (!p.rawData.children) { p.rawData.children = [] } if (typeof variable === 'string') { const name = variable const size = this.getSize(name) const rawData: Data = { name } const color = p.color ? p.color : this.colorScale(`${this.colorNumber += 1}`) const d: Mdata = { id: `${p.id}-${p.children.length}`, name, rawData, parent: p, left: p.left, collapse: false, color, gKey: this.gKey += 1, width: size.width, height: size.height, depth: p.depth + 1, x: 0, y: 0, dx: 0, dy: 0, px: 0, py: 0, children: [], _children: [] } p.children.push(d) p.rawData.children.push(rawData) this.renew() return d } else { const rawData = variable const m = this.createMdataFromData(rawData, `${p.id}-${p.children.length}`, p) p.children.push(m) p.rawData.children.push(rawData) this.renew() return m } } return null } expand (id: string): IsMdata { return this.eoc(id, false, [renewColor, renewId]) } collapse (id: string): IsMdata { return this.eoc(id, true) } /** * 展开或折叠(expand or collapse) */ eoc (id: string, collapse: boolean, plugins: Processer[] = []): IsMdata { const d = this.find(id) if (d) { d.collapse = collapse d.rawData.collapse = collapse ;[d._children, d.children] = [d.children, d._children] this.renew(...plugins) } return d } delete (id: string): void { const del = this.find(id) if (del && del.parent) { del.id = 'del' this.renew(renewId) } else { throw new Error(del ? '暂不支持删除根节点' : '未找到需要删除的节点') } } deleteOne (id: string): void { const del = this.find(id) if (del && del.parent) { const { parent, children, _children, collapse, rawData } = del const index = parseInt(id.split('-').pop() as string, 10) parent.children.splice(index, 1, ...(collapse ? _children : children)) parent.rawData.children?.splice(index, 1, ...(rawData.children || [])) children.forEach(c => { c.parent = parent if (c.depth === 1) { c.rawData.left = c.left } }) this.renew(renewId) } } addSibling (id: string, name: string, before = false): IsMdata { const d = this.find(id) if (d && d.parent) { const index = parseInt(id.split('-').pop() as string, 10) const { parent, left } = d const rawSibling: Data = { name, left } const size = this.getSize(name) const start = before ? index : index + 1 const color = parent.color ? parent.color : this.colorScale(`${this.colorNumber += 1}`) const sibling: Mdata = { name, parent, children: [], _children: [], color, collapse: false, rawData: rawSibling, id: `${parent.id}-${start}`, left, gKey: this.gKey += 1, depth: d.depth, width: size.width, height: size.height, x: 0, y: 0, dx: 0, dy: 0, px: 0, py: 0, } parent.children.splice(start, 0, sibling) parent.rawData.children?.splice(start, 0, rawSibling) this.renew(renewId) return sibling } return null } addParent (id: string, name: string): IsMdata { const d = this.find(id) if (d && d.parent) { const { parent: oldP, left, color } = d const size = this.getSize(name) const index = parseInt(d.id.split('-').pop() as string, 10) const rawP: Data = { name, children: [d.rawData], left } oldP.rawData.children?.splice(index, 1, rawP) const p: Mdata = { rawData: rawP, left, name, color, collapse: false, parent: oldP, id: d.id, depth: d.depth, width: size.width, height: size.height, gKey: this.gKey += 1, children: [d], _children: [], x: 0, y: 0, dx: 0, dy: 0, px: 0, py: 0 } d.parent = p oldP.children.splice(index, 1, p) this.renew(renewId) return p } return null } changeLeft (id: string): IsMdata { const d = this.find(id) if (d) { d.left = !d.left this.renew() } return d } } export default ImData
the_stack
import {AfterViewInit, Component, ElementRef, HostBinding, Injector, OnDestroy, OnInit, ViewChild} from '@angular/core'; import {AbstractComponent} from '@common/component/abstract.component'; import {StateService} from '../service/state.service'; import {EngineService} from '../service/engine.service'; import {Engine} from '@domain/engine-monitoring/engine'; import {filter} from 'rxjs/operators'; import {StringUtil} from '@common/util/string.util'; import {CriterionComponent} from '../../data-storage/component/criterion/criterion.component'; import {Criteria} from '@domain/datasource/criteria'; import {ActivatedRoute} from '@angular/router'; import * as _ from 'lodash'; import {PageResult} from '@domain/common/page'; import {TimezoneService} from '../../data-storage/service/timezone.service'; import {EngineMonitoringUtil} from '../util/engine-monitoring.util'; import * as moment from 'moment'; declare let $: any; @Component({ selector: '[query]', templateUrl: './query.component.html', styles: ['.ddp-wrap-top-filtering .ddp-filter-search .ddp-form-filter-search {width: 280px;}'] }) export class QueryComponent extends AbstractComponent implements OnInit, OnDestroy, AfterViewInit { @HostBinding('class') public hostClass: string = 'ddp-wrap-contents-det'; // noinspection JSUnusedLocalSymbols constructor(protected elementRef: ElementRef, protected injector: Injector, private activatedRoute: ActivatedRoute, private stateService: StateService, private engineService: EngineService, private timezoneService: TimezoneService) { super(elementRef, injector); } @ViewChild(CriterionComponent) private readonly criterionComponent: CriterionComponent; public queryTotalList: any[]; public queryList: any[]; // search public searchKeyword: string; public selectedContentSort: Order = new Order(); public showDetail: boolean; public queryDetail: any; public ngOnInit() { super.ngOnInit(); this.subscriptions.push( this.stateService.changeTab$ .pipe(filter(({current}) => current.isQuery())) .subscribe(({next}) => this._changeTab(next)) ); // get criterion list this.engineService.getCriterionListInQuery() .then((result: Criteria.Criterion) => { // init criterion list this.criterionComponent.initCriterionList(result); this.subscriptions.push(this.activatedRoute.queryParams.subscribe(params => { const paramKeys = Object.keys(params); const isExistSearchParams = paramKeys.length > 0; const searchParams = {}; // if exist search param in URL if (isExistSearchParams) { paramKeys.forEach((key) => { if (key === 'size') { this.page.size = Number(params['size']); } else if (key === 'page') { this.page.page = Number(params['page']); } else if (key === 'sort') { const sortParam = params['sort'].split(','); this.selectedContentSort.key = sortParam[0]; this.selectedContentSort.sort = sortParam[1]; } else if (key === 'containsText') { this.searchKeyword = params['containsText']; } else { searchParams[key] = params[key].split(','); } }); // TODO 추후 criterion component로 이동 delete searchParams['pseudoParam']; // init criterion search param this.criterionComponent.initSearchParams(searchParams); } else { searchParams[Criteria.ListCriterionKey.STARTED_TIME + Criteria.QUERY_DELIMITER + Criteria.KEY_DATETIME_TYPE_SUFFIX] = ['BETWEEN']; searchParams[Criteria.ListCriterionKey.STARTED_TIME + Criteria.QUERY_DELIMITER + 'startedTimeFrom'] = [moment().subtract(1, 'hours').format('YYYY-MM-DDTHH:mm:ss.SSSZ')]; searchParams[Criteria.ListCriterionKey.STARTED_TIME + Criteria.QUERY_DELIMITER + 'startedTimeTo'] = [moment().format('YYYY-MM-DDTHH:mm:ss.SSSZ')]; this.criterionComponent.initSearchParams(searchParams); } this.pageResult.size = this.page.size; this.pageResult.number = this.page.page; this._getQueryList(); })); }) .catch(error => this.commonExceptionHandler(error)); } public ngAfterViewInit() { super.ngAfterViewInit(); } public ngOnDestroy() { super.ngOnDestroy(); } public isEmptyList(): boolean { return this.pageResult.totalElements === 0 || this.queryTotalList === undefined; } public reloadPage(isFirstPage: boolean = true) { (isFirstPage) && (this.page.page = 0); this.router.navigate( [this.router.url.replace(/\?.*/gi, '')], {queryParams: this._getQueryParams(), replaceUrl: true} ).then(); } // function - reloadPage public changePage(data: { page: number, size: number }): void { // if more datasource list if (data) { this.page.page = data.page; this.page.size = data.size; this._getQueryPagingList(); } } /** * Search connection keypress event * @param {string} keyword */ public onChangedSearchKeyword(keyword: string): void { // set search keyword this.searchKeyword = keyword; // reload page this.reloadPage(true); } public highlightSearchText(name, searchText): string { return EngineMonitoringUtil.highlightSearchText(name, searchText); } // function - highlightSearchText /** * Changed filter * @param _searchParams */ public onChangedFilter(_searchParams): void { // reload page this.reloadPage(true); } /** * criterion api function * @param criterionKey * @returns {Promise<any>} */ public criterionApiFunc(criterionKey: any) { // require injector in constructor return this.injector.get(EngineService).getCriterionInQuery(criterionKey); } public sortQueryList(key: string): void { // set selected sort if (this.selectedContentSort.key !== key) { this.selectedContentSort.key = key; this.selectedContentSort.sort = 'desc'; } else { // asc, desc switch (this.selectedContentSort.sort) { case 'asc': this.selectedContentSort.sort = 'desc'; break; case 'desc': this.selectedContentSort.sort = 'asc'; break; case 'default': this.selectedContentSort.sort = 'desc'; break; } } // reload page this.reloadPage(true); } public onClickQuery(query): void { this.queryDetail = query; this.showDetail = true; if (query.queryId !== '') { this._getQueryDetail(query.queryId); } } public closeDetail(): void { this.showDetail = false; this.queryDetail = undefined; } public getStatusClass(querySuccess: string): string { if ('true' === querySuccess) { return 'ddp-success'; } else if ('false' === querySuccess) { return 'ddp-fail'; } else { return ''; } } public get getTimezone(): string { return this.timezoneService.getBrowserTimezone().utc; } private _changeTab(contentType: Engine.ContentType) { this.router.navigate([`${Engine.Constant.ROUTE_PREFIX}${contentType}`]); } private _filteringQueryList(): any[] { // if search keyword not empty if (StringUtil.isNotEmpty(this.searchKeyword)) { return _.cloneDeep(this.queryTotalList).filter(item => { return item.queryId.indexOf(this.searchKeyword) > -1 || item.datasource.indexOf(this.searchKeyword) > -1; }) } else { return _.cloneDeep(this.queryTotalList); } } private _getQueryPagingList() { const list = this._filteringQueryList(); this.pageResult = new PageResult(); this.pageResult.size = this.page.size; this.pageResult.number = this.page.page; this.pageResult.totalElements = list.length; this.pageResult.totalPages = Math.ceil(this.pageResult.totalElements / this.pageResult.size); const endSize = (this.page.page + 1) * this.pageResult.size < this.pageResult.totalElements ? (this.page.page + 1) * this.pageResult.size : this.pageResult.totalElements; this.queryList = list.slice(this.page.page * this.pageResult.size, endSize); } private _getQueryList() { const filterParam = this.criterionComponent.getSearchParams(); filterParam['key'] = this.selectedContentSort.key; filterParam['sort'] = this.selectedContentSort.sort === 'asc' ? 'asc' : 'desc'; this.loadingShow(); // if search keyword not empty this.engineService.getQueryList(filterParam).then((data) => { this.loadingHide(); this.queryTotalList = data; this._getQueryPagingList(); }).catch((error) => this.commonExceptionHandler(error)); } private _getQueryParams() { const params = { page: this.page.page, size: this.page.size, pseudoParam: (new Date()).getTime(), sort: this.selectedContentSort.key + ',' + this.selectedContentSort.sort }; const searchParams = this.criterionComponent.getUrlQueryParams(); // set criterion searchParams && Object.keys(searchParams).forEach((key) => { if (searchParams[key].length > 0) { params[key] = searchParams[key].join(','); } }); // if search keyword not empty if (StringUtil.isNotEmpty(this.searchKeyword)) { params['containsText'] = this.searchKeyword.trim(); } return params; } private _getQueryDetail(queryId: string) { this.loadingShow(); this.engineService.getQueryDetail(queryId).then((data: any[]) => { this.queryDetail['query'] = false; this.queryDetail['exception'] = false; this.queryDetail['querytime'] = false; this.loadingHide(); if (data.length > 0) { this.queryDetail['query'] = true; if (!_.isNil(data[0].exception)) { this.queryDetail['exception'] = data[0].exception; } if (!_.isNil(data[0].querytime)) { this.queryDetail['querytime'] = data[0].querytime; } setTimeout(() => { try { $('#queryInformation').html('<pre>' + JSON.stringify(JSON.parse(data[0].query), undefined, 4) + '</pre>'); } catch (e) { $('#queryInformation').text(data[0].query); } }, 50); } }).catch((error) => this.commonExceptionHandler(error)); } } class Order { key: string = '__time'; sort: string = 'default'; }
the_stack
import type { HunspellCosts, HunspellInformation } from '../models/DictionaryInformation'; import { hunspellInformationToSuggestionCostDef, __testing__ } from './mapHunspellInformation'; // cspell:ignore conv OCONV const { affMap, affRepConv, affNoTry, affTry, affKey, affTryFirstCharacterReplace, calcCosts, affMapCaps, affKeyCaps, affTryAccents, affMapAccents, } = __testing__; const sampleAff = ` # comment. # cspell:ignore eéèëê iíìïî TRY abc MAP 3 MAP eéèëê MAP aáà MAP iíìïî OCONV 2 OCONV ij ij OCONV IJ IJ ICONV 9 ICONV áá aa ICONV éé ee ICONV íé ie ICONV óó oo ICONV úú uu ICONV óé oe ICONV ’ ' ICONV ij ij ICONV IJ IJ REP ^ß ss NO-TRY -1234567890 # cspell:ignore asdfghjkl qwertyuiop zxcvbnm KEY qwertyuiop|asdfghjkl|zxcvbnm `; describe('mapHunspellInformation', () => { // cspell:ignore aàâä test.each` line | costs | expected ${''} | ${{}} | ${undefined} ${'MAP aàâäAÀÂÄ'} | ${{}} | ${{ map: 'aàâäAÀÂÄ', replace: 25, swap: 25 }} ${'MAP 😁😀😊😂🤣😬'} | ${{}} | ${{ map: '😁😀😊😂🤣😬', replace: 25, swap: 25 }} ${'MAP aàâäAÀÂÄ'} | ${{ mapCost: 1 }} | ${{ map: 'aàâäAÀÂÄ', replace: 1, swap: 1 }} ${'MAP ß(ss)'} | ${{}} | ${{ map: 'ß(ss)', replace: 25, swap: 25 }} `('affMap "$line" $costs', ({ line, costs, expected }) => { expect(affMap(line, calcCosts(costs))).toEqual(expected); }); test.each` line | costs | expected ${''} | ${{}} | ${undefined} ${'MAP aàâäAÀÂÄ'} | ${{}} | ${{ map: 'aA|àÀ|âÂ|äÄ|Aa|Àà|Ââ|Ää', replace: 1 }} ${'MAP 😁😀😊😂🤣😬'} | ${{}} | ${undefined} ${'MAP aàâäAÀÂÄ'} | ${c({ capsCosts: 2 })} | ${{ map: 'aA|àÀ|âÂ|äÄ|Aa|Àà|Ââ|Ää', replace: 2 }} ${'MAP ß(ss)'} | ${{}} | ${{ map: 'ß(SS)(ss)|(ss)(SS)', replace: 1 }} `('affMapCaps "$line" $costs', ({ line, costs, expected }) => { expect(affMapCaps(line, calcCosts(costs))).toEqual(expected); }); test.each` line | costs | expected ${''} | ${{}} | ${undefined} ${'MAP 😁😀😊😂🤣😬'} | ${{}} | ${[]} ${'MAP aàâäAÀÂÄ'} | ${{}} | ${[{ map: 'a(à)à|A(À)À|a(â)â|A(Â)Â|a(ä)ä|A(Ä)Ä', replace: 1 }, { map: '(à)à|(À)À|(â)â|(Â)Â|(ä)ä|(Ä)Ä|(À)À|(à)à|(Â)Â|(â)â|(Ä)Ä|(ä)ä', replace: 0 }]} ${'MAP aàâäAÀÂÄ'} | ${c({ accentCosts: 2 })} | ${[{ map: 'a(à)à|A(À)À|a(â)â|A(Â)Â|a(ä)ä|A(Ä)Ä', replace: 2 }, { map: '(à)à|(À)À|(â)â|(Â)Â|(ä)ä|(Ä)Ä|(À)À|(à)à|(Â)Â|(â)â|(Ä)Ä|(ä)ä', replace: 0 }]} ${'MAP ß(ss)'} | ${{}} | ${[]} `('affMapCaps "$line" $costs', ({ line, costs, expected }) => { expect(affMapAccents(line, calcCosts(costs))).toEqual(expected); }); test.each` line | costs | expected ${''} | ${{}} | ${undefined} ${'MAP aàâäAÀÂÄ'} | ${{}} | ${undefined} ${'NO-TRY aàâäAÀÂÄ'} | ${{}} | ${undefined} ${'TRY abc'} | ${c({ mapCost: 1 })} | ${[{ map: 'ABCabc', replace: 100, insDel: 100, swap: 100 }, { map: 'Aa|Bb|Cc', replace: 1 }]} ${'TRY abc'} | ${c({ tryCharCost: 90 })} | ${[{ map: 'ABCabc', replace: 90, insDel: 90, swap: 90 }, { map: 'Aa|Bb|Cc', replace: 1 }]} ${'TRY abc'} | ${c({ firstLetterPenalty: 10 })} | ${[{ map: 'ABCabc', replace: 100, insDel: 100, swap: 100 }, { map: 'Aa|Bb|Cc', replace: 1 }]} `('affTry "$line" $costs', ({ line, costs, expected }) => { expect(affTry(line, calcCosts(costs))).toEqual(expected); }); test.each` line | costs | expected ${''} | ${{}} | ${undefined} ${'MAP aàâäAÀÂÄ'} | ${{}} | ${undefined} ${'TRY aàâäAÀÂÄ'} | ${{}} | ${undefined} ${'NO-TRY abc'} | ${c({ mapCost: 1 })} | ${{ map: 'abc', insDel: 10, penalty: 210 }} ${'NO-TRY abc'} | ${c({ tryCharCost: 90 })} | ${{ map: 'abc', insDel: 20, penalty: 200 }} ${'NO-TRY abc'} | ${c({ firstLetterPenalty: 10 })} | ${{ map: 'abc', insDel: 10, penalty: 210 }} `('affNoTry "$line" $costs', ({ line, costs, expected }) => { expect(affNoTry(line, calcCosts(costs))).toEqual(expected); }); test.each` line | costs | expected ${''} | ${{}} | ${undefined} ${'MAP aàâäAÀÂÄ'} | ${{}} | ${undefined} ${'TRY abc'} | ${c({ mapCost: 1 })} | ${{ map: '(^a)(^b)(^c)(^)', replace: 96, penalty: 8 }} ${'TRY abc'} | ${c({ tryCharCost: 90 })} | ${{ map: '(^a)(^b)(^c)(^)', replace: 86, penalty: 8 }} ${'TRY abc'} | ${c({ firstLetterPenalty: 10 })} | ${{ map: '(^a)(^b)(^c)(^)', replace: 90, penalty: 20 }} `('affTryFirstCharacterReplace "$line" $costs', ({ line, costs, expected }) => { expect(affTryFirstCharacterReplace(line, calcCosts(costs))).toEqual(expected); }); // cspell:ignore qwer zxcv test.each` line | costs | expected ${''} | ${{}} | ${undefined} ${'MAP aàâäAÀÂÄ'} | ${{}} | ${undefined} ${'KEY qwer|asdf|zxcv'} | ${c({ mapCost: 1 })} | ${{ map: 'qw|we|er|as|sd|df|zx|xc|cv|QW|WE|ER|AS|SD|DF|ZX|XC|CV', replace: 99, swap: 99 }} ${'KEY qwer|a|asdf|zxcv'} | ${c({ keyboardCost: 74 })} | ${{ map: 'qw|we|er|as|sd|df|zx|xc|cv|QW|WE|ER|AS|SD|DF|ZX|XC|CV', replace: 74, swap: 74 }} ${'KEY qwer春😁|a|asdf|zxcv'} | ${c()} | ${{ map: 'qw|we|er|r春|春(😁)|as|sd|df|zx|xc|cv|QW|WE|ER|R春|AS|SD|DF|ZX|XC|CV', replace: 99, swap: 99 }} ${'KEY a😁b'} | ${c()} | ${{ map: 'a(😁)|(😁)b|A(😁)|(😁)B', replace: 99, swap: 99 }} `('affKey "$line" $costs', ({ line, costs, expected }) => { expect(affKey(line, calcCosts(costs))).toEqual(expected); }); test.each` line | costs | expected ${''} | ${{}} | ${undefined} ${'MAP aàâäAÀÂÄ'} | ${{}} | ${undefined} ${'KEY qwer|a|asdf|zxcv'} | ${c({ keyboardCost: 74 })} | ${{ map: 'qQ|wW|eE|rR|aA|sS|dD|fF|zZ|xX|cC|vV', replace: 1 }} ${'KEY qwer|a|asdf|zxcv'} | ${c({ capsCosts: 2 })} | ${{ map: 'qQ|wW|eE|rR|aA|sS|dD|fF|zZ|xX|cC|vV', replace: 2 }} ${'KEY qwer春😁|a|asdf|zxcv'} | ${c()} | ${{ map: 'qQ|wW|eE|rR|aA|sS|dD|fF|zZ|xX|cC|vV', replace: 1 }} ${'KEY a😁b'} | ${c()} | ${{ map: 'aA|bB', replace: 1 }} `('affKeyCaps "$line" $costs', ({ line, costs, expected }) => { expect(affKeyCaps(line, calcCosts(costs))).toEqual(expected); }); // cspell:ignore qwér aasdfzxcv abcdéefghi test.each` line | costs | expected ${''} | ${{}} | ${undefined} ${'MAP aàâäAÀÂÄ'} | ${{}} | ${undefined} ${'TRY abcdéefghi'} | ${c({ keyboardCost: 74 })} | ${[{ map: 'e(é)é|E(É)É', replace: 1 }, { map: '(é)é|(É)É', replace: 0 }]} ${'TRY abcdéefghi'} | ${c({ accentCosts: 33 })} | ${[{ map: 'e(é)é|E(É)É', replace: 33 }, { map: '(é)é|(É)É', replace: 0 }]} ${'TRY 春😁|aasdfzxcv'} | ${c()} | ${[]} ${'TRY a😁b'} | ${c()} | ${[]} `('affTryAccents "$line" $costs', ({ line, costs, expected }) => { expect(affTryAccents(line, calcCosts(costs))).toEqual(expected); }); test.each` line | costs | expected ${''} | ${{}} | ${undefined} ${'REP o oo'} | ${{}} | ${{ map: 'o(oo)', replace: 75 }} ${'REP ^a A'} | ${{ mapCost: 1 }} | ${{ map: '(^a)(^A)', replace: 75 }} ${'REP $ en$'} | ${{ replaceCosts: 55 }} | ${{ map: '$(en$)', replace: 55 }} ${'REP ^af$ aff'} | ${{}} | ${{ map: '(^af$)(^aff$)', replace: 75 }} ${'REP ß ss'} | ${{}} | ${{ map: 'ß(ss)', replace: 75 }} ${'REP ß 0'} | ${{}} | ${{ map: 'ß()', replace: 75 }} ${'REP 25'} | ${{}} | ${undefined} ${'ICONV 25'} | ${{}} | ${undefined} ${'OCONV 25'} | ${{}} | ${undefined} ${'ICONV áá aa'} | ${{}} | ${{ map: '(áá)(aa)', replace: 30 }} ${'OCONV ss ß'} | ${{ replaceCosts: 55 }} | ${{ map: '(ss)ß', replace: 30 }} ${'OCONV ss ß'} | ${{ ioConvertCost: 25 }} | ${{ map: '(ss)ß', replace: 25 }} `('affRepConv "$line" $costs', ({ line, costs, expected }) => { expect(affRepConv(line, calcCosts(costs))).toEqual(expected); }); const AFFs: [string, HunspellCosts | undefined][] = [ ['', undefined], [ ` TRY abc `, undefined, ], [sampleAff, undefined], ]; test.each(AFFs)('hunspellInformationToSuggestionCostDef <%s>', (aff, costs) => { const info: HunspellInformation = { aff }; if (costs) { info.costs = costs; } const defs = hunspellInformationToSuggestionCostDef(info, undefined); expect(defs).toMatchSnapshot(); }); }); function c(hc: HunspellCosts = {}): HunspellCosts { return hc; }
the_stack
import * as debugFactory from "debug"; import { QueryConfig } from "pg"; import LRU from "@graphile/lru"; const debug = debugFactory("pg-sql2"); function debugError(err: Error) { debug(err); return err; } const $$trusted = Symbol("trusted"); interface SQLRawNode { text: string; type: "RAW"; [$$trusted]: true; } interface SQLIdentifierNode { names: Array<string | symbol>; type: "IDENTIFIER"; [$$trusted]: true; } interface SQLValueNode { value: any; type: "VALUE"; [$$trusted]: true; } export type SQLNode = SQLRawNode | SQLValueNode | SQLIdentifierNode; export type SQLQuery = Array<SQLNode>; export type SQL = SQLNode | SQLQuery; const CACHE_RAW_NODES = new LRU<string, SQLRawNode>({ maxLength: 2000 }); function makeRawNode(text: string): SQLRawNode { const n = CACHE_RAW_NODES.get(text); if (n) { return n; } if (typeof text !== "string") { throw new Error("Invalid argument to makeRawNode - expected string"); } const newNode: SQLRawNode = { type: "RAW", text, [$$trusted]: true }; CACHE_RAW_NODES.set(text, newNode); return newNode; } function isStringOrSymbol(val: any): val is string | symbol { return typeof val === "string" || typeof val === "symbol"; } function makeIdentifierNode(names: Array<string | symbol>): SQLIdentifierNode { if ( !Array.isArray(names) || names.length === 0 || !names.every(isStringOrSymbol) ) { throw new Error( "Invalid argument to makeIdentifierNode - expected array of strings/symbols" ); } return { type: "IDENTIFIER", names, [$$trusted]: true }; } function makeValueNode(rawValue: any): SQLValueNode { return { type: "VALUE", value: rawValue, [$$trusted]: true }; } function ensureNonEmptyArray<T>( array: Array<T>, allowZeroLength = false ): Array<T> { if (!Array.isArray(array)) { throw debugError(new Error("Expected array")); } if (!allowZeroLength && array.length < 1) { throw debugError(new Error("Expected non-empty array")); } for (let idx = 0, l = array.length; idx < l; idx++) { if (array[idx] == null) { throw debugError( new Error(`Array index ${idx} is ${String(array[idx])}`) ); } } return array; } export function compile(sql: SQLQuery | SQLNode): QueryConfig { const items = Array.isArray(sql) ? sql : [sql]; const itemCount = items.length; // Join this to generate the SQL query const sqlFragments = []; // Values hold the JavaScript values that are represented in the query // string by placeholders. They are eager because they were provided before // compile time. const values = []; // If we use the exact same `sql.value` node more than once, we should use // the same placeholder for both (for performance and efficiency) const valueNodeToPlaceholder = new Map(); // When we come accross a symbol in our identifier, we create a unique // alias for it that shouldn’t be in the users schema. This helps maintain // sanity when constructing large Sql queries with many aliases. let nextSymbolId = 0; const symbolToIdentifier = new Map(); for (let itemIndex = 0; itemIndex < itemCount; itemIndex++) { const item: SQLNode = enforceValidNode(items[itemIndex]); switch (item.type) { case "RAW": sqlFragments.push(item.text); break; case "IDENTIFIER": { const nameCount = item.names.length; const mappedNames = []; for (let nameIndex = 0; nameIndex < nameCount; nameIndex++) { const name: string | symbol = item.names[nameIndex]; if (typeof name === "string") { mappedNames.push(escapeSqlIdentifier(name)); } else if (typeof name === "symbol") { // Get the correct identifier string for this symbol. let identifierForSymbol = symbolToIdentifier.get(name); // If there is no identifier, create one and set it. if (!identifierForSymbol) { identifierForSymbol = `__local_${nextSymbolId++}__`; symbolToIdentifier.set(name, identifierForSymbol); } // Return the identifier. Since we create it, we won’t have to // escape it because we know all of the characters are safe. mappedNames.push(identifierForSymbol); } else { throw debugError( new Error(`Expected string or symbol, received '${String(name)}'`) ); } } sqlFragments.push( nameCount === 1 ? mappedNames[0] : mappedNames.join(".") ); break; } case "VALUE": { let placeholder = valueNodeToPlaceholder.get(item); // If there's no placeholder for this value node, create one if (!placeholder) { values.push(item.value); placeholder = `$${values.length}`; valueNodeToPlaceholder.set(item, placeholder); } sqlFragments.push(placeholder); break; } default: // This cannot happen } } const text = sqlFragments.join(""); if (values.length > 65535) { throw new Error( "PostgreSQL allows the use of up to 65535 placeholders; but your statement wants to use ${values.length} placeholders. To solve this issue you could split the statement into multiple statements, or pass more values into a single placeholder by using JSON, arrays, or similar techniques." ); } return { text, values, }; } function enforceValidNode(node: any): SQLNode { if (node !== null && node[$$trusted] === true) { return node; } throw new Error(`Expected SQL item, instead received '${String(node)}'.`); } /** * A template string tag that creates a `Sql` query out of some strings and * some values. Use this to construct all PostgreSQL queries to avoid SQL * injection. * * Note that using this function, the user *must* specify if they are injecting * raw text. This makes a SQL injection vulnerability harder to create. */ // LRU not necessary const CACHE_SIMPLE_FRAGMENTS = new Map<string, SQLQuery>(); export function query( strings: TemplateStringsArray, ...values: Array<SQL> ): SQLQuery { if (!Array.isArray(strings)) { throw new Error( "sql.query should be used as a template literal, not a function call!" ); } const first = strings[0]; // Reduce memory churn with a cache if (strings.length === 1 && typeof first === "string" && first.length < 20) { const cached = CACHE_SIMPLE_FRAGMENTS.get(first); if (cached) { return cached; } const node = [makeRawNode(first)]; CACHE_SIMPLE_FRAGMENTS.set(first, node); return node; } const items = []; for (let i = 0, l = strings.length; i < l; i++) { const text = strings[i]; if (typeof text !== "string") { throw new Error( "sql.query should be used as a template literal, not a function call." ); } if (text.length > 0) { items.push(makeRawNode(text)); } if (values[i]) { const val = values[i]; if (Array.isArray(val)) { const nodes: SQLQuery = val.map(enforceValidNode); items.push(...nodes); } else { const node: SQLNode = enforceValidNode(val); items.push(node); } } } return items; } /** * Creates a Sql item for some raw Sql text. Just plain ol‘ raw Sql. This * method is dangerous though because it involves no escaping, so proceed * with caution! */ export function raw(text: string): SQLNode { return makeRawNode(String(text)); } /** * Creates a Sql item for a Sql identifier. A Sql identifier is anything like * a table, schema, or column name. An identifier may also have a namespace, * thus why many names are accepted. */ export function identifier(...names: Array<string | symbol>): SQLNode { return makeIdentifierNode(ensureNonEmptyArray(names)); } /** * Creates a Sql item for a value that will be included in our final query. * This value will be added in a way which avoids Sql injection. */ export function value(val: any): SQLNode { return makeValueNode(val); } const trueNode = raw(`TRUE`); const falseNode = raw(`FALSE`); const nullNode = raw(`NULL`); /** * If the value is simple will inline it into the query, otherwise will defer * to value. */ export function literal(val: string | number | boolean | null): SQLNode { if (typeof val === "string" && val.match(/^[-a-zA-Z0-9_@! ]*$/)) { return raw(`'${val}'`); } else if (typeof val === "number" && Number.isFinite(val)) { if (Number.isInteger(val)) { return raw(String(val)); } else { return raw(`'${0 + val}'::float`); } } else if (typeof val === "boolean") { return val ? trueNode : falseNode; } else if (val == null) { return nullNode; } else { return makeValueNode(val); } } /** * Join some Sql items together seperated by a string. Useful when dealing * with lists of Sql items that doesn’t make sense as a Sql query. */ export function join(items: Array<SQL>, rawSeparator = ""): SQLQuery { ensureNonEmptyArray(items, true); if (typeof rawSeparator !== "string") { throw new Error("Invalid separator - must be a string"); } const separator = rawSeparator; const currentItems = []; const sepNode = makeRawNode(separator); for (let i = 0, l = items.length; i < l; i++) { const rawItem: SQL = items[i]; const itemsToAppend: SQLNode | SQLQuery = Array.isArray(rawItem) ? rawItem.map(enforceValidNode) : [enforceValidNode(rawItem)]; if (i === 0 || !separator) { currentItems.push(...itemsToAppend); } else { currentItems.push(sepNode, ...itemsToAppend); } } return currentItems; } // Copied from https://github.com/brianc/node-postgres/blob/860cccd53105f7bc32fed8b1de69805f0ecd12eb/lib/client.js#L285-L302 // Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c // Trivial performance optimisations by Benjie. // Replaced with regexp because it's 11x faster by Benjie. export function escapeSqlIdentifier(str: string) { return `"${str.replace(/"/g, '""')}"`; } export const blank = query``; export { query as fragment, // sql.null deprecated; use `sql.NULL` instead. nullNode as null, nullNode as NULL, trueNode as TRUE, falseNode as FALSE, };
the_stack
import { K8sManagement } from './k8s-sdk/k8s-management' import { BoosterConfig, Logger } from '@boostercloud/framework-types' import { getProjectNamespaceName, createProjectZipFile, uploadFile, waitForIt } from './utils' import { uploadService } from './templates/upload-service-template' import { boosterVolumeClaim } from './templates/volume-claim-template' import { boosterService } from './templates/booster-service-template' import { Template, TemplateValues } from './templates/template-types' import { uploaderPod } from './templates/file-uploader-app-template' import { boosterAppPod } from './templates/booster-app-template' import { HelmManager } from './helm-manager' import { DaprManager } from './dapr-manager' import { scopeLogger } from '../helpers/logger' import fetch from 'node-fetch' export class DeployManager { private clusterManager: K8sManagement private namespace: string private templateValues: TemplateValues private helmManager: HelmManager private DaprRepo = 'https://daprio.azurecr.io/helm/v1/repo' private daprManager: DaprManager private logger: Logger constructor( logger: Logger, configuration: BoosterConfig, clusterManager: K8sManagement, daprManager: DaprManager, helmManager: HelmManager ) { this.clusterManager = clusterManager this.daprManager = daprManager this.namespace = getProjectNamespaceName(configuration) this.helmManager = helmManager this.templateValues = { environment: configuration.environmentName, namespace: this.namespace, clusterVolume: boosterVolumeClaim.name, serviceType: 'LoadBalancer', } this.logger = scopeLogger('DeployManager', logger) } /** * verify that helm is installed and if not tries to install it */ public async ensureHelmIsReady(): Promise<void> { const l = scopeLogger('ensureHelmIsReady', this.logger) l.debug('Calling `helmManager.isVersion3()`') await this.helmManager.isVersion3() } /** * verify that Dapr is installed and if not tries to install it */ public async ensureDaprExists(): Promise<void> { const l = scopeLogger('ensureDaprExists', this.logger) l.debug('Checking if `dapr` repo is installed') const repoInstalled = await this.helmManager.isRepoInstalled('dapr') if (!repoInstalled) { l.debug('Repo is not installed, installing') await this.helmManager.installRepo('dapr', this.DaprRepo) } l.debug('Checking if `dapr-operator` pod exists') const daprPod = await this.clusterManager.getPodFromNamespace(this.namespace, 'dapr-operator') if (!daprPod) { l.debug("Dapr pod doesn't exist, creating with helm") await this.helmManager.exec(`install dapr dapr/dapr --namespace ${this.namespace}`) l.debug('Waiting for pod to be ready') await this.clusterManager.waitForPodToBeReady(this.namespace, 'dapr-operator') await this.daprManager.allowDaprToReadSecrets() } } /** * verify that the event store is present and in a negative case, it tries to create one through Dapr Manager */ public async ensureEventStoreExists(): Promise<void> { const l = scopeLogger('ensureEventStoreExists', this.logger) l.debug('Starting to configure event store') await this.daprManager.configureEventStore() } /** * check that the specified namespace exists and if not it tries to create it */ public async ensureNamespaceExists(): Promise<void> { const l = scopeLogger('ensureNamespaceExists', this.logger) l.debug('Getting namespace', this.namespace) const currentNameSpace = await this.clusterManager.getNamespace(this.namespace) l.debug('getNamespace finished, I got:', currentNameSpace, ' -- will create new on undefined') const nameSpaceExists = currentNameSpace ?? (await this.clusterManager.createNamespace(this.namespace)) if (!nameSpaceExists) { l.debug("Namespace didn't exist, throwing error....") throw new Error('Unable to create a namespace for your project, please check your Kubectl configuration') } } /** * verify that the specified Persistent Volume Claim and in a negative case it tries to create it */ public async ensureVolumeClaimExists(): Promise<void> { const l = scopeLogger('ensureVolumeClaimExists', this.logger) l.debug('Getting volume claim') const clusterVolumeClaim = await this.clusterManager.getVolumeClaimFromNamespace( this.namespace, this.templateValues.clusterVolume ) if (!clusterVolumeClaim) { l.debug("Couldn't get volume claim, applying template") const clusterResponse = await this.clusterManager.applyTemplate(boosterVolumeClaim.template, this.templateValues) if (clusterResponse.length == 0) { l.debug("Cluster didn't respond after applying template, throwing") throw new Error('Unable to create a volume claim for your project, please check your Kubectl configuration') } } } /** * Set the type for services in case you are running the cluster locally or in a cloud provider */ public async setServiceType(): Promise<void> { const mainNode = await this.clusterManager.getMainNode() if (mainNode?.name === 'minikube') { this.templateValues.serviceType = 'NodePort' } } /** * verify that the upload service is running and in a negative case it tries to create it */ public async ensureUploadServiceExists(): Promise<void> { const l = scopeLogger('ensureUploadServiceExists', this.logger) l.debug('ensuring service is ready') return await this.ensureServiceIsReady(uploadService) } /** * verify that the booster service is running and in a negative case it tries to create it */ public async ensureBoosterServiceExists(): Promise<void> { const l = scopeLogger('ensureBoosterServiceExists', this.logger) l.debug('Ensuring service is ready') return await this.ensureServiceIsReady(boosterService) } /** * verify that the upload pod is running and in a negative case it tries to create it */ public async ensureUploadPodExists(): Promise<void> { const l = scopeLogger('ensureUploadPodExists', this.logger) l.debug('Ensuring pod is ready') await this.ensurePodIsReady(uploaderPod) l.debug('Waiting for pod to be ready') await this.clusterManager.waitForPodToBeReady(this.namespace, uploaderPod.name) } /** * verify that the booster pod is running and in a negative case it tries to create it */ public async ensureBoosterPodExists(): Promise<void> { const l = scopeLogger('ensureBoosterPodExists', this.logger) l.debug('Ensuring pod is ready') await this.ensurePodIsReady(boosterAppPod, true) } /** * upload all the user code into the cluster and create the express server index for the booster project */ public async uploadUserCode(): Promise<void> { const l = scopeLogger('uploadUserCode', this.logger) l.debug('Waiting for Upload service to be ready') const fileUploadService = await this.clusterManager.waitForServiceToBeReady(this.namespace, uploadService.name) l.debug('Creating zip file') const codeZipFile = await createProjectZipFile(l) const fileUploadServiceAddress = fileUploadService?.port ? `${fileUploadService?.ip}:${fileUploadService?.port}` : fileUploadService?.ip l.debug('Waiting for Upload service to be accesible') await this.waitForServiceToBeAvailable(fileUploadServiceAddress) l.debug('Uploading file') const fileUploadResponse = await uploadFile(l, fileUploadServiceAddress, codeZipFile) if (fileUploadResponse.statusCode !== 200) { l.debug('Cannot upload code, throwing') throw new Error('Unable to upload your code, please check the fileuploader pod for more information') } } /** * deploy a booster app pod inside the cluster and get the booster app url from the cluster */ public async deployBoosterApp( eventStoreHost: string, eventStoreUser: string, eventStorePassword: string ): Promise<string> { this.templateValues.dbHost = eventStoreHost this.templateValues.dbUser = eventStoreUser this.templateValues.dbPass = eventStorePassword const l = scopeLogger('deployBoosterApp', this.logger) l.debug('Ensuring booster pod exists') await this.ensureBoosterPodExists() l.debug('Waiting for pod to be ready') await this.clusterManager.waitForPodToBeReady(this.namespace, boosterAppPod.name) l.debug('Getting service ip') const service = await this.clusterManager.waitForServiceToBeReady(this.namespace, boosterService.name) const boosterServiceAddress = service?.port ? `${service?.ip}:${service.port}` : service?.ip l.debug('Got booster service address', boosterServiceAddress ?? 'UNDEFINED') return boosterServiceAddress ?? '' } /** * delete Dapr services from cluster */ public async deleteDapr(): Promise<void> { await this.daprManager.deleteDaprService() } /** * delete Redis event store from cluster if it was create automatically by booster during deploy */ public async deleteRedis(): Promise<void> { await this.daprManager.deleteEventStore() } /** * delete all booster resources from the cluster */ public async deleteAllResources(): Promise<void> { await this.clusterManager.deleteNamespace(this.namespace) } private async waitForServiceToBeAvailable(url: string | undefined, timeout = 180000): Promise<void> { const l = scopeLogger('waitForServiceToBeAvailable', this.logger) if (!url) { throw new Error('Service Url not valid') } await waitForIt( () => { l.debug('Getting service from namespace') return fetch(`http://${url}`) .then((response) => { return response.status }) .catch(() => { return 0 }) }, (requestStatus) => { return requestStatus === 200 }, 'Unable to get the services in available status', timeout ) } private async ensureServiceIsReady(template: Template): Promise<void> { const l = scopeLogger('ensureServiceIsReady', this.logger) l.debug('Getting service from namespace') const clusterService = await this.clusterManager.getServiceFromNamespace(this.namespace, template.name) if (!clusterService) { l.debug("Didn't get cluster service, applying template") await this.applyTemplate(template, this.templateValues) } } private async ensurePodIsReady(template: Template, forceRestart = false): Promise<void> { const l = scopeLogger('ensurePodIsReady', this.logger) l.debug('Getting pod from namespace') const clusterPod = await this.clusterManager.getPodFromNamespace(this.namespace, template.name) if (!clusterPod) { l.debug('No pod found, applying template') await this.applyTemplate(template, this.templateValues) } else if (forceRestart) { l.debug('Force restart found, applying template') this.templateValues.timestamp = Date.now().toString() await this.applyTemplate(template, this.templateValues) } } private async applyTemplate(template: Template, templateValues: TemplateValues): Promise<boolean> { const l = scopeLogger('applyTemplate', this.logger) l.debug('Applying template') const clusterResponse = await this.clusterManager.applyTemplate(template.template, templateValues) if (clusterResponse.length == 0) { l.debug("Cluster didn't respond throwing") throw new Error( `Unable to create ${template.name} service for your project, please check your Kubectl configuration` ) } return true } }
the_stack
import {isIE10} from './setup'; import * as assert from 'assert'; import isolate from '@cycle/isolate'; import xs, {Stream, MemoryStream} from 'xstream'; import delay from 'xstream/extra/delay'; import concat from 'xstream/extra/concat'; import {setup, run as cycleRun} from '@cycle/run'; const Snabbdom = require('snabbdom-pragma'); import { h, svg, div, thunk, span, h2, h3, h4, button, select, option, p, makeDOMDriver, DOMSource, MainDOMSource, VNode, } from '../../src/index'; declare global { namespace JSX { interface Element extends VNode {} // tslint:disable-line interface IntrinsicElements { [elemName: string]: any; } } } function createRenderTarget(id: string | null = null) { const element = document.createElement('div'); element.className = 'cycletest'; if (id) { element.id = id; } document.body.appendChild(element); return element; } describe('DOM Rendering', function() { it('should render DOM elements even when DOMSource is not utilized', function(done) { function main() { return { DOM: xs.of( div('.my-render-only-container', [h2('Cycle.js framework')]) ), }; } cycleRun(main, { DOM: makeDOMDriver(createRenderTarget()), }); setTimeout(() => { const myContainer = document.querySelector( '.my-render-only-container' ) as HTMLElement; assert.notStrictEqual(myContainer, null); assert.notStrictEqual(typeof myContainer, 'undefined'); assert.strictEqual(myContainer.tagName, 'DIV'); const header = myContainer.querySelector('h2') as HTMLElement; assert.notStrictEqual(header, null); assert.notStrictEqual(typeof header, 'undefined'); assert.strictEqual(header.textContent, 'Cycle.js framework'); done(); }, 150); }); it('should support snabbdom dataset module by default', function(done) { const thisBrowserSupportsDataset = typeof document.createElement('DIV').dataset !== 'undefined'; function app(_sources: {DOM: MainDOMSource}) { return { DOM: xs.of( div('.my-class', { dataset: {foo: 'Foo'}, }) ), }; } if (!thisBrowserSupportsDataset) { done(); } else { const {sinks, sources, run} = setup(app, { DOM: makeDOMDriver(createRenderTarget()), }); let dispose: any; sources.DOM.select(':root') .element() .drop(1) .take(1) .addListener({ next: (root: Element) => { const elem = root.querySelector('.my-class') as HTMLElement; assert.notStrictEqual(elem, null); assert.notStrictEqual(typeof elem, 'undefined'); assert.strictEqual(elem.tagName, 'DIV'); assert.strictEqual(elem.dataset.foo, 'Foo'); setTimeout(() => { dispose(); done(); }); }, }); dispose = run(); } }); it('should render in a DocumentFragment as container', function(done) { if (isIE10) { done(); return; } function app(_sources: {DOM: MainDOMSource}) { return { DOM: xs.of( select('.my-class', [ option({attrs: {value: 'foo'}}, 'Foo'), option({attrs: {value: 'bar'}}, 'Bar'), option({attrs: {value: 'baz'}}, 'Baz'), ]) ), }; } const docfrag = document.createDocumentFragment(); const {sinks, sources, run} = setup(app, { DOM: makeDOMDriver(docfrag), }); let dispose: any; sources.DOM.select(':root') .element() .drop(1) .take(1) .addListener({ next: (root: Element) => { const selectEl = root.querySelector('.my-class') as HTMLElement; assert.notStrictEqual(selectEl, null); assert.notStrictEqual(typeof selectEl, 'undefined'); assert.strictEqual(selectEl.tagName, 'SELECT'); const options = selectEl.querySelectorAll('option'); assert.strictEqual(options.length, 3); setTimeout(() => { dispose(); done(); }); }, }); dispose = run(); }); it('should convert a simple virtual-dom <select> to DOM element', function(done) { function app(_sources: {DOM: MainDOMSource}) { return { DOM: xs.of( select('.my-class', [ option({attrs: {value: 'foo'}}, 'Foo'), option({attrs: {value: 'bar'}}, 'Bar'), option({attrs: {value: 'baz'}}, 'Baz'), ]) ), }; } const {sinks, sources, run} = setup(app, { DOM: makeDOMDriver(createRenderTarget()), }); let dispose: any; sources.DOM.select(':root') .element() .drop(1) .take(1) .addListener({ next: (root: Element) => { const selectEl = root.querySelector('.my-class') as HTMLElement; assert.notStrictEqual(selectEl, null); assert.notStrictEqual(typeof selectEl, 'undefined'); assert.strictEqual(selectEl.tagName, 'SELECT'); setTimeout(() => { dispose(); done(); }); }, }); dispose = run(); }); it('should convert a simple virtual-dom <select> (JSX) to DOM element', function(done) { function app(_sources: {DOM: DOMSource}) { return { DOM: xs.of( <select className="my-class"> <option value="foo">Foo</option> <option value="bar">Bar</option> <option value="baz">Baz</option> </select> ), }; } const {sinks, sources, run} = setup(app, { DOM: makeDOMDriver(createRenderTarget()), }); let dispose: any; sources.DOM.select(':root') .element() .drop(1) .take(1) .addListener({ next: (root: Element) => { const selectEl = root.querySelector('.my-class') as HTMLSelectElement; assert.notStrictEqual(selectEl, null); assert.notStrictEqual(typeof selectEl, 'undefined'); assert.strictEqual(selectEl.tagName, 'SELECT'); setTimeout(() => { dispose(); done(); }); }, }); dispose = run(); }); it('should reuse existing DOM tree under the given root element', function(done) { function app(_sources: {DOM: MainDOMSource}) { return { DOM: xs.of( select('.my-class', [ option({attrs: {value: 'foo'}}, 'Foo'), option({attrs: {value: 'bar'}}, 'Bar'), option({attrs: {value: 'baz'}}, 'Baz'), ]) ), }; } // Create DOM tree with 2 <option>s under <select> const rootElem = createRenderTarget(); const selectElem = document.createElement('SELECT'); selectElem.className = 'my-class'; rootElem.appendChild(selectElem); const optionElem1 = document.createElement('OPTION'); optionElem1.setAttribute('value', 'foo'); optionElem1.textContent = 'Foo'; selectElem.appendChild(optionElem1); const optionElem2 = document.createElement('OPTION'); optionElem2.setAttribute('value', 'bar'); optionElem2.textContent = 'Bar'; selectElem.appendChild(optionElem2); const {sinks, sources, run} = setup(app, { DOM: makeDOMDriver(rootElem), }); let dispose: any; sources.DOM.select(':root') .element() .drop(1) .take(1) .addListener({ next: (root: Element) => { assert.strictEqual(root.childNodes.length, 1); const selectEl = root.childNodes[0] as HTMLElement; assert.strictEqual(selectEl.tagName, 'SELECT'); assert.strictEqual(selectEl.childNodes.length, 3); const option1 = selectEl.childNodes[0] as HTMLElement; const option2 = selectEl.childNodes[1] as HTMLElement; const option3 = selectEl.childNodes[2] as HTMLElement; assert.strictEqual(option1.tagName, 'OPTION'); assert.strictEqual(option2.tagName, 'OPTION'); assert.strictEqual(option3.tagName, 'OPTION'); assert.strictEqual(option1.textContent, 'Foo'); assert.strictEqual(option2.textContent, 'Bar'); assert.strictEqual(option3.textContent, 'Baz'); setTimeout(() => { dispose(); done(); }); }, }); dispose = run(); }); it('should give elements as a value-over-time', function(done) { function app(_sources: {DOM: MainDOMSource}) { return { DOM: xs.merge(xs.of(h2('.value-over-time', 'Hello test')), xs.never()), }; } const {sinks, sources, run} = setup(app, { DOM: makeDOMDriver(createRenderTarget()), }); let dispose: any; let firstSubscriberRan = false; let secondSubscriberRan = false; const element$ = sources.DOM.select(':root').element(); element$ .drop(1) .take(1) .addListener({ next: (root: Element) => { assert.strictEqual(firstSubscriberRan, false); firstSubscriberRan = true; const header = root.querySelector('.value-over-time') as HTMLElement; assert.notStrictEqual(header, null); assert.notStrictEqual(typeof header, 'undefined'); assert.strictEqual(header.tagName, 'H2'); }, }); setTimeout(() => { // This samples the element$ after 400ms, and should synchronously get // some element into the subscriber. assert.strictEqual(secondSubscriberRan, false); element$.take(1).addListener({ next: (root: Element) => { assert.strictEqual(secondSubscriberRan, false); secondSubscriberRan = true; const header = root.querySelector('.value-over-time') as HTMLElement; assert.notStrictEqual(header, null); assert.notStrictEqual(typeof header, 'undefined'); assert.strictEqual(header.tagName, 'H2'); setTimeout(() => { dispose(); done(); }); }, }); assert.strictEqual(secondSubscriberRan, true); }, 400); dispose = run(); }); it('should have DevTools flag in elements source stream', function(done) { function app(_sources: {DOM: MainDOMSource}) { return { DOM: xs.merge(xs.of(h2('.value-over-time', 'Hello test')), xs.never()), }; } const {sinks, sources, run} = setup(app, { DOM: makeDOMDriver(createRenderTarget()), }); const element$ = sources.DOM.select(':root').elements(); assert.strictEqual((element$ as any)._isCycleSource, 'DOM'); done(); }); it('should have DevTools flag in element source stream', function(done) { function app(_sources: {DOM: MainDOMSource}) { return { DOM: xs.merge(xs.of(h2('.value-over-time', 'Hello test')), xs.never()), }; } const {sinks, sources, run} = setup(app, { DOM: makeDOMDriver(createRenderTarget()), }); const element$ = sources.DOM.select(':root').element(); assert.strictEqual((element$ as any)._isCycleSource, 'DOM'); done(); }); it('should allow snabbdom Thunks in the VTree', function(done) { function renderThunk(greeting: string) { return h4('Constantly ' + greeting); } function app(_sources: {DOM: MainDOMSource}) { return { DOM: xs .periodic(10) .take(5) .map(i => div([thunk('h4', 'key1', renderThunk, ['hello' + 0])])), }; } const {sinks, sources, run} = setup(app, { DOM: makeDOMDriver(createRenderTarget()), }); let dispose: any; sources.DOM.select(':root') .element() .drop(1) .take(1) .addListener({ next: (root: Element) => { const h4Elem = root.querySelector('h4') as HTMLElement; assert.notStrictEqual(h4Elem, null); assert.notStrictEqual(typeof h4Elem, 'undefined'); assert.strictEqual(h4Elem.tagName, 'H4'); assert.strictEqual(h4Elem.textContent, 'Constantly hello0'); dispose(); done(); }, }); dispose = run(); }); it('should render embedded HTML within SVG <foreignObject>', function(done) { const thisBrowserSupportsForeignObject = (document as any).implementation.hasFeature( 'www.http://w3.org/TR/SVG11/feature#Extensibility', '1.1' ); function app(_sources: {DOM: MainDOMSource}) { return { DOM: xs.of( svg({attrs: {width: 150, height: 50}}, [ svg.foreignObject({attrs: {width: '100%', height: '100%'}}, [ p('.embedded-text', 'This is HTML embedded in SVG'), ]), ]) ), }; } if (!thisBrowserSupportsForeignObject) { done(); } else { const {sinks, sources, run} = setup(app, { DOM: makeDOMDriver(createRenderTarget()), }); let dispose: any; sources.DOM.select(':root') .element() .drop(1) .take(1) .addListener({ next: (root: Element) => { const embeddedHTML = root.querySelector( 'p.embedded-text' ) as HTMLElement; assert.strictEqual( embeddedHTML.namespaceURI, 'http://www.w3.org/1999/xhtml' ); assert.notStrictEqual(embeddedHTML.clientWidth, 0); assert.notStrictEqual(embeddedHTML.clientHeight, 0); setTimeout(() => { dispose(); done(); }); }, }); dispose = run(); } }); it('should filter out null/undefined children', function(done) { function app(_sources: {DOM: MainDOMSource}) { return { DOM: xs .periodic(10) .take(5) .map(i => div('.parent', [ 'Child 1', null, h4('.child3', [ null, 'Grandchild 31', div('.grandchild32', [null, 'Great grandchild 322']), ]), undefined, ]) ), }; } const {sinks, sources, run} = setup(app, { DOM: makeDOMDriver(createRenderTarget()), }); let dispose: any; sources.DOM.select(':root') .element() .drop(1) .take(1) .addListener({ next: (root: Element) => { const divParent = root.querySelector('div.parent') as HTMLElement; const h4Child = root.querySelector('h4.child3') as HTMLElement; const grandchild = root.querySelector( 'div.grandchild32' ) as HTMLElement; assert.strictEqual(divParent.childNodes.length, 2); assert.strictEqual(h4Child.childNodes.length, 2); assert.strictEqual(grandchild.childNodes.length, 1); dispose(); done(); }, }); dispose = run(); }); it('should render correctly even if hyperscript-helper first is empty string', function(done) { function app(_sources: {DOM: MainDOMSource}) { return { DOM: xs.of(h4('', {}, ['Hello world'])), }; } const {sinks, sources, run} = setup(app, { DOM: makeDOMDriver(createRenderTarget()), }); let dispose: any; sources.DOM.select(':root') .element() .drop(1) .take(1) .addListener({ next: (root: Element) => { const H4 = root.querySelector('h4') as HTMLElement; assert.strictEqual(H4.textContent, 'Hello world'); setTimeout(() => { dispose(); done(); }); }, }); dispose = run(); }); it('should render textContent "0" given hyperscript content value number 0', function(done) { function app(_sources: {DOM: MainDOMSource}) { return { DOM: xs.of(div('.my-class', 0)), }; } const {sinks, sources, run} = setup(app, { DOM: makeDOMDriver(createRenderTarget()), }); let dispose: any; sources.DOM.select(':root') .element() .drop(1) .take(1) .addListener({ next: (root: Element) => { const divEl = root.querySelector('.my-class') as HTMLElement; assert.strictEqual(divEl.textContent, '0'); setTimeout(() => { dispose(); done(); }); }, }); dispose = run(); }); });
the_stack
import { getVoidLogger } from '@backstage/backend-common'; import { ConfigReader } from '@backstage/config'; import { ScmIntegrations } from '@backstage/integration'; import fs from 'fs-extra'; import mockFs from 'mock-fs'; import os from 'os'; import path, { resolve as resolvePath } from 'path'; import { ParsedLocationAnnotation } from '../../helpers'; import { addBuildTimestampMetadata, getGeneratorKey, getMkdocsYml, getRepoUrlFromLocationAnnotation, patchMkdocsYmlPreBuild, storeEtagMetadata, validateMkdocsYaml, } from './helpers'; const mockEntity = { apiVersion: 'version', kind: 'TestKind', metadata: { name: 'testName', }, }; const mkdocsYml = fs.readFileSync( resolvePath(__filename, '../__fixtures__/mkdocs.yml'), ); const mkdocsYmlWithExtensions = fs.readFileSync( resolvePath(__filename, '../__fixtures__/mkdocs_with_extensions.yml'), ); const mkdocsYmlWithRepoUrl = fs.readFileSync( resolvePath(__filename, '../__fixtures__/mkdocs_with_repo_url.yml'), ); const mkdocsYmlWithEditUri = fs.readFileSync( resolvePath(__filename, '../__fixtures__/mkdocs_with_edit_uri.yml'), ); const mkdocsYmlWithValidDocDir = fs.readFileSync( resolvePath(__filename, '../__fixtures__/mkdocs_valid_doc_dir.yml'), ); const mkdocsYmlWithInvalidDocDir = fs.readFileSync( resolvePath(__filename, '../__fixtures__/mkdocs_invalid_doc_dir.yml'), ); const mkdocsYmlWithInvalidDocDir2 = fs.readFileSync( resolvePath(__filename, '../__fixtures__/mkdocs_invalid_doc_dir2.yml'), ); const mkdocsYmlWithComments = fs.readFileSync( resolvePath(__filename, '../__fixtures__/mkdocs_with_comments.yml'), ); const mockLogger = getVoidLogger(); const rootDir = os.platform() === 'win32' ? 'C:\\rootDir' : '/rootDir'; const scmIntegrations = ScmIntegrations.fromConfig(new ConfigReader({})); describe('helpers', () => { describe('getGeneratorKey', () => { it('should return techdocs as the only generator key', () => { const key = getGeneratorKey(mockEntity); expect(key).toBe('techdocs'); }); }); describe('getRepoUrlFromLocationAnnotation', () => { it.each` url | repo_url | edit_uri ${'https://github.com/backstage/backstage'} | ${'https://github.com/backstage/backstage'} | ${undefined} ${'https://github.com/backstage/backstage/tree/main/examples/techdocs/'} | ${undefined} | ${'https://github.com/backstage/backstage/edit/main/examples/techdocs/docs'} ${'https://github.com/backstage/backstage/tree/main/'} | ${undefined} | ${'https://github.com/backstage/backstage/edit/main/docs'} ${'https://gitlab.com/backstage/backstage'} | ${'https://gitlab.com/backstage/backstage'} | ${undefined} ${'https://gitlab.com/backstage/backstage/-/blob/main/examples/techdocs/'} | ${undefined} | ${'https://gitlab.com/backstage/backstage/-/edit/main/examples/techdocs/docs'} ${'https://gitlab.com/backstage/backstage/-/blob/main/'} | ${undefined} | ${'https://gitlab.com/backstage/backstage/-/edit/main/docs'} `('should convert $url', ({ url: target, repo_url, edit_uri }) => { const parsedLocationAnnotation: ParsedLocationAnnotation = { type: 'url', target, }; expect( getRepoUrlFromLocationAnnotation( parsedLocationAnnotation, scmIntegrations, ), ).toEqual({ repo_url, edit_uri }); }); it.each` url | edit_uri ${'https://github.com/backstage/backstage/tree/main/examples/techdocs/'} | ${'https://github.com/backstage/backstage/edit/main/examples/techdocs/custom/folder'} ${'https://github.com/backstage/backstage/tree/main/'} | ${'https://github.com/backstage/backstage/edit/main/custom/folder'} ${'https://gitlab.com/backstage/backstage/-/blob/main/examples/techdocs/'} | ${'https://gitlab.com/backstage/backstage/-/edit/main/examples/techdocs/custom/folder'} ${'https://gitlab.com/backstage/backstage/-/blob/main/'} | ${'https://gitlab.com/backstage/backstage/-/edit/main/custom/folder'} `( 'should convert $url with custom docsFolder', ({ url: target, edit_uri }) => { const parsedLocationAnnotation: ParsedLocationAnnotation = { type: 'url', target, }; expect( getRepoUrlFromLocationAnnotation( parsedLocationAnnotation, scmIntegrations, './custom/folder', ), ).toEqual({ edit_uri }); }, ); it.each` url ${'https://bitbucket.org/backstage/backstage/src/master/examples/techdocs/'} ${'https://bitbucket.org/backstage/backstage/src/master/'} ${'https://dev.azure.com/organization/project/_git/repository?path=%2Fexamples%2Ftechdocs'} ${'https://dev.azure.com/organization/project/_git/repository?path=%2F'} `('should ignore $url', ({ url: target }) => { const parsedLocationAnnotation: ParsedLocationAnnotation = { type: 'url', target, }; expect( getRepoUrlFromLocationAnnotation( parsedLocationAnnotation, scmIntegrations, ), ).toEqual({}); }); it('should ignore unsupported location type', () => { const parsedLocationAnnotation: ParsedLocationAnnotation = { type: 'dir', target: '/home/user/workspace/docs-repository', }; expect( getRepoUrlFromLocationAnnotation( parsedLocationAnnotation, scmIntegrations, ), ).toEqual({}); }); }); describe('patchMkdocsYmlPreBuild', () => { beforeEach(() => { mockFs({ '/mkdocs.yml': mkdocsYml, '/mkdocs_with_repo_url.yml': mkdocsYmlWithRepoUrl, '/mkdocs_with_edit_uri.yml': mkdocsYmlWithEditUri, '/mkdocs_with_extensions.yml': mkdocsYmlWithExtensions, '/mkdocs_with_comments.yml': mkdocsYmlWithComments, }); }); afterEach(() => { mockFs.restore(); }); it('should add edit_uri to mkdocs.yml', async () => { const parsedLocationAnnotation: ParsedLocationAnnotation = { type: 'url', target: 'https://github.com/backstage/backstage', }; await patchMkdocsYmlPreBuild( '/mkdocs.yml', mockLogger, parsedLocationAnnotation, scmIntegrations, ); const updatedMkdocsYml = await fs.readFile('/mkdocs.yml'); expect(updatedMkdocsYml.toString()).toContain( 'repo_url: https://github.com/backstage/backstage', ); }); it('should add repo_url to mkdocs.yml that contains custom yaml tags', async () => { const parsedLocationAnnotation: ParsedLocationAnnotation = { type: 'url', target: 'https://github.com/backstage/backstage', }; await patchMkdocsYmlPreBuild( '/mkdocs_with_extensions.yml', mockLogger, parsedLocationAnnotation, scmIntegrations, ); const updatedMkdocsYml = await fs.readFile('/mkdocs_with_extensions.yml'); expect(updatedMkdocsYml.toString()).toContain( 'repo_url: https://github.com/backstage/backstage', ); expect(updatedMkdocsYml.toString()).toContain( "emoji_index: !!python/name:materialx.emoji.twemoji ''", ); }); it('should not override existing repo_url in mkdocs.yml', async () => { const parsedLocationAnnotation: ParsedLocationAnnotation = { type: 'url', target: 'https://github.com/neworg/newrepo', }; await patchMkdocsYmlPreBuild( '/mkdocs_with_repo_url.yml', mockLogger, parsedLocationAnnotation, scmIntegrations, ); const updatedMkdocsYml = await fs.readFile('/mkdocs_with_repo_url.yml'); expect(updatedMkdocsYml.toString()).toContain( 'repo_url: https://github.com/backstage/backstage', ); expect(updatedMkdocsYml.toString()).not.toContain( 'repo_url: https://github.com/neworg/newrepo', ); }); it('should not override existing edit_uri in mkdocs.yml', async () => { const parsedLocationAnnotation: ParsedLocationAnnotation = { type: 'url', target: 'https://github.com/neworg/newrepo', }; await patchMkdocsYmlPreBuild( '/mkdocs_with_edit_uri.yml', mockLogger, parsedLocationAnnotation, scmIntegrations, ); const updatedMkdocsYml = await fs.readFile('/mkdocs_with_edit_uri.yml'); expect(updatedMkdocsYml.toString()).toContain( 'edit_uri: https://github.com/backstage/backstage/edit/main/docs', ); expect(updatedMkdocsYml.toString()).not.toContain( 'https://github.com/neworg/newrepo', ); }); it('should not update mkdocs.yml if nothing should be changed', async () => { const parsedLocationAnnotation: ParsedLocationAnnotation = { type: 'dir', target: '/unsupported/path', }; await patchMkdocsYmlPreBuild( '/mkdocs_with_comments.yml', mockLogger, parsedLocationAnnotation, scmIntegrations, ); const updatedMkdocsYml = await fs.readFile('/mkdocs_with_comments.yml'); expect(updatedMkdocsYml.toString()).toContain( '# This is a comment that is removed after editing', ); expect(updatedMkdocsYml.toString()).not.toContain('edit_uri'); expect(updatedMkdocsYml.toString()).not.toContain('repo_url'); }); }); describe('addBuildTimestampMetadata', () => { beforeEach(() => { mockFs.restore(); mockFs({ [rootDir]: { 'invalid_techdocs_metadata.json': 'dsds', 'techdocs_metadata.json': '{"site_name": "Tech Docs"}', }, }); }); afterEach(() => { mockFs.restore(); }); it('should create the file if it does not exist', async () => { const filePath = path.join(rootDir, 'wrong_techdocs_metadata.json'); await addBuildTimestampMetadata(filePath, mockLogger); // Check if the file exists await expect( fs.access(filePath, fs.constants.F_OK), ).resolves.not.toThrowError(); }); it('should throw error when the JSON is invalid', async () => { const filePath = path.join(rootDir, 'invalid_techdocs_metadata.json'); await expect( addBuildTimestampMetadata(filePath, mockLogger), ).rejects.toThrowError('Unexpected token d in JSON at position 0'); }); it('should add build timestamp to the metadata json', async () => { const filePath = path.join(rootDir, 'techdocs_metadata.json'); await addBuildTimestampMetadata(filePath, mockLogger); const json = await fs.readJson(filePath); expect(json.build_timestamp).toBeLessThanOrEqual(Date.now()); }); }); describe('storeEtagMetadata', () => { beforeEach(() => { mockFs.restore(); mockFs({ [rootDir]: { 'invalid_techdocs_metadata.json': 'dsds', 'techdocs_metadata.json': '{"site_name": "Tech Docs"}', }, }); }); afterEach(() => { mockFs.restore(); }); it('should throw error when the JSON is invalid', async () => { const filePath = path.join(rootDir, 'invalid_techdocs_metadata.json'); await expect( storeEtagMetadata(filePath, 'etag123abc'), ).rejects.toThrowError('Unexpected token d in JSON at position 0'); }); it('should add etag to the metadata json', async () => { const filePath = path.join(rootDir, 'techdocs_metadata.json'); await storeEtagMetadata(filePath, 'etag123abc'); const json = await fs.readJson(filePath); expect(json.etag).toBe('etag123abc'); }); }); describe('getMkdocsYml', () => { afterEach(() => { mockFs.restore(); }); const inputDir = resolvePath(__filename, '../__fixtures__/'); it('returns expected contents when .yml file is present', async () => { const key = path.join(inputDir, 'mkdocs.yml'); mockFs({ [key]: mkdocsYml }); const { path: mkdocsPath, content } = await getMkdocsYml(inputDir); expect(mkdocsPath).toBe(key); expect(content).toBe(mkdocsYml.toString()); }); it('returns expected contents when .yaml file is present', async () => { const key = path.join(inputDir, 'mkdocs.yaml'); mockFs({ [key]: mkdocsYml }); const { path: mkdocsPath, content } = await getMkdocsYml(inputDir); expect(mkdocsPath).toBe(key); expect(content).toBe(mkdocsYml.toString()); }); it('throws when neither .yml nor .yaml file is present', async () => { const invalidInputDir = resolvePath(__filename); await expect(getMkdocsYml(invalidInputDir)).rejects.toThrowError( /Could not read MkDocs YAML config file mkdocs.yml or mkdocs.yaml for validation/, ); }); }); describe('validateMkdocsYaml', () => { const inputDir = resolvePath(__filename, '../__fixtures__/'); it('should return true on when no docs_dir present', async () => { await expect( validateMkdocsYaml(inputDir, mkdocsYml.toString()), ).resolves.toBeUndefined(); }); it('should return true on when a valid docs_dir is present', async () => { await expect( validateMkdocsYaml(inputDir, mkdocsYmlWithValidDocDir.toString()), ).resolves.toBeUndefined(); }); it('should return false on absolute doc_dir path', async () => { await expect( validateMkdocsYaml(inputDir, mkdocsYmlWithInvalidDocDir.toString()), ).rejects.toThrow(); }); it('should return false on doc_dir path that traverses directory structure backwards', async () => { await expect( validateMkdocsYaml(inputDir, mkdocsYmlWithInvalidDocDir2.toString()), ).rejects.toThrow(); }); it('should validate files with custom yaml tags', async () => { await expect( validateMkdocsYaml(inputDir, mkdocsYmlWithExtensions.toString()), ).resolves.toBeUndefined(); }); }); });
the_stack
import { SENSITIVE_STRING } from "@aws-sdk/smithy-client"; import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; /** * <p>You do not have sufficient permissions to perform this action. </p> */ export interface AccessDeniedException extends __SmithyException, $MetadataBearer { name: "AccessDeniedException"; $fault: "client"; message: string | undefined; } export namespace AccessDeniedException { /** * @internal */ export const filterSensitiveLog = (obj: AccessDeniedException): any => ({ ...obj, }); } export enum AccountAccessType { /** * Indicates that the customer is using Grafana to monitor resources in their current account. */ CURRENT_ACCOUNT = "CURRENT_ACCOUNT", /** * Indicates that the customer is using Grafana to monitor resources in organizational units. */ ORGANIZATION = "ORGANIZATION", } /** * <p>A structure that defines which attributes in the IdP assertion are to be used to define * information about the users authenticated by the IdP to use the workspace.</p> */ export interface AssertionAttributes { /** * <p>The name of the attribute within the SAML assertion to use as the user full "friendly" names for SAML users.</p> */ name?: string; /** * <p>The name of the attribute within the SAML assertion to use as the login names for SAML users.</p> */ login?: string; /** * <p>The name of the attribute within the SAML assertion to use as the email names for SAML users.</p> */ email?: string; /** * <p>The name of the attribute within the SAML assertion to use as the user full "friendly" names for user groups.</p> */ groups?: string; /** * <p>The name of the attribute within the SAML assertion to use as the user roles.</p> */ role?: string; /** * <p>The name of the attribute within the SAML assertion to use as the user full "friendly" names for the users' organizations.</p> */ org?: string; } export namespace AssertionAttributes { /** * @internal */ export const filterSensitiveLog = (obj: AssertionAttributes): any => ({ ...obj, }); } export enum LicenseType { /** * Grafana Enterprise License. */ ENTERPRISE = "ENTERPRISE", /** * Grafana Enterprise Free Trial License. */ ENTERPRISE_FREE_TRIAL = "ENTERPRISE_FREE_TRIAL", } export interface AssociateLicenseRequest { /** * <p>The ID of the workspace to associate the license with.</p> */ workspaceId: string | undefined; /** * <p>The type of license to associate with the workspace.</p> */ licenseType: LicenseType | string | undefined; } export namespace AssociateLicenseRequest { /** * @internal */ export const filterSensitiveLog = (obj: AssociateLicenseRequest): any => ({ ...obj, }); } export enum AuthenticationProviderTypes { /** * Indicates that AMG workspace has AWS SSO enabled as its authentication provider. */ AWS_SSO = "AWS_SSO", /** * Indicates that the AMG workspace has SAML enabled as its authentication provider. */ SAML = "SAML", } export enum SamlConfigurationStatus { /** * Indicates that SAML on an AMG workspace is enabled and has been configured. */ CONFIGURED = "CONFIGURED", /** * Indicates that SAML on an AMG workspace is enabled but has not been configured. */ NOT_CONFIGURED = "NOT_CONFIGURED", } /** * <p>A structure that describes whether the workspace uses SAML, Amazon Web Services SSO, or both methods * for user authentication, and whether that authentication is fully configured.</p> */ export interface AuthenticationSummary { /** * <p>Specifies whether the workspace uses SAML, Amazon Web Services SSO, or both methods for user * authentication.</p> */ providers: (AuthenticationProviderTypes | string)[] | undefined; /** * <p>Specifies whether the workplace's user authentication method is fully configured.</p> */ samlConfigurationStatus?: SamlConfigurationStatus | string; } export namespace AuthenticationSummary { /** * @internal */ export const filterSensitiveLog = (obj: AuthenticationSummary): any => ({ ...obj, }); } export enum DataSourceType { /** * Amazon OpenSearch Service */ AMAZON_OPENSEARCH_SERVICE = "AMAZON_OPENSEARCH_SERVICE", /** * CloudWatch Logs */ CLOUDWATCH = "CLOUDWATCH", /** * Managed Prometheus */ PROMETHEUS = "PROMETHEUS", /** * IoT SiteWise */ SITEWISE = "SITEWISE", /** * Timestream */ TIMESTREAM = "TIMESTREAM", /** * X-Ray */ XRAY = "XRAY", } export enum NotificationDestinationType { /** * AWS Simple Notification Service */ SNS = "SNS", } export enum PermissionType { /** * Customer Managed */ CUSTOMER_MANAGED = "CUSTOMER_MANAGED", /** * Service Managed */ SERVICE_MANAGED = "SERVICE_MANAGED", } export enum WorkspaceStatus { /** * Workspace is active. */ ACTIVE = "ACTIVE", /** * Workspace is being created. */ CREATING = "CREATING", /** * Workspace creation failed. */ CREATION_FAILED = "CREATION_FAILED", /** * Workspace is being deleted. */ DELETING = "DELETING", /** * Workspace deletion failed. */ DELETION_FAILED = "DELETION_FAILED", /** * Workspace is in an invalid state, it can only and should be deleted. */ FAILED = "FAILED", /** * Failed to remove enterprise license from workspace. */ LICENSE_REMOVAL_FAILED = "LICENSE_REMOVAL_FAILED", /** * Workspace update failed. */ UPDATE_FAILED = "UPDATE_FAILED", /** * Workspace is being updated. */ UPDATING = "UPDATING", /** * Workspace upgrade failed. */ UPGRADE_FAILED = "UPGRADE_FAILED", /** * Workspace is being upgraded to enterprise. */ UPGRADING = "UPGRADING", } /** * <p>A structure containing information about an Amazon Managed Grafana workspace in your account.</p> */ export interface WorkspaceDescription { /** * <p>Specifies whether the workspace can access Amazon Web Services resources in this Amazon Web Services account only, or whether it can also access Amazon Web Services resources in * other accounts in the same organization. If this is <code>ORGANIZATION</code>, the * <code>workspaceOrganizationalUnits</code> parameter specifies which organizational units * the workspace can access.</p> */ accountAccessType?: AccountAccessType | string; /** * <p>The date that the workspace was created.</p> */ created: Date | undefined; /** * <p>Specifies the Amazon Web Services data sources that have been configured to have IAM * roles and permissions created to allow * Amazon Managed Grafana to read data from these sources.</p> */ dataSources: (DataSourceType | string)[] | undefined; /** * <p>The user-defined description of the workspace.</p> */ description?: string; /** * <p>The URL that users can use to access the Grafana console in the workspace.</p> */ endpoint: string | undefined; /** * <p>The version of Grafana supported in this workspace.</p> */ grafanaVersion: string | undefined; /** * <p>The unique ID of this workspace.</p> */ id: string | undefined; /** * <p>The most recent date that the workspace was modified.</p> */ modified: Date | undefined; /** * <p>The name of the workspace.</p> */ name?: string; /** * <p>The name of the IAM role that is used to access resources through Organizations.</p> */ organizationRoleName?: string; /** * <p>The Amazon Web Services notification channels that Amazon Managed Grafana can automatically create IAM * roles and permissions for, to allow * Amazon Managed Grafana to use these channels.</p> */ notificationDestinations?: (NotificationDestinationType | string)[]; /** * <p>Specifies the organizational units that this workspace is allowed to use data sources * from, if this workspace is in an account that is part of an organization.</p> */ organizationalUnits?: string[]; /** * <p>If this is <code>Service Managed</code>, Amazon Managed Grafana automatically creates the IAM roles * and provisions the permissions that the workspace needs to use Amazon Web Services data sources and notification channels.</p> * <p>If this is <code>CUSTOMER_MANAGED</code>, you manage those roles and permissions * yourself. If you are creating this workspace in a member account of an organization and that account is not a * delegated administrator account, and * you want the workspace to access data sources in other Amazon Web Services accounts in the * organization, you must choose <code>CUSTOMER_MANAGED</code>.</p> * <p>For more information, see <a href="https://docs.aws.amazon.com/grafana/latest/userguide/AMG-manage-permissions.html">Amazon Managed Grafana permissions and policies for * Amazon Web Services data sources and notification channels</a> * </p> */ permissionType?: PermissionType | string; /** * <p>The name of the CloudFormation stack set that is used to generate IAM roles * to be used for this workspace.</p> */ stackSetName?: string; /** * <p>The current status of the workspace.</p> */ status: WorkspaceStatus | string | undefined; /** * <p>The IAM role that grants permissions to the Amazon Web Services resources that the * workspace will view data from. This role must already exist.</p> */ workspaceRoleArn?: string; /** * <p>Specifies whether this workspace has a full Grafana Enterprise license or a free trial license.</p> */ licenseType?: LicenseType | string; /** * <p>Specifies whether this workspace has already fully used its free trial for Grafana Enterprise.</p> */ freeTrialConsumed?: boolean; /** * <p>If this workspace has a full Grafana Enterprise license, this specifies when the license ends and * will need to be renewed.</p> */ licenseExpiration?: Date; /** * <p>If this workspace is currently in the free trial period for Grafana Enterprise, this value specifies * when that free trial ends.</p> */ freeTrialExpiration?: Date; /** * <p>A structure that describes whether the workspace uses SAML, Amazon Web Services SSO, or both methods * for user authentication.</p> */ authentication: AuthenticationSummary | undefined; } export namespace WorkspaceDescription { /** * @internal */ export const filterSensitiveLog = (obj: WorkspaceDescription): any => ({ ...obj, ...(obj.description && { description: SENSITIVE_STRING }), ...(obj.name && { name: SENSITIVE_STRING }), ...(obj.organizationRoleName && { organizationRoleName: SENSITIVE_STRING }), ...(obj.organizationalUnits && { organizationalUnits: SENSITIVE_STRING }), ...(obj.workspaceRoleArn && { workspaceRoleArn: SENSITIVE_STRING }), }); } export interface AssociateLicenseResponse { /** * <p>A structure containing data about the workspace.</p> */ workspace: WorkspaceDescription | undefined; } export namespace AssociateLicenseResponse { /** * @internal */ export const filterSensitiveLog = (obj: AssociateLicenseResponse): any => ({ ...obj, ...(obj.workspace && { workspace: WorkspaceDescription.filterSensitiveLog(obj.workspace) }), }); } /** * <p>Unexpected error while processing the request. Retry the request.</p> */ export interface InternalServerException extends __SmithyException, $MetadataBearer { name: "InternalServerException"; $fault: "server"; $retryable: {}; /** * <p>A description of the error.</p> */ message: string | undefined; /** * <p>How long to wait before you retry this operation.</p> */ retryAfterSeconds?: number; } export namespace InternalServerException { /** * @internal */ export const filterSensitiveLog = (obj: InternalServerException): any => ({ ...obj, }); } /** * <p>The request references a resource that does not exist.</p> */ export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer { name: "ResourceNotFoundException"; $fault: "client"; /** * <p>The value of a parameter in the request caused an error.</p> */ message: string | undefined; /** * <p>The ID of the resource that is associated with the error.</p> */ resourceId: string | undefined; /** * <p>The type of the resource that is associated with the error.</p> */ resourceType: string | undefined; } export namespace ResourceNotFoundException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({ ...obj, }); } /** * <p>The request was denied because of request throttling. Retry the request.</p> */ export interface ThrottlingException extends __SmithyException, $MetadataBearer { name: "ThrottlingException"; $fault: "client"; $retryable: {}; /** * <p>A description of the error.</p> */ message: string | undefined; /** * <p>The ID of the service that is associated with the error.</p> */ serviceCode?: string; /** * <p>The ID of the service quota that was exceeded.</p> */ quotaCode?: string; /** * <p>The value of a parameter in the request caused an error.</p> */ retryAfterSeconds?: number; } export namespace ThrottlingException { /** * @internal */ export const filterSensitiveLog = (obj: ThrottlingException): any => ({ ...obj, }); } /** * <p>A structure that contains information about a request parameter that caused an error.</p> */ export interface ValidationExceptionField { /** * <p>The name of the field that caused the validation error.</p> */ name: string | undefined; /** * <p>A message describing why this field couldn't be validated.</p> */ message: string | undefined; } export namespace ValidationExceptionField { /** * @internal */ export const filterSensitiveLog = (obj: ValidationExceptionField): any => ({ ...obj, }); } export enum ValidationExceptionReason { CANNOT_PARSE = "CANNOT_PARSE", FIELD_VALIDATION_FAILED = "FIELD_VALIDATION_FAILED", OTHER = "OTHER", UNKNOWN_OPERATION = "UNKNOWN_OPERATION", } /** * <p>The value of a parameter in the request caused an error.</p> */ export interface ValidationException extends __SmithyException, $MetadataBearer { name: "ValidationException"; $fault: "client"; /** * <p>A description of the error.</p> */ message: string | undefined; /** * <p>The reason that the operation failed.</p> */ reason: ValidationExceptionReason | string | undefined; /** * <p>A list of fields that might be associated with the error.</p> */ fieldList?: ValidationExceptionField[]; } export namespace ValidationException { /** * @internal */ export const filterSensitiveLog = (obj: ValidationException): any => ({ ...obj, }); } export interface DescribeWorkspaceAuthenticationRequest { /** * <p>The ID of the workspace to return authentication information about.</p> */ workspaceId: string | undefined; } export namespace DescribeWorkspaceAuthenticationRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorkspaceAuthenticationRequest): any => ({ ...obj, }); } /** * <p>A structure containing information about how this workspace works with * Amazon Web Services SSO. </p> */ export interface AwsSsoAuthentication { /** * <p>The ID of the Amazon Web Services SSO-managed application that is created by Amazon Managed Grafana.</p> */ ssoClientId?: string; } export namespace AwsSsoAuthentication { /** * @internal */ export const filterSensitiveLog = (obj: AwsSsoAuthentication): any => ({ ...obj, }); } /** * <p>A structure containing the identity provider (IdP) metadata used to integrate the * identity provider with this workspace. You can specify the metadata either by providing a * URL to its location in the <code>url</code> parameter, or by specifying the full metadata * in XML format in the <code>xml</code> parameter.</p> */ export type IdpMetadata = IdpMetadata.UrlMember | IdpMetadata.XmlMember | IdpMetadata.$UnknownMember; export namespace IdpMetadata { /** * <p>The URL of the location containing the metadata.</p> */ export interface UrlMember { url: string; xml?: never; $unknown?: never; } /** * <p>The actual full metadata file, in XML format.</p> */ export interface XmlMember { url?: never; xml: string; $unknown?: never; } export interface $UnknownMember { url?: never; xml?: never; $unknown: [string, any]; } export interface Visitor<T> { url: (value: string) => T; xml: (value: string) => T; _: (name: string, value: any) => T; } export const visit = <T>(value: IdpMetadata, visitor: Visitor<T>): T => { if (value.url !== undefined) return visitor.url(value.url); if (value.xml !== undefined) return visitor.xml(value.xml); return visitor._(value.$unknown[0], value.$unknown[1]); }; /** * @internal */ export const filterSensitiveLog = (obj: IdpMetadata): any => { if (obj.url !== undefined) return { url: obj.url }; if (obj.xml !== undefined) return { xml: obj.xml }; if (obj.$unknown !== undefined) return { [obj.$unknown[0]]: "UNKNOWN" }; }; } /** * <p>This structure defines which groups defined in the SAML assertion attribute are to be mapped * to the Grafana <code>Admin</code> and <code>Editor</code> roles in the workspace.</p> */ export interface RoleValues { /** * <p>A list of groups from the SAML assertion attribute to grant the Grafana * <code>Editor</code> role to.</p> */ editor?: string[]; /** * <p>A list of groups from the SAML assertion attribute to grant the Grafana * <code>Admin</code> role to.</p> */ admin?: string[]; } export namespace RoleValues { /** * @internal */ export const filterSensitiveLog = (obj: RoleValues): any => ({ ...obj, }); } /** * <p>A structure containing information about how this workspace works with * SAML. </p> */ export interface SamlConfiguration { /** * <p>A structure containing the identity provider (IdP) metadata used to integrate the * identity provider with this workspace.</p> */ idpMetadata: IdpMetadata | undefined; /** * <p>A structure that defines which attributes in the SAML assertion are to be used to define information about * the users authenticated by that IdP to use the workspace.</p> */ assertionAttributes?: AssertionAttributes; /** * <p>A structure containing arrays that map group names in the SAML assertion to the * Grafana <code>Admin</code> and <code>Editor</code> roles in the workspace.</p> */ roleValues?: RoleValues; /** * <p>Lists which organizations defined in the SAML assertion are allowed to use the Amazon Managed Grafana workspace. * If this is empty, all organizations in the assertion attribute have access.</p> */ allowedOrganizations?: string[]; /** * <p>How long a sign-on session by a SAML user is valid, before the user has to sign on * again.</p> */ loginValidityDuration?: number; } export namespace SamlConfiguration { /** * @internal */ export const filterSensitiveLog = (obj: SamlConfiguration): any => ({ ...obj, ...(obj.idpMetadata && { idpMetadata: IdpMetadata.filterSensitiveLog(obj.idpMetadata) }), }); } /** * <p>A structure containing information about how this workspace works with * SAML. </p> */ export interface SamlAuthentication { /** * <p>Specifies whether the workspace's SAML configuration is complete.</p> */ status: SamlConfigurationStatus | string | undefined; /** * <p>A structure containing details about how this workspace works with * SAML. </p> */ configuration?: SamlConfiguration; } export namespace SamlAuthentication { /** * @internal */ export const filterSensitiveLog = (obj: SamlAuthentication): any => ({ ...obj, ...(obj.configuration && { configuration: SamlConfiguration.filterSensitiveLog(obj.configuration) }), }); } /** * <p>A structure containing information about the user authentication methods used by the workspace.</p> */ export interface AuthenticationDescription { /** * <p>Specifies whether this workspace uses Amazon Web Services SSO, SAML, or both methods to authenticate * users to use the Grafana console in the Amazon Managed Grafana workspace.</p> */ providers: (AuthenticationProviderTypes | string)[] | undefined; /** * <p>A structure containing information about how this workspace works with * SAML, including what attributes within the assertion are to be mapped to user information in the workspace. </p> */ saml?: SamlAuthentication; /** * <p>A structure containing information about how this workspace works with * Amazon Web Services SSO. </p> */ awsSso?: AwsSsoAuthentication; } export namespace AuthenticationDescription { /** * @internal */ export const filterSensitiveLog = (obj: AuthenticationDescription): any => ({ ...obj, ...(obj.saml && { saml: SamlAuthentication.filterSensitiveLog(obj.saml) }), }); } export interface DescribeWorkspaceAuthenticationResponse { /** * <p>A structure containing information about the authentication methods used in * the workspace.</p> */ authentication: AuthenticationDescription | undefined; } export namespace DescribeWorkspaceAuthenticationResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorkspaceAuthenticationResponse): any => ({ ...obj, ...(obj.authentication && { authentication: AuthenticationDescription.filterSensitiveLog(obj.authentication) }), }); } /** * <p>A resource was in an inconsistent state during an update or a deletion.</p> */ export interface ConflictException extends __SmithyException, $MetadataBearer { name: "ConflictException"; $fault: "client"; /** * <p>A description of the error.</p> */ message: string | undefined; /** * <p>The ID of the resource that is associated with the error.</p> */ resourceId: string | undefined; /** * <p>The type of the resource that is associated with the error.</p> */ resourceType: string | undefined; } export namespace ConflictException { /** * @internal */ export const filterSensitiveLog = (obj: ConflictException): any => ({ ...obj, }); } export interface UpdateWorkspaceAuthenticationRequest { /** * <p>The ID of the workspace to update the authentication for.</p> */ workspaceId: string | undefined; /** * <p>Specifies whether this workspace uses SAML 2.0, Amazon Web Services Single Sign On, or both to authenticate * users for using the Grafana console within a workspace. For more information, * see <a href="https://docs.aws.amazon.com/grafana/latest/userguide/authentication-in-AMG.html">User authentication in * Amazon Managed Grafana</a>.</p> */ authenticationProviders: (AuthenticationProviderTypes | string)[] | undefined; /** * <p>If the workspace uses SAML, use this structure to * map SAML assertion attributes to workspace user information and * define which groups in the assertion attribute are to have the <code>Admin</code> and <code>Editor</code> roles * in the workspace.</p> */ samlConfiguration?: SamlConfiguration; } export namespace UpdateWorkspaceAuthenticationRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateWorkspaceAuthenticationRequest): any => ({ ...obj, ...(obj.samlConfiguration && { samlConfiguration: SamlConfiguration.filterSensitiveLog(obj.samlConfiguration) }), }); } export interface UpdateWorkspaceAuthenticationResponse { /** * <p>A structure that describes the user authentication for this workspace after the update is made.</p> */ authentication: AuthenticationDescription | undefined; } export namespace UpdateWorkspaceAuthenticationResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateWorkspaceAuthenticationResponse): any => ({ ...obj, ...(obj.authentication && { authentication: AuthenticationDescription.filterSensitiveLog(obj.authentication) }), }); } export interface DisassociateLicenseRequest { /** * <p>The ID of the workspace to remove the Grafana Enterprise license from.</p> */ workspaceId: string | undefined; /** * <p>The type of license to remove from the workspace.</p> */ licenseType: LicenseType | string | undefined; } export namespace DisassociateLicenseRequest { /** * @internal */ export const filterSensitiveLog = (obj: DisassociateLicenseRequest): any => ({ ...obj, }); } export interface DisassociateLicenseResponse { /** * <p>A structure containing information about the workspace.</p> */ workspace: WorkspaceDescription | undefined; } export namespace DisassociateLicenseResponse { /** * @internal */ export const filterSensitiveLog = (obj: DisassociateLicenseResponse): any => ({ ...obj, ...(obj.workspace && { workspace: WorkspaceDescription.filterSensitiveLog(obj.workspace) }), }); } export enum UserType { /** * SSO group. */ SSO_GROUP = "SSO_GROUP", /** * SSO user. */ SSO_USER = "SSO_USER", } export interface ListPermissionsRequest { /** * <p>The maximum number of results to include in the response.</p> */ maxResults?: number; /** * <p>The token to use when requesting the next set of results. You received this token from a previous * <code>ListPermissions</code> operation.</p> */ nextToken?: string; /** * <p>(Optional) If you specify <code>SSO_USER</code>, then only the permissions of Amazon Web Services SSO users * are returned. If you specify <code>SSO_GROUP</code>, only the permissions of Amazon Web Services SSO groups * are returned.</p> */ userType?: UserType | string; /** * <p>(Optional) Limits the results to only the user that matches this ID.</p> */ userId?: string; /** * <p>(Optional) Limits the results to only the group that matches this ID.</p> */ groupId?: string; /** * <p>The ID of the workspace to list permissions for. This parameter is required.</p> */ workspaceId: string | undefined; } export namespace ListPermissionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListPermissionsRequest): any => ({ ...obj, }); } export enum Role { /** * Role Admin. */ ADMIN = "ADMIN", /** * Role Editor. */ EDITOR = "EDITOR", } /** * <p>A structure that specifies one user or group in the workspace.</p> */ export interface User { /** * <p>The ID of the user or group.</p> */ id: string | undefined; /** * <p>Specifies whether this is a single user or a group.</p> */ type: UserType | string | undefined; } export namespace User { /** * @internal */ export const filterSensitiveLog = (obj: User): any => ({ ...obj, }); } /** * <p>A structure containing the identity of one user or group and the <code>Admin</code> * or <code>Editor</code> role that they have.</p> */ export interface PermissionEntry { /** * <p>A structure with the ID of the user or group with this role.</p> */ user: User | undefined; /** * <p>Specifies whether the user or group has the <code>Admin</code> * or <code>Editor</code> role.</p> */ role: Role | string | undefined; } export namespace PermissionEntry { /** * @internal */ export const filterSensitiveLog = (obj: PermissionEntry): any => ({ ...obj, }); } export interface ListPermissionsResponse { /** * <p>The token to use in a subsequent <code>ListPermissions</code> operation to return * the next set of results.</p> */ nextToken?: string; /** * <p>The permissions returned by the operation.</p> */ permissions: PermissionEntry[] | undefined; } export namespace ListPermissionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListPermissionsResponse): any => ({ ...obj, }); } export enum UpdateAction { /** * Add permissions. */ ADD = "ADD", /** * Revoke permissions. */ REVOKE = "REVOKE", } /** * <p>Contains the instructions for one Grafana role permission update in a * <a href="https://docs.aws.amazon.com/grafana/latest/APIReference/API_UpdatePermissions.html">UpdatePermissions</a> operation.</p> */ export interface UpdateInstruction { /** * <p>Specifies whether this update is to add or revoke role permissions.</p> */ action: UpdateAction | string | undefined; /** * <p>The role to add or revoke for the user or the group specified in <code>users</code>.</p> */ role: Role | string | undefined; /** * <p>A structure that specifies the user or group to add or revoke the role for.</p> */ users: User[] | undefined; } export namespace UpdateInstruction { /** * @internal */ export const filterSensitiveLog = (obj: UpdateInstruction): any => ({ ...obj, }); } export interface UpdatePermissionsRequest { /** * <p>An array of structures that contain the permission updates to make.</p> */ updateInstructionBatch: UpdateInstruction[] | undefined; /** * <p>The ID of the workspace to update.</p> */ workspaceId: string | undefined; } export namespace UpdatePermissionsRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdatePermissionsRequest): any => ({ ...obj, }); } /** * <p>A structure containing information about one error encountered while performing an * <a href="https://docs.aws.amazon.com/grafana/latest/APIReference/API_UpdatePermissions.html">UpdatePermissions</a> operation.</p> */ export interface UpdateError { /** * <p>The error code.</p> */ code: number | undefined; /** * <p>The message for this error.</p> */ message: string | undefined; /** * <p>Specifies which permission update caused the error.</p> */ causedBy: UpdateInstruction | undefined; } export namespace UpdateError { /** * @internal */ export const filterSensitiveLog = (obj: UpdateError): any => ({ ...obj, }); } export interface UpdatePermissionsResponse { /** * <p>An array of structures that contain the errors from the operation, if any.</p> */ errors: UpdateError[] | undefined; } export namespace UpdatePermissionsResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdatePermissionsResponse): any => ({ ...obj, }); } export interface CreateWorkspaceRequest { /** * <p>Specifies whether the workspace can access Amazon Web Services resources in this Amazon Web Services account only, or whether it can also access Amazon Web Services resources in * other accounts in the same organization. If you specify <code>ORGANIZATION</code>, you must * specify which organizational units the workspace can access in the * <code>workspaceOrganizationalUnits</code> parameter.</p> */ accountAccessType: AccountAccessType | string | undefined; /** * <p>A unique, case-sensitive, user-provided identifier to ensure the idempotency of the request.</p> */ clientToken?: string; /** * <p>The name of an IAM role that already exists to use with Organizations to access Amazon Web Services * data sources and notification channels in other accounts in an organization.</p> */ organizationRoleName?: string; /** * <p>If you specify <code>Service Managed</code>, Amazon Managed Grafana automatically creates * the IAM roles and provisions the permissions that the workspace needs to use * Amazon Web Services data sources and notification channels.</p> * <p>If you specify <code>CUSTOMER_MANAGED</code>, you will manage those roles and * permissions yourself. If you are creating this workspace in a member account of an * organization that is not a delegated administrator account, and you want the workspace to access data sources in other Amazon Web Services * accounts in the organization, you must choose <code>CUSTOMER_MANAGED</code>.</p> * <p>For more information, see <a href="https://docs.aws.amazon.com/grafana/latest/userguide/AMG-manage-permissions.html">Amazon Managed Grafana permissions and policies for * Amazon Web Services data sources and notification channels</a> * </p> */ permissionType: PermissionType | string | undefined; /** * <p>The name of the CloudFormation stack set to use to generate IAM roles * to be used for this workspace.</p> */ stackSetName?: string; /** * <p>Specify the Amazon Web Services data sources that you want to be queried in this * workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to read data from these * sources. You must still add them as data sources in the Grafana console in the * workspace.</p> * <p>If you don't specify a data source here, you can still add it as a data source in the * workspace console later. However, you will then have to manually configure permissions for * it.</p> */ workspaceDataSources?: (DataSourceType | string)[]; /** * <p>A description for the workspace. This is used only to help you identify this workspace.</p> */ workspaceDescription?: string; /** * <p>The name for the workspace. It does not have to be unique.</p> */ workspaceName?: string; /** * <p>Specify the Amazon Web Services notification channels that you plan to use in this workspace. Specifying these * data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow * Amazon Managed Grafana to use these channels.</p> */ workspaceNotificationDestinations?: (NotificationDestinationType | string)[]; /** * <p>Specifies the organizational units that this workspace is allowed to use data sources * from, if this workspace is in an account that is part of an organization.</p> */ workspaceOrganizationalUnits?: string[]; /** * <p>The workspace needs an IAM role that grants permissions to the Amazon Web Services resources that the * workspace will view data from. If you already have a role that you want to use, specify it here. If you omit * this field and you specify some Amazon Web Services resources in <code>workspaceDataSources</code> or * <code>workspaceNotificationDestinations</code>, a new IAM role with the necessary permissions is * automatically created.</p> */ workspaceRoleArn?: string; /** * <p>Specifies whether this workspace uses SAML 2.0, Amazon Web Services Single Sign On, or both to authenticate * users for using the Grafana console within a workspace. For more information, * see <a href="https://docs.aws.amazon.com/grafana/latest/userguide/authentication-in-AMG.html">User authentication in * Amazon Managed Grafana</a>.</p> */ authenticationProviders: (AuthenticationProviderTypes | string)[] | undefined; } export namespace CreateWorkspaceRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateWorkspaceRequest): any => ({ ...obj, ...(obj.organizationRoleName && { organizationRoleName: SENSITIVE_STRING }), ...(obj.workspaceDescription && { workspaceDescription: SENSITIVE_STRING }), ...(obj.workspaceName && { workspaceName: SENSITIVE_STRING }), ...(obj.workspaceOrganizationalUnits && { workspaceOrganizationalUnits: SENSITIVE_STRING }), ...(obj.workspaceRoleArn && { workspaceRoleArn: SENSITIVE_STRING }), }); } export interface CreateWorkspaceResponse { /** * <p>A structure containing data about the workspace that was created.</p> */ workspace: WorkspaceDescription | undefined; } export namespace CreateWorkspaceResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateWorkspaceResponse): any => ({ ...obj, ...(obj.workspace && { workspace: WorkspaceDescription.filterSensitiveLog(obj.workspace) }), }); } /** * <p>The request would cause a service quota to be exceeded.</p> */ export interface ServiceQuotaExceededException extends __SmithyException, $MetadataBearer { name: "ServiceQuotaExceededException"; $fault: "client"; /** * <p>A description of the error.</p> */ message: string | undefined; /** * <p>The ID of the resource that is associated with the error.</p> */ resourceId: string | undefined; /** * <p>The type of the resource that is associated with the error.</p> */ resourceType: string | undefined; /** * <p>The value of a parameter in the request caused an error.</p> */ serviceCode: string | undefined; /** * <p>The ID of the service quota that was exceeded.</p> */ quotaCode: string | undefined; } export namespace ServiceQuotaExceededException { /** * @internal */ export const filterSensitiveLog = (obj: ServiceQuotaExceededException): any => ({ ...obj, }); } export interface DeleteWorkspaceRequest { /** * <p>The ID of the workspace to delete.</p> */ workspaceId: string | undefined; } export namespace DeleteWorkspaceRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteWorkspaceRequest): any => ({ ...obj, }); } export interface DeleteWorkspaceResponse { /** * <p>A structure containing information about the workspace that was deleted.</p> */ workspace: WorkspaceDescription | undefined; } export namespace DeleteWorkspaceResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteWorkspaceResponse): any => ({ ...obj, ...(obj.workspace && { workspace: WorkspaceDescription.filterSensitiveLog(obj.workspace) }), }); } export interface DescribeWorkspaceRequest { /** * <p>The ID of the workspace to display information about.</p> */ workspaceId: string | undefined; } export namespace DescribeWorkspaceRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorkspaceRequest): any => ({ ...obj, }); } export interface DescribeWorkspaceResponse { /** * <p>A structure containing information about the workspace.</p> */ workspace: WorkspaceDescription | undefined; } export namespace DescribeWorkspaceResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeWorkspaceResponse): any => ({ ...obj, ...(obj.workspace && { workspace: WorkspaceDescription.filterSensitiveLog(obj.workspace) }), }); } export interface ListWorkspacesRequest { /** * <p>The maximum number of workspaces to include in the results.</p> */ maxResults?: number; /** * <p>The token for the next set of workspaces to return. (You receive this token from a * previous <code>ListWorkspaces</code> operation.)</p> */ nextToken?: string; } export namespace ListWorkspacesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListWorkspacesRequest): any => ({ ...obj, }); } /** * <p>A structure that contains some information about one workspace in the account.</p> */ export interface WorkspaceSummary { /** * <p>The date that the workspace was created.</p> */ created: Date | undefined; /** * <p>The customer-entered description of the workspace.</p> */ description?: string; /** * <p>The URL endpoint to use to access the Grafana console in the workspace.</p> */ endpoint: string | undefined; /** * <p>The Grafana version that the workspace is running.</p> */ grafanaVersion: string | undefined; /** * <p>The unique ID of the workspace.</p> */ id: string | undefined; /** * <p>The most recent date that the workspace was modified.</p> */ modified: Date | undefined; /** * <p>The name of the workspace.</p> */ name?: string; /** * <p>The Amazon Web Services notification channels that Amazon Managed Grafana can automatically * create IAM roles and permissions for, which allows Amazon Managed Grafana to use * these channels.</p> */ notificationDestinations?: (NotificationDestinationType | string)[]; /** * <p>The current status of the workspace.</p> */ status: WorkspaceStatus | string | undefined; /** * <p>A structure containing information about the authentication methods used in * the workspace.</p> */ authentication: AuthenticationSummary | undefined; } export namespace WorkspaceSummary { /** * @internal */ export const filterSensitiveLog = (obj: WorkspaceSummary): any => ({ ...obj, ...(obj.description && { description: SENSITIVE_STRING }), ...(obj.name && { name: SENSITIVE_STRING }), }); } export interface ListWorkspacesResponse { /** * <p>An array of structures that contain some information about the workspaces in the account.</p> */ workspaces: WorkspaceSummary[] | undefined; /** * <p>The token to use when requesting the next set of workspaces.</p> */ nextToken?: string; } export namespace ListWorkspacesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListWorkspacesResponse): any => ({ ...obj, ...(obj.workspaces && { workspaces: obj.workspaces.map((item) => WorkspaceSummary.filterSensitiveLog(item)) }), }); } export interface UpdateWorkspaceRequest { /** * <p>Specifies whether the workspace can access Amazon Web Services resources in this Amazon Web Services account only, or whether it can also access Amazon Web Services resources in * other accounts in the same organization. If you specify <code>ORGANIZATION</code>, you must * specify which organizational units the workspace can access in the * <code>workspaceOrganizationalUnits</code> parameter.</p> */ accountAccessType?: AccountAccessType | string; /** * <p>The name of an IAM role that already exists to use to access resources through Organizations.</p> */ organizationRoleName?: string; /** * <p>If you specify <code>Service Managed</code>, Amazon Managed Grafana automatically creates * the IAM roles and provisions the permissions that the workspace needs to use * Amazon Web Services data sources and notification channels.</p> * <p>If you specify <code>CUSTOMER_MANAGED</code>, you will manage those roles and * permissions yourself. If you are creating this workspace in a member account of an * organization and that account is not a delegated administrator account, and you want the workspace to access data sources in other Amazon Web Services * accounts in the organization, you must choose <code>CUSTOMER_MANAGED</code>.</p> * <p>For more information, see <a href="https://docs.aws.amazon.com/grafana/latest/userguide/AMG-manage-permissions.html">Amazon Managed Grafana permissions and policies for * Amazon Web Services data sources and notification channels</a> * </p> */ permissionType?: PermissionType | string; /** * <p>The name of the CloudFormation stack set to use to generate IAM roles * to be used for this workspace.</p> */ stackSetName?: string; /** * <p>Specify the Amazon Web Services data sources that you want to be queried in this * workspace. Specifying these data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow Amazon Managed Grafana to read data from these * sources. You must still add them as data sources in the Grafana console in the * workspace.</p> * <p>If you don't specify a data source here, you can still add it as a data source later in * the workspace console. However, you will then have to manually configure permissions for * it.</p> */ workspaceDataSources?: (DataSourceType | string)[]; /** * <p>A description for the workspace. This is used only to help you identify this workspace.</p> */ workspaceDescription?: string; /** * <p>The ID of the workspace to update.</p> */ workspaceId: string | undefined; /** * <p>A new name for the workspace to update.</p> */ workspaceName?: string; /** * <p>Specify the Amazon Web Services notification channels that you plan to use in this workspace. Specifying these * data sources here enables Amazon Managed Grafana to create IAM roles and permissions that allow * Amazon Managed Grafana to use these channels.</p> */ workspaceNotificationDestinations?: (NotificationDestinationType | string)[]; /** * <p>Specifies the organizational units that this workspace is allowed to use data sources * from, if this workspace is in an account that is part of an organization.</p> */ workspaceOrganizationalUnits?: string[]; /** * <p>The workspace needs an IAM role that grants permissions to the Amazon Web Services resources that the * workspace will view data from. If you already have a role that you want to use, specify it here. If you omit * this field and you specify some Amazon Web Services resources in <code>workspaceDataSources</code> or * <code>workspaceNotificationDestinations</code>, a new IAM role with the necessary permissions is * automatically created.</p> */ workspaceRoleArn?: string; } export namespace UpdateWorkspaceRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateWorkspaceRequest): any => ({ ...obj, ...(obj.organizationRoleName && { organizationRoleName: SENSITIVE_STRING }), ...(obj.workspaceDescription && { workspaceDescription: SENSITIVE_STRING }), ...(obj.workspaceName && { workspaceName: SENSITIVE_STRING }), ...(obj.workspaceOrganizationalUnits && { workspaceOrganizationalUnits: SENSITIVE_STRING }), ...(obj.workspaceRoleArn && { workspaceRoleArn: SENSITIVE_STRING }), }); } export interface UpdateWorkspaceResponse { /** * <p>A structure containing data about the workspace that was created.</p> */ workspace: WorkspaceDescription | undefined; } export namespace UpdateWorkspaceResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateWorkspaceResponse): any => ({ ...obj, ...(obj.workspace && { workspace: WorkspaceDescription.filterSensitiveLog(obj.workspace) }), }); }
the_stack
import { EventEmitter } from "./event" const print = console.log.bind(console) const _indexedDB = (typeof window != "undefined") ? ( window.indexedDB || window["mozIndexedDB"] || window["webkitIndexedDB"] || window["msIndexedDB"]) : null as unknown as IDBFactory export const supported = !!_indexedDB // UpgradeFun is a function provided to Database.open and is called when an upgrade is needed. // The function can modify object stores and indexes during immediate execution. // In other words: Any code in a promise (or after await) can not modify object stores or indexes. type UpgradeFun = (t :UpgradeTransaction)=>Promise<void> interface StoreInfo { readonly autoIncrement: boolean readonly indexNames: DOMStringList readonly keyPath: string | string[] } interface DatabaseSnapshot { readonly storeNames :string[] readonly storeInfo :Map<string,StoreInfo> } interface StoreChangeEvent { store :string type :"clear" } interface RecordDeleteEvent { store :string type :"delete" key :IDBValidKey|IDBKeyRange // input key, not effective key } interface RecordUpdateEvent { store :string type :"update" // put or add key :IDBValidKey value :any // always undefined for remote events } type ChangeEvent = StoreChangeEvent | RecordDeleteEvent | RecordUpdateEvent interface DatabaseEventMap { "open": undefined "change": ChangeEvent "remotechange": ChangeEvent } // interface Migrator { // // upgradeSchema is called for every version step, i.e. upgrading from // // version 3 -> 5 will call: // // - upgradeSchema(3, 4, t) // // - upgradeSchema(4, 5, t) // upgradeSchema(prevVersion :number, newVersion :number, t :UpgradeTransaction) // // migrateData is called only once and after all calls to upgradeSchema. // migrateData(prevVersion :number, newVersion :number) // } // open opens a database, creating and/or upgrading it as needed. export function open(name :string, version :number, upgradefun? :UpgradeFun) :Promise<Database> { let db = new Database(name, version) return db.open(upgradefun).then(() => db) } // delete removes an entire database // export { _delete as delete };function _delete(name :string, onblocked? :()=>void) :Promise<void> { return new Promise<void>((resolve, reject) => { let r = _indexedDB.deleteDatabase(name) r.onblocked = onblocked || (() => { r.onblocked = undefined r.onsuccess = undefined r.onerror = undefined reject(new Error("db blocked")) }) r.onsuccess = () => { if (navigator.userAgent.match(/Safari\//)) { // Safari <=12.1.1 has a race condition bug where even after onsuccess is called, // the database sometimes remains but without and actual object stores. // This condition causes a subsequent open request to succeed without invoking an // upgrade handler, and thus yielding an empty database. // Running a second pass of deleteDatabase seem to work around this bug. let r = _indexedDB.deleteDatabase(name) r.onsuccess = () => { resolve() } r.onerror = () => { reject(r.error) } } else { resolve() } } r.onerror = () => { reject(r.error) } }) } export class Database extends EventEmitter<DatabaseEventMap> { readonly db :IDBDatabase // underlying object readonly name :string readonly version :number // autoReopenOnClose controls if the database should be reopened and recreated when the // user deletes the underlying data in their web browser. When this is false, all operations // will suddenly start failing if the user deleted the database, while when this is true, // operations always operate in transactions either on the old (before deleting) database or // a new recreated database. autoReopenOnClose :boolean = true readonly isOpen = false _lastSnapshot :DatabaseSnapshot _broadcastChannel :BroadcastChannel|undefined _requirePromise :Promise<Database|null>|null = null constructor(name :string, version :number) { super() this.name = name this.version = version } // require is a high-level function that can be used instead of open() to cause a database // to be opened lazily and just once. It also provides an easy safety net for hosts that // lack IndexedDB support. // // Example use: // // const db = new xdb.Database("mydb", 1) // const useDB = () => localdb.require(async t => { // log(`upgrade database ${t.prevVersion} -> ${t.nextVersion}`) // if (t.prevVersion < 1) { // t.createStore("users", { keyPath: "email" }) // } // }) // async function saveUser(user) { // if (await useDB()) { // return db.set("users", user) // } // } // require(upgradefun? :UpgradeFun) :Promise<Database|null> { if (!supported) { return Promise.resolve(null) } if (!this._requirePromise) { this._requirePromise = this.open(upgradefun).then(() => this) } return this._requirePromise } // open the database, creating and/or upgrading it as needed using optional upgradefun open(upgradefun? :UpgradeFun) :Promise<void> { return openDatabase(this, upgradefun).then(() => { this._setupCoordination() return this._onopen(upgradefun) }) } _reopen(upgradefun? :UpgradeFun) :Promise<void> { // print("_reopen (database is closing)") if (!this.autoReopenOnClose) { return } let db = this let delayedTransactions :DelayedTransaction<any>[] = [] this.transaction = function(mode: IDBTransactionMode, ...stores :string[]) :Transaction<any> { let resolve :()=>void let reject :(e:Error)=>void let t = new DelayedTransaction<any>((_resolve, _reject) => { resolve = _resolve reject = _reject }) t._resolve = resolve t._reject = reject t._db = db t._stores = stores t._mode = mode delayedTransactions.push(t) return t } // reopen return openDatabase(this, upgradefun).then(db => { delete this.transaction // remove override for (let t of delayedTransactions) { t._flushDelayed() } return this._onopen(upgradefun) }) } async _onopen(upgradefun? :UpgradeFun) :Promise<void> { this._snapshot() this.db.onclose = () => { ;(this as any).isOpen = false this._reopen(upgradefun) } ;(this as any).isOpen = true this.triggerEvent("open") } _snapshot() { let storeNames = this.storeNames let storeInfo = new Map<string,StoreInfo>() if (storeNames.length > 0) { let t = this.db.transaction(storeNames, "readonly") // @ts-ignore workaround for Safari bug // eval("1+1") for (let storeName of storeNames) { let s = t.objectStore(storeName) storeInfo.set(storeName, { autoIncrement: s.autoIncrement, indexNames: s.indexNames, keyPath: s.keyPath, } as StoreInfo) } } this._lastSnapshot = { storeNames, storeInfo, } } _setupCoordination() { if (typeof BroadcastChannel == "undefined") { // environment doesn't support BroadcastChannel. No coordination. return } this._broadcastChannel = new BroadcastChannel(`xdb:${this.name}.${this.version}`) this._broadcastChannel.onmessage = ev => { this.triggerEvent("remotechange", ev.data as ChangeEvent) } } _broadcastChange(ev :ChangeEvent) { if (this._broadcastChannel) { this._broadcastChannel.postMessage(ev) } this.triggerEvent("change", ev) } // close the database. // // The connection is not actually closed until all transactions created using this // connection are complete. No new transactions can be created for this connection once // this method is called. Methods that create transactions throw an exception if a closing // operation is pending. close() :void { // Note: This does NOT cause a "close" event to be emitted. There's a disctinction // between calling close() on a database object vs the "close" event occurring. // // - Calling close() causes the database object to become invalid and allows for // Database.delete. // // - The "close" event occurs when the user deletes the database. However, any instance // of a database object remains valid. // // A "close" event occurs when the database is deleted by the user, for instance // via "delete website data" in web browser settings or use of developer console. // Since that action renders the database object useless, we automatically reopen // the database when this happens, and run the upgrade function which will handle // initialization of the database. // ;(this as any).isOpen = false this.db.close() } // storeNames is a list of objects store names that currently exist in the database. // Use ObjectStore.indexNames to list indexes of a given store. get storeNames() :string[] { return Array.from(this.db.objectStoreNames) } // getStore starts a new transaction in mode on the named store. // You can access the transaction via ObjectStore.transaction. getStore<T=any>(store :string, mode :IDBTransactionMode) :ObjectStore<T> { return this.transaction<T>(mode, store).objectStore(store) } // transaction starts a new transaction. // // Its operations need to be defined immediately after creation. // Transactions are Promises and complete when the transaction finishes. // // It's usually better to use read() or modify() instead of transaction() as those methods // handle transaction promise as part of operation promises. // transaction<T=any>(mode: IDBTransactionMode, ...stores :string[]) :Transaction<T> { return createTransaction<T>(this, this.db.transaction(stores, mode)) } // modify encapsulates operations on object stores in one transaction. // Returns the results of the input functions' results. // // This is uesful since working simply with transaction objects, it's easy to forget to catch // all cases of promise resolution. Consider the following code: // // let [foo] = this.readwrite("foo") // await foo.add({ message: "hello" }) // await foo.transaction // // What happens if the record already exists and the "add" call fails? // An error is thrown early and we never get to await the transaction (= unhandled rejection.) // // To fix this, we would need to rewrite the above code as: // // let [foo] = this.readwrite("foo") // await Promise.all([ // foo.add({ message: "hello" }), // foo.transaction, // ]) // // And that's exactly what this function does. We can rewrite the above as: // // await this.modify(["foo"], foo => foo.add({ message: "hello" })) // // For multiple independent operations, you can provide multiple functions: // // await this.modify(["foo"], // foo => foo.add({ message: "hello" }), // asnyc foo => { // let msg = await foo.get("1") // await foo.put({ message: msg.message + " (copy)" }) // }, // ) // modify(stores :string[], ...f :((...s:ObjectStore<any>[])=>Promise<any>)[]) :Promise<any[]> { let t = this.transaction("readwrite", ...stores) let sv = stores.map(name => t.objectStore(name)) return Promise.all([ t, ...f.map(f => f(...sv)) ]).then(r => (r.shift(), r)) } // read is like modify but operates on a read-only snapshot of the database. // To read a single object, perfer to use get() instead. // Returns the values of the input functions' results. // // Example of retrieving two objects: // // let [message, user] = await db.read(["messages", "users"], // (m, _) => m.get("hello"), // (_, u) => u.get("robin@lol.cat") // ) // read(stores :string[], ...f :((...s:ObjectStore<any>[])=>Promise<any>)[]) :Promise<any[]> { let t = this.transaction("readonly", ...stores) let sv = stores.map(name => t.objectStore(name)) return Promise.all(f.map(f => f(...sv))) // note: ignore transaction promise } // get a single object from store. See ObjectStore.get get<T=any>(store :string, query :IDBValidKey|IDBKeyRange) :Promise<T|null> { return this.getStore<T>(store, "readonly").get(query) } // getAll retrieves multiple values from store. See ObjectStore.getAll getAll(store :string, query?: IDBValidKey|IDBKeyRange, count?: number): Promise<any[]> { return this.getStore(store, "readonly").getAll(query, count) } // add a single object to store. See ObjectStore.add add(store :string, value :any, key? :IDBValidKey): Promise<IDBValidKey> { let s = this.getStore(store, "readwrite") return Promise.all([s.add(value, key), s.transaction]).then(v => v[0]) } // put a single object in store. See ObjectStore.put put(store :string, value: any, key?: IDBValidKey): Promise<IDBValidKey> { let s = this.getStore(store, "readwrite") return Promise.all([s.put(value, key), s.transaction]).then(v => v[0]) } // delete a single object from store. See ObjectStore.delete delete(store :string, key :IDBValidKey|IDBKeyRange): Promise<void> { let s = this.getStore(store, "readwrite") return Promise.all([s.delete(key), s.transaction]) as any as Promise<void> } // getAllKeys retrieves all keys. See ObjectStore.getAllKeys getAllKeys( store :string, query? :IDBValidKey|IDBKeyRange, count? :number, ) :Promise<IDBValidKey[]> { return this.getStore(store, "readonly").getAllKeys(query, count) } } export class UpgradeTransaction { readonly prevVersion :number readonly nextVersion :number _t :Transaction<any> // the one transaction all upgrade operations share db :Database constructor(db :Database, t :IDBTransaction, prevVersion :number, nextVersion :number) { this._t = createTransaction(db, t) this.db = db this.prevVersion = prevVersion this.nextVersion = nextVersion } // storeNames is a list of objects store names that currently exist in the database. // Use ObjectStore.indexNames to list indexes of a given store. get storeNames() :string[] { return Array.from(this.db.db.objectStoreNames) } // hasStore returns true if the database contains the named object store hasStore(name :string) :boolean { return this.db.db.objectStoreNames.contains(name) } // getStore retrieves the names object store getStore<T=any>(name :string) :ObjectStore<T> { return this._t.objectStore(name) } // createStore creates a new object store createStore<T=any>(name :string, params? :IDBObjectStoreParameters) :ObjectStore<T> { let os = this.db.db.createObjectStore(name, params) return new ObjectStore<T>(this.db, os, this._t) } // deleteStore deletes the object store with the given name deleteStore(name :string) :void { this.db.db.deleteObjectStore(name) } } export class Transaction<T> extends Promise<void> { readonly db :Database transaction :IDBTransaction // underlying transaction object readonly aborted :boolean = false // true if abort() was called // when true, abort() causes the transaction to be rejected (i.e. error.) // when false, abort() causes the transaction to be fulfilled. errorOnAbort :boolean = true abort() :void { ;(this as any).aborted = true this.transaction.abort() } objectStore(name :string) :ObjectStore<T> { return new ObjectStore<T>(this.db, this.transaction.objectStore(name), this) } } export class ObjectStore<T> { readonly db :Database readonly store :IDBObjectStore readonly transaction :Transaction<T> // associated transaction // autoIncrement is true if the store has a key generator get autoIncrement() :boolean { return this.store.autoIncrement } // indexNames is the names of indexes get indexNames() :DOMStringList { return this.store.indexNames } // name of the store. Note: Can be "set" _only_ within an upgrade transaction. get name() :string { return this.store.name } set name(name :string) { this.store.name = name } constructor(db :Database, store :IDBObjectStore, transaction: Transaction<T>) { this.db = db this.store = store this.transaction = transaction } // clear deletes _all_ records in store clear() :Promise<void> { return this._promise(() => this.store.clear()).then(() => { this.db._broadcastChange({ type:"clear", store: this.store.name }) }) } // count the number of records matching the given key or key range in query count(key? :IDBValidKey|IDBKeyRange) :Promise<number> { return this._promise(() => this.store.count(key)) } // get retrieves the value of the first record matching the given key or key range in query. // Returns undefined if there was no matching record. get(query :IDBValidKey|IDBKeyRange) :Promise<any|undefined> { return this._promise(() => this.store.get(query)) } // getAll retrieves the values of the records matching the given key or key range in query, // up to count, if provided. getAll(query? :IDBValidKey|IDBKeyRange, count? :number) :Promise<any[]> { return this._promise(() => this.store.getAll(query, count)) } // Retrieves the key of the first record matching the given key or key range in query. // Returns undefined if there was no matching key. getKey(query :IDBValidKey|IDBKeyRange) :Promise<IDBValidKey|undefined> { return this._promise(() => this.store.getKey(query)) } // getAllKeys retrieves the keys of records matching the given key or key range in query, // up to count if given. getAllKeys(query? :IDBValidKey|IDBKeyRange, count? :number) :Promise<IDBValidKey[]> { return this._promise(() => this.store.getAllKeys(query, count)) } // add inserts a new record. If a record already exists in the object store with the key, // then an error is raised. add(value :any, key? :IDBValidKey) :Promise<IDBValidKey> { return this._promise(() => this.store.add(value, key)).then(key => (this.db._broadcastChange({ type: "update", store: this.store.name, key, value }), key) ) } // put inserts or updates a record. put(value :any, key? :IDBValidKey) :Promise<IDBValidKey> { return this._promise(() => this.store.put(value, key)).then(key => (this.db._broadcastChange({ type: "update", store: this.store.name, key, value }), key) ) } // delete removes records in store with the given key or in the given key range in query. // Deleting a record that does not exists does _not_ cause an error but succeeds. delete(key :IDBValidKey|IDBKeyRange) :Promise<void> { return this._promise(() => this.store.delete(key)).then(() => (this.db._broadcastChange({ type: "delete", store: this.store.name, key }), undefined) ) } // createIndex creates a new index in store with the given name, keyPath and options and // returns a new IDBIndex. If the keyPath and options define constraints that cannot be // satisfied with the data already in store the upgrade transaction will abort with // a "ConstraintError" DOMException. // Throws an "InvalidStateError" DOMException if not called within an upgrade transaction. createIndex(name :string, keyPath :string|string[], options? :IDBIndexParameters) :IDBIndex { return this.store.createIndex(name, keyPath, options) } // deleteIndex deletes the index in store with the given name. // Throws an "InvalidStateError" DOMException if not called within an upgrade transaction. deleteIndex(name :string) :void { this.store.deleteIndex(name) } // getIndex retrieves the named index. getIndex<IT=T>(name :string) :Index<IT> { return new Index<IT>(this, this.store.index(name)) } _promise<R,T extends IDBRequest = IDBRequest>(f :()=>IDBRequest<R>) :Promise<R> { return new Promise<R>((resolve, reject) => { let r = f() r.onsuccess = () => { resolve(r.result) } r.onerror = () => { reject(r.error) } }) } } class Index<T> { readonly store :ObjectStore<T> readonly index :IDBIndex constructor(store :ObjectStore<T>, index :IDBIndex) { this.store = store this.index = index } get keyPath(): string | string[] { return this.index.keyPath } get multiEntry(): boolean { return this.index.multiEntry } get name(): string { return this.index.name } set name(v :string) { this.index.name = v } // only valid during upgrade get unique(): boolean { return this.index.unique } count(key? :IDBValidKey|IDBKeyRange) :Promise<number> { return this._promise(() => this.index.count(key)) } get(key :IDBValidKey|IDBKeyRange) :Promise<T|undefined> { return this._promise(() => this.index.get(key)) } getAll(query? :IDBValidKey|IDBKeyRange, count? :number) :Promise<T[]> { return this._promise(() => this.index.getAll(query, count)) } // TOOD: implement more methods _promise<R,T extends IDBRequest = IDBRequest>(f :()=>IDBRequest<R>) :Promise<R> { return new Promise<R>((resolve, reject) => { let r = f() r.onsuccess = () => { resolve(r.result) } r.onerror = () => { reject(r.error) } }) } } // used for zero-downtime database re-opening class DelayedTransaction<T> extends Transaction<T> { _db :Database _mode :IDBTransactionMode _stores :string[] _resolve :()=>void _reject :(e:Error)=>void _delayed :DelayedObjectStore<T>[] = [] _flushDelayed() { // print("DelayedTransaction _flushDelayed") this.abort = Transaction.prototype.abort this.objectStore = Transaction.prototype.objectStore this.transaction = this._db.db.transaction(this._stores, this._mode) activateDelayedTransaction(this) if (this.aborted) { this.abort() } for (let os of this._delayed) { os._flushDelayed() } this._delayed = [] } abort() :void { ;(this as any).aborted = true } objectStore(name :string) :ObjectStore<T> { let info = this._db._lastSnapshot.storeInfo.get(name)! if (!info) { throw new Error("object store not found") } let os = new DelayedObjectStore<T>( this._db, { name, autoIncrement: info.autoIncrement, indexNames: info.indexNames, keyPath: info.keyPath, } as any as IDBObjectStore, this ) // TODO: support ObjectStore.getIndex(name:string):IDBIndex this._delayed.push(os) return os } } interface DelayedObjectStoreAction<R> { resolve :(v:R)=>any reject :(e:Error)=>void f :()=>IDBRequest<R> } class DelayedObjectStore<T> extends ObjectStore<T> { _delayed :DelayedObjectStoreAction<any>[] = [] _flushDelayed() { // print("DelayedObjectStore _flushDelayed", this._delayed) ;(this as any).store = this.transaction.transaction.objectStore(this.store.name) this._promise = ObjectStore.prototype._promise this._delayed.forEach(({ f, resolve, reject }) => { let r = f() r.onsuccess = () => { resolve(r.result) } r.onerror = () => { reject(r.error) } }) this._delayed = [] } _promise<R,T extends IDBRequest = IDBRequest>(f :()=>IDBRequest<R>) :Promise<R> { return new Promise<R>((resolve, reject) => { this._delayed.push({ f, resolve, reject }) }) } } // export class MemoryDatabase extends Database { // close() :void {} // open(upgradefun? :UpgradeFun) :Promise<void> { // return Promise.resolve() // } // transaction(mode: IDBTransactionMode, ...stores :string[]) :MemTransaction { // return new MemTransaction(this, stores, mode) // } // } // class MemObjectStore extends ObjectStore { // _data = new Map<any,any>() // clear() :Promise<void> { // this._data.clear() // return Promise.resolve() // } // count(key? :IDBValidKey|IDBKeyRange) :Promise<number> { // // TODO count keys // return Promise.resolve(this._data.size) // } // get(query :IDBValidKey|IDBKeyRange) :Promise<any|undefined> { // return Promise.resolve(this._data.get(query)) // } // getAll(query? :IDBValidKey|IDBKeyRange, count? :number) :Promise<any[]> { // // TOOD: get multiple // return Promise.resolve(this._data.get(query)) // } // getKey(query :IDBValidKey|IDBKeyRange) :Promise<IDBValidKey|undefined> { // let key :IDBValidKey|undefined // for (let k of this._data.keys()) { // key = k as IDBValidKey // break // } // return Promise.resolve(key) // } // getAllKeys(query? :IDBValidKey|IDBKeyRange, count? :number) :Promise<IDBValidKey[]> { // return Promise.resolve(Array.from(this._data.keys())) // } // add(value :any, key? :IDBValidKey) :Promise<IDBValidKey> { // if (this._data.has(key)) { // } // } // // put inserts or updates a record. // put(value :any, key? :IDBValidKey) :Promise<IDBValidKey> { // return this._promise(() => this.store.put(value, key)).then(key => // (this.db._broadcastChange({ type: "update", store: this.store.name, key }), key) // ) // } // // delete removes records in store with the given key or in the given key range in query. // // Deleting a record that does not exists does _not_ cause an error but succeeds. // delete(key :IDBValidKey|IDBKeyRange) :Promise<void> { // return this._promise(() => this.store.delete(key)).then(key => // (this.db._broadcastChange({ type: "delete", store: this.store.name, key }), key) // ) // } // } // class MemTransaction extends Transaction { // db :MemoryDatabase // stores :string[] // mode :IDBTransactionMode // constructor(db :MemoryDatabase, stores :string[], mode: IDBTransactionMode) { // super(resolve => resolve()) // this.db = db // this.stores = stores // this.mode = mode // } // abort() :void { // ;(this as any).aborted = true // } // objectStore(name :string) :ObjectStore { // let os = new MemObjectStore( // this._db, // { // name, // autoIncrement: info.autoIncrement, // indexNames: info.indexNames, // keyPath: info.keyPath, // } as any as IDBObjectStore, // this // ) // // TODO: support ObjectStore.getIndex(name:string):IDBIndex // this._delayed.push(os) // return os // } // } function activateDelayedTransaction<T=any>(t :DelayedTransaction<T>) { let tr = t.transaction let resolve = t._resolve ; (t as any)._resolve = undefined let reject = t._reject ; (t as any)._reject = undefined tr.oncomplete = () => { resolve() } tr.onerror = () => { reject(tr.error) } tr.onabort = () => { ;(t as any).aborted = true if (t.errorOnAbort) { reject(new Error("transaction aborted")) } else { resolve() } } } function createTransaction<T=any>(db :Database, tr :IDBTransaction) :Transaction<T> { // Note: For complicated reasons related to Promise implementation in V8, we // can't customize the Transaction constructor. var t = new Transaction<T>((resolve, reject) => { tr.oncomplete = () => { resolve() } tr.onerror = () => { reject(tr.error) } tr.onabort = () => { ;(t as any).aborted = true if (t.errorOnAbort) { reject(new Error("transaction aborted")) } else { resolve() } } }) ;(t as any).db = db t.transaction = tr return t } function openDatabase(db :Database, upgradef? :UpgradeFun) :Promise<IDBDatabase> { return new Promise<IDBDatabase>((_resolve, reject) => { // Note on pcount: upgradef may take an arbitrary amount of time to complete. // The semantics of open() are so that open() should complete when the database // is ready for use, meaning we need to include any upgrades into the "open" action. // The onsuccess handler is called whenever the last operation in an update function // completes, which may be sooner than when other code in the upgrade function completes, // like for instance "post upgrade" code run that e.g. logs on the network. // To solve for this, we simply count promises with pcount and resolve when pcount // reaches zero (no outstanding processes.) let openReq = _indexedDB.open(db.name, db.version) let pcount = 1 // promise counter; starts with 1 outstanding process (the "open" action) let resolve = () => { if (--pcount == 0) { ;(db as any).db = openReq.result _resolve() } } if (upgradef) { openReq.onupgradeneeded = ev => { ;(db as any).db = openReq.result let u = new UpgradeTransaction(db, openReq.transaction, ev.oldVersion, ev.newVersion) let onerr = err => { // abort the upgrade if upgradef fails try { u._t.abort() } catch(_) {} reject(err) } pcount++ u._t.then(resolve).catch(onerr) pcount++ try { upgradef(u).then(resolve).catch(onerr) } catch (err) { onerr(err) } } } openReq.onsuccess = () => { resolve() } openReq.onerror = () => { reject(openReq.error) } }) }
the_stack
import { DerEncodedPublicKey, HttpAgentRequest, PublicKey, requestIdOf, Signature, SignIdentity, } from '@dfinity/agent'; import { Principal } from '@dfinity/principal'; import * as cbor from 'simple-cbor'; import { fromHexString, toHexString } from '../buffer'; const domainSeparator = new TextEncoder().encode('\x1Aic-request-auth-delegation'); const requestDomainSeparator = new TextEncoder().encode('\x0Aic-request'); function _parseBlob(value: unknown): ArrayBuffer { if (typeof value !== 'string' || value.length < 64) { throw new Error('Invalid public key.'); } return fromHexString(value); } /** * A single delegation object that is signed by a private key. This is constructed by * `DelegationChain.create()`. * * {@see DelegationChain} */ export class Delegation { constructor( public readonly pubkey: ArrayBuffer, public readonly expiration: bigint, public readonly targets?: Principal[], ) {} public toCBOR(): cbor.CborValue { // Expiration field needs to be encoded as a u64 specifically. return cbor.value.map({ pubkey: cbor.value.bytes(this.pubkey), expiration: cbor.value.u64(this.expiration.toString(16), 16), ...(this.targets && { targets: cbor.value.array(this.targets.map(t => cbor.value.bytes(t.toUint8Array()))), }), }); } public toJSON(): JsonnableDelegation { // every string should be hex and once-de-hexed, // discoverable what it is (e.g. de-hex to get JSON with a 'type' property, or de-hex to DER // with an OID). After de-hex, if it's not obvious what it is, it's an ArrayBuffer. return { expiration: this.expiration.toString(16), pubkey: toHexString(this.pubkey), ...(this.targets && { targets: this.targets.map(p => p.toHex()) }), }; } } /** * Type of ReturnType<Delegation.toJSON>. * The goal here is to stringify all non-JSON-compatible types to some bytes representation we can * stringify as hex. * (Hex shouldn't be ambiguous ever, because you can encode as DER with semantic OIDs). */ interface JsonnableDelegation { // A BigInt of Nanoseconds since epoch as hex expiration: string; // Hexadecimal representation of the DER public key. pubkey: string; // Array of strings, where each string is hex of principal blob (*NOT* textual representation). targets?: string[]; } /** * A signed delegation, which lends its identity to the public key in the delegation * object. This is constructed by `DelegationChain.create()`. * * {@see DelegationChain} */ export interface SignedDelegation { delegation: Delegation; signature: Signature; } /** * Sign a single delegation object for a period of time. * * @param from The identity that lends its delegation. * @param to The identity that receives the delegation. * @param expiration An expiration date for this delegation. * @param targets Limit this delegation to the target principals. */ async function _createSingleDelegation( from: SignIdentity, to: PublicKey, expiration: Date, targets?: Principal[], ): Promise<SignedDelegation> { const delegation: Delegation = new Delegation( to.toDer(), BigInt(+expiration) * BigInt(1000000), // In nanoseconds. targets, ); // The signature is calculated by signing the concatenation of the domain separator // and the message. // Note: To ensure Safari treats this as a user gesture, ensure to not use async methods // besides the actualy webauthn functionality (such as `sign`). Safari will de-register // a user gesture if you await an async call thats not fetch, xhr, or setTimeout. const challenge = new Uint8Array([ ...domainSeparator, ...new Uint8Array(requestIdOf(delegation)), ]); const signature = await from.sign(challenge); return { delegation, signature, }; } export interface JsonnableDelegationChain { publicKey: string; delegations: Array<{ signature: string; delegation: { pubkey: string; expiration: string; targets?: string[]; }; }>; } /** * A chain of delegations. This is JSON Serializable. * This is the object to serialize and pass to a DelegationIdentity. It does not keep any * private keys. */ export class DelegationChain { /** * Create a delegation chain between two (or more) keys. By default, the expiration time * will be very short (15 minutes). * * To build a chain of more than 2 identities, this function needs to be called multiple times, * passing the previous delegation chain into the options argument. For example: * * @example * const rootKey = createKey(); * const middleKey = createKey(); * const bottomeKey = createKey(); * * const rootToMiddle = await DelegationChain.create( * root, middle.getPublicKey(), Date.parse('2100-01-01'), * ); * const middleToBottom = await DelegationChain.create( * middle, bottom.getPublicKey(), Date.parse('2100-01-01'), { previous: rootToMiddle }, * ); * * // We can now use a delegation identity that uses the delegation above: * const identity = DelegationIdentity.fromDelegation(bottomKey, middleToBottom); * * @param from The identity that will delegate. * @param to The identity that gets delegated. It can now sign messages as if it was the * identity above. * @param expiration The length the delegation is valid. By default, 15 minutes from calling * this function. * @param options A set of options for this delegation. expiration and previous * @param options.previous - Another DelegationChain that this chain should start with. * @param options.targets - targets that scope the delegation (e.g. Canister Principals) */ public static async create( from: SignIdentity, to: PublicKey, expiration: Date = new Date(Date.now() + 15 * 60 * 1000), options: { previous?: DelegationChain; targets?: Principal[]; } = {}, ): Promise<DelegationChain> { const delegation = await _createSingleDelegation(from, to, expiration, options.targets); return new DelegationChain( [...(options.previous?.delegations || []), delegation], options.previous?.publicKey || from.getPublicKey().toDer(), ); } /** * Creates a DelegationChain object from a JSON string. * * @param json The JSON string to parse. */ public static fromJSON(json: string | JsonnableDelegationChain): DelegationChain { const { publicKey, delegations } = typeof json === 'string' ? JSON.parse(json) : json; if (!Array.isArray(delegations)) { throw new Error('Invalid delegations.'); } const parsedDelegations: SignedDelegation[] = delegations.map(signedDelegation => { const { delegation, signature } = signedDelegation; const { pubkey, expiration, targets } = delegation; if (targets !== undefined && !Array.isArray(targets)) { throw new Error('Invalid targets.'); } return { delegation: new Delegation( _parseBlob(pubkey), BigInt(`0x${expiration}`), // expiration in JSON is an hexa string (See toJSON() below). targets && targets.map((t: unknown) => { if (typeof t !== 'string') { throw new Error('Invalid target.'); } return Principal.fromHex(t); }), ), signature: _parseBlob(signature) as Signature, }; }); return new this(parsedDelegations, _parseBlob(publicKey) as DerEncodedPublicKey); } /** * Creates a DelegationChain object from a list of delegations and a DER-encoded public key. * * @param delegations The list of delegations. * @param publicKey The DER-encoded public key of the key-pair signing the first delegation. */ public static fromDelegations( delegations: SignedDelegation[], publicKey: DerEncodedPublicKey, ): DelegationChain { return new this(delegations, publicKey); } protected constructor( public readonly delegations: SignedDelegation[], public readonly publicKey: DerEncodedPublicKey, ) {} public toJSON(): JsonnableDelegationChain { return { delegations: this.delegations.map(signedDelegation => { const { delegation, signature } = signedDelegation; const { targets } = delegation; return { delegation: { expiration: delegation.expiration.toString(16), pubkey: toHexString(delegation.pubkey), ...(targets && { targets: targets.map(t => t.toHex()), }), }, signature: toHexString(signature), }; }), publicKey: toHexString(this.publicKey), }; } } /** * An Identity that adds delegation to a request. Everywhere in this class, the name * innerKey refers to the SignIdentity that is being used to sign the requests, while * originalKey is the identity that is being borrowed. More identities can be used * in the middle to delegate. */ export class DelegationIdentity extends SignIdentity { /** * Create a delegation without having access to delegateKey. * * @param key The key used to sign the reqyests. * @param delegation A delegation object created using `createDelegation`. */ public static fromDelegation( key: Pick<SignIdentity, 'sign'>, delegation: DelegationChain, ): DelegationIdentity { return new this(key, delegation); } protected constructor( private _inner: Pick<SignIdentity, 'sign'>, private _delegation: DelegationChain, ) { super(); } public getDelegation(): DelegationChain { return this._delegation; } public getPublicKey(): PublicKey { return { toDer: () => this._delegation.publicKey, }; } public sign(blob: ArrayBuffer): Promise<Signature> { return this._inner.sign(blob); } public async transformRequest(request: HttpAgentRequest): Promise<unknown> { const { body, ...fields } = request; const requestId = await requestIdOf(body); return { ...fields, body: { content: body, sender_sig: await this.sign( new Uint8Array([...requestDomainSeparator, ...new Uint8Array(requestId)]), ), sender_delegation: this._delegation.delegations, sender_pubkey: this._delegation.publicKey, }, }; } }
the_stack
interface DbState { database: Database; version: DOMString; transaction: (callback: SQLTransactionCallback, errorCallback?: SQLTransactionErrorCallback, successCallback?: SQLVoidCallback) => void; readTransaction: (callback: SQLTransactionCallback, errorCallback?: SQLTransactionErrorCallback, successCallback?: SQLVoidCallback) => void; changeVersion: (oldVersion: DOMString, newVersion: DOMString, callback?: SQLTransactionCallback, errorCallback?: SQLTransactionErrorCallback, successCallback?: SQLVoidCallback) => void } interface SqlQuery { sql: DOMString; args?: ObjectArray | undefined; } interface Results { data: any[]; sqlResultSet: SQLResultSet; } (function () { var dbName: string = "websql-tests"; // run the test createDatabase(dbName); function log(...msg: any[]) { if (console && console.log) { console.log.apply(console, msg); } } function createDatabase(name: string) { var tableOne = { name: "tableOne", columns: ["i_id", "s_name", "d_last"], }; var tableTwo = { name: "tableTwo", columns: ["i_thing", "s_description", "d_decimal"], }; openDatabase(dbName, "1", dbName, 1024 * 1024, function (dbState) { createTables(dbState, [ { name: tableOne.name, columns: tableOne.columns }, { name: tableTwo.name, columns: tableTwo.columns }, ], function (res) { writeRecords(dbState, [ { name: tableOne.name, data: createMockRecord(tableOne.columns) }, { name: tableOne.name, data: createMockRecord(tableOne.columns) }, { name: tableTwo.name, data: createMockRecord(tableTwo.columns) }, { name: tableTwo.name, data: createMockRecord(tableTwo.columns) }, { name: tableTwo.name, data: createMockRecord(tableTwo.columns) }, ], function (ress) { log(ress); readRecords(dbState, [tableOne.name, tableTwo.name], function (resss) { log(resss); }); }); }); }); } function initDb(db: Database): DbState { return { database: db, version: db.version, transaction: db.transaction.bind(db), readTransaction: db.readTransaction.bind(db), changeVersion: db.changeVersion.bind(db) }; } function openDatabase(name: string, version: string, displayName: string, estimatedSize: number, callback: (dbState: DbState) => void) { estimatedSize = estimatedSize || (5 * 1024 * 1024); try { if (!window.openDatabase) { log("WebSQL not implemented"); } else { // seems to synchronously open WebSQL, even though window.openDatabase is async var db: Database = window.openDatabase(name, version, displayName, estimatedSize); var dbState = initDb(db); if (db) { callback(dbState); } else { log("Failed to open database"); } } } catch (ex) { log("Failed to open database '" + name + "': " + (JSON && JSON.stringify ? JSON.stringify(ex) : ex)); } } function createTables(dbState: DbState, tableDefs: { name: string; columns: string[]; }[], callback: (rec: SQLResultSet[][]) => void) { var res: SQLResultSet[][] = []; var resI = 0, count = tableDefs.length; for (var i = 0; i < count; i++) { createTable(dbState, tableDefs[i].name, tableDefs[i].columns, function (rec: SQLResultSet[]) { res.push(rec); resI++; if (resI == count) { callback(res); } }); } } function createTable(dbState: DbState, name: string, columns: string[], callback: (rec: SQLResultSet[]) => void) { var sqls: SqlQuery[] = []; var colDefs = columns.map((col) => { var colType: string = null; var type = col.charAt(0); switch (type) { case 'i': case 'l': colType = "INTEGER"; break; case 'f': case 'd': colType = "REAL"; break; case 'b': case 'z': colType = "INTEGER"; break; case 's': colType = "TEXT"; break; default: colType = "TEXT"; } return col + " " + colType; }); sqls.push({ sql: "CREATE TABLE IF NOT EXISTS " + name + " (" + colDefs.join(",") + ")", args: [] }); execSqlStatements(dbState.transaction, sqls, callback); } /** column name prefixes * 'i', 'l' - integer * 'f', 'd' - float * 'b', 'z' - boolean * 's' - string * other - null */ function createMockRecord(columns: string[]): any { var rec: { [id: string]: any } = {}; for (var i = 0, size = columns.length; i < size; i++) { var col = columns[i]; var type = col.charAt(0); switch (type) { case 'i': case 'l': rec[col] = parseInt((Math.random() * 1000000).toString()); break; case 'f': case 'd': rec[col] = (Math.random() - 0.5) * 2000000; break; case 'b': case 'z': rec[col] = Math.random() > 0.5; break; case 's': rec[col] = String.fromCharCode.apply(String, new Array(Math.round(Math.random() * 21)).join(".").split("").map((k) => 65 + Math.round(Math.random() * 25))); break; default: rec[col] = null; } } return rec; } function writeRecords(dbState: DbState, tableDefs: { name: string; data: any; }[], callback: (rec: SQLResultSet[][]) => void) { var res: SQLResultSet[][] = []; var resI = 0, count = tableDefs.length; for (var i = 0; i < count; i++) { writeRecord(dbState, tableDefs[i].name, tableDefs[i].data, function (rec: SQLResultSet[]) { res.push(rec); resI++; if (resI == count) { callback(res); } }); } } function writeRecord(dbState: DbState, tableName: string, record: any, callback: (rec: SQLResultSet[]) => void) { var props = Object.keys(record); var propCount = props.length; var args: ObjectArray = []; var sqlStatement = { sql: "INSERT INTO " + tableName + " values(" + (new Array(propCount + 1).join("?").split("").join(",")) + ")", args: args }; for (var i = 0; i < propCount; i++) { var prop = props[i]; args.push(record[prop]); } execSqlStatements(dbState.transaction, [sqlStatement], callback); } function readRecords(dbState: DbState, tableNames: string[], callback: (rec: Results[]) => void) { var res: Results[] = []; var resI = 0, count = tableNames.length; for (var i = 0; i < count; i++) { readRecord(dbState, tableNames[i], function (rec: Results) { res.push(rec); resI++; if (resI == count) { callback(res); } }); } } function readRecord(dbState: DbState, tableName: string, callback: (rec: Results) => void) { var args: ObjectArray = []; var sqlStatement = { sql: "SELECT * FROM " + tableName, args: args }; execSqlStatements(dbState.transaction, [sqlStatement], function (rec: SQLResultSet[]) { var resObjs: Results[] = resultSetToResults(rec); callback(resObjs[0]); }); } function resultSetToResults(results: SQLResultSet[]) { var resObjs: Results[] = []; for (var i = 0, count = results.length; i < count; i++) { var resAry: any[] = []; var sqlRsI = results[i]; var resObj = { data: resAry, sqlResultSet: sqlRsI }; resObjs.push(resObj); var rows = sqlRsI.rows; var rI = 0; for (var rI = 0, rCount = sqlRsI.rows.length; rI < rCount; rI++) { var r = rows.item(rI); resAry.push(r); } } return resObjs; } function compareRecords(rec1: any, rec2: any): boolean { var props = Object.keys(rec1); for (var i = 0, size = props.length; i < size; i++) { var prop = props[i]; if (rec1[prop] !== rec2[prop]) { return false; } } return true; } function execSqlStatements<T, U>(xactMethod: (callback: SQLTransactionCallback) => void, sqlStatement: SqlQuery[], callback: (rs: SQLResultSet[]) => void) { var results: SQLResultSet[] = []; var sqlCount = sqlStatement.length; var resI = 0; function execCommand(xact: SQLTransaction, sql: DOMString, args: ObjectArray) { xact.executeSql(sql, args || [], function (xact: SQLTransaction, rs: SQLResultSet): void { results.push(rs); resI++; if (resI === sqlCount) { callback(results); } }, function (transaction, err) { log(err, transaction); return false; }); } xactMethod(function (xact: SQLTransaction): void { for (var i = 0; i < sqlCount; i++) { execCommand(xact, sqlStatement[i].sql, sqlStatement[i].args); } }); } } ());
the_stack
import * as assert from 'assert'; import { IgnoreFile } from 'vs/workbench/services/search/common/ignoreFile'; function runAssert(input: string, ignoreFile: string, ignoreFileLocation: string, shouldMatch: boolean, traverse: boolean) { return (prefix: string) => { const isDir = input.endsWith('/'); const rawInput = isDir ? input.slice(0, input.length - 1) : input; const matcher = new IgnoreFile(ignoreFile, prefix + ignoreFileLocation); if (traverse) { const traverses = matcher.isPathIncludedInTraversal(prefix + rawInput, isDir); if (shouldMatch) { assert(traverses, `${ignoreFileLocation}: ${ignoreFile} should traverse ${isDir ? 'dir' : 'file'} ${prefix}${rawInput}`); } else { assert(!traverses, `${ignoreFileLocation}: ${ignoreFile} should not traverse ${isDir ? 'dir' : 'file'} ${prefix}${rawInput}`); } } else { const ignores = matcher.isArbitraryPathIgnored(prefix + rawInput, isDir); if (shouldMatch) { assert(ignores, `${ignoreFileLocation}: ${ignoreFile} should ignore ${isDir ? 'dir' : 'file'} ${prefix}${rawInput}`); } else { assert(!ignores, `${ignoreFileLocation}: ${ignoreFile} should not ignore ${isDir ? 'dir' : 'file'} ${prefix}${rawInput}`); } } }; } function assertNoTraverses(ignoreFile: string, ignoreFileLocation: string, input: string) { const runWithPrefix = runAssert(input, ignoreFile, ignoreFileLocation, false, true); runWithPrefix(''); runWithPrefix('/someFolder'); } function assertTraverses(ignoreFile: string, ignoreFileLocation: string, input: string) { const runWithPrefix = runAssert(input, ignoreFile, ignoreFileLocation, true, true); runWithPrefix(''); runWithPrefix('/someFolder'); } function assertIgnoreMatch(ignoreFile: string, ignoreFileLocation: string, input: string) { const runWithPrefix = runAssert(input, ignoreFile, ignoreFileLocation, true, false); runWithPrefix(''); runWithPrefix('/someFolder'); } function assertNoIgnoreMatch(ignoreFile: string, ignoreFileLocation: string, input: string) { const runWithPrefix = runAssert(input, ignoreFile, ignoreFileLocation, false, false); runWithPrefix(''); runWithPrefix('/someFolder'); } suite('Parsing .gitignore files', () => { test('paths with trailing slashes do not match files', () => { let i = 'node_modules/\n'; assertNoIgnoreMatch(i, '/', '/node_modules'); assertIgnoreMatch(i, '/', '/node_modules/'); assertNoIgnoreMatch(i, '/', '/inner/node_modules'); assertIgnoreMatch(i, '/', '/inner/node_modules/'); }); test('parsing simple gitignore files', () => { let i = 'node_modules\nout\n'; assertIgnoreMatch(i, '/', '/node_modules'); assertNoTraverses(i, '/', '/node_modules'); assertIgnoreMatch(i, '/', '/node_modules/file'); assertIgnoreMatch(i, '/', '/dir/node_modules'); assertIgnoreMatch(i, '/', '/dir/node_modules/file'); assertIgnoreMatch(i, '/', '/out'); assertNoTraverses(i, '/', '/out'); assertIgnoreMatch(i, '/', '/out/file'); assertIgnoreMatch(i, '/', '/dir/out'); assertIgnoreMatch(i, '/', '/dir/out/file'); i = '/node_modules\n/out\n'; assertIgnoreMatch(i, '/', '/node_modules'); assertIgnoreMatch(i, '/', '/node_modules/file'); assertNoIgnoreMatch(i, '/', '/dir/node_modules'); assertNoIgnoreMatch(i, '/', '/dir/node_modules/file'); assertIgnoreMatch(i, '/', '/out'); assertIgnoreMatch(i, '/', '/out/file'); assertNoIgnoreMatch(i, '/', '/dir/out'); assertNoIgnoreMatch(i, '/', '/dir/out/file'); i = 'node_modules/\nout/\n'; assertNoIgnoreMatch(i, '/', '/node_modules'); assertIgnoreMatch(i, '/', '/node_modules/'); assertIgnoreMatch(i, '/', '/node_modules/file'); assertIgnoreMatch(i, '/', '/dir/node_modules/'); assertNoIgnoreMatch(i, '/', '/dir/node_modules'); assertIgnoreMatch(i, '/', '/dir/node_modules/file'); assertIgnoreMatch(i, '/', '/out/'); assertNoIgnoreMatch(i, '/', '/out'); assertIgnoreMatch(i, '/', '/out/file'); assertNoIgnoreMatch(i, '/', '/dir/out'); assertIgnoreMatch(i, '/', '/dir/out/'); assertIgnoreMatch(i, '/', '/dir/out/file'); }); test('parsing files-in-folder exclude', () => { let i = 'node_modules/*\n'; assertNoIgnoreMatch(i, '/', '/node_modules'); assertNoIgnoreMatch(i, '/', '/node_modules/'); assertTraverses(i, '/', '/node_modules'); assertTraverses(i, '/', '/node_modules/'); assertIgnoreMatch(i, '/', '/node_modules/something'); assertNoTraverses(i, '/', '/node_modules/something'); assertIgnoreMatch(i, '/', '/node_modules/something/else'); assertIgnoreMatch(i, '/', '/node_modules/@types'); assertNoTraverses(i, '/', '/node_modules/@types'); i = 'node_modules/**/*\n'; assertNoIgnoreMatch(i, '/', '/node_modules'); assertNoIgnoreMatch(i, '/', '/node_modules/'); assertIgnoreMatch(i, '/', '/node_modules/something'); assertIgnoreMatch(i, '/', '/node_modules/something/else'); assertIgnoreMatch(i, '/', '/node_modules/@types'); }); test('parsing simple negations', () => { let i = 'node_modules/*\n!node_modules/@types\n'; assertNoIgnoreMatch(i, '/', '/node_modules'); assertTraverses(i, '/', '/node_modules'); assertIgnoreMatch(i, '/', '/node_modules/something'); assertNoTraverses(i, '/', '/node_modules/something'); assertIgnoreMatch(i, '/', '/node_modules/something/else'); assertNoIgnoreMatch(i, '/', '/node_modules/@types'); assertTraverses(i, '/', '/node_modules/@types'); assertTraverses(i, '/', '/node_modules/@types/boop'); i = '*.log\n!important.log\n'; assertIgnoreMatch(i, '/', '/test.log'); assertIgnoreMatch(i, '/', '/inner/test.log'); assertNoIgnoreMatch(i, '/', '/important.log'); assertNoIgnoreMatch(i, '/', '/inner/important.log'); assertNoTraverses(i, '/', '/test.log'); assertNoTraverses(i, '/', '/inner/test.log'); assertTraverses(i, '/', '/important.log'); assertTraverses(i, '/', '/inner/important.log'); }); test('nested .gitignores', () => { let i = 'node_modules\nout\n'; assertIgnoreMatch(i, '/inner/', '/inner/node_modules'); assertIgnoreMatch(i, '/inner/', '/inner/more/node_modules'); i = '/node_modules\n/out\n'; assertIgnoreMatch(i, '/inner/', '/inner/node_modules'); assertNoIgnoreMatch(i, '/inner/', '/inner/more/node_modules'); assertNoIgnoreMatch(i, '/inner/', '/node_modules'); i = 'node_modules/\nout/\n'; assertNoIgnoreMatch(i, '/inner/', '/inner/node_modules'); assertIgnoreMatch(i, '/inner/', '/inner/node_modules/'); assertNoIgnoreMatch(i, '/inner/', '/inner/more/node_modules'); assertIgnoreMatch(i, '/inner/', '/inner/more/node_modules/'); assertNoIgnoreMatch(i, '/inner/', '/node_modules'); }); test('file extension matches', () => { let i = '*.js\n'; assertNoIgnoreMatch(i, '/', '/myFile.ts'); assertIgnoreMatch(i, '/', '/myFile.js'); assertNoIgnoreMatch(i, '/', '/inner/myFile.ts'); assertIgnoreMatch(i, '/', '/inner/myFile.js'); i = '/*.js'; assertNoIgnoreMatch(i, '/', '/myFile.ts'); assertIgnoreMatch(i, '/', '/myFile.js'); assertNoIgnoreMatch(i, '/', '/inner/myFile.ts'); assertNoIgnoreMatch(i, '/', '/inner/myFile.js'); i = '**/*.js'; assertNoIgnoreMatch(i, '/', '/myFile.ts'); assertIgnoreMatch(i, '/', '/myFile.js'); assertNoIgnoreMatch(i, '/', '/inner/myFile.ts'); assertIgnoreMatch(i, '/', '/inner/myFile.js'); assertNoIgnoreMatch(i, '/', '/inner/more/myFile.ts'); assertIgnoreMatch(i, '/', '/inner/more/myFile.js'); i = 'inner/*.js'; assertNoIgnoreMatch(i, '/', '/myFile.ts'); assertNoIgnoreMatch(i, '/', '/myFile.js'); assertNoIgnoreMatch(i, '/', '/inner/myFile.ts'); assertIgnoreMatch(i, '/', '/inner/myFile.js'); assertNoIgnoreMatch(i, '/', '/inner/more/myFile.ts'); assertNoIgnoreMatch(i, '/', '/inner/more/myFile.js'); i = '/inner/*.js'; assertNoIgnoreMatch(i, '/', '/myFile.ts'); assertNoIgnoreMatch(i, '/', '/myFile.js'); assertNoIgnoreMatch(i, '/', '/inner/myFile.ts'); assertIgnoreMatch(i, '/', '/inner/myFile.js'); assertNoIgnoreMatch(i, '/', '/inner/more/myFile.ts'); assertNoIgnoreMatch(i, '/', '/inner/more/myFile.js'); i = '**/inner/*.js'; assertNoIgnoreMatch(i, '/', '/myFile.ts'); assertNoIgnoreMatch(i, '/', '/myFile.js'); assertNoIgnoreMatch(i, '/', '/inner/myFile.ts'); assertIgnoreMatch(i, '/', '/inner/myFile.js'); assertNoIgnoreMatch(i, '/', '/inner/more/myFile.ts'); assertNoIgnoreMatch(i, '/', '/inner/more/myFile.js'); i = '**/inner/**/*.js'; assertNoIgnoreMatch(i, '/', '/myFile.ts'); assertNoIgnoreMatch(i, '/', '/myFile.js'); assertNoIgnoreMatch(i, '/', '/inner/myFile.ts'); assertIgnoreMatch(i, '/', '/inner/myFile.js'); assertNoIgnoreMatch(i, '/', '/inner/more/myFile.ts'); assertIgnoreMatch(i, '/', '/inner/more/myFile.js'); i = '**/more/*.js'; assertNoIgnoreMatch(i, '/', '/myFile.ts'); assertNoIgnoreMatch(i, '/', '/myFile.js'); assertNoIgnoreMatch(i, '/', '/inner/myFile.ts'); assertNoIgnoreMatch(i, '/', '/inner/myFile.js'); assertNoIgnoreMatch(i, '/', '/inner/more/myFile.ts'); assertIgnoreMatch(i, '/', '/inner/more/myFile.js'); }); test('real world example: vscode-js-debug', () => { let i = `.cache/ .profile/ .cdp-profile/ .headless-profile/ .vscode-test/ .DS_Store node_modules/ out/ dist /coverage /.nyc_output demos/web-worker/vscode-pwa-dap.log demos/web-worker/vscode-pwa-cdp.log .dynamic-testWorkspace **/test/**/*.actual /testWorkspace/web/tmp /testWorkspace/**/debug.log /testWorkspace/webview/win/true/ *.cpuprofile`; let included = [ '/distro', '/inner/coverage', '/inner/.nyc_output', '/inner/demos/web-worker/vscode-pwa-dap.log', '/inner/demos/web-worker/vscode-pwa-cdp.log', '/testWorkspace/webview/win/true', '/a/best/b/c.actual', '/best/b/c.actual', ]; let excluded = [ '/.profile/', '/inner/.profile/', '/.DS_Store', '/inner/.DS_Store', '/coverage', '/.nyc_output', '/demos/web-worker/vscode-pwa-dap.log', '/demos/web-worker/vscode-pwa-cdp.log', '/.dynamic-testWorkspace', '/inner/.dynamic-testWorkspace', '/test/.actual', '/test/hello.actual', '/a/test/.actual', '/a/test/b.actual', '/a/test/b/.actual', '/a/test/b/c.actual', '/a/b/test/.actual', '/a/b/test/f/c.actual', '/testWorkspace/web/tmp', '/testWorkspace/debug.log', '/testWorkspace/a/debug.log', '/testWorkspace/a/b/debug.log', '/testWorkspace/webview/win/true/', '/.cpuprofile', '/a.cpuprofile', '/aa/a.cpuprofile', '/aaa/aa/a.cpuprofile', ]; for (const include of included) { assertNoIgnoreMatch(i, '/', include); } for (const exclude of excluded) { assertIgnoreMatch(i, '/', exclude); } }); test('real world example: vscode', () => { const i = `.DS_Store .cache npm-debug.log Thumbs.db node_modules/ .build/ extensions/**/dist/ /out*/ /extensions/**/out/ src/vs/server resources/server build/node_modules coverage/ test_data/ test-results/ yarn-error.log vscode.lsif vscode.db /.profile-oss`; let included = [ '/inner/extensions/dist', '/inner/extensions/boop/dist/test', '/inner/extensions/boop/doop/dist', '/inner/extensions/boop/doop/dist/test', '/inner/extensions/boop/doop/dist/test', '/inner/extensions/out/test', '/inner/extensions/boop/out', '/inner/extensions/boop/out/test', '/inner/out/', '/inner/out/test', '/inner/out1/', '/inner/out1/test', '/inner/out2/', '/inner/out2/test', '/inner/.profile-oss', // Files. '/extensions/dist', '/extensions/boop/doop/dist', '/extensions/boop/out', ]; let excluded = [ '/extensions/dist/', '/extensions/boop/dist/test', '/extensions/boop/doop/dist/', '/extensions/boop/doop/dist/test', '/extensions/boop/doop/dist/test', '/extensions/out/test', '/extensions/boop/out/', '/extensions/boop/out/test', '/out/', '/out/test', '/out1/', '/out1/test', '/out2/', '/out2/test', '/.profile-oss', ]; for (const include of included) { assertNoIgnoreMatch(i, '/', include); } for (const exclude of excluded) { assertIgnoreMatch(i, '/', exclude); } }); test('various advanced constructs found in popular repos', () => { const runTest = ({ pattern, included, excluded }: { pattern: string; included: string[]; excluded: string[] }) => { for (const include of included) { assertNoIgnoreMatch(pattern, '/', include); } for (const exclude of excluded) { assertIgnoreMatch(pattern, '/', exclude); } }; runTest({ pattern: `**/node_modules /packages/*/dist`, excluded: [ '/node_modules', '/test/node_modules', '/node_modules/test', '/test/node_modules/test', '/packages/a/dist', '/packages/abc/dist', '/packages/abc/dist/test', ], included: [ '/inner/packages/a/dist', '/inner/packages/abc/dist', '/inner/packages/abc/dist/test', '/packages/dist', '/packages/dist/test', '/packages/a/b/dist', '/packages/a/b/dist/test', ], }); runTest({ pattern: `.yarn/* # !.yarn/cache !.yarn/patches !.yarn/plugins !.yarn/releases !.yarn/sdks !.yarn/versions`, excluded: [ '/.yarn/test', '/.yarn/cache', ], included: [ '/inner/.yarn/test', '/inner/.yarn/cache', '/.yarn/patches', '/.yarn/plugins', '/.yarn/releases', '/.yarn/sdks', '/.yarn/versions', ], }); runTest({ pattern: `[._]*s[a-w][a-z] [._]s[a-w][a-z] *.un~ *~`, excluded: [ '/~', '/abc~', '/inner/~', '/inner/abc~', '/.un~', '/a.un~', '/test/.un~', '/test/a.un~', '/.saa', '/....saa', '/._._sby', '/inner/._._sby', '/_swz', ], included: [ '/.jaa', ], }); // TODO: the rest of these :) runTest({ pattern: `*.pbxuser !default.pbxuser *.mode1v3 !default.mode1v3 *.mode2v3 !default.mode2v3 *.perspectivev3 !default.perspectivev3`, excluded: [], included: [], }); runTest({ pattern: `[Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ *.[Mm]etrics.xml [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* bld/ [Bb]in/ [Oo]bj/ [Ll]og/`, excluded: [], included: [], }); runTest({ pattern: `Dockerfile* !/tests/bud/*/Dockerfile* !/tests/conformance/**/Dockerfile*`, excluded: [], included: [], }); runTest({ pattern: `*.pdf *.html !author_bio.html !colo.html !copyright.html !cover.html !ix.html !titlepage.html !toc.html`, excluded: [], included: [], }); runTest({ pattern: `/log/* /tmp/* !/log/.keep !/tmp/.keep`, excluded: [], included: [], }); }); });
the_stack
import { EventEmitter } from 'events' import * as rlp from 'rlp' import ms from 'ms' import snappy from 'snappyjs' import { debug as createDebugLogger } from 'debug' import { int2buffer, buffer2int, assertEq, formatLogData } from '../util' import { Peer, DISCONNECT_REASONS } from '../rlpx/peer' const DEBUG_BASE_NAME = 'devp2p:les' const debug = createDebugLogger(DEBUG_BASE_NAME) const verbose = createDebugLogger('verbose').enabled export const DEFAULT_ANNOUNCE_TYPE = 1 /** * Will be set to the first successfully connected peer to allow for * debugging with the `devp2p:FIRST_PEER` debugger */ let _firstPeer = '' type SendMethod = (code: LES.MESSAGE_CODES, data: Buffer) => any export class LES extends EventEmitter { _version: number _peer: Peer _send: SendMethod _status: LES.Status | null _peerStatus: LES.Status | null _statusTimeoutId: NodeJS.Timeout // Message debuggers (e.g. { 'GET_BLOCK_HEADERS': [debug Object], ...}) private msgDebuggers: { [key: string]: (debug: string) => void } = {} constructor(version: number, peer: Peer, send: SendMethod) { super() this._version = version this._peer = peer this._send = send this._status = null this._peerStatus = null this._statusTimeoutId = setTimeout(() => { this._peer.disconnect(DISCONNECT_REASONS.TIMEOUT) }, ms('5s')) this.initMsgDebuggers() } static les2 = { name: 'les', version: 2, length: 21, constructor: LES } static les3 = { name: 'les', version: 3, length: 23, constructor: LES } static les4 = { name: 'les', version: 4, length: 23, constructor: LES } _handleMessage(code: LES.MESSAGE_CODES, data: any) { const payload = rlp.decode(data) const messageName = this.getMsgPrefix(code) const debugMsg = `Received ${messageName} message from ${this._peer._socket.remoteAddress}:${this._peer._socket.remotePort}` if (code !== LES.MESSAGE_CODES.STATUS) { const logData = formatLogData(data.toString('hex'), verbose) this.debug(messageName, `${debugMsg}: ${logData}`) } switch (code) { case LES.MESSAGE_CODES.STATUS: { assertEq( this._peerStatus, null, 'Uncontrolled status message', this.debug.bind(this), 'STATUS' ) const statusArray: any = {} payload.forEach(function (value: any) { statusArray[value[0].toString()] = value[1] }) this._peerStatus = statusArray const peerStatusMsg = `${this._peerStatus ? this._getStatusString(this._peerStatus) : ''}` this.debug(messageName, `${debugMsg}: ${peerStatusMsg}`) this._handleStatus() break } case LES.MESSAGE_CODES.ANNOUNCE: case LES.MESSAGE_CODES.GET_BLOCK_HEADERS: case LES.MESSAGE_CODES.BLOCK_HEADERS: case LES.MESSAGE_CODES.GET_BLOCK_BODIES: case LES.MESSAGE_CODES.BLOCK_BODIES: case LES.MESSAGE_CODES.GET_RECEIPTS: case LES.MESSAGE_CODES.RECEIPTS: case LES.MESSAGE_CODES.GET_PROOFS: case LES.MESSAGE_CODES.PROOFS: case LES.MESSAGE_CODES.GET_CONTRACT_CODES: case LES.MESSAGE_CODES.CONTRACT_CODES: case LES.MESSAGE_CODES.GET_HEADER_PROOFS: case LES.MESSAGE_CODES.HEADER_PROOFS: case LES.MESSAGE_CODES.SEND_TX: case LES.MESSAGE_CODES.GET_PROOFS_V2: case LES.MESSAGE_CODES.PROOFS_V2: case LES.MESSAGE_CODES.GET_HELPER_TRIE_PROOFS: case LES.MESSAGE_CODES.HELPER_TRIE_PROOFS: case LES.MESSAGE_CODES.SEND_TX_V2: case LES.MESSAGE_CODES.GET_TX_STATUS: case LES.MESSAGE_CODES.TX_STATUS: if (this._version >= LES.les2.version) break return case LES.MESSAGE_CODES.STOP_MSG: case LES.MESSAGE_CODES.RESUME_MSG: if (this._version >= LES.les3.version) break return default: return } this.emit('message', code, payload) } _handleStatus() { if (this._status === null || this._peerStatus === null) return clearTimeout(this._statusTimeoutId) assertEq( this._status['protocolVersion'], this._peerStatus['protocolVersion'], 'Protocol version mismatch', this.debug.bind(this), 'STATUS' ) assertEq( this._status['networkId'], this._peerStatus['networkId'], 'NetworkId mismatch', this.debug.bind(this), 'STATUS' ) assertEq( this._status['genesisHash'], this._peerStatus['genesisHash'], 'Genesis block mismatch', this.debug.bind(this), 'STATUS' ) this.emit('status', this._peerStatus) if (_firstPeer === '') { this._addFirstPeerDebugger() } } getVersion() { return this._version } _getStatusString(status: LES.Status) { let sStr = `[V:${buffer2int(status['protocolVersion'])}, ` sStr += `NID:${buffer2int(status['networkId'] as Buffer)}, HTD:${buffer2int( status['headTd'] )}, ` sStr += `HeadH:${status['headHash'].toString('hex')}, HeadN:${buffer2int(status['headNum'])}, ` sStr += `GenH:${status['genesisHash'].toString('hex')}` if (status['serveHeaders']) sStr += `, serveHeaders active` if (status['serveChainSince']) sStr += `, ServeCS: ${buffer2int(status['serveChainSince'])}` if (status['serveStateSince']) sStr += `, ServeSS: ${buffer2int(status['serveStateSince'])}` if (status['txRelay']) sStr += `, txRelay active` if (status['flowControl/BL']) sStr += `, flowControl/BL set` if (status['flowControl/MRR']) sStr += `, flowControl/MRR set` if (status['flowControl/MRC']) sStr += `, flowControl/MRC set` if (status['forkID']) sStr += `, forkID: [crc32: ${status['forkID'][0].toString('hex')}, nextFork: ${buffer2int( status['forkID'][1] )}]` if (status['recentTxLookup']) sStr += `, recentTxLookup: ${buffer2int(status['recentTxLookup'])}` sStr += `]` return sStr } sendStatus(status: LES.Status) { if (this._status !== null) return if (!status.announceType) { status['announceType'] = int2buffer(DEFAULT_ANNOUNCE_TYPE) } status['protocolVersion'] = int2buffer(this._version) status['networkId'] = this._peer._common.chainIdBN().toArrayLike(Buffer) this._status = status const statusList: any[][] = [] Object.keys(status).forEach((key) => { statusList.push([key, status[key]]) }) this.debug( 'STATUS', `Send STATUS message to ${this._peer._socket.remoteAddress}:${ this._peer._socket.remotePort } (les${this._version}): ${this._getStatusString(this._status)}` ) let payload = rlp.encode(statusList) // Use snappy compression if peer supports DevP2P >=v5 if (this._peer._hello?.protocolVersion && this._peer._hello?.protocolVersion >= 5) { payload = snappy.compress(payload) } this._send(LES.MESSAGE_CODES.STATUS, payload) this._handleStatus() } /** * * @param code Message code * @param payload Payload (including reqId, e.g. `[1, [437000, 1, 0, 0]]`) */ sendMessage(code: LES.MESSAGE_CODES, payload: any) { const messageName = this.getMsgPrefix(code) const logData = formatLogData(rlp.encode(payload).toString('hex'), verbose) const debugMsg = `Send ${messageName} message to ${this._peer._socket.remoteAddress}:${this._peer._socket.remotePort}: ${logData}` this.debug(messageName, debugMsg) switch (code) { case LES.MESSAGE_CODES.STATUS: throw new Error('Please send status message through .sendStatus') case LES.MESSAGE_CODES.ANNOUNCE: // LES/1 case LES.MESSAGE_CODES.GET_BLOCK_HEADERS: case LES.MESSAGE_CODES.BLOCK_HEADERS: case LES.MESSAGE_CODES.GET_BLOCK_BODIES: case LES.MESSAGE_CODES.BLOCK_BODIES: case LES.MESSAGE_CODES.GET_RECEIPTS: case LES.MESSAGE_CODES.RECEIPTS: case LES.MESSAGE_CODES.GET_PROOFS: case LES.MESSAGE_CODES.PROOFS: case LES.MESSAGE_CODES.GET_CONTRACT_CODES: case LES.MESSAGE_CODES.CONTRACT_CODES: case LES.MESSAGE_CODES.GET_HEADER_PROOFS: case LES.MESSAGE_CODES.HEADER_PROOFS: case LES.MESSAGE_CODES.SEND_TX: case LES.MESSAGE_CODES.GET_PROOFS_V2: // LES/2 case LES.MESSAGE_CODES.PROOFS_V2: case LES.MESSAGE_CODES.GET_HELPER_TRIE_PROOFS: case LES.MESSAGE_CODES.HELPER_TRIE_PROOFS: case LES.MESSAGE_CODES.SEND_TX_V2: case LES.MESSAGE_CODES.GET_TX_STATUS: case LES.MESSAGE_CODES.TX_STATUS: if (this._version >= LES.les2.version) break throw new Error(`Code ${code} not allowed with version ${this._version}`) case LES.MESSAGE_CODES.STOP_MSG: case LES.MESSAGE_CODES.RESUME_MSG: if (this._version >= LES.les3.version) break throw new Error(`Code ${code} not allowed with version ${this._version}`) default: throw new Error(`Unknown code ${code}`) } payload = rlp.encode(payload) // Use snappy compression if peer supports DevP2P >=v5 if (this._peer._hello?.protocolVersion && this._peer._hello?.protocolVersion >= 5) { payload = snappy.compress(payload) } this._send(code, payload) } getMsgPrefix(msgCode: LES.MESSAGE_CODES) { return LES.MESSAGE_CODES[msgCode] } private initMsgDebuggers() { const MESSAGE_NAMES = Object.values(LES.MESSAGE_CODES).filter( (value) => typeof value === 'string' ) as string[] for (const name of MESSAGE_NAMES) { this.msgDebuggers[name] = createDebugLogger(`${DEBUG_BASE_NAME}:${name}`) } } /** * Called once on the peer where a first successful `STATUS` * msg exchange could be achieved. * * Can be used together with the `devp2p:FIRST_PEER` debugger. */ _addFirstPeerDebugger() { const ip = this._peer._socket.remoteAddress if (ip) { this.msgDebuggers[ip] = createDebugLogger(`devp2p:FIRST_PEER`) this._peer._addFirstPeerDebugger() _firstPeer = ip } } /** * Debug message both on the generic as well as the * per-message debug logger * @param messageName Capitalized message name (e.g. `GET_BLOCK_HEADERS`) * @param msg Message text to debug */ private debug(messageName: string, msg: string) { debug(msg) if (this.msgDebuggers[messageName]) { this.msgDebuggers[messageName](msg) } } } export namespace LES { export interface Status { [key: string]: any protocolVersion: Buffer networkId: Buffer headTd: Buffer headHash: Buffer headNum: Buffer genesisHash: Buffer serveHeaders: Buffer serveChainSince: Buffer serveStateSince: Buffer txRelay: Buffer 'flowControl/BL': Buffer 'flowControl/MRR': Buffer 'flowControl/MRC': Buffer announceType: Buffer forkID: [Buffer, Buffer] recentTxLookup: Buffer } export enum MESSAGE_CODES { // LES/1 STATUS = 0x00, ANNOUNCE = 0x01, GET_BLOCK_HEADERS = 0x02, BLOCK_HEADERS = 0x03, GET_BLOCK_BODIES = 0x04, BLOCK_BODIES = 0x05, GET_RECEIPTS = 0x06, RECEIPTS = 0x07, GET_PROOFS = 0x08, PROOFS = 0x09, GET_CONTRACT_CODES = 0x0a, CONTRACT_CODES = 0x0b, GET_HEADER_PROOFS = 0x0d, HEADER_PROOFS = 0x0e, SEND_TX = 0x0c, // LES/2 GET_PROOFS_V2 = 0x0f, PROOFS_V2 = 0x10, GET_HELPER_TRIE_PROOFS = 0x11, HELPER_TRIE_PROOFS = 0x12, SEND_TX_V2 = 0x13, GET_TX_STATUS = 0x14, TX_STATUS = 0x15, // LES/3 STOP_MSG = 0x16, RESUME_MSG = 0x17, } }
the_stack
import { TypedArrayConstructor, TypedArray, NestedArrayData } from "../../src/nestedArray/types"; import { createNestedArray, rangeTypedArray } from "../../src/nestedArray"; import { Slice } from "../../src/core/types"; import { slice } from "../../src/core/slice"; import { sliceNestedArray } from "../../src/nestedArray/ops"; describe("NestedArray slicing", () => { interface TestCase { name: string; shape: number[]; constr: TypedArrayConstructor<TypedArray>; selection: (Slice | number)[]; expected: NestedArrayData | number; expectedShape?: number[]; } const testCases: TestCase[] = [ { name: "1d_3", shape: [3], constr: Int32Array, selection: [slice(null)], expected: Int32Array.from([0, 1, 2]), }, { name: "1d_3", shape: [3], constr: Int32Array, selection: [slice(null, null, 1)], expected: Int32Array.from([0, 1, 2]), }, { name: "1d_3_subset", shape: [3], constr: Int32Array, selection: [slice(1, 3)], expected: Int32Array.from([1, 2]), }, { name: "1d_3_superset", shape: [3], constr: Int32Array, selection: [slice(0, 100)], expected: Int32Array.from([0, 1, 2]), }, { name: "1d_3_empty", shape: [3], constr: Int32Array, selection: [slice(5, 100)], expected: Int32Array.from([]), }, { name: "1d_5_step_2", shape: [5], constr: Int32Array, selection: [slice(1, null, 2)], expected: Int32Array.from([1, 3]), }, { name: "1d_5_super_subset_step_-1", shape: [5], constr: Int32Array, selection: [slice(5, 2, -1)], expected: Int32Array.from([4, 3]), }, { name: "1d_5_subset_step_-1", shape: [5], constr: Int32Array, selection: [slice(4, 0, -1)], expected: Int32Array.from([4, 3, 2, 1]), }, { name: "1d_5_subset_step_-2", shape: [5], constr: Int32Array, selection: [slice(4, 0, -2)], expected: Int32Array.from([4, 2]), }, { name: "1d_5_step_-1_A", shape: [5], constr: Int32Array, selection: [slice(null, null, -1)], expected: Int32Array.from([4, 3, 2, 1, 0]), }, { name: "1d_5_step_-1_B", shape: [5], constr: Int32Array, selection: [slice(null, -3, -1)], expected: Int32Array.from([4, 3]), }, { name: "1d_5_step_-2", shape: [5], constr: Int32Array, selection: [slice(null, -3, -2)], expected: Int32Array.from([4]), }, { name: "2d_2x3", shape: [2, 3], constr: Int32Array, selection: [slice(null)], expected: [Int32Array.from([0, 1, 2]), Int32Array.from([3, 4, 5])], expectedShape: [2, 3], }, { name: "2d_2x3", shape: [2, 3], constr: Int32Array, selection: [slice(null), slice(null)], expected: [Int32Array.from([0, 1, 2]), Int32Array.from([3, 4, 5])], }, { name: "2d_2x3_inverse", shape: [2, 3], constr: Int32Array, selection: [slice(null, null, -1), slice(null)], expected: [Int32Array.from([3, 4, 5]), Int32Array.from([0, 1, 2])], }, { name: "2d_2x3_empty_result_A", shape: [2, 3], constr: Int32Array, selection: [slice(0, 0)], expected: new Int32Array(0), expectedShape: [0, 3], }, { name: "2d_2x3_empty_result_B", shape: [2, 3], constr: Int32Array, selection: [slice(null), slice(0, 0)], expected: [Int32Array.from([]), Int32Array.from([])], }, { name: "2d_2x3_slice_A", shape: [2, 3], constr: Int32Array, selection: [slice(0, 1), slice(null)], expected: [Int32Array.from([0, 1, 2])], }, { name: "2d_2x3_slice_B", shape: [2, 3], constr: Int32Array, selection: [slice(1, 2), slice(null)], expected: [Int32Array.from([3, 4, 5])], }, { name: "2d_2x3_slice_C", shape: [2, 3], constr: Int32Array, selection: [slice(1, 2), slice(0, 2)], expected: [Int32Array.from([3, 4])], }, { name: "2d_2x3_slice_D", shape: [2, 3], constr: Int32Array, selection: [slice(1, 2), slice(null, 0, -1)], expected: [Int32Array.from([5, 4])], }, { name: "2d_2x3_slice_E", shape: [2, 3], constr: Int32Array, selection: [slice(1, 2), slice(null, null, -1)], expected: [Int32Array.from([5, 4, 3])], }, { name: "2d_2x3_slice_F", shape: [2, 3], constr: Int32Array, selection: [0, slice(null, null, -1)], expected: Int32Array.from([2, 1, 0]), }, { name: "4d_1x2x2x4", shape: [1, 2, 2, 4], constr: Int32Array, selection: [slice(null), slice(null), slice(null), slice(null)], expected: [[[Int32Array.from([0, 1, 2, 3]), Int32Array.from([4, 5, 6, 7])], [Int32Array.from([8, 9, 10, 11]), Int32Array.from([12, 13, 14, 15])]]] }, { name: "4d_1x2x2x4_inverse_dim1", shape: [1, 2, 2, 4], constr: Int32Array, selection: [slice(null), slice(null, null, -1), slice(null), slice(null)], expected: [[[Int32Array.from([8, 9, 10, 11]), Int32Array.from([12, 13, 14, 15])], [Int32Array.from([0, 1, 2, 3]), Int32Array.from([4, 5, 6, 7])]]] }, { name: "4d_1x2x2x4_inverse_dim1_step5", shape: [1, 2, 2, 4], constr: Int32Array, selection: [slice(null), slice(null, null, -5), slice(null), slice(null)], expected: [[[Int32Array.from([8, 9, 10, 11]), Int32Array.from([12, 13, 14, 15])]]] }, { name: "4d_1x2x2x4_inverse_dim1_step5_slice", shape: [1, 2, 2, 4], constr: Int32Array, selection: [slice(null), slice(null, null, -5), slice(null), slice(0, 2)], expected: [[[Int32Array.from([8, 9]), Int32Array.from([12, 13])]]] }, { name: "4d_1x2x2x4_squeeze_simple", shape: [1, 2, 2, 4], constr: Int32Array, selection: [0], expected: [[Int32Array.from([0, 1, 2, 3]), Int32Array.from([4, 5, 6, 7])], [Int32Array.from([8, 9, 10, 11]), Int32Array.from([12, 13, 14, 15])]] }, { name: "1d_squeeze", shape: [3], constr: Int32Array, selection: [1], expected: 1, }, { name: "1d_squeeze_negative_dim", shape: [3], constr: Int32Array, selection: [-1], expected: 2, }, { name: "1d_squeeze_wrongtype", shape: [3], constr: Int32Array, selection: -1 as any, // Not allowed by typing, but actually supported expected: 2, }, { name: "2d_2x3_squeeze", shape: [2, 3], constr: Int32Array, selection: [1], expected: Int32Array.from([3, 4, 5]), }, { name: "2d_2x3_squeeze_last_dim", shape: [2, 3], constr: Int32Array, selection: [slice(null), 0], expected: Int32Array.from([0, 3]), }, { name: "2d_2x3_squeeze_neg_neg", shape: [2, 3], constr: Int32Array, selection: [-2, -1], expected: 2, }, { name: "4d_1x2x2x4_squeeze_A", shape: [1, 2, 2, 4], constr: Int32Array, selection: [0, 0, slice(null), 0], expected: Int32Array.from([0, 4]), }, { name: "4d_1x2x2x4_squeeze_B", shape: [1, 2, 2, 4], constr: Int32Array, selection: [0, 1, slice(null), 0], expected: Int32Array.from([8, 12]), }, { name: "4d_1x2x2x4_empty", shape: [1, 2, 2, 4], constr: Int32Array, selection: [0, slice(5, 5), slice(null)], expected: new Int32Array(0), expectedShape: [0, 2, 4], }, ]; test.each(testCases)(`%p`, (t: TestCase) => { const data = rangeTypedArray(t.shape, t.constr); const nestedArray = (createNestedArray(data.buffer, t.constr, t.shape)); const initialShape = t.shape.map(x => x); // Copy to check if it got mutated const [sliceResult, sliceShape] = sliceNestedArray(nestedArray, t.shape, t.selection); let expectedOutputShape = t.expectedShape; // We can naively determine it, this breaks for selections where some dimensions are empty if (expectedOutputShape === undefined) { expectedOutputShape = []; let x = t.expected; while (typeof x !== "number" && x !== undefined) { expectedOutputShape.push((x as ArrayLike<any>).length); x = x[0]; } } expect(sliceResult).toEqual(t.expected); expect(sliceShape).toEqual(expectedOutputShape); expect(initialShape).toEqual(t.shape); }); });
the_stack
'use strict' const Uniq: any = require('lodash.uniq') const Eraro: any = require('eraro') import Nua from 'nua' import { Ordu, TaskSpec } from 'ordu' // TODO: refactor: use.js->plugin.js and contain *_plugin api methods too const Common: any = require('./common') const Print: any = require('./print') /* $lab:coverage:on$ */ exports.api_use = api_use const intern = exports.intern = make_intern() function api_use(callpoint: any, opts: any) { const tasks = make_tasks() const ordu = new Ordu({ debug: opts.debug }) ordu.operator('seneca_plugin', intern.op.seneca_plugin) ordu.operator('seneca_export', intern.op.seneca_export) ordu.operator('seneca_options', intern.op.seneca_options) ordu.operator('seneca_complete', intern.op.seneca_complete) ordu.add([ tasks.args, tasks.load, tasks.normalize, tasks.preload, { name: 'pre_meta', exec: tasks.meta }, { name: 'pre_legacy_extend', exec: tasks.legacy_extend }, tasks.delegate, tasks.call_define, tasks.options, tasks.define, { name: 'post_meta', exec: tasks.meta }, { name: 'post_legacy_extend', exec: tasks.legacy_extend }, tasks.call_prepare, tasks.complete, ]) return { use: make_use(ordu, callpoint), ordu, tasks, } } interface UseCtx { seq: { index: number } args: string[] seneca: any, callpoint: any } // TODO: not satisfactory interface UseData { seq: number args: string[] plugin: any meta: any delegate: any plugin_done: any exports: any prepare: any } function make_use(ordu: any, callpoint: any) { let seq = { index: 0 } return function use() { let self = this let args = [...arguments] if (0 === args.length) { throw self.error('use_no_args') } let ctx: UseCtx = { seq: seq, args: args, seneca: this, callpoint: callpoint(true) } let data: UseData = { seq: -1, args: [], plugin: null, meta: null, delegate: null, plugin_done: null, exports: {}, prepare: {}, } async function run() { await ordu.exec(ctx, data, { done: function(res: any) { if (res.err) { var err = res.err.seneca ? res.err : self.private$.error(res.err, res.err.code) err.plugin = err.plugin || (data.plugin ? (data.plugin.fullname || data.plugin.name) : args.join(' ')) err.plugin_callpoint = err.plugin_callpoint || ctx.callpoint self.die(err) } } }) } // NOTE: don't wait for result! run() return self } } function make_tasks(): any { return { // TODO: args validation? args: (spec: TaskSpec) => { let args: any[] = [...spec.ctx.args] // DEPRECATED: Remove when Seneca >= 4.x // Allow chaining with seneca.use('options', {...}) // see https://github.com/rjrodger/seneca/issues/80 if ('options' === args[0]) { spec.ctx.seneca.options(args[1]) return { op: 'stop', why: 'legacy-options' } } // Plugin definition function is under property `define`. // `init` is deprecated from 4.x // TODO: use-plugin expects `init` - update use-plugin to make this customizable if (null != args[0] && 'object' === typeof args[0]) { args[0].init = args[0].define || args[0].init } return { op: 'merge', out: { plugin: { args } } } }, load: (spec: TaskSpec) => { let args: string[] = spec.data.plugin.args let seneca: any = spec.ctx.seneca let private$: any = seneca.private$ // TODO: use-plugin needs better error message for malformed plugin desc let desc = private$.use.build_plugin_desc(...args) desc.callpoint = spec.ctx.callpoint if (private$.ignore_plugins[desc.full]) { seneca.log.info({ kind: 'plugin', case: 'ignore', plugin_full: desc.full, plugin_name: desc.name, plugin_tag: desc.tag, }) return { op: 'stop', why: 'ignore' } } else { let plugin: any = private$.use.use_plugin_desc(desc) return { op: 'merge', out: { plugin } } } }, normalize: (spec: TaskSpec) => { let plugin: any = spec.data.plugin let modify: any = {} // NOTE: `define` is the property for the plugin definition action. // The property `init` will be deprecated in 4.x modify.define = plugin.define || plugin.init modify.fullname = Common.make_plugin_key(plugin) modify.loading = true return { op: 'merge', out: { plugin: modify } } }, preload: (spec: TaskSpec) => { let seneca: any = spec.ctx.seneca let plugin: any = spec.data.plugin let so: any = seneca.options() // Don't reload plugins if load_once true. if (so.system.plugin.load_once) { if (seneca.has_plugin(plugin)) { return { op: 'stop', why: 'already-loaded', out: { plugin: { loading: false } } } } } let meta: any = {} if ('function' === typeof plugin.define.preload) { // TODO: need to capture errors meta = plugin.define.preload.call(seneca, plugin) || {} } let name = meta.name || plugin.name let fullname = Common.make_plugin_key(name, plugin.tag) return { op: 'seneca_plugin', out: { merge: { meta, plugin: { name, fullname } }, plugin } } }, // Handle plugin meta data returned by plugin define function meta: (spec: TaskSpec) => { let seneca: any = spec.ctx.seneca let plugin: any = spec.data.plugin let meta: any = spec.data.meta let exports: any = {} exports[plugin.name] = meta.export || plugin exports[plugin.fullname] = meta.export || plugin let exportmap: any = meta.exportmap || meta.exports || {} Object.keys(exportmap).forEach(k => { let v: any = exportmap[k] if (void 0 !== v) { let exportfullname = plugin.fullname + '/' + k exports[exportfullname] = v // Also provide exports on untagged plugin name. This is the // standard name that other plugins use let exportname = plugin.name + '/' + k exports[exportname] = v } }) if (meta.order) { if (meta.order.plugin) { let tasks: any[] = Array.isArray(meta.order.plugin) ? meta.order.plugin : [meta.order.plugin] seneca.order.plugin.add(tasks) delete meta.order.plugin } } return { op: 'seneca_export', out: { exports } } }, // NOTE: mutates spec.ctx.seneca legacy_extend: (spec: TaskSpec) => { let seneca: any = spec.ctx.seneca // let plugin: any = spec.data.plugin let meta: any = spec.data.meta if (meta.extend && 'object' === typeof meta.extend) { if ('function' === typeof meta.extend.action_modifier) { seneca.private$.action_modifiers.push(meta.extend.action_modifier) } // FIX: needs to use logging.load_logger if ('function' === typeof meta.extend.logger) { if ( !meta.extend.logger.replace && 'function' === typeof seneca.private$.logger.add ) { seneca.private$.logger.add(meta.extend.logger) } else { seneca.private$.logger = meta.extend.logger } } } //seneca.register(plugin, meta) }, delegate: (spec: TaskSpec) => { let seneca: any = spec.ctx.seneca let plugin: any = spec.data.plugin // Adjust Seneca API to be plugin specific. let delegate = seneca.delegate({ plugin$: { name: plugin.name, tag: plugin.tag, }, fatal$: true, }) delegate.private$ = Object.create(seneca.private$) delegate.private$.ge = delegate.private$.ge.gate() delegate.die = Common.makedie(delegate, { type: 'plugin', plugin: plugin.name, }) let actdeflist: any = [] delegate.add = function() { let argsarr = [...arguments] let actdef = argsarr[argsarr.length - 1] || {} if ('function' === typeof actdef) { actdef = {} argsarr.push(actdef) } actdef.plugin_name = plugin.name || '-' actdef.plugin_tag = plugin.tag || '-' actdef.plugin_fullname = plugin.fullname // TODO: is this necessary? actdef.log = delegate.log actdeflist.push(actdef) seneca.add.apply(delegate, argsarr) // FIX: should be this return delegate } delegate.__update_plugin__ = function(plugin: any) { delegate.context.name = plugin.name || '-' delegate.context.tag = plugin.tag || '-' delegate.context.full = plugin.fullname || '-' actdeflist.forEach(function(actdef: any) { actdef.plugin_name = plugin.name || actdef.plugin_name || '-' actdef.plugin_tag = plugin.tag || actdef.plugin_tag || '-' actdef.plugin_fullname = plugin.fullname || actdef.plugin_fullname || '-' }) } delegate.init = function(init: any) { // TODO: validate init_action is function let pat: any = { role: 'seneca', plugin: 'init', init: plugin.name, } if (null != plugin.tag && '-' != plugin.tag) { pat.tag = plugin.tag } delegate.add(pat, function(_: any, reply: any): any { init.call(this, reply) }) } delegate.context.plugin = plugin delegate.context.plugin.mark = Math.random() return { op: 'merge', out: { delegate } } }, call_define: (spec: TaskSpec) => { let plugin: any = spec.data.plugin let delegate: any = spec.data.delegate // FIX: mutating context!!! let seq: number = spec.ctx.seq.index++ let plugin_define_pattern: any = { role: 'seneca', plugin: 'define', name: plugin.name, seq: seq, } if (plugin.tag !== null) { plugin_define_pattern.tag = plugin.tag } return new Promise(resolve => { // seneca delegate.add(plugin_define_pattern, (_: any, reply: any) => { resolve({ op: 'merge', out: { seq, plugin_done: reply } }) }) delegate.act({ role: 'seneca', plugin: 'define', name: plugin.name, tag: plugin.tag, seq: seq, default$: {}, fatal$: true, local$: true, }) }) }, options: (spec: TaskSpec) => { let plugin: any = spec.data.plugin let delegate: any = spec.data.delegate let so = delegate.options() let fullname = plugin.fullname let defaults = plugin.defaults || {} let fullname_options = Object.assign( {}, // DEPRECATED: remove in 4 so[fullname], so.plugin[fullname], // DEPRECATED: remove in 4 so[fullname + '$' + plugin.tag], so.plugin[fullname + '$' + plugin.tag] ) let shortname = fullname !== plugin.name ? plugin.name : null if (!shortname && fullname.indexOf('seneca-') === 0) { shortname = fullname.substring('seneca-'.length) } let shortname_options = Object.assign( {}, // DEPRECATED: remove in 4 so[shortname], so.plugin[shortname], // DEPRECATED: remove in 4 so[shortname + '$' + plugin.tag], so.plugin[shortname + '$' + plugin.tag] ) let base: any = {} // NOTE: plugin error codes are in their own namespaces // TODO: test this!!! let errors = plugin.errors || (plugin.define && plugin.define.errors) if (errors) { base.errors = errors } let outopts = Object.assign( base, shortname_options, fullname_options, plugin.options || {} ) let resolved_options: any = {} let Joi = delegate.util.Joi let defaults_values = 'function' === typeof (defaults) ? defaults({ Joi }) : defaults let joi_schema: any = intern.prepare_spec( Joi, defaults_values, { allow_unknown: true }, {} ) let joi_out = joi_schema.validate(outopts) let err: Error | undefined = void 0 if (joi_out.error) { err = delegate.error('invalid_plugin_option', { name: fullname, err_msg: joi_out.error.message, options: outopts, }) } else { resolved_options = joi_out.value } return { op: 'seneca_options', err: err, out: { plugin: { options: resolved_options, options_schema: joi_schema } } } }, // TODO: move data modification to returned operation define: (spec: TaskSpec) => { let seneca: any = spec.ctx.seneca let plugin: any = spec.data.plugin let delegate: any = spec.data.delegate let plugin_options: any = spec.data.plugin.options delegate.log.debug({ kind: 'plugin', case: 'DEFINE', name: plugin.name, tag: plugin.tag, options: plugin_options, callpoint: spec.ctx.callpoint, }) let meta = intern.define_plugin( delegate, plugin, seneca.util.clean(plugin_options) ) plugin.meta = meta // legacy api for service function if ('function' === typeof meta) { meta = { service: meta } } // Plugin may have changed its own name dynamically plugin.name = meta.name || plugin.name plugin.tag = meta.tag || plugin.tag || (plugin.options && plugin.options.tag$) plugin.fullname = Common.make_plugin_key(plugin) plugin.service = meta.service || plugin.service delegate.__update_plugin__(plugin) seneca.private$.plugins[plugin.fullname] = plugin seneca.private$.plugin_order.byname.push(plugin.name) seneca.private$.plugin_order.byname = Uniq( seneca.private$.plugin_order.byname ) seneca.private$.plugin_order.byref.push(plugin.fullname) // 3.x Backwards compatibility - REMOVE in 4.x if ('amqp-transport' === plugin.name) { seneca.options({ legacy: { meta: true } }) } if ('function' === typeof plugin_options.defined$) { plugin_options.defined$(plugin) } // TODO: test this, with preload, explicitly return { op: 'merge', out: { meta, } } }, call_prepare: (spec: TaskSpec) => { let plugin: any = spec.data.plugin let plugin_options: any = spec.data.plugin.options let delegate: any = spec.data.delegate // If init$ option false, do not execute init action. if (false === plugin_options.init$) { return } let exports = (spec.data as any).exports delegate.log.debug({ kind: 'plugin', case: 'INIT', name: plugin.name, tag: plugin.tag, exports: exports, }) return new Promise(resolve => { delegate.act( { role: 'seneca', plugin: 'init', seq: spec.data.seq, init: plugin.name, tag: plugin.tag, default$: {}, fatal$: true, local$: true, }, function(err: Error, res: any) { resolve({ op: 'merge', out: { prepare: { err, res } } }) } ) }) }, complete: (spec: TaskSpec) => { let prepare: any = spec.data.prepare let plugin: any = spec.data.plugin let plugin_done: any = spec.data.plugin_done let plugin_options: any = spec.data.plugin.options let delegate: any = spec.data.delegate let so = delegate.options() if (prepare) { if (prepare.err) { let plugin_out: any = {} plugin_out.err_code = 'plugin_init' plugin_out.plugin_error = prepare.err.message if (prepare.err.code === 'action-timeout') { plugin_out.err_code = 'plugin_init_timeout' plugin_out.timeout = so.timeout } return { op: 'seneca_complete', out: { plugin: plugin_out } } } let fullname = plugin.name + (plugin.tag ? '$' + plugin.tag : '') if (so.debug.print && so.debug.print.options) { Print.plugin_options(delegate, fullname, plugin_options) } delegate.log.info({ kind: 'plugin', case: 'READY', name: plugin.name, tag: plugin.tag, }) if ('function' === typeof plugin_options.inited$) { plugin_options.inited$(plugin) } } plugin_done() return { op: 'seneca_complete', out: { plugin: { loading: false } } } } } } function make_intern() { return { // TODO: explicit tests for these operators op: { seneca_plugin: (tr: any, ctx: any, data: any): any => { Nua(data, tr.out.merge, { preserve: true }) ctx.seneca.private$.plugins[data.plugin.fullname] = tr.out.plugin return { stop: false } }, seneca_export: (tr: any, ctx: any, data: any): any => { // NOTE/plugin/774a: when loading multiple tagged plugins, // last plugin wins the plugin name on the exports. This is // consistent with general Seneca principal that plugin load // order is significant, as later plugins override earlier // action patterns. Thus later plugins override exports too. Object.assign(data.exports, tr.out.exports) Object.assign(ctx.seneca.private$.exports, tr.out.exports) return { stop: false } }, seneca_options: (tr: any, ctx: any, data: any): any => { Nua(data.plugin, tr.out.plugin, { preserve: true }) let plugin_fullname: string = data.plugin.fullname let plugin_options = data.plugin.options let plugin_options_update: any = { plugin: {} } plugin_options_update.plugin[plugin_fullname] = plugin_options ctx.seneca.options(plugin_options_update) return { stop: false } }, seneca_complete: (tr: any, _ctx: any, data: any): any => { Nua(data.plugin, tr.out.plugin, { preserve: true }) if (data.prepare.err) { data.delegate.die( data.delegate.error(data.prepare.err, data.plugin.err_code, data.plugin)) } return { stop: true } }, }, define_plugin: function(delegate: any, plugin: any, options: any): any { // legacy plugins if (plugin.define.length > 1) { let fnstr = plugin.define.toString() plugin.init_func_sig = (fnstr.match(/^(.*)\r*\n/) || [])[1] let ex = delegate.error('unsupported_legacy_plugin', plugin) throw ex } if (options.errors) { plugin.eraro = Eraro({ package: 'seneca', msgmap: options.errors, override: true, }) } let meta try { meta = plugin.define.call(delegate, options) || {} } catch (e) { Common.wrap_error(e, 'plugin_define_failed', { fullname: plugin.fullname, message: ( e.message + (' (' + e.stack.match(/\n.*?\n/)).replace(/\n.*\//g, '') ).replace(/\n/g, ''), options: options, repo: plugin.repo ? ' ' + plugin.repo + '/issues' : '', }) } meta = 'string' === typeof meta ? { name: meta } : meta meta.options = meta.options || options let updated_options: any = {} updated_options[plugin.fullname] = meta.options delegate.options(updated_options) return meta }, // copied from https://github.com/rjrodger/optioner // TODO: remove unnecessary vars+code prepare_spec: function(Joi: any, spec: any, opts: any, ctxt: any) { if (Joi.isSchema(spec, { legacy: true })) { return spec } let joiobj = Joi.object() if (opts.allow_unknown) { joiobj = joiobj.unknown() } let joi = intern.walk( Joi, joiobj, spec, '', opts, ctxt, function(valspec: any) { if (valspec && Joi.isSchema(valspec, { legacy: true })) { return valspec } else { let typecheck = typeof valspec //typecheck = 'function' === typecheck ? 'func' : typecheck if (opts.must_match_literals) { return Joi.any() .required() .valid(valspec) } else { if (void 0 === valspec) { return Joi.any().optional() } else if (null == valspec) { return Joi.any().default(null) } else if ('number' === typecheck && Number.isInteger(valspec)) { return Joi.number() .integer() .default(valspec) } else if ('string' === typecheck) { return Joi.string() .empty('') .default(() => valspec) } else { return Joi[typecheck]().default(() => valspec) } } } }) return joi }, // copied from https://github.com/rjrodger/optioner // TODO: remove unnecessary vars+code walk: function( Joi: any, start_joiobj: any, obj: any, path: any, opts: any, ctxt: any, mod: any) { let joiobj = start_joiobj // NOTE: use explicit Joi construction for checking within arrays if (Array.isArray(obj)) { return Joi.array().default(obj) } else { for (let p in obj) { let v = obj[p] let t = typeof v let kv: any = {} if (null != v && !Joi.isSchema(v, { legacy: true }) && 'object' === t) { let np = '' === path ? p : path + '.' + p let childjoiobj = Joi.object().default() if (opts.allow_unknown) { childjoiobj = childjoiobj.unknown() } kv[p] = intern.walk(Joi, childjoiobj, v, np, opts, ctxt, mod) } else { kv[p] = mod(v) } joiobj = joiobj.keys(kv) } return joiobj } } } }
the_stack
import { Injectable, Injector } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; import { ArtemisOrionConnector, ExerciseView, OrionState } from 'app/shared/orion/orion'; import { Router } from '@angular/router'; import { REPOSITORY } from 'app/exercises/programming/manage/code-editor/code-editor-instructor-base-container.component'; import { stringifyCircular } from 'app/shared/util/utils'; import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; import { Annotation } from 'app/exercises/programming/shared/code-editor/ace/code-editor-ace.component'; import { Feedback } from 'app/entities/feedback.model'; import { OrionTutorAssessmentComponent } from 'app/orion/assessment/orion-tutor-assessment.component'; import { AlertService } from 'app/core/util/alert.service'; /** * Return the global native browser window object with any type to prevent type errors */ function theWindow(): any { return window; } /** * This is the main interface between an IDE (e.g. IntelliJ) and this webapp. If a student has the Orion plugin * installed (https://github.com/ls1intum/Orion), this service will be used for communication between the * IDE Artemis itself. * * The communication itself is bidirectional, meaning that the IDE can call Typescript code * using the by the JavaUpcallBridge interface defined methods. On the other side, the Angular app can execute * Kotlin/Java code inside the IDE by calling the JavaDowncallBridge interface. * * In order to be always available, it is essential that this service gets instantiated right after loading the app * in the browser. This service has to always be available in the native window object, so that if an IDE is connected, * it can find the object during the integrated IDE browser instantiation. */ @Injectable({ providedIn: 'root', }) export class OrionConnectorService implements ArtemisOrionConnector { private orionState: OrionState; private orionStateSubject: BehaviorSubject<OrionState>; activeAssessmentComponent: OrionTutorAssessmentComponent | undefined = undefined; constructor(private injector: Injector, private alertService: AlertService) {} static initConnector(connector: OrionConnectorService) { theWindow().artemisClientConnector = connector; connector.orionState = { opened: -1, view: ExerciseView.STUDENT, cloning: false, building: false }; connector.orionStateSubject = new BehaviorSubject<OrionState>(connector.orionState); } /** * Yes, this is not best practice. But since this bridge service is an APP_INITIALIZER and has to be set on * the window object right in the beginning (so that the IDE can interact with Artemis as soon as the page has been * loaded), it should be fine to actually load the router only when it is needed later in the process. * Otherwise we would have a cyclic dependency problem on app startup */ get router(): Router { return this.injector.get(Router); } /** * Login to the Git client within the IDE with the same credentials as used for Artemis * * @param username The username of the current user * @param password The password of the current user. This is stored safely in the IDE's password safe */ login(username: string, password: string) { theWindow().orionSharedUtilConnector.login(username, password); } /** * "Imports" a project/exercise by cloning th repository on the local machine of the user and opening the new project. * * @param repository The full URL of the repository of a programming exercise * @param exercise The exercise for which the repository should get cloned. */ importParticipation(repository: string, exercise: ProgrammingExercise) { theWindow().orionExerciseConnector.importParticipation(repository, stringifyCircular(exercise)); } /** * Submits all changes on the local machine of the user by staging and committing every file. Afterwards, all commits * get pushed to the remote master branch */ submit() { theWindow().orionVCSConnector.submit(); } /** * Get the state object of the IDE. The IDE sets different internal states in this object, e.g. the ID of the currently * opened exercise * * @return An observable containing the internal state of the IDE */ state(): Observable<OrionState> { return this.orionStateSubject; } /** * Logs a message to the debug console of the opened IDE * * @param message The message to log in the development environment */ log(message: string) { theWindow().orionSharedUtilConnector.log(message); } /** * Gets called by the IDE. Informs the Angular app about a newly opened exercise. * * @param opened The ID of the exercise that was opened by the user. * @param viewString ExerciseView which is currently open in in the IDE as string */ onExerciseOpened(opened: number, viewString: string): void { const view = ExerciseView[viewString]; this.setIDEStateParameter({ view }); this.setIDEStateParameter({ opened }); } /** * Notify the IDE that a new build has started */ onBuildStarted(problemStatement: string) { theWindow().orionBuildConnector.onBuildStarted(problemStatement); } /** * Notify the IDE that a build finished and all results have been sent */ onBuildFinished() { theWindow().orionBuildConnector.onBuildFinished(); } /** * Notify the IDE that a build failed. Alternative to onBuildFinished * Transforms the annotations to the format used by orion: * { errors: { [fileName: string]: Annotation[] }; timestamp: number } * * @param buildErrors All compile errors for the current build */ onBuildFailed(buildErrors: Array<Annotation>) { theWindow().orionBuildConnector.onBuildFailed( JSON.stringify({ errors: buildErrors.reduce( // Group annotations by filename (buildLogErrors, { fileName, timestamp, ...rest }) => ({ ...buildLogErrors, [fileName]: [...(buildLogErrors[fileName] || []), { ...rest, ts: timestamp }], }), {}, ), timestamp: buildErrors.length > 0 ? buildErrors[0].timestamp : Date.now(), }), ); } /** * Notifies the IDE about a completed test (both positive or negative). In the case of an error, * you can also send a message containing some information about why the test failed. * * @param success True if the test was successful, false otherwise * @param message A detail message explaining the test result * @param testName The name of finished test */ onTestResult(success: boolean, testName: string, message: string) { theWindow().orionBuildConnector.onTestResult(success, testName, message); } /** * Notifies Artemis if the IDE is currently building (and testing) the checked out exercise * * @param building True, a building process is currently open, false otherwise */ isBuilding(building: boolean): void { this.setIDEStateParameter({ building }); } /** * Notifies Artemis if the IDE is in the process of importing (i.e. cloning) an exercise) * * @param cloning True, if there is a open clone process, false otherwise */ isCloning(cloning: boolean): void { this.setIDEStateParameter({ cloning }); } private setIDEStateParameter(patch: Partial<OrionState>) { Object.assign(this.orionState, patch); this.orionStateSubject.next(this.orionState); } /** * Gets triggered if a build/test run was started from inside the IDE. This means that we have to navigate * to the related exercise page in order to listen for any new results * * @param courseId * @param exerciseId */ startedBuildInOrion(courseId: number, exerciseId: number) { this.router.navigateByUrl(`/courses/${courseId}/exercises/${exerciseId}?withIdeSubmit=true`); } /** * Updates the assessment of the currently open submission * @param submissionId Id of the open submission, for validation * @param feedback all inline feedback, as JSON */ updateAssessment(submissionId: number, feedback: string) { if (this.activeAssessmentComponent) { const feedbackAsArray = JSON.parse(feedback) as Feedback[]; this.activeAssessmentComponent!.updateFeedback(submissionId, feedbackAsArray); } else { this.alertService.error('artemisApp.orion.assessment.updateFailed'); } } /** * Edit the given exercise in the IDE as an instructor. This will trigger the import of the exercise * (if it is not already imported) and opens the created project afterwards. * * @param exercise The exercise to be imported */ editExercise(exercise: ProgrammingExercise): void { this.isCloning(true); theWindow().orionExerciseConnector.editExercise(stringifyCircular(exercise)); } /** * Selects an instructor repository in the IDE. The selected repository will be used for all future actions * that reference an instructor repo s.a. submitting the code. * * @param repository The repository to be selected for all future interactions */ selectRepository(repository: REPOSITORY): void { theWindow().orionVCSConnector.selectRepository(repository); } /** * Orders the plugin to run the maven test command locally */ buildAndTestLocally(): void { theWindow().orionBuildConnector.buildAndTestLocally(); } /** * Assess the exercise as a tutor. Triggers downloading/opening the exercise as tutor * * @param exercise The exercise to be imported */ assessExercise(exercise: ProgrammingExercise): void { this.isCloning(true); theWindow().orionExerciseConnector.assessExercise(stringifyCircular(exercise)); } /** * Downloads a submission into the opened tutor project * * @param submissionId id of the submission, used to navigate to the corresponding URL * @param correctionRound correction round, also needed to navigate to the correct URL * @param base64data the student's submission as base64 */ downloadSubmission(submissionId: number, correctionRound: number, base64data: string) { theWindow().orionExerciseConnector.downloadSubmission(String(submissionId), String(correctionRound), base64data); } /** * Initializes the feedback comments. * * @param submissionId if of the submission, for validation purposes * @param feedback current feedback */ initializeAssessment(submissionId: number, feedback: Array<Feedback>) { theWindow().orionExerciseConnector.initializeAssessment(String(submissionId), stringifyCircular(feedback)); } }
the_stack
import S3 from 'aws-sdk/clients/s3'; import Rekognition from 'aws-sdk/clients/rekognition'; import sharp, { FormatEnum, OverlayOptions, ResizeOptions } from 'sharp'; import { BoundingBox, BoxSize, ImageEdits, ImageFitTypes, ImageFormatTypes, ImageHandlerError, ImageRequestInfo, RekognitionCompatibleImage, StatusCodes } from './lib'; export class ImageHandler { private readonly LAMBDA_PAYLOAD_LIMIT = 6 * 1024 * 1024; constructor(private readonly s3Client: S3, private readonly rekognitionClient: Rekognition) {} /** * Main method for processing image requests and outputting modified images. * @param imageRequestInfo An image request. * @returns Processed and modified image encoded as base64 string. */ async process(imageRequestInfo: ImageRequestInfo): Promise<string> { const { originalImage, edits } = imageRequestInfo; let base64EncodedImage = ''; if (edits && Object.keys(edits).length) { let image: sharp.Sharp = null; if (edits.rotate !== undefined && edits.rotate === null) { image = sharp(originalImage, { failOnError: false }); } else { const metadata = await sharp(originalImage, { failOnError: false }).metadata(); image = metadata.orientation ? sharp(originalImage, { failOnError: false }).withMetadata({ orientation: metadata.orientation }) : sharp(originalImage, { failOnError: false }).withMetadata(); } const modifiedImage = await this.applyEdits(image, edits); if (imageRequestInfo.outputFormat !== undefined) { if (imageRequestInfo.outputFormat === ImageFormatTypes.WEBP && typeof imageRequestInfo.reductionEffort !== 'undefined') { modifiedImage.webp({ reductionEffort: imageRequestInfo.reductionEffort }); } else { modifiedImage.toFormat(ImageHandler.convertImageFormatType(imageRequestInfo.outputFormat)); } } const imageBuffer = await modifiedImage.toBuffer(); base64EncodedImage = imageBuffer.toString('base64'); } else { // change output format if specified if (imageRequestInfo.outputFormat !== undefined) { const modifiedImage = sharp(originalImage, { failOnError: false }); modifiedImage.toFormat(ImageHandler.convertImageFormatType(imageRequestInfo.outputFormat)); const imageBuffer = await modifiedImage.toBuffer(); base64EncodedImage = imageBuffer.toString('base64'); } else { base64EncodedImage = originalImage.toString('base64'); } } // binary data need to be base64 encoded to pass to the API Gateway proxy https://docs.aws.amazon.com/apigateway/latest/developerguide/lambda-proxy-binary-media.html. // checks whether base64 encoded image fits in 6M limit, see https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html. if (base64EncodedImage.length > this.LAMBDA_PAYLOAD_LIMIT) { throw new ImageHandlerError(StatusCodes.REQUEST_TOO_LONG, 'TooLargeImageException', 'The converted image is too large to return.'); } return base64EncodedImage; } /** * Applies image modifications to the original image based on edits. * @param originalImage The original sharp image. * @param edits The edits to be made to the original image. * @returns A modifications to the original image. */ public async applyEdits(originalImage: sharp.Sharp, edits: ImageEdits): Promise<sharp.Sharp> { if (edits.resize === undefined) { edits.resize = {}; edits.resize.fit = ImageFitTypes.INSIDE; } else { if (edits.resize.width) edits.resize.width = Math.round(Number(edits.resize.width)); if (edits.resize.height) edits.resize.height = Math.round(Number(edits.resize.height)); } // Apply the image edits for (const edit in edits) { switch (edit) { case 'overlayWith': { let imageMetadata: sharp.Metadata = await originalImage.metadata(); if (edits.resize) { const imageBuffer = await originalImage.toBuffer(); const resizeOptions: ResizeOptions = edits.resize; imageMetadata = await sharp(imageBuffer).resize(resizeOptions).metadata(); } const { bucket, key, wRatio, hRatio, alpha, options } = edits.overlayWith; const overlay = await this.getOverlayImage(bucket, key, wRatio, hRatio, alpha, imageMetadata); const overlayMetadata = await sharp(overlay).metadata(); const overlayOption: OverlayOptions = { ...options, input: overlay }; if (options) { const { left: leftOption, top: topOption } = options; const getSize = (editSize: string | undefined, imageSize: number, overlaySize: number): number => { let resultSize = NaN; if (editSize !== undefined) { if (editSize.endsWith('p')) { resultSize = parseInt(editSize.replace('p', '')); resultSize = Math.floor(resultSize < 0 ? imageSize + (imageSize * resultSize) / 100 - overlaySize : (imageSize * resultSize) / 100); } else { resultSize = parseInt(editSize); if (resultSize < 0) { resultSize = imageSize + resultSize - overlaySize; } } } return resultSize; }; const left = getSize(leftOption, imageMetadata.width, overlayMetadata.width); if (!isNaN(left)) overlayOption.left = left; const top = getSize(topOption, imageMetadata.height, overlayMetadata.height); if (!isNaN(top)) overlayOption.top = top; } originalImage.composite([overlayOption]); break; } case 'smartCrop': { // smart crop can be boolean or object if (edits.smartCrop === true || typeof edits.smartCrop === 'object') { const { faceIndex, padding } = typeof edits.smartCrop === 'object' ? edits.smartCrop : { faceIndex: undefined, padding: undefined }; const { imageBuffer, format } = await this.getRekognitionCompatibleImage(originalImage); const boundingBox = await this.getBoundingBox(imageBuffer.data, faceIndex ?? 0); const cropArea = this.getCropArea(boundingBox, padding ?? 0, imageBuffer.info); try { originalImage.extract(cropArea); // convert image back to previous format if (format !== imageBuffer.info.format) { originalImage.toFormat(format); } } catch (error) { throw new ImageHandlerError( StatusCodes.BAD_REQUEST, 'SmartCrop::PaddingOutOfBounds', 'The padding value you provided exceeds the boundaries of the original image. Please try choosing a smaller value or applying padding via Sharp for greater specificity.' ); } } break; } case 'roundCrop': { // round crop can be boolean or object if (edits.roundCrop === true || typeof edits.roundCrop === 'object') { const { top, left, rx, ry } = typeof edits.roundCrop === 'object' ? edits.roundCrop : { top: undefined, left: undefined, rx: undefined, ry: undefined }; const imageBuffer = await originalImage.toBuffer({ resolveWithObject: true }); const width = imageBuffer.info.width; const height = imageBuffer.info.height; // check for parameters, if not provided, set to defaults const radiusX = rx && rx >= 0 ? rx : Math.min(width, height) / 2; const radiusY = ry && ry >= 0 ? ry : Math.min(width, height) / 2; const topOffset = top && top >= 0 ? top : height / 2; const leftOffset = left && left >= 0 ? left : width / 2; const ellipse = Buffer.from(`<svg viewBox="0 0 ${width} ${height}"> <ellipse cx="${leftOffset}" cy="${topOffset}" rx="${radiusX}" ry="${radiusY}" /></svg>`); const overlayOptions: OverlayOptions[] = [{ input: ellipse, blend: 'dest-in' }]; const data = await originalImage.composite(overlayOptions).toBuffer(); originalImage = sharp(data).withMetadata().trim(); } break; } case 'contentModeration': { // content moderation can be boolean or object if (edits.contentModeration === true || typeof edits.contentModeration === 'object') { const { minConfidence, blur, moderationLabels } = typeof edits.contentModeration === 'object' ? edits.contentModeration : { minConfidence: undefined, blur: undefined, moderationLabels: undefined }; const { imageBuffer, format } = await this.getRekognitionCompatibleImage(originalImage); const inappropriateContent = await this.detectInappropriateContent(imageBuffer.data, minConfidence); const blurValue = blur !== undefined ? Math.ceil(blur) : 50; if (blurValue >= 0.3 && blurValue <= 1000) { if (moderationLabels) { for (const moderationLabel of inappropriateContent.ModerationLabels) { if (moderationLabels.includes(moderationLabel.Name)) { originalImage.blur(blur); break; } } } else if (inappropriateContent.ModerationLabels.length) { originalImage.blur(blur); } } // convert image back to previous format if (format !== imageBuffer.info.format) { originalImage.toFormat(format); } } break; } case 'crop': { try { originalImage.extract(edits.crop); } catch (error) { throw new ImageHandlerError( StatusCodes.BAD_REQUEST, 'Crop::AreaOutOfBounds', 'The cropping area you provided exceeds the boundaries of the original image. Please try choosing a correct cropping value.' ); } break; } default: { if (edit in originalImage) { originalImage[edit](edits[edit]); } } } } // Return the modified image return originalImage; } /** * Gets an image to be used as an overlay to the primary image from an Amazon S3 bucket. * @param bucket The name of the bucket containing the overlay. * @param key The object keyname corresponding to the overlay. * @param wRatio The width rate of the overlay image. * @param hRatio The height rate of the overlay image. * @param alpha The transparency alpha to the overlay. * @param sourceImageMetadata The metadata of the source image. * @returns An image to bo ber used as an overlay. */ public async getOverlayImage(bucket: string, key: string, wRatio: string, hRatio: string, alpha: string, sourceImageMetadata: sharp.Metadata): Promise<Buffer> { const params = { Bucket: bucket, Key: key }; try { const { width, height } = sourceImageMetadata; const overlayImage: S3.GetObjectOutput = await this.s3Client.getObject(params).promise(); const resizeOptions: ResizeOptions = { fit: ImageFitTypes.INSIDE }; // Set width and height of the watermark image based on the ratio const zeroToHundred = /^(100|[1-9]?[0-9])$/; if (zeroToHundred.test(wRatio)) { resizeOptions.width = Math.floor((width * parseInt(wRatio)) / 100); } if (zeroToHundred.test(hRatio)) { resizeOptions.height = Math.floor((height * parseInt(hRatio)) / 100); } // If alpha is not within 0-100, the default alpha is 0 (fully opaque). const alphaValue = zeroToHundred.test(alpha) ? parseInt(alpha) : 0; const imageBuffer = Buffer.isBuffer(overlayImage.Body) ? overlayImage.Body : Buffer.from(overlayImage.Body as Uint8Array); return await sharp(imageBuffer) .resize(resizeOptions) .composite([ { input: Buffer.from([255, 255, 255, 255 * (1 - alphaValue / 100)]), raw: { width: 1, height: 1, channels: 4 }, tile: true, blend: 'dest-in' } ]) .toBuffer(); } catch (error) { throw new ImageHandlerError(error.statusCode ? error.statusCode : StatusCodes.INTERNAL_SERVER_ERROR, error.code, error.message); } } /** * Calculates the crop area for a smart-cropped image based on the bounding box data returned by Amazon Rekognition, as well as padding options and the image metadata. * @param boundingBox The bounding box of the detected face. * @param padding Set of options for smart cropping. * @param boxSize Sharp image metadata. * @returns Calculated crop area for a smart-cropped image. */ public getCropArea(boundingBox: BoundingBox, padding: number, boxSize: BoxSize): BoundingBox { // calculate needed options dimensions let left = Math.floor(boundingBox.left * boxSize.width - padding); let top = Math.floor(boundingBox.top * boxSize.height - padding); let extractWidth = Math.floor(boundingBox.width * boxSize.width + padding * 2); let extractHeight = Math.floor(boundingBox.height * boxSize.height + padding * 2); // check if dimensions fit within image dimensions and re-adjust if necessary left = left < 0 ? 0 : left; top = top < 0 ? 0 : top; const maxWidth = boxSize.width - left; const maxHeight = boxSize.height - top; extractWidth = extractWidth > maxWidth ? maxWidth : extractWidth; extractHeight = extractHeight > maxHeight ? maxHeight : extractHeight; // Calculate the smart crop area return { left: left, top: top, width: extractWidth, height: extractHeight }; } /** * Gets the bounding box of the specified face index within an image, if specified. * @param imageBuffer The original image. * @param faceIndex The zero-based face index value, moving from 0 and up as confidence decreases for detected faces within the image. * @returns The bounding box of the specified face index within an image. */ public async getBoundingBox(imageBuffer: Buffer, faceIndex: number): Promise<BoundingBox> { const params = { Image: { Bytes: imageBuffer } }; try { const response = await this.rekognitionClient.detectFaces(params).promise(); if (response.FaceDetails.length <= 0) { return { height: 1, left: 0, top: 0, width: 1 }; } const boundingBox: { Height?: number; Left?: number; Top?: number; Width?: number } = {}; // handle bounds > 1 and < 0 for (const bound in response.FaceDetails[faceIndex].BoundingBox) { if (response.FaceDetails[faceIndex].BoundingBox[bound] < 0) boundingBox[bound] = 0; else if (response.FaceDetails[faceIndex].BoundingBox[bound] > 1) boundingBox[bound] = 1; else boundingBox[bound] = response.FaceDetails[faceIndex].BoundingBox[bound]; } // handle bounds greater than the size of the image if (boundingBox.Left + boundingBox.Width > 1) { boundingBox.Width = 1 - boundingBox.Left; } if (boundingBox.Top + boundingBox.Height > 1) { boundingBox.Height = 1 - boundingBox.Top; } return { height: boundingBox.Height, left: boundingBox.Left, top: boundingBox.Top, width: boundingBox.Width }; } catch (error) { console.error(error); if (error.message === "Cannot read property 'BoundingBox' of undefined" || error.message === "Cannot read properties of undefined (reading 'BoundingBox')") { throw new ImageHandlerError( StatusCodes.BAD_REQUEST, 'SmartCrop::FaceIndexOutOfRange', 'You have provided a FaceIndex value that exceeds the length of the zero-based detectedFaces array. Please specify a value that is in-range.' ); } else { throw new ImageHandlerError(error.statusCode ? error.statusCode : StatusCodes.INTERNAL_SERVER_ERROR, error.code, error.message); } } } /** * Detects inappropriate content in an image. * @param imageBuffer The original image. * @param minConfidence The options to pass to the detectModerationLabels Rekognition function. * @returns Detected inappropriate content in an image. */ private async detectInappropriateContent(imageBuffer: Buffer, minConfidence: number | undefined): Promise<Rekognition.DetectModerationLabelsResponse> { try { const params = { Image: { Bytes: imageBuffer }, MinConfidence: minConfidence ?? 75 }; return await this.rekognitionClient.detectModerationLabels(params).promise(); } catch (error) { console.error(error); throw new ImageHandlerError(error.statusCode ? error.statusCode : StatusCodes.INTERNAL_SERVER_ERROR, error.code, error.message); } } /** * Converts serverless image handler image format type to 'sharp' format. * @param imageFormatType Result output file type. * @returns Converted 'sharp' format. */ private static convertImageFormatType(imageFormatType: ImageFormatTypes): keyof FormatEnum { switch (imageFormatType) { case ImageFormatTypes.JPG: return 'jpg'; case ImageFormatTypes.JPEG: return 'jpeg'; case ImageFormatTypes.PNG: return 'png'; case ImageFormatTypes.WEBP: return 'webp'; case ImageFormatTypes.TIFF: return 'tiff'; case ImageFormatTypes.HEIF: return 'heif'; case ImageFormatTypes.RAW: return 'raw'; default: throw new ImageHandlerError(StatusCodes.INTERNAL_SERVER_ERROR, 'UnsupportedOutputImageFormatException', `Format to ${imageFormatType} not supported`); } } /** * Converts the image to a rekognition compatible format if current format is not compatible. * @param image the image to be modified by rekognition. * @returns object containing image buffer data and original image format. */ private async getRekognitionCompatibleImage(image: sharp.Sharp): Promise<RekognitionCompatibleImage> { const metadata = await image.metadata(); const format = metadata.format; let imageBuffer: { data: Buffer; info: sharp.OutputInfo }; // convert image to png if not jpeg or png if (!['jpeg', 'png'].includes(format)) { imageBuffer = await image.png().toBuffer({ resolveWithObject: true }); } else { imageBuffer = await image.toBuffer({ resolveWithObject: true }); } return { imageBuffer: imageBuffer, format: format }; } }
the_stack
import { Point, Range, TextEditor } from "atom"; import escapeStringRegexp from "escape-string-regexp"; import stripIndent from "strip-indent"; import compact from "lodash/compact"; import { log, isMultilanguageGrammar, getEmbeddedScope, rowRangeForCodeFoldAtBufferRow, js_idx_to_char_idx, } from "./utils"; import type { HydrogenCellType } from "./hydrogen"; export function normalizeString(code: string | null | undefined) { if (code) { return code.replace(/\r\n|\r/g, "\n"); } return null; } export function getRow(editor: TextEditor, row: number) { return normalizeString(editor.lineTextForBufferRow(row)); } export function getTextInRange(editor: TextEditor, start: Point, end: Point) { const code = editor.getTextInBufferRange([start, end]); return normalizeString(code); } export function getRows(editor: TextEditor, startRow: number, endRow: number) { const code = editor.getTextInBufferRange({ start: { row: startRow, column: 0, }, end: { row: endRow, column: 9999999, }, }); return normalizeString(code); } export function getMetadataForRow( editor: TextEditor, anyPointInCell: Point ): HydrogenCellType { if (isMultilanguageGrammar(editor.getGrammar())) { return "codecell"; } let cellType: HydrogenCellType = "codecell"; const buffer = editor.getBuffer(); anyPointInCell = new Point( anyPointInCell.row, buffer.lineLengthForRow(anyPointInCell.row) ); const regexString = getRegexString(editor); if (regexString) { const regex = new RegExp(regexString); buffer.backwardsScanInRange( regex, new Range(new Point(0, 0), anyPointInCell), ({ match }) => { for (let i = 1; i < match.length; i++) { if (match[i]) { switch (match[i]) { case "md": case "markdown": cellType = "markdown"; break; case "codecell": default: cellType = "codecell"; break; } } } } ); } return cellType; } export function removeCommentsMarkdownCell( editor: TextEditor, text: string ): string { const commentStartString = getCommentStartString(editor); if (!commentStartString) { return text; } const lines = text.split("\n"); const editedLines = []; lines.forEach((line) => { if (line.startsWith(commentStartString)) { // Remove comment from start of line editedLines.push(line.slice(commentStartString.length)); } else { editedLines.push(line); } }); return stripIndent(editedLines.join("\n")); } export function getSelectedText(editor: TextEditor) { return normalizeString(editor.getSelectedText()); } export function isComment(editor: TextEditor, position: Point) { const scope = editor.scopeDescriptorForBufferPosition(position); const scopeString = scope.getScopeChain(); return scopeString.includes("comment.line"); } export function isBlank(editor: TextEditor, row: number) { return editor.getBuffer().isRowBlank(row); } export function escapeBlankRows( editor: TextEditor, startRow: number, endRow: number ) { while (endRow > startRow) { if (!isBlank(editor, endRow)) { break; } endRow -= 1; } return endRow; } export function getFoldRange(editor: TextEditor, row: number) { const range = rowRangeForCodeFoldAtBufferRow(editor, row); if (!range) { return; } if ( range[1] < editor.getLastBufferRow() && getRow(editor, range[1] + 1) === "end" ) { range[1] += 1; } log("getFoldRange:", range); return range; } export function getFoldContents(editor: TextEditor, row: number) { const range = getFoldRange(editor, row); if (!range) { return; } return { code: getRows(editor, range[0], range[1]), row: range[1], }; } export function getCodeToInspect(editor: TextEditor) { const selectedText = getSelectedText(editor); let code; let cursorPosition; if (selectedText) { code = selectedText; cursorPosition = code.length; } else { const cursor = editor.getLastCursor(); const row = cursor.getBufferRow(); code = getRow(editor, row); cursorPosition = cursor.getBufferColumn(); // TODO: use kernel.complete to find a selection const identifierEnd = code ? code.slice(cursorPosition).search(/\W/) : -1; if (identifierEnd !== -1) { cursorPosition += identifierEnd; } } cursorPosition = js_idx_to_char_idx(cursorPosition, code); return [code, cursorPosition]; } export function getCommentStartString( editor: TextEditor ): string | null | undefined { const { commentStartString, // $FlowFixMe: This is an unofficial API } = editor.tokenizedBuffer.commentStringsForPosition( editor.getCursorBufferPosition() ); if (!commentStartString) { log("CellManager: No comment string defined in root scope"); return null; } return commentStartString.trimRight(); } export function getRegexString(editor: TextEditor) { const commentStartString = getCommentStartString(editor); if (!commentStartString) { return null; } const escapedCommentStartString = escapeStringRegexp(commentStartString); const regexString = `${escapedCommentStartString} *%% *(md|markdown)?| *<(codecell|md|markdown)>| *(In\[[0-9 ]*\])`; return regexString; } export function getBreakpoints(editor: TextEditor) { const buffer = editor.getBuffer(); const breakpoints = []; const regexString = getRegexString(editor); if (regexString) { const regex = new RegExp(regexString, "g"); buffer.scan(regex, ({ range }) => { if (isComment(editor, range.start)) { breakpoints.push(range.start); } }); } breakpoints.push(buffer.getEndPosition()); log("CellManager: Breakpoints:", breakpoints); return breakpoints; } function getCell(editor: TextEditor, anyPointInCell?: Point) { if (!anyPointInCell) { anyPointInCell = editor.getCursorBufferPosition(); } const buffer = editor.getBuffer(); anyPointInCell = new Point( anyPointInCell.row, buffer.lineLengthForRow(anyPointInCell.row) ); let start = new Point(0, 0); let end = buffer.getEndPosition(); const regexString = getRegexString(editor); if (!regexString) { return new Range(start, end); } const regex = new RegExp(regexString); if (anyPointInCell.row >= 0) { buffer.backwardsScanInRange( regex, new Range(start, anyPointInCell), ({ range }) => { start = new Point(range.start.row + 1, 0); } ); } buffer.scanInRange(regex, new Range(anyPointInCell, end), ({ range }) => { end = range.start; }); log( "CellManager: Cell [start, end]:", [start, end], "anyPointInCell:", anyPointInCell ); return new Range(start, end); } function isEmbeddedCode( editor: TextEditor, referenceScope: string, row: number ) { const scopes = editor .scopeDescriptorForBufferPosition(new Point(row, 0)) .getScopesArray(); return scopes.includes(referenceScope); } function getCurrentFencedCodeBlock(editor: TextEditor) { const buffer = editor.getBuffer(); const { row: bufferEndRow } = buffer.getEndPosition(); const cursor = editor.getCursorBufferPosition(); let start = cursor.row; let end = cursor.row; const scope = getEmbeddedScope(editor, cursor); if (!scope) { return getCell(editor); } while (start > 0 && isEmbeddedCode(editor, scope, start - 1)) { start -= 1; } while (end < bufferEndRow && isEmbeddedCode(editor, scope, end + 1)) { end += 1; } return new Range([start, 0], [end + 1, 0]); } export function getCurrentCell(editor: TextEditor) { if (isMultilanguageGrammar(editor.getGrammar())) { return getCurrentFencedCodeBlock(editor); } return getCell(editor); } export function getCells(editor: TextEditor, breakpoints: Array<Point> = []) { if (breakpoints.length !== 0) { breakpoints.sort((a, b) => a.compare(b)); } else { breakpoints = getBreakpoints(editor); } return getCellsForBreakPoints(editor, breakpoints); } export function getCellsForBreakPoints( editor: TextEditor, breakpoints: Array<Point> ): Array<Range> { let start = new Point(0, 0); // Let start be earliest row with text editor.scan(/\S/, (match) => { start = new Point(match.range.start.row, 0); match.stop(); }); return compact( breakpoints.map((end) => { const cell = end.isEqual(start) ? null : new Range(start, end); start = new Point(end.row + 1, 0); return cell; }) ); } function centerScreenOnCursorPosition(editor: TextEditor) { const cursorPosition = editor.element.pixelPositionForScreenPosition( editor.getCursorScreenPosition() ).top; const editorHeight = editor.element.getHeight(); editor.element.setScrollTop(cursorPosition - editorHeight / 2); } export function moveDown(editor: TextEditor, row: number) { const lastRow = editor.getLastBufferRow(); if (row >= lastRow) { editor.moveToBottom(); editor.insertNewline(); return; } while (row < lastRow) { row += 1; if (!isBlank(editor, row)) { break; } } editor.setCursorBufferPosition({ row, column: 0, }); atom.config.get("Hydrogen.centerOnMoveDown") && centerScreenOnCursorPosition(editor); } export function findPrecedingBlock( editor: TextEditor, row: number, indentLevel: number ) { let previousRow = row - 1; while (previousRow >= 0) { const previousIndentLevel = editor.indentationForBufferRow(previousRow); const sameIndent = previousIndentLevel <= indentLevel; const blank = isBlank(editor, previousRow); const isEnd = getRow(editor, previousRow) === "end"; if (isBlank(editor, row)) { row = previousRow; } if (sameIndent && !blank && !isEnd) { const cell = getCell(editor, new Point(row, 0)); if (cell.start.row > row) { return { code: "", row, }; } return { code: getRows(editor, previousRow, row), row, }; } previousRow -= 1; } return null; } export function findCodeBlock(editor: TextEditor) { const selectedText = getSelectedText(editor); if (selectedText) { const selectedRange = editor.getSelectedBufferRange(); const cell = getCell(editor, selectedRange.end); const startPoint = cell.start.isGreaterThan(selectedRange.start) ? cell.start : selectedRange.start; let endRow = selectedRange.end.row; if (selectedRange.end.column === 0) { endRow -= 1; } endRow = escapeBlankRows(editor, startPoint.row, endRow); if (startPoint.isGreaterThanOrEqual(selectedRange.end)) { return { code: "", row: endRow, }; } return { code: getTextInRange(editor, startPoint, selectedRange.end), row: endRow, }; } const cursor = editor.getLastCursor(); const row = cursor.getBufferRow(); log("findCodeBlock:", row); const indentLevel = cursor.getIndentLevel(); let foldable = editor.isFoldableAtBufferRow(row); const foldRange = rowRangeForCodeFoldAtBufferRow(editor, row); if (!foldRange || foldRange[0] == null || foldRange[1] == null) { foldable = false; } if (foldable) { return getFoldContents(editor, row); } if (isBlank(editor, row) || getRow(editor, row) === "end") { return findPrecedingBlock(editor, row, indentLevel); } const cell = getCell(editor, new Point(row, 0)); if (cell.start.row > row) { return { code: "", row, }; } return { code: getRow(editor, row), row, }; } export function foldCurrentCell(editor: TextEditor) { const cellRange = getCurrentCell(editor); const newRange = adjustCellFoldRange(editor, cellRange); editor.setSelectedBufferRange(newRange); editor.getSelections()[0].fold(); } export function foldAllButCurrentCell(editor: TextEditor) { const initialSelections = editor.getSelectedBufferRanges(); // I take .slice(1) because there's always an empty cell range from [0,0] to // [0,0] const allCellRanges = getCells(editor).slice(1); const currentCellRange = getCurrentCell(editor); const newRanges = allCellRanges .filter((cellRange) => !cellRange.isEqual(currentCellRange)) .map((cellRange) => adjustCellFoldRange(editor, cellRange)); editor.setSelectedBufferRanges(newRanges); editor.getSelections().forEach((selection) => selection.fold()); // Restore selections editor.setSelectedBufferRanges(initialSelections); } function adjustCellFoldRange(editor: TextEditor, range: Range) { const startRow = range.start.row > 0 ? range.start.row - 1 : 0; const startWidth = editor.lineTextForBufferRow(startRow).length; const endRow = range.end.row == editor.getLastBufferRow() ? range.end.row : range.end.row - 1; const endWidth = editor.lineTextForBufferRow(endRow).length; return new Range( new Point(startRow, startWidth), new Point(endRow, endWidth) ); } export function getEscapeBlankRowsEndRow(editor: TextEditor, end: Point) { return end.row === editor.getLastBufferRow() ? end.row : end.row - 1; }
the_stack
import React, { useCallback, useContext, useEffect, useMemo } from 'react' import Spin from 'antd/lib/spin' import cn from 'classnames' import { matchPath } from 'react-router' import { Dispatch } from 'redux' import { ReactComponent as IconAlbum } from 'assets/img/iconAlbum.svg' import { ReactComponent as IconBigSearch } from 'assets/img/iconBigSearch.svg' import { ReactComponent as IconNote } from 'assets/img/iconNote.svg' import { ReactComponent as IconPlaylists } from 'assets/img/iconPlaylists.svg' import { ReactComponent as IconUser } from 'assets/img/iconUser.svg' import { Name } from 'common/models/Analytics' import { UserCollection } from 'common/models/Collection' import { UID } from 'common/models/Identifiers' import Status from 'common/models/Status' import { User } from 'common/models/User' import Card from 'components/card/mobile/Card' import MobilePageContainer from 'components/general/MobilePageContainer' import Header from 'components/general/header/mobile/Header' import { HeaderContext } from 'components/general/header/mobile/HeaderContextProvider' import CardLineup from 'containers/lineup/CardLineup' import Lineup from 'containers/lineup/Lineup' import NavContext, { LeftPreset, CenterPreset, RightPreset } from 'containers/nav/store/context' import { tracksActions } from 'containers/search-page/store/lineups/tracks/actions' import useTabs from 'hooks/useTabs/useTabs' import { LineupState } from 'models/common/Lineup' import { make, useRecord } from 'store/analytics/actions' import { getLocationPathname } from 'store/routing/selectors' import { useSelector } from 'utils/reducer' import { albumPage, playlistPage, profilePage, fullSearchResultsPage, SEARCH_PAGE } from 'utils/route' import styles from './SearchPageContent.module.css' const NATIVE_MOBILE = process.env.REACT_APP_NATIVE_MOBILE type SearchPageContentProps = { tracks: LineupState<{}> playlists: UserCollection[] albums: UserCollection[] artists: User[] match: any searchText: string dispatch: Dispatch playing: boolean buffering: boolean containerRef: HTMLElement | null currentQueueItem: { source: any track: any user: any uid: UID } search: { albumUids: UID[] artistUids: UID[] playlistUids: UID[] trackUids: UID[] searchText: string status: Status tracks: any } isTagSearch: boolean goToRoute: (route: string) => void } const TrackSearchPageMessages = { title1: "Sorry, we couldn't find anything matching", title1Tag: "Sorry, we couldn't find any tags matching", title2: 'Please check your spelling or try broadening your search.' } const Loading = () => { return ( <div className={styles.centeringContainer}> <Spin size='large' className={styles.spin} /> </div> ) } const NoResults = ({ isTagSearch, searchText }: { isTagSearch: boolean searchText: string }) => ( <div className={styles.centeringContainer}> <div className={styles.noResults}> <IconBigSearch /> <div> {isTagSearch ? TrackSearchPageMessages.title1Tag : TrackSearchPageMessages.title1} </div> <span>{`"${searchText}"`}</span> <div>{TrackSearchPageMessages.title2}</div> </div> </div> ) type SearchStatusWrapperProps = { status: Status children: JSX.Element } const SearchStatusWrapper = React.memo( ({ status, children }: SearchStatusWrapperProps) => { switch (status) { case Status.LOADING: case Status.ERROR: // TODO return <Loading /> case Status.SUCCESS: return children } } ) const TracksSearchPage = ({ search, searchText, tracks, dispatch, buffering, playing, currentQueueItem, containerRef, isTagSearch }: SearchPageContentProps) => { const numTracks = Object.keys(tracks.entries).length const loadingStatus = (() => { // We need to account for the odd case where search.status === success but // the tracks are still loading in (tracks.status === loading && tracks.entries === 0), // and in this case still show a loading screen. const searchAndTracksSuccess = search.status === Status.SUCCESS && tracks.status === Status.SUCCESS const searchSuccessTracksLoadingMore = search.status === Status.SUCCESS && tracks.status === Status.LOADING && numTracks > 0 if (searchAndTracksSuccess || searchSuccessTracksLoadingMore) { return Status.SUCCESS } else if (search.status === Status.ERROR) { return Status.ERROR } else { return Status.LOADING } })() return ( <SearchStatusWrapper status={loadingStatus}> {numTracks ? ( <div className={styles.lineupContainer}> <Lineup selfLoad lineup={tracks} playingSource={currentQueueItem.source} playingUid={currentQueueItem.uid} playingTrackId={ currentQueueItem.track && currentQueueItem.track.track_id } playing={playing} buffering={buffering} scrollParent={containerRef} loadMore={(offset: number, limit: number) => dispatch(tracksActions.fetchLineupMetadatas(offset, limit)) } playTrack={(uid: UID) => dispatch(tracksActions.play(uid))} pauseTrack={() => dispatch(tracksActions.pause())} actions={tracksActions} /> </div> ) : ( <NoResults searchText={searchText} isTagSearch={isTagSearch} /> )} </SearchStatusWrapper> ) } const ALBUM_CATEGORY_NAME = 'Artists' enum CardType { ALBUM = 'ALBUM', PLAYLIST = 'PLAYLIST', USER = 'USER' } type CardSearchPageProps = { cardType: CardType } & SearchPageContentProps const cardSearchPageMessages = { followers: 'Followers' } /* * Component capable of rendering albums/playlists/people */ const CardSearchPage = ({ albums, playlists, artists, goToRoute, cardType, search, isTagSearch, searchText }: CardSearchPageProps) => { const entities: Array<UserCollection | User> = (() => { switch (cardType) { case CardType.ALBUM: return albums case CardType.PLAYLIST: return playlists case CardType.USER: return artists } })() const cards = entities.map(e => { const { id, userId, route, primaryText, secondaryText, imageSize } = (() => { switch (cardType) { case CardType.USER: { const user = e as User const followers = `${user.follower_count} ${cardSearchPageMessages.followers}` return { id: user.user_id, userId: user.user_id, route: profilePage(user.handle), primaryText: user.name, secondaryText: followers, imageSize: user._profile_picture_sizes, isVerified: user.is_verified } } case CardType.ALBUM: case CardType.PLAYLIST: { const routeFunc = cardType === CardType.ALBUM ? albumPage : playlistPage const collection = e as UserCollection return { userId: collection.playlist_owner_id, id: collection.playlist_id, route: routeFunc( collection.user.handle, collection.playlist_name, collection.playlist_id ), primaryText: collection.playlist_name, secondaryText: collection.user.handle, imageSize: collection._cover_art_sizes, isVerified: false } } } })() return ( <Card key={id} id={id} userId={userId} isUser={cardType === CardType.USER} imageSize={imageSize} primaryText={primaryText} secondaryText={secondaryText} onClick={() => goToRoute(route)} className='' /> ) }) return ( <SearchStatusWrapper status={search.status}> {entities.length ? ( <div className={styles.lineupContainer}> <CardLineup categoryName={ALBUM_CATEGORY_NAME} cards={cards} /> </div> ) : ( <NoResults searchText={searchText} isTagSearch={isTagSearch} /> )} </SearchStatusWrapper> ) } const messages = { title: 'More Results', tagSearchTitle: 'Tag Search', tracksTitle: 'Tracks', albumsTitle: 'Albums', playlistsTitle: 'Playlists', peopleTitle: 'Profiles' } enum Tabs { TRACKS = 'TRACKS', ALBUMS = 'ALBUMS', PLAYLISTS = 'PLAYLISTS', PEOPLE = 'PEOPLE' } const SearchPageContent = (props: SearchPageContentProps) => { const searchTitle = props.isTagSearch ? 'Tag Search' : 'Search' // Set nav header const { setLeft, setCenter, setRight } = useContext(NavContext)! useEffect(() => { // If native, add the ability to navigate back to the native search if (NATIVE_MOBILE) { setLeft(LeftPreset.BACK) setCenter(CenterPreset.LOGO) setRight(null) } else { // If non-native mobile, show the notification and search icons setLeft(LeftPreset.NOTIFICATION) setCenter(CenterPreset.LOGO) setRight(RightPreset.SEARCH) } }, [setLeft, setCenter, setRight]) const record = useRecord() const { searchText } = props const didChangeTabsFrom = useCallback( (from: string, to: string) => { if (from !== to) record( make(Name.SEARCH_TAB_CLICK, { term: searchText, tab: to.toLowerCase() as | 'people' | 'tracks' | 'albums' | 'playlists' }) ) }, [record, searchText] ) const { isTagSearch } = props // Show fewer tabs if this is a tagSearch const computedTabs = useMemo(() => { return isTagSearch ? { didChangeTabsFrom, tabs: [ { icon: <IconNote />, text: messages.tracksTitle, label: Tabs.TRACKS }, { icon: <IconUser />, text: messages.peopleTitle, label: Tabs.PEOPLE } ], elements: [ <TracksSearchPage key='tagTrackSearch' {...props} />, <CardSearchPage key='tagUserSearch' {...props} cardType={CardType.USER} /> ] } : { didChangeTabsFrom, tabs: [ { icon: <IconUser />, text: messages.peopleTitle, label: Tabs.PEOPLE }, { icon: <IconNote />, text: messages.tracksTitle, label: Tabs.TRACKS }, { icon: <IconAlbum />, text: messages.albumsTitle, label: Tabs.ALBUMS }, { icon: <IconPlaylists />, text: messages.playlistsTitle, label: Tabs.PLAYLISTS } ], elements: [ <CardSearchPage key='userSearch' {...props} cardType={CardType.USER} />, <TracksSearchPage key='trackSearch' {...props} />, <CardSearchPage key='albumSearch' {...props} cardType={CardType.ALBUM} />, <CardSearchPage key='playlistSearch' {...props} cardType={CardType.PLAYLIST} /> ] } }, [isTagSearch, props, didChangeTabsFrom]) const { tabs, body } = useTabs(computedTabs) const { setHeader } = useContext(HeaderContext) const pathname = useSelector(getLocationPathname) useEffect(() => { const isSearchPage = matchPath(pathname, { path: SEARCH_PAGE }) if (!isSearchPage) return setHeader( <> <Header className={styles.header} title={isTagSearch ? messages.tagSearchTitle : messages.title} /> <div className={cn(styles.tabBar, { [styles.nativeTabBar]: NATIVE_MOBILE })} > {tabs} </div> </> ) }, [setHeader, tabs, pathname, isTagSearch]) return ( <MobilePageContainer title={`${searchTitle} ${searchText}`} description={`Search results for ${searchText}`} canonicalUrl={fullSearchResultsPage(searchText)} > <div className={styles.tabContainer}> <div className={styles.pageContainer}>{body}</div> </div> </MobilePageContainer> ) } export default SearchPageContent
the_stack
import { addFunction, amplifyPushAuth, amplifyPushMissingFuncSecret, createNewProjectDir, deleteProject, deleteProjectDir, getCategoryParameters, getParameters, getProjectMeta, getSSMParameters, initJSProjectWithProfile, invokeFunction, overrideFunctionCodeNode, removeFunction, setCategoryParameters, updateFunction, } from 'amplify-e2e-core'; import { addEnvironment, addEnvironmentYes, removeEnvironment } from '../environment/env'; describe('function secret value', () => { let projRoot: string; beforeEach(async () => { projRoot = await createNewProjectDir('funcsecrets'); }); afterEach(async () => { await deleteProject(projRoot); deleteProjectDir(projRoot); }); it('configures secret that is accessible in the cloud', async () => { // add func with secret await initJSProjectWithProfile(projRoot, { disableAmplifyAppCreation: false }); const random = Math.floor(Math.random() * 10000); const funcName = `secretsTest${random}`; await addFunction( projRoot, { functionTemplate: 'Hello World', name: funcName, secretsConfig: { operation: 'add', name: 'TEST_SECRET', value: 'testsecretvalue', }, }, 'nodejs', ); // override lambda code to fetch the secret and return the value overrideFunctionCodeNode(projRoot, funcName, 'retrieve-secret.js'); await amplifyPushAuth(projRoot); const lambdaEvent = { secretNames: ['TEST_SECRET'], }; const meta = getProjectMeta(projRoot); const { Region: region } = (Object.values(meta.function)[0] as any).output; // check that the lambda response includes the secret value const response = await invokeFunction(`${funcName}-integtest`, JSON.stringify(lambdaEvent), region); expect(JSON.parse(response.Payload.toString())[0]?.Value).toEqual('testsecretvalue'); }); it('removes secrets immediately when func not pushed', async () => { // add func w/ secret await initJSProjectWithProfile(projRoot, { disableAmplifyAppCreation: false }); const random = Math.floor(Math.random() * 10000); const funcName = `secretsTest${random}`; await addFunction( projRoot, { functionTemplate: 'Hello World', name: funcName, secretsConfig: { operation: 'add', name: 'TEST_SECRET', value: 'testsecretvalue', }, }, 'nodejs', ); // remove secret await updateFunction( projRoot, { secretsConfig: { operation: 'delete', name: 'TEST_SECRET', }, }, 'nodejs', ); // check that ssm param doesn't exist const meta = getProjectMeta(projRoot); const { AmplifyAppId: appId, Region: region } = meta?.providers?.awscloudformation; expect(appId).toBeDefined(); await expectParams([], ['TEST_SECRET'], region, appId, 'integtest', funcName); }); it('removes secrets immediately when unpushed function is removed from project', async () => { // add func w/ secret await initJSProjectWithProfile(projRoot, { disableAmplifyAppCreation: false }); const random = Math.floor(Math.random() * 10000); const funcName = `secretsTest${random}`; await addFunction( projRoot, { functionTemplate: 'Hello World', name: funcName, secretsConfig: { operation: 'add', name: 'TEST_SECRET', value: 'testsecretvalue', }, }, 'nodejs', ); await removeFunction(projRoot, funcName); // check that ssm param doesn't exist const meta = getProjectMeta(projRoot); const { AmplifyAppId: appId, Region: region } = meta?.providers?.awscloudformation; expect(appId).toBeDefined(); await expectParams([], ['TEST_SECRET'], region, appId, 'integtest', funcName); }); it('removes secrets on push when func is already pushed', async () => { // add func w/ secret await initJSProjectWithProfile(projRoot, { disableAmplifyAppCreation: false }); const random = Math.floor(Math.random() * 10000); const funcName = `secretsTest${random}`; await addFunction( projRoot, { functionTemplate: 'Hello World', name: funcName, secretsConfig: { operation: 'add', name: 'TEST_SECRET', value: 'testsecretvalue', }, }, 'nodejs', ); await amplifyPushAuth(projRoot); // remove secret await updateFunction( projRoot, { secretsConfig: { operation: 'delete', name: 'TEST_SECRET', }, }, 'nodejs', ); // check that ssm param still exists const meta = getProjectMeta(projRoot); const { AmplifyAppId: appId, Region: region } = meta?.providers?.awscloudformation; expect(appId).toBeDefined(); await expectParams([{ name: 'TEST_SECRET', value: 'testsecretvalue' }], [], region, appId, 'integtest', funcName); await amplifyPushAuth(projRoot); // check that ssm param doesn't exist await expectParams([], ['TEST_SECRET'], region, appId, 'integtest', funcName); }); it('removes secrets on push when pushed function is removed', async () => { // add func w/ secret await initJSProjectWithProfile(projRoot, { disableAmplifyAppCreation: false }); const random = Math.floor(Math.random() * 10000); const funcName = `secretsTest${random}`; await addFunction( projRoot, { functionTemplate: 'Hello World', name: funcName, secretsConfig: { operation: 'add', name: 'TEST_SECRET', value: 'testsecretvalue', }, }, 'nodejs', ); await amplifyPushAuth(projRoot); // remove function await removeFunction(projRoot, funcName); // check that ssm param still exists const meta = getProjectMeta(projRoot); const { AmplifyAppId: appId, Region: region } = meta?.providers?.awscloudformation; expect(appId).toBeDefined(); await expectParams([{ name: 'TEST_SECRET', value: 'testsecretvalue' }], [], region, appId, 'integtest', funcName); await amplifyPushAuth(projRoot); // check that ssm param doesn't exist await expectParams([], ['TEST_SECRET'], region, appId, 'integtest', funcName); }); it('removes / copies secrets when env removed / added, respectively', async () => { // add func w/ secret await initJSProjectWithProfile(projRoot, { disableAmplifyAppCreation: false }); const random = Math.floor(Math.random() * 10000); const funcName = `secretsTest${random}`; await addFunction( projRoot, { functionTemplate: 'Hello World', name: funcName, secretsConfig: { operation: 'add', name: 'TEST_SECRET', value: 'testsecretvalue', }, }, 'nodejs', ); const newEnvName = 'testtest'; await addEnvironmentYes(projRoot, { envName: newEnvName }); // check that ssm param exists for new env const meta = getProjectMeta(projRoot); const { AmplifyAppId: appId, Region: region } = meta?.providers?.awscloudformation; expect(appId).toBeDefined(); await expectParams([{ name: 'TEST_SECRET', value: 'testsecretvalue' }], [], region, appId, newEnvName, funcName); await removeEnvironment(projRoot, { envName: 'integtest' }); // check that ssm param doesn't exist in removed env await expectParams([], ['TEST_SECRET'], region, appId, 'integtest', funcName); }); it('prompts for missing secrets and removes unused secrets on push', async () => { // add func w/ secret await initJSProjectWithProfile(projRoot, { disableAmplifyAppCreation: false }); const random = Math.floor(Math.random() * 10000); const funcName = `secretsTest${random}`; await addFunction( projRoot, { functionTemplate: 'Hello World', name: funcName, secretsConfig: { operation: 'add', name: 'TEST_SECRET', value: 'testsecretvalue', }, }, 'nodejs', ); await amplifyPushAuth(projRoot); // replace contents of function-parameters.json with a different secret name // this will make amplify think the original secret has been removed and a new one has been added const funcParams = getCategoryParameters(projRoot, 'function', funcName); funcParams.secretNames = ['A_NEW_SECRET']; setCategoryParameters(projRoot, 'function', funcName, funcParams); // trigger a func update overrideFunctionCodeNode(projRoot, funcName, 'retrieve-secret.js'); // push -> should prompt for value for new secret await amplifyPushMissingFuncSecret(projRoot, 'anewtestsecretvalue'); const meta = getProjectMeta(projRoot); const { AmplifyAppId: appId, Region: region } = meta?.providers?.awscloudformation; expect(appId).toBeDefined(); // check that old value is removed and new one is added await expectParams([{ name: 'A_NEW_SECRET', value: 'anewtestsecretvalue' }], ['TEST_SECRET'], region, appId, 'integtest', funcName); }); }); const expectParams = async ( expectToExist: NameValuePair[], expectNotExist: string[], region: string, appId: string, envName: string, funcName: string, ) => { const result = await getSSMParameters(region, appId, envName, funcName, expectToExist.map(exist => exist.name).concat(expectNotExist)); const mapName = (name: string) => `/amplify/${appId}/${envName}/AMPLIFY_${funcName}_${name}`; expect(result.InvalidParameters.length).toBe(expectNotExist.length); expect(result.InvalidParameters.sort()).toEqual(expectNotExist.map(mapName).sort()); expect(result.Parameters.length).toBe(expectToExist.length); const mappedResult = result.Parameters.map(param => ({ name: param.Name, value: param.Value })).sort(sortByName); const mappedExpect = expectToExist .map(exist => ({ name: `/amplify/${appId}/${envName}/AMPLIFY_${funcName}_${exist.name}`, value: exist.value })) .sort(sortByName); expect(mappedResult).toEqual(mappedExpect); }; const sortByName = (a: NameValuePair, b: NameValuePair) => a.name.localeCompare(b.name); type NameValuePair = { name: string; value: string };
the_stack
declare namespace google { export function load( moduleName: string, moduleVersion: string, optionalSettings?: any ): void; } declare namespace google.earth { /** * Specifies the current stage of the flow of events. */ export type GEEventPhaseEnum = any; /** * Specifies how a feature should be displayed in a list view. */ export type KmlListItemTypeEnum = any; /** * Specifies which color mode effect to apply to the base color. */ export type KmlColorModeEnum = any; /* * Specifies how the altitude property is interpreted. */ export type KmlAltitudeModeEnum = any; /** * Specifies how the link is refreshed. */ export type KmlRefreshModeEnum = any; /** * Specifies how the link is refreshed when the viewport changes. */ export type KmlViewRefreshModeEnum = any; /** * Specifies which units a value is specified in. */ type KmlUnitsEnum = any; /** * Specifies if the map type is Earth or sky mode. */ type GEMapTypeEnum = any; /** * Specifies if a control is always visible, always hidden, * or visible only when the user intends to use the control. */ type GEVisibilityEnum = any; /** * Specifies what to sample when performing a hit test. */ type GEHitTestModeEnum = any; /** * Specifies the size of the navigation control. */ type GENavigationControlEnum = any; /** * Specifies the state of viewer options, including sunlight, * Street View, and historical imagery. */ type GEViewerOptionsValueEnum = any; /* * Specifies the viewer option types. */ type GEViewerOptionsTypeEnum = any; /** * Whether or not the Google Earth Browser Plug-in and API are supported on the current browser and operating system. */ export function isSupported(): boolean; /** * Whether or not the Google Earth Browser Plug-in is currently installed on the user's machine. * * Note: if the plug-in is not installed, the user will be presented with a 'download' link upon calls to google.earth.createInstance(). */ export function isInstalled(): boolean; /** * Attempts to create an instance of the plugin under the given web browser HTML DOM node. * Upon success, calls the function passed in as the initCallback argument. * Upon failure, calls the function passed in as the failureCallback argument and displays an error message to the user in place of the plug-in object. * * Note: * * The HTML DOM must be loaded before this function can be called. * Common usage is to call this function upon the <body>'s load event, or to use google.setOnLoadCallback. */ export function createInstance( domNode: string|Element, initCallback: (plugin: GEPlugin) => void, failureCallback: (error: any) => void, options?: any ): void; /** * Attaches a listener to a given object for a specific event; when the event occurs on the object, the given callback is invoked. */ export function addEventListener( targetObject: any, eventID: string, listenerCallback: (event: KmlEvent) => void, useCapture?: boolean ): void; /** * Removes an event listener previously added using google.earth.addEventListener() from the event chain. * * Note: * * You must pass in the exact same function object as was passed to addEventListener. * If you are using an anonymous function callback, it will need to be refactored into its own variable. */ export function removeEventListener( targetObject: any, eventID: string, listenerCallback: (event: KmlEvent) => void, useCapture?: boolean ): void; /** * Retrieves and parses a KML or KMZ file at the given URL and returns an instance of a KmlFeature-derived class representing the parsed KML object model. * * Note: This function does not display the feature on the Earth. See below for more information. */ export function fetchKml( pluginInstance: GEPlugin, url: string, completionCallback: (feature: KmlFeature) => void ): void; /** * Efficiently executes an arbitrary, user-defined function (the batch function), minimizing the amount of overhead incurred during cross-process communication between the web browser and Google Earth Plugin. * This method is useful for batching together a large set of calls to the Earth API, for example, a large number of consecutive calls to KmlCoordArray.pushLatLngAlt. */ export function executeBatch(pluginInstance: GEPlugin, batchFunction: Function): void; /** * Sets the language to be used for new instances of the plugin. * Needs to be called before google.earth.createInstance(). * Affects road and border labels, the error message displayed when the plugin fails to load, as well as the language of the Terms of Use page linked from the plugin. */ export function setLanguage(languageCode: string): void; /** * This interface enables programmatic and user-driven interaction with photo overlays in the Google Earth Plugin. * * Note: This interface is still under development. */ export class GEPhotoOverlayViewer { /** * Enters the given photo overlay object, exiting any other currently active photo overlay. * If the argument is null, then any currently active photo overlay is exited and normal global navigation is enabled. */ setPhotoOverlay(photoOverlay: KmlPhotoOverlay): void; } /** * Used to manipulate the navigation controls in Google Earth. */ export class GENavigationControl { /** * Whether the control is always visible, always hidden, or visible only when the user intends to use the control. * * See also: * * * GEPlugin.VISIBILITY_SHOW * * GEPlugin.VISIBILITY_HIDE * * GEPlugin.VISIBILITY_AUTO */ getVisibility(): GEVisibilityEnum; /** * Whether the control is always visible, always hidden, or visible only when the user intends to use the control. * * See also: * * * GEPlugin.VISIBILITY_SHOW * * GEPlugin.VISIBILITY_HIDE * * GEPlugin.VISIBILITY_AUTO */ setVisibility(visibility: GEVisibilityEnum): void; /** * Specifies the size of the navigation control. * * See also: * * * GEPlugin.NAVIGATION_CONTROL_LARGE * * GEPlugin.NAVIGATION_CONTROL_SMALL */ getControlType(): GENavigationControlEnum; /** * Specifies the size of the navigation control. * * See also: * * * GEPlugin.NAVIGATION_CONTROL_LARGE * * GEPlugin.NAVIGATION_CONTROL_SMALL */ setControlType(controlType: GENavigationControlEnum): void; /** * The position of the navigation controls in Google Earth */ getScreenXY(): KmlVec2; /** * Enables or disables user-initiated entry to Street View imagery. * When true, the Pegman icon is present in the navigation controls, allowing a user to drag the Pegman onto a street to initiate Street View. * Users can also zoom down to ground level to enter Street View when this is set to true. */ setStreetViewEnabled(streetViewEnabled: boolean): void; /** * Whether Street View is enabled in the navigation controls. */ getStreetViewEnabled(): boolean; } /** * Defines a tour, which is a playlist of scripted camera and update events. * * Note: This interface is still under development. */ export class KmlTour extends KmlFeature {} /** * This interface enables programmatic and user-driven interaction with KML tours in the Google Earth Plugin. * * Note: This interface is still under development. */ export class GETourPlayer { /** * Enters the given tour object, exiting any other currently active tour. * This method does not automatically begin playing the tour. * If the argument is null, then any currently active tour is exited and normal globe navigation is enabled. */ setTour(tour: KmlTour): void; /** * Plays the currently active tour. */ play(): void; /** * Pauses the currently active tour. */ pause(): void; /** * Resets the currently active tour, stopping playback and rewinding to the start of the tour. */ reset(): void; /** * The current elapsed playing time of the active tour, in seconds. */ getCurrentTime(): number; /** * The current elapsed playing time of the active tour, in seconds. */ setCurrentTime(currentTime: number): void; /** * The total duration of the active tour, in seconds. If no tour is loaded, the behavior of this method is undefined. */ getDuration(): number; } /** * This interface contains result information obtained by calling GEView's hitTest method. * * See also: * * * GEView.hitTest */ export class GEHitTestResult { /** * Latitude of sampled point. */ getLatitude(): number; /** * Latitude of sampled point. */ setLatitude(latitude: number): void; /** * Longitude of sampled point. */ getLongitude(): number; /** * Longitude of sampled point. */ setLongitude(longitude: number): void; /** * Altitude of sampled point. */ getAltitude(): number; /** * Altitude of sampled point. */ setAltitude(altitude: number): void; } /** * Maps between two different icon styles. * Typically this interface is used to provide separate normal and highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon. */ export class KmlStyleMap extends KmlStyleSelector { /** * Sets both URLs for the placemark style. */ setUrl(normalStyleUrl: string, highlightStyleUrl: string): void; /** * Sets both placemark styles. */ setStyle(normalStyle: KmlStyle, highlightStyle: KmlStyle): void; /** * Defines a normal style for a placemark. */ getNormalStyleUrl(): string; /** * Defines a normal style for a placemark. */ setNormalStyleUrl(normalStyleUrl: string): void; /** * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. */ getHighlightStyleUrl(): string; /** * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. */ setHighlightStyleUrl(highlightStyleUrl: string): void; /** * Defines a normal style for a placemark. */ getNormalStyle(): KmlStyle; /** * Defines a normal style for a placemark. */ setNormalStyle(normalStyle: KmlStyle): void; /** * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. */ getHighlightStyle(): KmlStyle; /** * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. */ setHighlightStyle(highlightStyle: KmlStyle): void; } /** * References a KML file or KMZ archive on a remote network. * Use the Link property to specify the location of the KML file. * Within that property, you can define the refresh options for updating the file, based on time and camera change. * NetworkLinks can be used in combination with Regions to handle very large datasets efficiently. */ export class KmlNetworkLink extends KmlFeature { /** * Sets the link, refreshVisibility, and flyToView for the network link. */ set(link: KmlLink, refreshVisibility: boolean, flyToView: boolean): void; /** * Specifies the location of any of the following: * * * KML files fetched by network links * * Image files used by icons in icon styles, ground overlays, and screen overlays * * Model files used in the Model object */ getLink(): KmlLink; /** * Specifies the location of any of the following: * * * KML files fetched by network links * * Image files used by icons in icon styles, ground overlays, and screen overlays * * Model files used in the Model object */ setLink(link: KmlLink): void; /** * A value of 0 leaves the visibility of features within the control of the Google Earth user. * Set the value to 1 to reset the visibility of features each time the NetworkLink is refreshed. * For example, suppose a Placemark within the linked KML file has visibility set to 1 and the NetworkLink has refreshVisibility set to 1. * When the file is first loaded into Google Earth, the user can clear the check box next to the item to turn off display in the 3D viewer. * However, when the NetworkLink is refreshed, the Placemark will be made visible again, since its original visibility state was TRUE. */ getRefreshVisibility(): boolean; /** * A value of 0 leaves the visibility of features within the control of the Google Earth user. * Set the value to 1 to reset the visibility of features each time the NetworkLink is refreshed. * For example, suppose a Placemark within the linked KML file has visibility set to 1 and the NetworkLink has refreshVisibility set to 1. * When the file is first loaded into Google Earth, the user can clear the check box next to the item to turn off display in the 3D viewer. * However, when the NetworkLink is refreshed, the Placemark will be made visible again, since its original visibility state was TRUE. */ setRefreshVisibility(refreshVisibility: boolean): void; /** * A value of 1 causes Google Earth to fly to the view of the LookAt or Camera in the NetworkLinkControl (if it exists). */ getFlyToView(): boolean; /** * A value of 1 causes Google Earth to fly to the view of the LookAt or Camera in the NetworkLinkControl (if it exists). */ setFlyToView(flyToView: boolean): void; } /** * Draws an image overlay fixed to the screen. * Sample uses for ScreenOverlays are compasses, logos, and heads-up displays. * ScreenOverlay sizing is determined by the size element. * Positioning of the overlay is handled by mapping a point in the image specified by screenXY to a point on the screen specified by overlayXY. * Then the image is rotated by rotation degrees about a point relative to the screen specified by rotationXY. * * Note: * * screenXY and overlayXY behave opposite to their corresponding behaviors in KML. * This is due to a bug in the Earth API that will intentionally remain unfixed until a major version change. */ export class KmlScreenOverlay extends KmlOverlay { /** * Specifies a point on (or outside of) the overlay image that is mapped to the screen coordinate. * It requires x and y values, and the units for those values. * * Note: * * screenXY and overlayXY behave opposite to their corresponding behaviors in KML. * This is due to a bug in the Earth API that will intentionally remain unfixed until a major version change. */ getScreenXY(): KmlVec2; /** * Specifies a point relative to the screen origin that the overlay image is mapped to. * The x and y values can be specified in three different ways: as pixels ("pixels"), as fractions of the screen ("fraction"), or as inset pixels ("insetPixels"), which is an offset in pixels from the upper right corner of the screen. * The x and y positions can be specified in different ways - for example, x can be in pixels and y can be a fraction. * The origin of the coordinate system is in the lower left corner of the screen. * * Note: * * screenXY and overlayXY behave opposite to their corresponding behaviors in KML. * This is due to a bug in the Earth API that will intentionally remain unfixed until a major version change. */ getOverlayXY(): KmlVec2; /** * Point relative to the screen about which the screen overlay is rotated. */ getRotationXY(): KmlVec2; /** * Specifies the size of the image for the screen overlay, as follows: * * * A value of -1 indicates to use the native dimension * * A value of 0 indicates to maintain the aspect ratio * * A value of n sets the value of the dimension */ getSize(): KmlVec2; /** * Adjusts how the image is placed inside the field of view. * This element is useful if your image has been rotated and deviates slightly from a desired horizontal view. */ getRotation(): number; /** * Adjusts how the image is placed inside the field of view. * This element is useful if your image has been rotated and deviates slightly from a desired horizontal view. */ setRotation(rotation: number): void; } /** * Defines a photo overlay, which is a geographically located photograph of the Earth. * Photo overlays can be drawn onto 2D rectangles in three dimensional space, or in the case of panoramic photos, onto partial or full cylinders, or even spheres. * * Note: This interface is still under development. */ export class KmlPhotoOverlay extends KmlOverlay {} /** * Draws an image overlay draped onto the terrain. * The href child of Icon specifies the image to be used as the overlay. * If this object is omitted or contains no href, a rectangle is drawn using the color defined by the overlay. */ export class KmlGroundOverlay extends KmlOverlay { /** * Specifies the distance above the earth's surface. */ getAltitude(): number; /** * Specifies the distance above the earth's surface. */ setAltitude(altitude: number): void; /** * Specifies how the altitude property is interpreted. * * See also: * * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND * * GEPlugin.ALTITUDE_ABSOLUTE * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR */ getAltitudeMode(): KmlAltitudeModeEnum; /** * Specifies how the altitude property is interpreted. * * See also: * * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND * * GEPlugin.ALTITUDE_ABSOLUTE * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR */ setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; /** * The bounding box of the ground overlay. */ getLatLonBox(): KmlLatLonBox; /** * The bounding box of the ground overlay. */ setLatLonBox(latLonBox: KmlLatLonBox): void; } /** * The KmlOverlay object is an abstract object and cannot be used directly in a KML file. * Overlay is the base type for image overlays drawn on the planet surface or on the screen. * Icon specifies the image to use and can be configured to reload images based on a timer or by camera changes. * This object also includes specifications for stacking order of multiple overlays and for adding color and transparency values to the base image. */ export class KmlOverlay extends KmlFeature { /** * Specifies the color values. */ getColor(): KmlColor; /** * Defines the stacking order for the images in overlapping overlays. * Overlays with higher drawOrder values are drawn on top of overlays with lower drawOrder values. */ getDrawOrder(): number; /** * Defines the stacking order for the images in overlapping overlays. * Overlays with higher drawOrder values are drawn on top of overlays with lower drawOrder values. */ setDrawOrder(drawOrder: number): void; /** * Defines the image associated with the Overlay. */ getIcon(): KmlIcon; /** * Defines the image associated with the Overlay. */ setIcon(icon: KmlIcon): void; } /** * This class controls the display of sunlight, historical imagery, and Street View panoramas in the plugin. * The KmlViewerOptions object is passed to KmlAbstractView.setViewerOptions() */ export class KmlViewerOptions extends KmlObject { /** * Returns the current state of the specified viewer option type. * * See also: * * * GEPlugin.OPTION_STREET_VIEW * * GEPlugin.OPTION_SUNLIGHT * * GEPlugin.OPTION_HISTORICAL_IMAGERY * * GEPlugin.OPTION_STATE_DEFAULT * * GEPlugin.OPTION_STATE_ENABLED * * GEPlugin.OPTION_STATE_DISABLED */ setOption(type: GEViewerOptionsTypeEnum, state: GEViewerOptionsValueEnum): void; /** * Set the state of viewer options, including sunlight, Street View, and historical imagery. * * See also: * * * GEPlugin.OPTION_STREET_VIEW * * GEPlugin.OPTION_SUNLIGHT * * GEPlugin.OPTION_HISTORICAL_IMAGERY * * GEPlugin.OPTION_STATE_DEFAULT * * GEPlugin.OPTION_STATE_ENABLED * * GEPlugin.OPTION_STATE_DISABLED */ getOption(type: GEViewerOptionsValueEnum): GEViewerOptionsValueEnum; } /** * Describes rotation of a 3D model's coordinate system to position the object in Google Earth. */ export class KmlOrientation extends KmlObject { /** * Sets the heading, tilt, and roll of a model. */ set(heading: number, tilt: number, roll: number): void; /** * Rotation about the z axis (normal to the Earth's surface). * A value of 0 (the default) equals North. * A positive rotation is clockwise around the z axis and specified in degrees from 0 to 360. */ getHeading(): number; /** * Rotation about the z axis (normal to the Earth's surface). * A value of 0 (the default) equals North. * A positive rotation is clockwise around the z axis and specified in degrees from 0 to 360. */ setHeading(heading: number): void; /** * Rotation about the x axis. * A positive rotation is clockwise around the x axis and specified in degrees from 0 to 360. */ getTilt(): number; /** * Rotation about the x axis. * A positive rotation is clockwise around the x axis and specified in degrees from 0 to 360. */ setTilt(tilt: number): void; /** * Rotation about the y axis. * A positive rotation is clockwise around the y axis and specified in degrees from 0 to 360. */ getRoll(): number; /** * Rotation about the y axis. * A positive rotation is clockwise around the y axis and specified in degrees from 0 to 360. */ setRoll(roll: number): void; } /** * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. */ export class KmlLocation extends KmlObject { /** * Sets the latitude, longitude, and altitude of the Model. */ setLatLngAlt(lat: number, lng: number, alt: number): void; /** * Longitude of the Model's location. * Angular distance in degrees, relative to the Prime Meridian. * Values west of the Meridian range from -180 to 0 degrees. * Values east of the Meridian range from 0 to 180 degrees. */ getLongitude(): number; /** * Longitude of the Model's location. * Angular distance in degrees, relative to the Prime Meridian. * Values west of the Meridian range from -180 to 0 degrees. * Values east of the Meridian range from 0 to 180 degrees. */ setLongitude(longitude: number): void; /** * Latitude of the camera location. * Degrees north or south of the Equator (0 degrees). * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). */ getLatitude(): number; /** * Latitude of the camera location. * Degrees north or south of the Equator (0 degrees). * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). */ setLatitude(latitude: number): void; /** * Specifies the distance above the earth's surface. */ getAltitude(): number; /** * Specifies the distance above the earth's surface. */ setAltitude(altitude: number): void; } /** * Scales a model along the x, y, and z axes in the model's coordinate space. */ export class KmlScale extends KmlObject { /** * Sets the x, y, and z coordinates for a model. */ set(x: number, y: number, z: number): void; /** * Indicates the x coordinate. */ getX(): number; /** * Indicates the x coordinate. */ setX(x: number): void; /** * Indicates the y coordinate. */ getY(): number; /** * Indicates the y coordinate. */ setY(y: number): void; /** * Indicates the z coordinate. */ getZ(): number; /** * Indicates the z coordinate. */ setZ(z: number): void; } /** * A single tuple consisting of floating point values for longitude, latitude, and altitude (in that order). * Longitude and latitude values are in degrees. * * * longitude = -180 and <= 180 * * latitude = -90 and = 90 * * altitude values (optional) are in meters above sea level */ export class KmlCoord { /** * Sets the latitude, longitude, altitude. */ setLatLngAlt(latitude: number, longitude: number, altitude: number): void; /** * Degrees north or south of the Equator (0 degrees). * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). */ getLatitude(): number; /** * Degrees north or south of the Equator (0 degrees). * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). */ setLatitude(latitude: number): void; /** * Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. * Values east of the Meridian range from 0 to 180 degrees. */ getLongitude(): number; /** * Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. * Values east of the Meridian range from 0 to 180 degrees. */ setLongitude(longitude: number): void; /** * Distance from the earth's surface. */ getAltitude(): number; /** * Distance from the earth's surface. */ setAltitude(altitude: number): void; } /** * The KmlCoordArray object defines an array of coordinates. */ export class KmlCoordArray { /** * Returns the coordinates at the given index. */ get(index: number): KmlCoord; /** * Sets the coordinates at the given index.. */ set(index: number, coord: KmlCoord): void; /** * Sets the latitude, longitude, and altitude. */ setLatLngAlt( index: number, latitude: number, longitude: number, altitude: number ): void; /** * Appends one or more new elements to the end of an array and returns the new length of the array. */ pushLatLngAlt( latitude: number, longitude: number, altitude: number ): void; /** * Appends one or more new elements to the end of an array and returns the new length of the array. */ push(coordOrList: KmlCoord): void; /** * Deletes the last element of an array, decrements the array length, and returns the value that is removed. */ pop(): KmlCoord; /** * Adds an element or elements to the beginning of an array. */ unshift(coordOrList: KmlCoord): number; /** * Adds an element or elements to the beginning of an array. */ unshiftLatLngAlt( latitude: number, longitude: number, altitude: number ): void; /** * Removes and returns the first element of the array. */ shift(): KmlCoord; /** * Reverses the order of the elements in the array. */ reverse(): void; /** * Clears all of the elements in the array */ clear(): void; /** * Specifies the length of the index array. */ getLength(): number; } /** * The object corresponding to the retangular region in which Google Earth is displayed. */ export class GEWindow extends GEEventEmitter { /** * Gives the Google Earth object focus. */ focus(): void; /** * Removes focus from the Google Earth object. */ blur(): void; /** * Toggles the overall visibility of Google Earth inside the browser. */ getVisibility(): boolean; /** * Toggles the overall visibility of Google Earth inside the browser. */ setVisibility(visibility: boolean): void; } /** * The GEGlobe class encapsulates the Google Earth globe to determine access and event behavior. */ export class GEGlobe extends KmlObject { /** * Returns the altitude for a given location on the globe. * If the altitude data for the location has not yet been loaded, the return value is 0. */ getGroundAltitude(lat: number, lon: number): number; /** * The top-level features currently in the Earth instance. */ getFeatures(): GEFeatureContainer; } /** * Controls the behavior of the camera that views the scene in Google Earth. */ export class GEView { /** * Returns the screen x,y coordinates of a given point on the globe. * * Tip: project() is the inverse of hitTest(). * * See also: * * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND * * GEPlugin.ALTITUDE_ABSOLUTE * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR */ project( lat: number, lng: number, alt: number, altitudeMode: KmlAltitudeModeEnum ): KmlVec2; /** * Sets the camera that views the scene in Google Earth. */ setAbstractView(view: KmlAbstractView): void; /** * Creates and returns a new KmlLookAt object, initialized to the current camera position and orientation. * Use 'altitudeMode' to specify the altitude mode of the looked-at point. * * See also: * * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND * * GEPlugin.ALTITUDE_ABSOLUTE * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR */ copyAsLookAt(altitudeMode: KmlAltitudeModeEnum): KmlLookAt; /** * Creates and returns a new KmlCamera object, initialized to the current camera position and orientation. * Use 'altitudeMode' to specify the altitude mode of the new camera. * * See also: * * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND * * GEPlugin.ALTITUDE_ABSOLUTE * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR */ copyAsCamera(altitudeMode: KmlAltitudeModeEnum): KmlCamera; /** * Returns a bounding box that completely contains the region of the globe that is currently visible. * The returned box will be larger than what is strictly visible, if that is necessary to include everything that is visible. */ getViewportGlobeBounds(): KmlLatLonBox; /** * Given a point on the screen in pixel coordinates, returns a GEHitTestResult with information about the geographic location corresponding to the point on the screen. * Tip: hitTest() is the inverse of project(). * * See also: * * * GEPlugin.UNITS_PIXELS * * GEPlugin.UNITS_INSET_PIXELS * * GEPlugin.UNITS_FRACTION * * GEPlugin.HIT_TEST_GLOBE * * GEPlugin.HIT_TEST_TERRAIN * * GEPlugin.HIT_TEST_BUILDINGS */ hitTest( x: number, xUnits: KmlUnitsEnum, y: number, yUnits: KmlUnitsEnum, mode: GEHitTestModeEnum ): GEHitTestResult; } /** * Defines an image associated with an Icon style or overlay. */ export class KmlIcon extends KmlLink { /** * Gets the offset from the left (<gx:x>), in pixels, of the icon. */ getX(): number; /** * Specifies the icon's offset (<gx:x>), in pixels from the left side of its icon palette, if a palette has been specified in the <href> element. */ setX(x: number): number; /** * Gets the offset from the bottom (<gx:y>), in pixels, of the icon. */ getY(): number; /** * Specifies the offset (<gx:y>), in pixels from the bottom of its icon palette, if a palette has been specified in the <href> element. */ setY(y: number): void; /** * Gets the width (<gx:w>), in pixels, of the icon. */ getW(): number; /** * Specifies the width (<gx:w>), in pixels, of the icon to use. */ setW(w: number): void; /** * Gets the height (<gx:h>), in pixels, of the icon. */ getH(): number; /** * Specifies the height (<gx:h>), in pixels, of the icon to use. */ setH(h: number): void; } /** * Specifies the location of any KML files fetched by network links, image files used by icons in icon styles, ground overlays, and screen overlays, or model files used in the Model object. */ export class KmlLink extends KmlObject { /** * A URL (either an HTTP address or a local file specification). * When the parent of Link is a NetworkLink, href is a KML file. * When the parent of Link is a Model, href is a COLLADA file. * When the parent of Link is an Overlay, href is an image. */ getHref(): string; /** * A URL (either an HTTP address or a local file specification). * When the parent of Link is a NetworkLink, href is a KML file. * When the parent of Link is a Model, href is a COLLADA file. * When the parent of Link is an Overlay, href is an image. */ setHref(href: string): void; /** * Specifies to use a time-based refresh mode. * * See also: * * * GEPlugin.REFRESH_ON_CHANGE * * GEPlugin.REFRESH_ON_INTERVAL * * GEPlugin.REFRESH_ON_EXPIRE */ getRefreshMode(): KmlRefreshModeEnum; /** * Specifies to use a time-based refresh mode. * * See also: * * * GEPlugin.REFRESH_ON_CHANGE * * GEPlugin.REFRESH_ON_INTERVAL * * GEPlugin.REFRESH_ON_EXPIRE */ setRefreshMode(refreshMode: KmlRefreshModeEnum): void; /** * Indicates to refresh the file every n seconds. */ getRefreshInterval(): number; /** * Indicates to refresh the file every n seconds. */ setRefreshInterval(refreshInterval: number): void; /** * Specifies how the link is refreshed when the viewport changes. * * See also: * * * GEPlugin.VIEW_REFRESH_NEVER * * GEPlugin.VIEW_REFRESH_ON_STOP * * GEPlugin.VIEW_REFRESH_ON_REGION */ getViewRefreshMode(): KmlViewRefreshModeEnum; /** * Specifies how the link is refreshed when the viewport changes. * * See also: * * * GEPlugin.VIEW_REFRESH_NEVER * * GEPlugin.VIEW_REFRESH_ON_STOP * * GEPlugin.VIEW_REFRESH_ON_REGION */ setViewRefreshMode(viewRefreshMode: KmlViewRefreshModeEnum): void; /** * Specifies how the link is refreshed when the camera changes. */ getViewRefreshTime(): number; /** * Specifies how the link is refreshed when the camera changes. */ setViewRefreshTime(viewRefreshTime: number): void; /** * Scales the BBOX parameters before sending them to the server. * A value less than 1 specifies to use less than the full view (screen). * A value greater than 1 specifies to fetch an area that extends beyond the edges of the current view. */ getViewBoundScale(): number; /** * Scales the BBOX parameters before sending them to the server. * A value less than 1 specifies to use less than the full view (screen). * A value greater than 1 specifies to fetch an area that extends beyond the edges of the current view. */ setViewBoundScale(viewBoundScale: number): void; /** * Specifies the format of the query string that is appended to the Link's href before the file is fetched. * (If the href specifies a local file, this element is ignored.) */ getViewFormat(): string; /** * Specifies the format of the query string that is appended to the Link's href before the file is fetched. * (If the href specifies a local file, this element is ignored.) */ setViewFormat(viewFormat: string): void; } /** * Controls time in the plugin. */ export class GETime { /** * Set the plugin's clock rate. * A value of 1 corresponds with real time; to pass one year in the plugin for every real second, set the rate to 31536000 (60 times 60 times 24 times 365). */ setRate(rate: number): void; /** * Get the current plugin clock rate. */ getRate(): number; /** * Returns the current computer clock time as a KmlTimeStamp object. */ getSystemTime(): KmlTimeStamp; /** * Returns the GETimeControl object; this is the time slider. */ getControl(): GETimeControl; /** * Whether or not historical imagery is enabled. */ getHistoricalImageryEnabled(): boolean; /** * Turn historical imagery on or off. * For more information, read the Time chapter of the Developer's Guide. */ setHistoricalImageryEnabled(historicalImageryEnabled: boolean): void; /** * Get the current plugin time as a KmlTimeStamp or KmlTimeSpan. */ getTimePrimitive(): KmlTimePrimitive; /** * Sets the current plugin time. */ setTimePrimitive(timePrimitive: KmlTimePrimitive): void; } /** * Used to manipulate the behavior of the Google Earth options such as, navigation, flyToSpeed, scroll wheel speed and so on. */ export class GEOptions { /** * Sets the map type to Earth or sky mode. */ setMapType(type: GEMapTypeEnum): void; /** * Speed of zoom when user rolls the mouse wheel. Default is 1. * Set to a negative number to reverse the zoom direction. */ getScrollWheelZoomSpeed(): number; /** * Speed of zoom when user rolls the mouse wheel. Default is 1. * Set to a negative number to reverse the zoom direction. */ setScrollWheelZoomSpeed(scrollWheelZoomSpeed: number): void; /** * Specifies the speed at which the camera moves (0 to 5.0). * Set to SPEED_TELEPORT to immediately appear at selected destination. * * See also: * * * GEPlugin.SPEED_TELEPORT */ getFlyToSpeed(): number; /** * Specifies the speed at which the camera moves (0 to 5.0). * Set to SPEED_TELEPORT to immediately appear at selected destination. * * See also: * * * GEPlugin.SPEED_TELEPORT */ setFlyToSpeed(flyToSpeed: number): void; /** * Show or hide the status bar. Disabled by default. */ getStatusBarVisibility(): boolean; /** * Show or hide the status bar. Disabled by default. */ setStatusBarVisibility(statusBarVisibility: boolean): void; /** * Show or hide the grid. Disabled by default. */ getGridVisibility(): boolean; /** * Show or hide the grid. Disabled by default. */ setGridVisibility(gridVisibility: boolean): void; /** * Show or hide the overview map. Disabled by default. */ getOverviewMapVisibility(): boolean; /** * Show or hide the overview map. Disabled by default. */ setOverviewMapVisibility(overviewMapVisibility: boolean): void; /** * Show or hide the scale legend. Disabled by default. */ getScaleLegendVisibility(): boolean; /** * Show or hide the scale legend. Disabled by default. */ setScaleLegendVisibility(scaleLegendVisibility: boolean): void; /** * Show or hide the blue atmosphere that appears around the perimeter of the Earth. * On by default. */ getAtmosphereVisibility(): boolean; /** * Show or hide the blue atmosphere that appears around the perimeter of the Earth. * On by default. */ setAtmosphereVisibility(atmosphereVisibility: boolean): void; /** * Enable or disable user panning and zooming of the map. Enabled by default. * * Note: This also enables and disables keyboard navigation (arrow keys, page-up/page-down, etc). */ getMouseNavigationEnabled(): boolean; /** * Enable or disable user panning and zooming of the map. Enabled by default. * * Note: This also enables and disables keyboard navigation (arrow keys, page-up/page-down, etc). */ setMouseNavigationEnabled(mouseNavigationEnabled: boolean): void; /** * Returns true if the animation of features as they are added or removed from the globe has been enabled. */ getFadeInOutEnabled(): boolean; /** * Enable or disable the animation of a feature when it is added or removed from the Google Earth plugin. * The animation consists of a slight change of scale. Default is true. */ setFadeInOutEnabled(fadeInOutEnabled: boolean): void; /** * Returns true if display units are set to imperial units (feet and miles). * False denotes metric units (meters and kilometers). */ getUnitsFeetMiles(): boolean; /** * Set display units to imperial (feet and miles) or metric (meters and kilometers). * This setting affects only the values displayed in the status bar and the scale bar. * The values passed and returned with an object's getters and setters are always metric. */ setUnitsFeetMiles(unitsFeetMiles: boolean): void; /** * Enables or disables building selection. * If enabled, clicking a building will pop a feature balloon containing information from the Google 3D Warehouse database. */ setBuildingSelectionEnabled(buildingSelectionEnabled: boolean): void; /** * Whether or not building selection is enabled. */ getBuildingSelectionEnabled(): boolean; /** * Returns true if building highlighting is enabled. */ getBuildingHighlightingEnabled(): boolean; /** * Enables or disables building highlighting. * When enabled, buildings will be highlighted when they are moused over. */ setBuildingHighlightingEnabled(buildingHighlightingEnabled: boolean): void; /** * Returns the terrain exaggeration value. Valid values are in the range of 1.0 through 3.0. */ getTerrainExaggeration(): number; /** * Set the terrain exaggeration value. Valid values are in the range of 1.0 through 3.0. * Attempting to set outside of this range will result in the value being clamped. */ setTerrainExaggeration(terrainExaggeration: number): void; /** * When enabled, the view will change to 'ground level view' when the camera reaches ground level. * This view provides pan and lookAt controls, but no zoom slider. * The tilt will be set to 90, or parallel with level ground. */ setAutoGroundLevelViewEnabled(autoGroundLevelViewEnabled: boolean): void; /** * Whether automatic ground level view is enabled. */ getAutoGroundLevelViewEnabled(): boolean; } /** * Adds a node to the end of the list of children of a specified feature. * Returns the appended object. */ export class GESchemaObjectContainer<T extends KmlObject> { /** * Adds a node to the end of the list of children of a specified feature. * Returns the appended object. */ appendChild(object: T): void; /** * Removes a node from the list of children of a specified object. */ removeChild(oldChild: T): void; /** * Inserts a child before the referenced child in the list of objects. */ insertBefore(newChild: T, refChild: T): void; /** * Replaces existing child in the list of features. * Returns the old child. */ replaceChild(newChild: T, oldChild: T): void; /** * Returns true if the container is not empty. */ hasChildNodes(): boolean; /** * First child in the list of objects. */ getFirstChild(): T; /** * Last child in the list of objects. */ getLastChild(): T; /** * List of features (for KmlContainer), or list of features, styles, and schemas (for KmlDocument). * Returns true if there are any child nodes. */ getChildNodes(): KmlObjectList<T>; } /** * A container class that holds one or more features and allows the creation of nested hierarchies. */ export class GEFeatureContainer extends GESchemaObjectContainer<KmlFeature> {} /** * A container object that contains an array of geometries, typically the children of a multi-geometry. */ export class GEGeometryContainer extends GESchemaObjectContainer<KmlGeometry> {} /** * A container object that contains an array of closed line strings, typically the outer boundary of a Polygon. * Optionally, a LinearRing can also be used as the inner boundary of a Polygon to create holes in the Polygon. * A Polygon can contain multiple LinearRing objects used as inner boundaries. */ export class GELinearRingContainer extends GESchemaObjectContainer<KmlLinearRing> {} /** * A container that holds a collection of KmlStyle and KmlStyleMap objects. * The KmlStyleMap object selects a style based on the current mode of the Placemark. * An object derived from KmlStyleSelector is uniquely identified by its ID and its URL. */ export class GEStyleSelectorContainer extends GESchemaObjectContainer<KmlStyleSelector> {} /** * Defines the x and y coordinates of a 2D vector. */ export class KmlVec2 { /** * Sets the coordinates of the vector. */ set( x: number, xUnits: KmlUnitsEnum, y: number, yUnits: KmlUnitsEnum ): void; /** * Indicates the x coordinate. */ getX(): number; /** * Indicates the x coordinate. */ setX(x: number): void; /** * Indicates the y coordinate. */ getY(): number; /** * Indicates the y coordinate. */ setY(y: number): void; /** * Units in which the x value is specified. * * See also: * * * GEPlugin.UNITS_FRACTION * * GEPlugin.UNITS_PIXELS * * GEPlugin.UNITS_INSET_PIXELS */ getXUnits(): KmlUnitsEnum; /** * Units in which the x value is specified. * * See also: * * * GEPlugin.UNITS_FRACTION * * GEPlugin.UNITS_PIXELS * * GEPlugin.UNITS_INSET_PIXELS */ setXUnits(xUnits: KmlUnitsEnum): void; /** * Units in which the y value is specified. * * See also: * * * GEPlugin.UNITS_FRACTION * * GEPlugin.UNITS_PIyELS * * GEPlugin.UNITS_INSET_PIyELS */ getYUnits(): KmlUnitsEnum; /** * Units in which the y value is specified. * * See also: * * * GEPlugin.UNITS_FRACTION * * GEPlugin.UNITS_PIyELS * * GEPlugin.UNITS_INSET_PIyELS */ setYUnits(xUnits: KmlUnitsEnum): void; } /** * The GESun class controls the dawn to dusk views. */ export class GESun { /** * Specifies whether the feature is drawn in the 3D viewer when it is initially loaded. * In order for a feature to be visible, the visibility property and all of its ancestors must also be set to 1. */ getVisibility(): boolean; /** * Specifies whether the feature is drawn in the 3D viewer when it is initially loaded. * In order for a feature to be visible, the visibility property and all of its ancestors must also be set to 1. */ setVisibility(visibility: boolean): void; } /** * The KmlColor object values are expressed in hexadecimal notation. * The range of values for any one color component is 0 to 255 (00 to ff). * For alpha, 00 is fully transparent and ff is fully opaque. * The order of expression is aabbggrr, where aa=alpha (00 to ff); bb=blue (00 to ff); gg=green (00 to ff); rr=red (00 to ff). * For example, if you want to apply a blue color with 50 percent opacity to an overlay, * you would specify the following when setting color value: 7fff0000, where alpha=0x7f, blue=0xff, green=0x00, and red=0x00. */ export class KmlColor { /** * Set the color of an object. */ set(color: string): void; /** * Returns the color of an object. */ get(): string; /** * red numerical value */ getR(): number; /** * red numerical value */ setR(r: number): void; /** * green numerical value */ getG(): number; /** * green numerical value */ setG(g: number): void; /** * blue numerical value */ getB(): number; /** * blue numerical value */ setB(b: number): void; /** * opacity value */ getA(): number; /** * opacity value */ setA(a: number): void; } /** * The event object used with all KMLObjects. * For more information about events, see the Document Object Model Events specification at http: */ export class KmlEvent { /** * Cancels the default action of the event. * For example, calling this method in a placemark click handler prevents the placemark's default balloon from popping up. */ preventDefault(): void; /** * Prevents event propagation. * For example, if click event handlers are set up on both the GEGlobe and GEWindow objects, * and stopPropagation is called in the GEGlobe click event handler, the GEWindow event handler will not be triggered when the globe is clicked. */ stopPropagation(): void; /** * The object to which the KMLEvent was originally dispatched. */ getTarget(): GEEventEmitter; /** * The target whose event listeners are currently being processed. */ getCurrentTarget: GEEventEmitter; /** * The current stage of the flow of events. */ getEventPhase(): GEEventPhaseEnum; /** * Indicates whether or not an event is a bubbling event. */ getBubbles(): boolean; /** * Indicates whether the event can be cancelled. * * Note: Currently, cancelable has no effect. */ getCancelable(): boolean; } /** * Represents a mouse input event. */ export class KmlMouseEvent extends KmlEvent { /** * The button on the mouse was pressed. * Possible values include 0, 1, 2, where 0 is left, 1 is middle, and 2 is right mouse key. */ getButton(): number; /** * The x coordinate at which the event occurred, measured in pixels from the left edge of the plug-in window. */ getClientX(): number; /** * The y coordinate at which the event occurred, measured in pixels from the top edge of the plug-in window. */ getClientY(): number; /** * The x coordinate at which the event occurred, measured in pixels from the left edge of the computer screen. */ getScreenX(): number; /** * The y coordinate at which the event occurred, measured in pixels from the top edge of the computer screen. */ getScreenY(): number; /** * The latitude at which the event occurred, in decimal degrees. */ getLatitude(): number; /** * The longitude at which the event occurred, in decimal degrees. */ getLongitude(): number; /** * The altitude at which the event occurred, in meters. */ getAltitude(): number; /** * Indicates whether a mouse action occurred while on the Google Earth globe. */ getDidHitGlobe(): boolean; /** * Indicates whether the ALT key was held down when an event occurred. */ getAltKey(): boolean; /** * Indicates whether the CTRL key was held down when an event occurred. */ getCtrlKey(): boolean; /** * Indicates whether the SHIFT key was held down when an event occurred. */ getShiftKey(): boolean; /** * Used with the mouseover and mouseout events to specify a secondary target. * For mouseover, it specifies the object that the mouse was over. * For mouseout, it specifies the new object that the mouse is over. */ getRelatedTarget(): GEEventEmitter; /** * Returns the timestamp of the event, in Unix time. */ getTimeStamp(): number; } /** * Defines when and how an event gets passed in and triggered from the Google Earth Plug-in. */ export class GEEventEmitter { /** * Triggers an event when the user clicks a location in Google Earth with the mouse. */ click(event: KmlMouseEvent): void; /** * Triggers an event when the user double clicks a location in Google Earth with the mouse. */ dblclick(event: KmlMouseEvent): void; /** * Triggers an event when the user moves the mouse pointer over a location in Google Earth. */ mouseover(event: KmlMouseEvent): void; /** * Triggers an event when the user presses the mouse button over a location in Google Earth. */ mousedown(event: KmlMouseEvent): void; /** * Triggers an event when the user releases the mouse button over a location in Google Earth. */ mouseup(event: KmlMouseEvent): void; /** * Triggers an event when the user moves the mouse off of the object in Google Earth. */ mouseout(event: KmlMouseEvent): void; /** * Triggers an event when the user moves the mouse inside Google Earth. */ mousemove(event: KmlMouseEvent): void; } /** * The base class for all the other objects in the Google Earth Plug-in. * The methods and behavior of KMLObject are inherited by all other objects. * This is an abstract base class and cannot be used directly. * It provides the id attribute, which allows unique identification of an object. */ export class KmlObject extends GEEventEmitter { /** * The interface name (i.e. 'KmlPlacemark') of the object. */ getType(): string; /** * Test whether this object is the same as another object. * Useful for Chrome and Safari, where the comparison a==b sometimes fails for plugin objects. */ equals(compareTo: KmlObject): boolean; /** * The unique ID of the KML object. */ getId(): string; /** * The unique URL of the KML object. * This is the base address joined with the ID using the # character. * * For example: http://www.google.com/bar.kml#atlantis */ getUrl(): string; /** * The parent node of the KML object. */ getParentNode(): KmlObject; /** * The document that owns the KML object. */ getOwnerDocument(): KmlDocument; /** * Permanently deletes an object, allowing its ID to be reused. * Attempting to access the object once it is released will result in an error. */ release(): void; } /** * A collection of KmlObjects. */ export class KmlObjectList<T extends KmlObject> { /** * Gets an item from the object list. For example, list.item(0) returns the first object in the list. */ item(index: number): T; /** * Number of objects in collection. */ getLength(): number; } /** * The base class for KmlStyle and KmlStyleMap. */ export class KmlStyleSelector extends KmlObject {} /** * Defines the icon, label, line, list, polygon, and balloon styles. */ export class KmlStyle extends KmlStyleSelector { /** * Specifies how icons for point placemarks are drawn in Google Earth. */ getIconStyle(): KmlIconStyle; /** * Specifies how the name of a feature is drawn in the 3D viewer. * A custom color, color mode, and scale for the label (name) can be specified. */ getLabelStyle(): KmlLabelStyle; /** * Specifies the drawing style (color, color mode, and line width) for line geometry. * Line geometry includes the outlines of outlined polygons and the extruded tether of Placemark icons (if extrusion is enabled). */ getLineStyle(): KmlLineStyle; /** * Specifies the style for list geometry. */ getListStyle(): KmlListStyle; /** * Specifies the drawing style for polygons, including polygon extrusions (which look like the walls of buildings) and line extrusions (which look like solid fences). */ getPolyStyle(): KmlPolyStyle; /** * Specifies the drawing style for balloons. */ getBalloonStyle(): KmlBalloonStyle; } /** * The KmlColorStyle object is an abstract object. * It specifies the color and color mode of extended style types. */ export class KmlColorStyle extends KmlObject { /** * Color and opacity (alpha) values. */ getColor(): KmlColor; /** * Specifies which color mode effect to apply to the base color. * * See also: * * * GEPlugin.COLOR_NORMAL * * GEPlugin.COLOR_INHERIT * * GEPlugin.COLOR_RANDOM */ getColorMode(): KmlColorModeEnum; /** * Specifies which color mode effect to apply to the base color. * * See also: * * * GEPlugin.COLOR_NORMAL * * GEPlugin.COLOR_INHERIT * * GEPlugin.COLOR_RANDOM */ setColorMode(colorMode: KmlColorModeEnum): void; } /** * Specifies how icons for point placemarks are drawn in Google Earth. * The icon property specifies the icon image. * The scale property specifies the x, y scaling of the icon. * The color specified in the color property of KmlIconStyle is blended with the color of the Icon. */ export class KmlIconStyle extends KmlColorStyle { /** * Resizes the icon. */ getScale(): number; /** * Resizes the icon. */ setScale(scale: number): void; /** * The direction that icons are set to point, clockwise, and in degrees. */ getHeading(): number; /** * The direction that icons are set to point, clockwise, and in degrees. */ setHeading(heading: number): void; /** * A custom Icon. In KmlIconStyle, the only child element of KmlIcon is href and href is an HTTP address or a local file specification used to load an icon. */ getIcon(): KmlIcon; /** * A custom Icon. In KmlIconStyle, the only child element of KmlIcon is href and href is an HTTP address or a local file specification used to load an icon. */ setIcon(icon: KmlIcon): void; /** * Specifies the position within the Icon that is anchored to the point specified in the placemark. * The x and y values can be specified in three different ways: as pixels, as fractions of the icon, or as inset pixels, which is an offset in pixels from the upper right corner of the icon. * The x and y positions can be specified in different ways. * For example, x can be in pixels and y can be a fraction. * The origin of the coordinate system is in the lower left corner of the icon. */ getHotSpot(): KmlVec2; } /** * Specifies how the name of a feature is drawn in the 3D viewer. * A custom color, color mode, and scale for the label (name) can be specified. */ export class KmlLabelStyle extends KmlColorStyle { /** * Resizes the label. */ getScale(): number; /** * Resizes the label. */ setScale(scale: number): void; } /** * The KmlLineStyle object specifies the drawing style (color, color mode, and line width) for all line geometry. * Line geometry includes the outlines of outlined polygons and the extruded "tether" of Placemark icons (if extrusion is enabled). */ export class KmlLineStyle extends KmlColorStyle { /** * Width of the line, in pixels. */ getWidth(): number; /** * Width of the line, in pixels. */ setWidth(width: number): void; } /** * Specifies the drawing style for all polygons, including polygon extrusions (which look like the walls of buildings) and line extrusions (which look like solid fences). */ export class KmlPolyStyle extends KmlColorStyle { /** * Specifies whether or not to fill the polygon. Possible values 1 (fill) and 0 (no fill). */ getFill(): boolean; /** * Specifies whether or not to fill the polygon. Possible values 1 (fill) and 0 (no fill). */ setFill(fill: boolean): void; /** * Specifies whether to outline the polygon. Polygon outlines use the current KmlLineStyle. */ getOutline(): boolean; /** * Specifies whether to outline the polygon. Polygon outlines use the current KmlLineStyle. */ setOutline(outline: boolean): void; } /** * Specifies how a feature is displayed in the list view. */ export class KmlListStyle extends KmlObject { /** * Background color for the Snippet. */ getBgColor(): KmlColor; /** * Maximum number of lines of text for the Snippet. */ getMaxSnippetLines(): number; /** * Maximum number of lines of text for the Snippet. */ setMaxSnippetLines(maxSnippetLines: number): void; /** * Specifies how a feature should be displayed in a list view. */ getListItemType(): KmlListItemTypeEnum; } /** * Specifies how the description balloon for placemarks is drawn. */ export class KmlBalloonStyle extends KmlObject { /** * Background color of the balloon (optional). */ getBgColor(): KmlColor; /** * Foreground color for text. The default is black (ff000000). */ getTextColor(): KmlColor; /** * The text contained in the balloon. */ getText(): string; /** * The text contained in the balloon. */ setText(text: string): void; } /** * Specifies the top, bottom, right, and left sides of a bounding box on the Earth's surface. */ export class KmlLatLonBox extends KmlObject { /** * Sets the north, south, east, and west edges of the bounding box, as well as the rotation of the overlay. */ setBox( north: number, south: number, east: number, west: number, rotation: number ): void; /** * Specifies the latitude of the north edge of the bounding box, in decimal degrees from -90 to 90. */ getNorth(): number; /** * Specifies the latitude of the north edge of the bounding box, in decimal degrees from -90 to 90. */ setNorth(north: number): void; /** * Specifies the latitude of the south edge of the bounding box, in decimal degrees from -90 to 90. */ getSouth(): number; /** * Specifies the latitude of the south edge of the bounding box, in decimal degrees from -90 to 90. */ setSouth(south: number): void; /** * Specifies the longitude of the east edge of the bounding box, in decimal degrees from -180 to 180. * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) */ getEast(): number; /** * Specifies the longitude of the east edge of the bounding box, in decimal degrees from -180 to 180. * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) */ setEast(east: number): void; /** * Specifies the longitude of the west edge of the bounding box, in decimal degrees from -180 to 180. * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) */ getWest(): number; /** * Specifies the longitude of the west edge of the bounding box, in decimal degrees from -180 to 180. * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) */ setWest(west: number): void; /** * Specifies a rotation of the overlay about its center, in degrees. * Values can be +/-180. The default is 0 (north). * Rotations are specified in a counterclockwise direction. */ getRotation(): number; /** * Specifies a rotation of the overlay about its center, in degrees. * Values can be +/-180. The default is 0 (north). * Rotations are specified in a counterclockwise direction. */ setRotation(rotation: number): void; } /** * Specifies a bounding box that describes an area of interest defined by geographic coordinates and altitudes. */ export class KmlLatLonAltBox extends KmlLatLonBox { /** * Sets the north, south, east, west, rotation, minAltitude, maxAltitude, and altitudeMode of bounding box. */ setAltBox( north: number, south: number, east: number, west: number, rotation: number, minAltitude: number, maxAltitude: number, altitudeMode: KmlAltitudeModeEnum ): void; /** * Minimum altitude, specified in meters above sea level. */ getMinAltitude(): number; /** * Minimum altitude, specified in meters above sea level. */ setMinAltitude(minAltitude: number): void; /** * Maximim altitude, specified in meters above sea level. */ getMaxAltitude(): number; /** * Maximim altitude, specified in meters above sea level. */ setMaxAltitude(maxAltitude: number): void; /** * Specifies how the altitude property is interpreted. * * See also: * * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND * * GEPlugin.ALTITUDE_ABSOLUTE * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR */ getAltitudeMode(): KmlAltitudeModeEnum; /** * Specifies how the altitude property is interpreted. * * See also: * * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND * * GEPlugin.ALTITUDE_ABSOLUTE * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR */ setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): number; } /** * The KmlLod or level of detail, describes the size of the projected region on the screen that is required in order for the region to be considered active. * Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). */ export class KmlLod extends KmlObject { /** * Sets the minLodPixels, maxLodPixels, minFadeExtent, and maxFadeExtent for the projected region on the screen. */ set( minLodPixels: number, maxLodPixels: number, minFadeExtent: number, maxFadeExtent: number ): void; /** * Specifies measurement in screen pixels that represents the minimum limit of the visibility range for a given Region. * Google Earth calculates the size of the region when projected onto screen space. * Then it computes the square root of the region's area (if, for example, the Region is square and the viewpoint is directly above the Region, and the Region is not tilted, this measurement is equal to the width of the projected Region). * If this measurement falls within the limits defined by minLodPixels and maxLodPixels (and if the LatLonAltBox is in view), the region is active. * If this limit is not reached, the associated geometry is considered to be too far from the user's viewpoint to be drawn. */ getMinLodPixels(): number; /** * Specifies measurement in screen pixels that represents the minimum limit of the visibility range for a given Region. * Google Earth calculates the size of the region when projected onto screen space. * Then it computes the square root of the region's area (if, for example, the Region is square and the viewpoint is directly above the Region, and the Region is not tilted, this measurement is equal to the width of the projected Region). * If this measurement falls within the limits defined by minLodPixels and maxLodPixels (and if the LatLonAltBox is in view), the region is active. * If this limit is not reached, the associated geometry is considered to be too far from the user's viewpoint to be drawn. */ setMinLodPixels(minLodPixels: number): void; /** * Measurement in screen pixels that represents the maximum limit of the visibility range for a given Region. * A value of -1, the default, indicates "active to infinite size." */ getMaxLodPixels(): number; /** * Measurement in screen pixels that represents the maximum limit of the visibility range for a given Region. * A value of -1, the default, indicates "active to infinite size." */ setMaxLodPixels(maxLogPixels: number): void; /** * Distance over which the geometry fades, from fully opaque to fully transparent. * This ramp value, expressed in screen pixels, is applied at the minimum end of the LOD (visibility) limits. */ getMinFadeExtent(): number; /** * Distance over which the geometry fades, from fully opaque to fully transparent. * This ramp value, expressed in screen pixels, is applied at the minimum end of the LOD (visibility) limits. */ setMinFadeExtent(minFadeExtent: number): void; /** * Distance over which the geometry fades, from fully transparent to fully opaque. * This ramp value, expressed in screen pixels, is applied at the maximum end of the LOD (visibility) limits. */ getMaxFadeExtent(): number; /** * Distance over which the geometry fades, from fully transparent to fully opaque. * This ramp value, expressed in screen pixels, is applied at the maximum end of the LOD (visibility) limits. */ setMaxFadeExtent(maxFadeExtent: number): void; } /** * The KmlRegion object is used to set region objects and their properties. * A region contains a bounding box (LatLonAltBox) that describes an area of interest defined by geographic coordinates and altitudes. * In addition, a Region contains an LOD (level of detail) extent that defines a validity range of the associated Region in terms of projected screen size. * A Region is said to be "active" when the bounding box is within the user's view and the LOD requirements are met. * Objects associated with a Region are drawn only when the Region is active. * When the viewRefreshMode is onRegion, the Link or Icon is loaded only when the Region is active. */ export class KmlRegion extends KmlObject { /** * Sets the latLonAltBox and lod for the region. */ set(latLonAltBox: KmlLatLonAltBox, lod: KmlLod): void; /** * A bounding box that describes an area of interest defined by geographic coordinates and altitudes. */ getLatLonAltBox(): KmlLatLonAltBox; /** * A bounding box that describes an area of interest defined by geographic coordinates and altitudes. */ setLatLonAltBox(latLonAltBox: KmlLatLonAltBox): void; /** * LOD is an abbreviation for Level of Detail. * Lod describes the size of the projected region on the screen that is required in order for the region to be considered "active. * " Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). */ getLod(): KmlLod; /** * LOD is an abbreviation for Level of Detail. * Lod describes the size of the projected region on the screen that is required in order for the region to be considered "active. * " Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). */ setLod(lod: KmlLod): void; } /** * Represents a specific point in time. * The plugin accepts time in this format only; it does not accept JavaScript date or time objects. */ export class KmlDateTime { /** * Set the date. Accepts only XML Schema time (see XML Schema Part 2: Datatypes Second Edition). * The value can be expressed as yyyy-mm-ddThh:mm:sszzzzzz, where T is the separator between the date and the time, * and the time zone is either Z(for UTC) or zzzzzz, which represents +/-hh:mm in relation to UTC. * Additionally, the value can be expressed as a date only. */ set(date: string): void; /** * Returns the date and time in XML Schema time format. */ get(): string; } /** * An abstract object and cannot be used directly in a JavaScript file. * This element is extended by the TimeSpan and TimeStamp objects. */ export class KmlTimePrimitive extends KmlObject {} /** * Represents a single moment in time. * This is a simple element and contains no children. * Its value is a dateTime, specified in XML time. * The precision of the TimeStamp is dictated by the dateTime value in the when property. */ export class KmlTimeStamp extends KmlTimePrimitive { /** * Represents a single moment in time. * This is a simple element and contains no children. * Its value is a dateTime, specified in XML time. * The precision of the TimeStamp is dictated by the dateTime value in the when property. * * * dateTime gives second resolution * * date gives day resolution * * gYearMonth gives month resolution * * gYear gives year resolution */ getWhen(): KmlDateTime; } /** * Represents an extent in time bounded by begin and end dateTimes. */ export class KmlTimeSpan extends KmlTimePrimitive { /** * Describes the beginning instant of a time period. * If absent, the beginning of the period is unbounded. */ getBegin(): KmlDateTime; /** * Describes the ending instant of a time period. * If absent, the end of the period is unbounded. */ getEnd(): KmlDateTime; } /** * This is an abstract class and cannot be created directly. * This class is extended by KmlCamera and KmlLookAt. */ export class KmlAbstractView extends KmlObject { /** * Creates a new KmlLookAt object that matches as closely as possible this KmlAbstractView. * KmlLookAt is unable to represent roll, so roll values in the current view will not be passed to the new KmlLookAt object. * * If this view is already a KmlLookAt, this function returns a new KmlLookAt representing the same view. */ copyAsLookAt(): KmlLookAt; /** * Creates a new KmlCamera object that matches this KmlAbstractView. * * If this view is already a KmlCamera, this function returns a new KmlCamera representing the same view. */ copyAsCamera(): KmlCamera; /** * Returns the KmlTimeStamp or KmlTimeSpan object associated with this view. */ getTimePrimitive(): KmlTimePrimitive; /** * Associate a KmlTimeStamp or KmlTimeSpan object with this view. */ setTimePrimitive(timePrimitive: KmlTimePrimitive): void; /** * Returns the viewer options on the current view. * * See also: * * * GEPlugin.OPTION_STREET_VIEW * * GEPlugin.OPTION_SUNLIGHT * * GEPlugin.OPTION_HISTORICAL_IMAGERY */ getViewerOptions(): KmlViewerOptions; /** * Sets the viewer options on the current view. * * See also: * * * GEPlugin.OPTION_STREET_VIEW * * GEPlugin.OPTION_SUNLIGHT * * GEPlugin.OPTION_HISTORICAL_IMAGERY */ setViewerOptions(viewerOptions: KmlViewerOptions): void; } /** * Defines a camera that is associated with anything derived from feature. * The LookAt element positions the "camera" in relation to the object that is being viewed. * This class either positions the relative to a feature, or you can manually change the view, using ge.getView().setAbstractView(). */ export class KmlLookAt extends KmlAbstractView { /** * Sets the latitude, longitude, altitude, altitudeMode, heading, tilt, and range for the camera. */ set ( latitude: number, longitude: number, altitude: number, altitudeMode: KmlAltitudeModeEnum, heading: number, tilt: number, range: number ): void; /** * Latitude of the point the camera is looking at. * Degrees north or south of the Equator (0 degrees). * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). */ getLatitude(): number; /** * Latitude of the point the camera is looking at. * Degrees north or south of the Equator (0 degrees). * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). */ setLatitude(latitude: number): void; /** * Latitude of the point the camera is looking at. * Degrees north or south of the Equator (0 degrees). * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). */ getLongitude(): number; /** * Latitude of the point the camera is looking at. * Degrees north or south of the Equator (0 degrees). * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). */ setLongitude(longitude: number): void; /** * The distance in meters from the point specified by longitude, latitude, and altitude for the LookAt position. */ getRange(): number; /** * The distance in meters from the point specified by longitude, latitude, and altitude for the LookAt position. */ setRange(range: number): void; /** * Angle between the direction of the LookAt position and the normal to the surface of the earth. * Values range from 0 to 90 degrees. Values for tilt cannot be negative. * A tilt value of 0 degrees indicates viewing from directly above. * A tilt value of 90 degrees indicates viewing along the horizon. */ getTilt(): number; /** * Angle between the direction of the LookAt position and the normal to the surface of the earth. * Values range from 0 to 90 degrees. Values for tilt cannot be negative. * A tilt value of 0 degrees indicates viewing from directly above. * A tilt value of 90 degrees indicates viewing along the horizon. */ setTilt(tilt: number): void; /** * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. */ getHeading(): number; /** * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. */ setHeading(heading: number): void; /** * Distance from the earth's surface, in meters. */ getAltitude(): number; /** * Distance from the earth's surface, in meters. */ setAltitude(altitude: number): void; /** * Specifies how altitude components in the coordinates element are interpreted. */ getAltitudeMode(): KmlAltitudeModeEnum; /** * Specifies how altitude components in the coordinates element are interpreted. */ setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; } /** * Defines the camera that views the scene. * This element defines the position of the camera relative to the Earth's surface as well as the viewing direction of the camera. * The camera position is defined by longitude, latitude, altitude, and altitudeMode. * The viewing direction of the camera is defined by heading, tilt, and roll. * Camera can be a child element of any feature. */ export class KmlCamera extends KmlAbstractView { /** * Sets the latitude, longitude, altitude, alitudeMode, heading, tilt, and roll values. */ set( latitude: number, longitude: number, altitude: number, altitudeMode: KmlAltitudeModeEnum, heading: number, tilt: number, roll: number ): void; /** * Latitude of the camera location. Degrees north or south of the Equator (0 degrees). Values range from -90 degrees to 90 degrees. */ getLatitude(): number; /** * Latitude of the camera location. Degrees north or south of the Equator (0 degrees). Values range from -90 degrees to 90 degrees. */ setLatitude(latitude: number): void; /** * Longitude of the camera location. Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. * Values east of the Meridian range from 0 to 180 degrees. */ getLongitude(): number; /** * Longitude of the camera location. Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. * Values east of the Meridian range from 0 to 180 degrees. */ setLongitude(longitude: number): void; /** * Distance from the earth's surface. */ getAltitude(): number; /** * Distance from the earth's surface. */ setAltitude(altitude: number): void; /** * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. */ getHeading(): number; /** * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. */ setHeading(heading: number): void; /** * Angle between the direction of the camera position and the normal to the surface of the earth. Values range from 0 to 360 degrees. * A tilt value of 0 degrees indicates viewing from directly above, 90 degrees indicates viewing along the horizon, and 180 degrees indicates viewing straight up at the sky. */ getTilt(): number; /** * Angle between the direction of the camera position and the normal to the surface of the earth. Values range from 0 to 360 degrees. * A tilt value of 0 degrees indicates viewing from directly above, 90 degrees indicates viewing along the horizon, and 180 degrees indicates viewing straight up at the sky. */ setTilt(tilt: number): void; /** * Rotation, in degrees, of the camera around the Z axis. Values range from -180 to +180 degrees. */ getRoll(): number; /** * Rotation, in degrees, of the camera around the Z axis. Values range from -180 to +180 degrees. */ setRoll(roll: number): void; /** * Specifies how altitude components in the coordinates are interpreted. */ getAltitudeMode(): KmlAltitudeModeEnum; /** * Specifies how altitude components in the coordinates are interpreted. */ setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; } /** * The KmlGeometry object is an abstract object and cannot be used directly. * It provides a placeholder object for all derived Geometry objects. */ export class KmlGeometry extends KmlObject {} /** * Specifies an AltitudeMode for derived classes. */ export class KmlAltitudeGeometry extends KmlGeometry { /** * Specifies how altitude components in the geometry coordinates are interpreted. */ getAltitudeMode(): KmlAltitudeModeEnum; /** * Specifies how altitude components in the geometry coordinates are interpreted. */ setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; } /** * A 3D object described in a referenced COLLADA file. * COLLADA files have a .dae file extension. * Models are created in their own coordinate space and then located, positioned, and scaled in Google Earth. * Google Earth supports the COLLADA common profile, with the following exceptions: * * * Google Earth supports only triangles and lines as primitive types. The maximum number of triangles allowed is 21845. * * Google Earth does not support animation or skinning. * * Google Earth does not support external geometry references. */ export class KmlModel extends KmlAltitudeGeometry { /** * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. */ getLocation(): KmlLocation; /** * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. */ setLocation(location: KmlLocation): void; /** * Describes rotation of a 3D model's coordinate system to position the object in Google Earth. */ getOrientation(): KmlOrientation; /** * Describes rotation of a 3D model's coordinate system to position the object in Google Earth. */ setOrientation(orientation: KmlOrientation): void; /** * Scales a model along the x, y, and z axes in the model's coordinate space */ getScale(): KmlScale; /** * Scales a model along the x, y, and z axes in the model's coordinate space */ setScale(scale: KmlScale): void; /** * Returns the link of the collada model. */ getLink(): KmlLink; /** * Sets the link of the collada model. */ setLink(link: KmlLink): void; } /** * A container for zero or more geometry primitives associated with the same feature. */ export class KmlMultiGeometry extends KmlGeometry { /** * The collection of geometries that are children of this multi-geometry. */ getGeometries(): GEGeometryContainer; } /** * Specifies the behavior of the object's geometry. */ export class KmlExtrudableGeometry extends KmlAltitudeGeometry { /** * Specifies whether to connect the geometry to the ground. */ getExtrude(): boolean; /** * Specifies whether to connect the geometry to the ground. */ setExtrude(extrude: boolean): void; /** * Specifies whether to allow the geometry to follow the terrain elevation. */ getTessellate(): boolean; /** * Specifies whether to allow the geometry to follow the terrain elevation. */ setTessellate(tessellate: boolean): void; } /** * A Polygon is defined by an outer boundary and 0 or more inner boundaries. * The boundaries, in turn, are defined by LinearRings. * When a Polygon is extruded, its boundaries are connected to the ground to form additional polygons, which gives the appearance of a building or a box. * Extruded Polygons use PolyStyle for their color, color mode, and fill. */ export class KmlPolygon extends KmlExtrudableGeometry { /** * Contains a LinearRing element. */ getOuterBoundary(): KmlLinearRing; /** * Contains a LinearRing element. */ setOuterBoundary(outerBoundary: KmlLinearRing): void; /** * Contains a LinearRing element. * You can specify multiple innerBoundary properties, which create multiple cut-outs inside the Polygon. */ getInnerBoundaries(): GELinearRingContainer; } /** * A geographic location defined by longitude, latitude, and (optional) altitude. * When a Point is contained by a Placemark, the point itself determines the position of the Placemark's name and icon. * When a Point is extruded, it is connected to the ground with a line. This tether uses the current LineStyle. */ export class KmlPoint extends KmlExtrudableGeometry { /** * Sets altitudeMode, extrude, tessellate, latitude, longitude, and altitude values. */ set( latitude: number, longitude: number, altitude: number, altitudeMode: KmlAltitudeModeEnum, extrude: boolean, tessellate: boolean ): void; /** * Sets the latitude and longitude. */ setLatLng(latitude: number, longitude: number): void; /** * Sets the latitude, longitude, and altitide. */ setLatLngAlt(latitude: number, longitude: number, altitude: number): void; /** * The point's latitude, in degrees. */ getLatitude(): number; /** * The point's latitude, in degrees. */ setLatitude(latitude: number): void; /** * The point's longitude, in degrees. */ getLongitude(): number; /** * The point's longitude, in degrees. */ setLongitude(longitude: number): void; /** * The point's altitude, in meters. */ getAltitude(): number; /** * The point's altitude, in meters. */ setAltitude(altitude: number): void; } /** * Defines a connected set of line segments. * Use KmlLineStyle to specify the color, color mode, and width of the line. * When a LineString is extruded, the line is extended to the ground, forming a polygon that looks somewhat like a wall or fence. * For extruded LineStrings, the line itself uses the current LineStyle, and the extrusion uses the current PolyStyle. */ export class KmlLineString extends KmlExtrudableGeometry { /** * Two or more coordinate tuples, each consisting of floating point values for longitude, latitude, and altitude. * The altitude component is optional. */ getCoordinates(): KmlCoordArray; /** * Added to the altitude values for all points on the line string. * Adjusts the altitude of the feature as a whole, without the need to update each coordinate set. */ setAltitudeOffset(altitudeOffset: number): void; /** * Returns the altitudeOffset, or 0 if not set. */ getAltitudeOffset(): number; } /** * Defines a closed line string, typically the outer boundary of a Polygon. * Optionally, a LinearRing can also be used as the inner boundary of a Polygon to create holes in the Polygon. * A Polygon can contain multiple LinearRing elements used as inner boundaries. * You do not need to connect the first and last points. */ export class KmlLinearRing extends KmlLineString {} /** * The KmlFeature object is an abstract object and is the base for all feature types (for example Placemarks, Overlays, and NetworkLinks). */ export class KmlFeature extends KmlObject { /** * Retrieves the contents of the feature's <ExtendedData> element. * The retrieved contents are scrubbed to remove JavaScript; CSS; and iframe, embed, and object tags. * * It should be safe to insert the resulting HTML into your page without concern for malicious content embedded in the feature data; * however any feature depending on CSS or Javascript will not work. */ getBalloonHtml(): string; /** * Retrieves the contents of the feature's <ExtendedData> element. The contents are not scrubbed. * Use this method only if you trust the source of the feature data. */ getBalloonHtmlUnsafe(): string; /** * User-defined text displayed in the plugin as the label for the object (for example, for a Placemark). */ getName(): string; /** * User-defined text displayed in the plugin as the label for the object (for example, for a Placemark). */ setName(name: string): void; /** * Specifies whether the feature is drawn in the plugin. * In order for a feature to be visible, the visibility of all its ancestors must also be set to true. * In the Google Earth List View, each feature has a checkbox that allows the user to control visibility of the feature. */ getVisibility(): boolean; /** * Specifies whether the feature is drawn in the plugin. * In order for a feature to be visible, the visibility of all its ancestors must also be set to true. * In the Google Earth List View, each feature has a checkbox that allows the user to control visibility of the feature. */ setVisibility(visibility: boolean): void; /** * Default state of left panel. */ getOpen(): boolean; /** * Default state of left panel. */ setOpen(open: boolean): void; /** * Specifies a value representing an unstructured address written as a standard street, city, state address, and/or as a postal code. */ getAddress(): string; /** * Specifies a value representing an unstructured address written as a standard street, city, state address, and/or as a postal code. */ setAddress(address: string): void; /** * Specifies a short description of the feature. */ getSnippet(): string; /** * Specifies a short description of the feature. */ setSnippet(snippet: string): void; /** * User-supplied text that appears in the description balloon. */ getDescription(): string; /** * User-supplied text that appears in the description balloon. */ setDescription(description: string): void; /** * Stores either the lookAt or camera view. */ getAbstractView(): KmlAbstractView; /** * Stores either the lookAt or camera view. */ setAbstractView(abstractView: KmlAbstractView): void; /** * URI of a Style or StyleMap defined in a Document. * It refers to a Plug-in intitiated object. */ getStyleUrl(): string; /** * URI of a Style or StyleMap defined in a Document. * It refers to a Plug-in intitiated object. */ setStyleUrl(styleUrl: string): void; /** * The style based on the current mode of the Placemark. */ getStyleSelector(): KmlStyleSelector; /** * The style based on the current mode of the Placemark. */ setStyleSelector(styleSelector: KmlStyleSelector): void; /** * Specifies region objects and their properties. * A region contains a bounding box (LatLonAltBox) that describes an area of interest defined by geographic coordinates and altitudes. */ getRegion(): KmlRegion; /** * Specifies region objects and their properties. * A region contains a bounding box (LatLonAltBox) that describes an area of interest defined by geographic coordinates and altitudes. */ setRegion(region: KmlRegion): void; /** * Returns the KML for a feature. */ getKml(): string; /** * Returns previous sibling node within the container. */ getPreviousSibling(): KmlFeature; /** * Returns the next sibling node within the container. */ getNextSibling(): KmlFeature; /** * Returns the KmlTimeStamp or KmlTimeSpan object associated with this feature. */ getTimePrimitive(): KmlTimePrimitive; /** * Attach a KmlTimeStamp or KmlTimeSpan object to this feature. */ setTimePrimitive(timePrimitive: KmlTimePrimitive): void; /** * Returns the computed style of a feature, merging any inline styles with styles imported from setHref() or a StyleUrl. * * Note: Modifying the returned KmlStyle object is undefined and not recommended. */ getComputedStyle(): KmlStyle; /** * Experimental Feature — this is an experimental feature and can change (or even be removed) at any time. * The opacity of a feature, ranging from 0 (completely transparent) to 1 (complete opaque). * The opacity of a folder or document will influence the opacity of child features. * Thus, if a folder has an opacity of 0.5 and a child ground overlay in the folder also has an opacity of 0.5, the overlay will be drawn with an opacity of 0.25. */ getOpacity(): number; /** * Experimental Feature — this is an experimental feature and can change (or even be removed) at any time. * The opacity of a feature, ranging from 0 (completely transparent) to 1 (complete opaque). * The opacity of a folder or document will influence the opacity of child features. * Thus, if a folder has an opacity of 0.5 and a child ground overlay in the folder also has an opacity of 0.5, the overlay will be drawn with an opacity of 0.25. */ setOpacity(opacity: number): void; } /** * An abstract object and cannot be used directly. * A KmlContainer object holds one or more features and allows the creation of nested hierarchies. */ export class KmlContainer extends KmlFeature { /** * Get an element by ID. * This is functionally equivalent to getElementByUrl with an unspecified base URL. * * For example: getElementByUrl('#foo'). * * Usage is when finding objects created with JavaScript, which have unspecified base URLs. * The object must be a descendant of the container before it can be found. */ getElementById(id: string): KmlObject; /** * Get an element by URL. A URL consists of the base address and ID, joined with the # character. * * For example: http://www.google.com/bar.kml#here_be_monsters * * This applies to objects that are fetched. * In the case of plugin created objects, the URL is simply #foo. * The object must be a descendant of the container before it can be found. */ getElementByUrl(url: string): KmlObject; /** * Get an element by type. */ getElementsByType(type: string): KmlObjectList<KmlObject>; /** * A collection of features, such as name, description, and so on. */ getFeatures(): GEFeatureContainer; } /** * A Folder is used to arrange other features hierarchically (Folders, Placemarks, NetworkLinks, or Overlays). * A feature is visible only if it and all of its ancestors are visible. */ export class KmlFolder extends KmlContainer {} /** * A layer displayed in Google Earth. */ export class KmlLayer extends KmlFolder {} /** * A container for the various layers displayed with the Google Earth Plug-in. * It contains the same layers as Google Earth. */ export class KmlLayerRoot extends KmlFolder { /** * Returns the layer based on the layer's ID. */ getLayerById(id: string): KmlLayer; /** * Enables a layer based on its ID. */ enableLayerById(id: string, visibility: boolean): void; /** * Returns the drawing order for this database. */ getDrawOrder(): number; /** * Defines the drawing order for databases. * Drawing order is lowest to highest. * Google Earth Enterprise customers can add a side database and set the drawOrder to be either before or after that of the main database. * Side databases default to a drawing order of 0. */ setDrawOrder(drawOrder: number): void; } /** * A KmlDocument has containers that holds features and styles. * This container is required if you use shared styles. * It is recommended that you use shared styles, which require the following. * * 1. Define all Styles in a Document. Assign a unique ID to each Style. * 2. Within a given feature or StyleMap, reference the Style's ID using a styleUrl element. * * Note: Shared styles are not inherited by the features in the Document. */ export class KmlDocument extends KmlContainer { /** * Returns a list of elements using a particular style URL. */ getElementsByStyleUrl(styleUrl: string): KmlObjectList<KmlObject>; /** * Returns an array containing the style selectors present in the KML document. */ getStyleSelectors(): GEStyleSelectorContainer; } /** * The KmlPlacemark is a feature with associated Geometry. */ export class KmlPlacemark extends KmlFeature { /** * The geometry associated with the placemark. */ getGeometry(): KmlGeometry; /** * The geometry associated with the placemark. */ setGeometry(geometry: KmlGeometry): void; } /** * The base class for the three types of balloon windows that can overlay the 3D window. */ export class GEAbstractBalloon { /** * The ID of the balloon. */ getId(): string; /** * The ID of the balloon. */ setId(id: string): void; /** * Determines what the balloon is attached to. */ getFeature(): KmlFeature; /** * Determines what the balloon is attached to. */ setFeature(feature: KmlFeature): void; /** * Minimum width of the balloon. */ getMinWidth(): number; /** * Minimum width of the balloon. */ setMinWidth(minWidth: number): void; /** * Minimum height of the balloon. */ getMinHeight(): number; /** * Minimum height of the balloon. */ setMinHeight(minHeight: number): void; /** * Maximum width of the balloon. */ getMaxWidth(): number; /** * Maximum width of the balloon. */ setMaxWidth(maxWidth: number): void; /** * Maximum height of the balloon. */ getMaxHeight(): number; /** * Maximum height of the balloon. */ setMaxHeight(maxHeight: number): void; /** * When true, the balloon frame is displayed with a button that the user * can click to close the balloon. When false, the balloon frame is just * a plain frame. * * Default is true. */ getCloseButtonEnabled(): boolean; /** * When true, the balloon frame is displayed with a button that the user * can click to close the balloon. When false, the balloon frame is just * a plain frame. * * Default is true. */ setCloseButtonEnabled(closeButtonEnabled: boolean): void; } /** * Base class for GEHtmlStringBalloon and GEHtmlDivBalloon. */ export class GEFeatureBalloon extends GEAbstractBalloon {} /** * Creates a balloon that contains HTML. */ export class GEHtmlBalloon extends GEAbstractBalloon { /** * The color of the text in the balloon. * This must be set using the HTML hex format #RRGGBB. * If not set, it is interpreted as #000000. */ getForegroundColor(): string; /** * The color of the text in the balloon. * This must be set using the HTML hex format #RRGGBB. * If not set, it is interpreted as #000000. */ setForegroundColor(foregroundColor: string): void; /** * The background color of the balloon. * This must be set using the HTML hex format #RRGGBB. * If not set, the default is interpreted as #FFFFFF. */ getBackgroundColor(): string; /** * The background color of the balloon. * This must be set using the HTML hex format #RRGGBB. * If not set, the default is interpreted as #FFFFFF. */ setBackgroundColor(backgroundColor: string): void; } /** * The GEHtmlDivBalloon object creates a balloon based on the contentDiv property. */ export class GEHtmlDivBalloon extends GEHtmlBalloon { /** * An HTMLDivElement to be used as the contents of the balloon. * When the balloon is shown, the HTMLDivElement is attached to the balloon element in the web page. * You can manipulate this balloon using ordinary HTML DOM techniques. */ getContentDiv(): HTMLDivElement; /** * An HTMLDivElement to be used as the contents of the balloon. * When the balloon is shown, the HTMLDivElement is attached to the balloon element in the web page. * You can manipulate this balloon using ordinary HTML DOM techniques. */ setContentDiv(contentDiv: HTMLElement): void; } /** * The GEHtmlStringBalloon class represents a balloon based on the contentString. */ export class GEHtmlStringBalloon extends GEHtmlBalloon { /** * You can include any HTML using the contentString property. * When the balloon is visible, the content specified in contentString property, * is inserted directly into the balloon element in the web page. */ getContentString(): string; /** * You can include any HTML using the contentString property. * When the balloon is visible, the content specified in contentString property, * is inserted directly into the balloon element in the web page. */ setContentString(contentString: string): void; } /** * The base class for GETimeControl. */ export class GEControl {} /** * Represents the time slider object. */ export class GETimeControl extends GEControl { /** * Whether the time slider is visible or not. */ getVisibility(): GEVisibilityEnum; /** * Specifies whether the control is visible or hidden. */ setVisibility(visibility: GEVisibilityEnum): void; /** * Returns the clock rate that the plugin would use, if the play button on the time slider UI was pressed. * This rate is calculated by the plugin based on the time range currently present in the slider. */ getCalculatedRate(): number; /** * Returns a KmlTimeSpan object encompassing the earliest and latest times present in the time slider. * For more information, refer to the Time chapter of the Developer's Guide. */ getExtents(): KmlTimeSpan; /** * Returns an array containing the KmlTimeStamp objects associated with the historical imagery available in this view. */ getAvailableImageDates(): KmlObjectList<KmlTimeStamp>; } /** * The GEPlugin is the Google Earth Plugin's main object, and this is the object that is returned to the JavaScript application when you first create a plug-in instance. * GEPlugin provides factory methods for ructing other objects (placemarks, and so on), and is also used to retrieve the root document objects. */ export class GEPlugin { /** * A Specifies that altitudes are at ground level. For Ground overlays, this means that the image will be draped over the terrain. */ ALTITUDE_CLAMP_TO_GROUND: KmlAltitudeModeEnum; /** * Specifies that altitudes are to be interpreted as meters above or below ground level (i.e. the elevation of the terrain at the location). */ ALTITUDE_RELATIVE_TO_GROUND: KmlAltitudeModeEnum; /** * Specifies that altitudes are to be interpreted as meters above or below sea level, regardless of the actual elevation of the terrain beneath the object. * For example, if you set the altitude of an object to 10 meters with an absolute altitude mode, the object will appear to be at ground level if the terrain beneath is also 10 meters above sea level. * If the terrain is 3 meters above sea level, the object will appear elevated above the terrain by 7 meters. * If, on the other hand, the terrain is 15 meters above sea level, the object may be completely invisible. */ ALTITUDE_ABSOLUTE: KmlAltitudeModeEnum; /** * Specifies that altitudes are at sea floor level. */ ALTITUDE_CLAMP_TO_SEA_FLOOR: KmlAltitudeModeEnum; /** * Specifies that altitudes are to be interpreted as meters above sea floor (i.e. the elevation of the sea floor at the location). */ ALTITUDE_RELATIVE_TO_SEA_FLOOR: KmlAltitudeModeEnum; /** * Refresh when the file is loaded and whenever the Link parameters change. This refresh mode is the default. */ REFRESH_ON_CHANGE: KmlRefreshModeEnum; /** * Refresh every n seconds (specified in refreshInterval). */ REFRESH_ON_INTERVAL: KmlRefreshModeEnum; /** * Refresh when the expiration time is reached. * If a fetched file has a NetworkLinkControl, the expires time takes precedence over expiration times specified in HTTP headers. * If no expires time is specified, the HTTP max-age header is used (if present). * If max-age is not present, the Expires HTTP header is used (if present). */ REFRESH_ON_EXPIRE: KmlRefreshModeEnum; /** * Ignore changes in the view. Also ignore viewFormat parameters, if any. * This view refresh mode is the default. */ VIEW_REFRESH_NEVER: KmlViewRefreshModeEnum; /** * Refresh the file only when the user explicitly requests it. */ VIEW_REFRESH_ON_REQUEST: KmlViewRefreshModeEnum; /** * Refresh n seconds after movement stops, where n is specified in viewRefreshTime. */ VIEW_REFRESH_ON_STOP: KmlViewRefreshModeEnum; /** * Refresh only when the feature's Region becomes active. */ VIEW_REFRESH_ON_REGION: KmlViewRefreshModeEnum; /** * Screen coordinates are to be interpreted as a fraction of an item, like an image or Google Earth window. */ UNITS_FRACTION: KmlUnitsEnum; /** * Screen coordinates are to be interpreted as pixels from the left or bottom edge. */ UNITS_PIXELS: KmlUnitsEnum; /** * Screen coordinates are to be interpreted as pixels from the top or right edge. */ UNITS_INSET_PIXELS: KmlUnitsEnum; /** * Apply no color mode effect, i.e. use the base color as is. */ COLOR_NORMAL: KmlColorModeEnum; /** * Apply a random linear scale to the base color. See the KML <colorMode> documentation for more details. */ COLOR_RANDOM: KmlColorModeEnum; /** * Inherit the color mode from ancestor styles. */ COLOR_INHERIT: KmlColorModeEnum; /** * The Earth map type, used with GEOptions' setMapType. */ MAP_TYPE_EARTH: GEMapTypeEnum; /** * The Sky map type, used with GEOptions' setMapType. */ MAP_TYPE_SKY: GEMapTypeEnum; /** * Hide the UI element. */ VISIBILITY_HIDE: GEVisibilityEnum; /** * Show the UI element always. */ VISIBILITY_SHOW: GEVisibilityEnum; /** * Automatically show or hide the UI element depending on user interaction. */ VISIBILITY_AUTO: GEVisibilityEnum; /** * Specifies that fly-to should happen immediately, without a smooth transition. */ SPEED_TELEPORT: number; /** * The Layer ID of the terrain layer. Use as an argument to getLayerById() or enableLayerById(). */ LAYER_TERRAIN: string; /** * The Layer ID of the roads layer. Use as an argument to getLayerById() or enableLayerById(). */ LAYER_ROADS: string; /** * The Layer ID of the photorealistic buildings layer. Use as an argument to getLayerById() or enableLayerById(). */ LAYER_BUILDINGS: string; /** * The Layer ID of the low resolution (gray) buildings layer. * Use as an argument to getLayerById() or enableLayerById(). * Note that as photorealistic buildings continue to be created and added to the LAYER_BUILDINGS layer, the low-resolution version of those buildings will be removed from this layer. * This layer will therefore change over time. */ LAYER_BUILDINGS_LOW_RESOLUTION: string; /** * The Layer ID of the borders layer. Use as an argument to getLayerById() or enableLayerById(). */ LAYER_BORDERS: string; /** * The Layer ID of the trees layer. Use as an argument to getLayerById() or enableLayerById(). */ LAYER_TREES: string; /** * When using the GEView.hitTest method, this mode samples the globe (the earth's sphere at altitude 0, without terrain or buildings). */ HIT_TEST_GLOBE: GEHitTestModeEnum; /** * When using the GEView.hitTest method, this mode samples the earth's terrain (the ground surface, including variations in altitude). */ HIT_TEST_TERRAIN: GEHitTestModeEnum; /** * When using the GEView.hitTest method, this mode samples 3D buildings. */ HIT_TEST_BUILDINGS: GEHitTestModeEnum; /** * Sets the render state to its default value. Currently, sunlight, Street View, and historical imagery all default to a disabled state. */ OPTION_STATE_DEFAULT: GEViewerOptionsValueEnum; /** * Set the render state to on. Passed to the KmlViewerOptions.setOption method. */ OPTION_STATE_ENABLED: GEViewerOptionsValueEnum; /** * Set the render state to off. Passed to the KmlViewerOptions.setOption method. */ OPTION_STATE_DISABLED: GEViewerOptionsValueEnum; /** * Passed to the KmlViewerOptions.setOption method, along with a GEViewerOptionsValueEnum, to specify whether the Sun option should be visible. * Sun can also be enabled/disabled with GEPlugin.getSun. */ OPTION_SUNLIGHT: GEViewerOptionsTypeEnum; /** * Passed to the KmlViewerOptions.setOption method, along with a GEViewerOptionsValueEnum, to specify whether historical imagery should be enabled. */ OPTION_HISTORICAL_IMAGERY: GEViewerOptionsTypeEnum; /** * Passed to the KmlViewerOptions.setOption method, along with a GEViewerOptionsValueEnum, to specify whether Street View should be enabled when the view reaches ground level. * Note that this applies only to programmatic movement, such as fly-tos; to control whether the user can enter Street View using manual navigation controls, call ge.getPlugin().streetViewEnabled(true). */ OPTION_STREET_VIEW: GEViewerOptionsTypeEnum; /** * The feature's visibility is tied to its list item's checkbox state. */ LIST_ITEM_CHECK: KmlListItemTypeEnum; /** * When specified for a folder, document or network link, prevents all items from being made visible at once—that is, the user can turn all children off but cannot turn them all on at the same time. * This setting is useful for containers or network links containing large amounts of data. */ LIST_ITEM_CHECK_OFF_ONLY: KmlListItemTypeEnum; /** * Use a normal checkbox for visibility but do not display children in a list view. * The item's checkbox should allows the user to toggle visibility of the child objects in the viewport. */ LIST_ITEM_CHECK_HIDE_CHILDREN: KmlListItemTypeEnum; /** * When specified for a container (a folder or a document), only one of the container's items should be visible at a time. */ LIST_ITEM_RADIO_FOLDER: KmlListItemTypeEnum; /** * The large navigation control type, used with GENavigationControl.setControlType(). */ NAVIGATION_CONTROL_LARGE: GENavigationControlEnum; /** * The small navigation control type, used with GENavigationControl.setControlType(). */ NAVIGATION_CONTROL_SMALL: GENavigationControlEnum; /** * Parse a string of KML and return a handle to the root of the KML object structure that was created. */ parseKml(kml: string): KmlObject; /** * Get an element by ID. This is functionally equivalent to getElementByUrl with an unspecified base URL. * * For example: getElementByUrl('#foo'). * * Usage is when finding objects created with JavaScript, which have unspecified base URLs. * The object must be a descendant of the DOM before it can be found. */ getElementById(id: string): KmlObject; /** * Get an element by URL. A URL consists of the base address and the ID, joined with the # character. * * For example: http://www.google.com/bar.kml#here_be_monsters * * This applies to objects that are fetched. * In the case of plugin created objects, the URL is simply #foo. * The object must be a descendant of the DOM before it can be found. */ getElementByUrl(url: string): KmlObject; /** * Get a list of elements by type. */ getElementsByType(): KmlObjectList<KmlObject>; /** * Creates a placemark on the globe. * A Placemark is a feature with associated Geometry. * A Placemark with a Point has an icon associated with it that marks a point on the Earth in the 3D viewer. * (In the Google Earth 3D viewer, a Point Placemark is the only object you can click or roll over. * Other Geometry objects do not have an icon in the 3D viewer. * To allow the user to click in the 3D viewer, you would need to create a MultiGeometry object that contains both a Point and the other Geometry object.) */ createPlacemark(id: string): KmlPlacemark; /** * Creates a point on the globe. Specifies the geographic location defined by longitude, latitude, and (optional) altitude. */ createPoint(id: string): KmlPoint; /** * Creates a line string on Google Earth. */ createLineString(id: string): KmlLineString; /** * Creates a folder. * A KMLFolder is used to arrange other features hierarchically (Folders, Placemarks, NetworkLinks, or Overlays). * A feature is visible only if it and all its ancestors are visible. */ createFolder(id: string): KmlFolder; /** * Creates level of detail (LOD). * LOD describes the size of the projected region on the screen that is required in order for the region to be considered active. * Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). */ createLod(id: string): KmlLod; /** * Creates a LatLonBox, a bounding box that describes an area of interest defined by geographic coordinates and altitudes. */ createLatLonBox(id: string): KmlLatLonBox; /** * Creates a LatLonAltBox, a bounding box that describes an area of interest defined by geographic coordinates and altitudes. */ createLatLonAltBox(id: string): KmlLatLonAltBox; /** * Creates a Document. A Document is a container for features and styles. */ createDocument(id: string): KmlDocument; /** * Creates a Region in Google Earth. * A Region contains a bounding box that describes an area of interest defined by geographic coordinates and altitudes. */ createRegion(id: string): KmlRegion; /** * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. */ createLocation(id: string): KmlLocation; /** * Sets the rotation of a 3D model's coordinate system to position the object in Google Earth. */ createOrientation(id: string): KmlOrientation; /** * Sets the scale of a model along the x, y, and z axes in the model's coordinate space. */ createScale(id: string): KmlScale; /** * Creates a model. * A model is a 3D object described in a COLLADA file. * COLLADA files have a .dae file extension. * Models are created in their own coordinate space and then located, positioned, and scaled in Google Earth. */ createModel(id: string): KmlModel; /** * A Style defines an addressable style group that can be referenced by StyleMaps and features. */ createStyle(id: string): KmlStyle; /** * Creates a LinearRing. * A LinearRing defines a closed line string, typically the outer boundary of a Polygon. * Optionally, a LinearRing can also be used as the inner boundary of a Polygon to create holes in the Polygon. */ createLinearRing(id: string): KmlLinearRing; /** * Creates a Polygon. A Polygon is defined by an outer boundary and 0 or more inner boundaries. */ createPolygon(id: string): KmlPolygon; /** * Creates an Icon. An icon defines an image associated with an Icon style or overlay. */ createIcon(id: string): KmlIcon; /** * Creates a Link. * A Link specifies the location of KML files fetched by network links, image files used in any overlay, or model files used with the Model object. */ createLink(id: string): KmlLink; /** * Creates a GroundOverlay. * A GroundOverlay draws an image overlay draped onto the terrain. */ createGroundOverlay(id: string): KmlGroundOverlay; /** * Creates a NetworkLink. * A NetworkLink references a KML file or KMZ archive on a local or remote network. */ createNetworkLink(id: string): KmlNetworkLink; /** * Creates a ScreenOverlay. * A ScreenOverlay draws an image overlay fixed to the screen. */ createScreenOverlay(id: string): KmlScreenOverlay; /** * Creates a container for one or more geometry primitives associated with the same feature. */ createMultiGeometry(id: string): KmlMultiGeometry; /** * Creates a StyleMap. * A StyleMap maps between two different icon styles. * Typically, a StyleMap is used to provide separate normal and highlighted styles for a Placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. */ createStyleMap(id: string): KmlStyleMap; /** * Creates a new LookAt. * A LookAt element positions the camera view in relation to an object that is being viewed. */ createLookAt(id: string): KmlLookAt; /** * Creates a new Camera. * This element positions the camera relative to the Earth's surface and defines the view direction. */ createCamera(id: string): KmlCamera; /** * Creates a new viewer options object. */ createViewerOptions(id: string): KmlViewerOptions; /** * Create a KmlTimeStamp object. * For more information, refer to the Time chapter of the Google Earth API developer's guide. */ createTimeStamp(id: string): KmlTimeStamp; /** * Create a KmlTimeSpan object. * For more information, refer to the Time chapter of the Google Earth API developer's guide. */ createTimeSpan(id: string): KmlTimeSpan; /** * Creates a Feature balloon. */ createFeatureBalloon(id: string): GEFeatureBalloon; /** * Creates an HTML string balloon. */ createHtmlStringBalloon(id: string): GEHtmlStringBalloon; /** * Creates an Html Div Balloon. */ createHtmlDivBalloon(id: string): GEHtmlDivBalloon; /** * Returns the currently active balloon, or null. */ getBalloon(): GEAbstractBalloon; /** * Sets the given balloon as the active balloon, replacing any existing active balloon. * If the given feature is visible, then the balloon is displayed. Otherwise, the balloon is hidden. * * If the argument is null, then any existing active balloon will be hidden. */ setBalloon(newActiveBalloon: GEAbstractBalloon): void; /** * Used for debugging purposes; if this value is not equal to the value returned by getPluginVersion then there is a misconfiguration on the end user's system. * This check is automatically done during plugin instantiation. */ getEarthVersion(): string; /** * The version of the Google Earth Plug-in installed on the end user's machine. */ getPluginVersion(): string; /** * The options used to manipulate the behavior of the Google Earth plugin. */ getOptions(): GEOptions; /** * The time class used to manipulate the behavior of the Google Earth plugin time. */ getTime(): GETime; /** * Controls the window options. */ getWindow(): GEWindow; /** * Controls the globe behavior. */ getGlobe(): GEGlobe; /** * Displays the dawn to dusk views. */ getSun(): GESun; /** * Controls built-in layer behavior. */ getLayerRoot(): KmlLayerRoot; /** * Controls the plugin viewport. */ getView(): GEView; /** * Controls the navigation controls on the globe. */ getNavigationControl(): GENavigationControl; /** * The top-level features currently in the Earth object. */ getFeatures(): GEFeatureContainer; /** * Exposes functionality for interacting with KML tours. */ getTourPlayer(): GETourPlayer; /** * Exposes functionality for interacting with photo overlays. */ getPhotoOverlayViewer(): GEPhotoOverlayViewer; /** * Returns a number between 0 and 100 (inclusive) that indicates the progress of the streaming of imagery for the current view. * * A value of 100 means that the imagery is completely streamed in. */ getStreamingPercent(): number; } }
the_stack
import {ErrorResponse} from "helpers/api_request_builder"; import _ from "lodash"; import m from "mithril"; import Stream from "mithril/stream"; import {PackagesCRUD} from "models/package_repositories/packages_crud"; import {Package, PackageRepositories, PackageRepository, PackageRepositorySummary, Packages} from "models/package_repositories/package_repositories"; import {PackageRepositoriesCRUD} from "models/package_repositories/package_repositories_crud"; import {ExtensionTypeString, PackageRepoExtensionType} from "models/shared/plugin_infos_new/extension_type"; import {PluginInfoCRUD} from "models/shared/plugin_infos_new/plugin_info_crud"; import {AnchorVM, ScrollManager} from "views/components/anchor/anchor"; import {ButtonIcon, Primary} from "views/components/buttons"; import {FlashMessage, MessageType} from "views/components/flash_message"; import {SearchField} from "views/components/forms/input_fields"; import {HeaderPanel} from "views/components/header_panel"; import {NoPluginsOfTypeInstalled} from "views/components/no_plugins_installed"; import configRepoStyles from "views/pages/config_repos/index.scss"; import {PackageRepoScrollOptions, PackageRepositoriesWidget} from "views/pages/package_repositories/package_repositories_widget"; import { ClonePackageRepositoryModal, CreatePackageRepositoryModal, DeletePackageRepositoryModal, EditPackageRepositoryModal } from "views/pages/package_repositories/package_repository_modals"; import {Page, PageState} from "views/pages/page"; import {RequiresPluginInfos, SaveOperation} from "views/pages/page_operations"; import {ClonePackageModal, CreatePackageModal, DeletePackageModal, EditPackageModal, UsagePackageModal} from "./package_repositories/package_modals"; const pkgRepoAnchorVm: ScrollManager = new AnchorVM(); const pkgAnchorVM: ScrollManager = new AnchorVM(); export class PackageRepoOperations { onAdd: (e: MouseEvent) => void = () => _.noop; onEdit: (obj: PackageRepository, e: MouseEvent) => void = () => _.noop; onClone: (obj: PackageRepository, e: MouseEvent) => void = () => _.noop; onDelete: (obj: PackageRepository, e: MouseEvent) => void = () => _.noop; } export class PackageOperations { onAdd: (packageRepo: PackageRepository, e: MouseEvent) => void = () => _.noop; onEdit: (obj: Package, e: MouseEvent) => void = () => _.noop; onClone: (obj: Package, e: MouseEvent) => void = () => _.noop; onDelete: (obj: Package, e: MouseEvent) => void = () => _.noop; showUsages: (obj: Package, e: MouseEvent) => void = () => _.noop; } interface State extends RequiresPluginInfos, SaveOperation { packageRepositories: Stream<PackageRepositories>; packages: Stream<Packages>; packageRepoOperations: PackageRepoOperations; packageOperations: PackageOperations; searchText: Stream<string>; } export class PackageRepositoriesPage extends Page<null, State> { public static getMergedList(originalPkgRepos: Stream<PackageRepositories>, pkgs: Stream<Packages>): PackageRepositories { const pkgRepos = originalPkgRepos(); if (!pkgs || _.isEmpty(pkgs())) { return pkgRepos; } pkgRepos.forEach((pkgRepo) => { const pkgsForRepo = pkgs() .filter((pkg) => pkg.packageRepo().id() === pkgRepo.repoId()); pkgRepo.packages().forEach((pkg) => { const completePkg = pkgsForRepo.find((p) => p.id() === pkg.id()); if (completePkg !== undefined) { pkg.autoUpdate(completePkg.autoUpdate()); pkg.configuration(completePkg.configuration()); pkg.packageRepo(new PackageRepositorySummary(pkgRepo.repoId(), pkgRepo.name())); } }); }); return pkgRepos; } oninit(vnode: m.Vnode<null, State>) { super.oninit(vnode); vnode.state.searchText = Stream(); vnode.state.packageRepositories = Stream(); vnode.state.packages = Stream(); vnode.state.pluginInfos = Stream(); vnode.state.onSuccessfulSave = (msg: m.Children) => { this.flashMessage.setMessage(MessageType.success, msg); this.fetchData(vnode); }; vnode.state.onError = (msg: m.Children) => { this.flashMessage.setMessage(MessageType.alert, msg); }; this.setPackageRepoOperations(vnode); this.setPackageOperations(vnode); } componentToDisplay(vnode: m.Vnode<null, State>): m.Children { const scrollOptions = this.parsePackageRepoLink(pkgRepoAnchorVm, pkgAnchorVM); let noPluginMsg; if (!this.isPluginInstalled(vnode)) { noPluginMsg = <NoPluginsOfTypeInstalled extensionType={new PackageRepoExtensionType()}/>; } const mergedPackageRepos: Stream<PackageRepositories> = Stream(PackageRepositoriesPage.getMergedList(vnode.state.packageRepositories, vnode.state.packages)); const filteredPackageRepos: Stream<PackageRepositories> = Stream(); if (vnode.state.searchText()) { const results = _.filter(mergedPackageRepos(), (vm: PackageRepository) => vm.matches(vnode.state.searchText())); if (_.isEmpty(results)) { return <div> {noPluginMsg} <FlashMessage type={MessageType.info}>No Results for the search string: <em>{vnode.state.searchText()}</em></FlashMessage> </div>; } filteredPackageRepos(results); } else { filteredPackageRepos(mergedPackageRepos()); } return <div> {noPluginMsg} <FlashMessage type={this.flashMessage.type} message={this.flashMessage.message}/> <PackageRepositoriesWidget packageRepositories={filteredPackageRepos} pluginInfos={vnode.state.pluginInfos} packageRepoOperations={vnode.state.packageRepoOperations} packageOperations={vnode.state.packageOperations} scrollOptions={scrollOptions}/> </div>; } pageName(): string { return "Package Repositories"; } fetchData(vnode: m.Vnode<null, State>): Promise<any> { return Promise.all([PackageRepositoriesCRUD.all(), PackagesCRUD.all(), PluginInfoCRUD.all({type: ExtensionTypeString.PACKAGE_REPO})]) .then((result) => { result[0].do((successResponse) => { vnode.state.packageRepositories(successResponse.body); this.pageState = PageState.OK; }, (errorResponse) => { this.flashMessage.setMessage(MessageType.alert, JSON.parse(errorResponse.body!).message); this.pageState = PageState.FAILED; }); result[1].do((successResponse) => { vnode.state.packages(successResponse.body); this.pageState = PageState.OK; }, (errorResponse) => { this.flashMessage.setMessage(MessageType.alert, JSON.parse(errorResponse.body!).message); this.pageState = PageState.FAILED; }); result[2].do((successResponse) => { vnode.state.pluginInfos(successResponse.body); this.pageState = PageState.OK; }, (errorResponse) => { this.flashMessage.setMessage(MessageType.alert, JSON.parse(errorResponse.body!).message); this.pageState = PageState.FAILED; }); }); } helpText(): m.Children { return PackageRepositoriesWidget.helpText(); } protected headerPanel(vnode: m.Vnode<null, State>): any { const buttons = [ <Primary icon={ButtonIcon.ADD} disabled={!this.isPluginInstalled(vnode)} onclick={vnode.state.packageRepoOperations.onAdd}> Create Package Repository </Primary> ]; if (!_.isEmpty(vnode.state.packageRepositories())) { const searchBox = <div className={configRepoStyles.wrapperForSearchBox}> <SearchField property={vnode.state.searchText} dataTestId={"search-box"} placeholder="Search for a package repository or a package"/> </div>; buttons.splice(0, 0, searchBox); } return <HeaderPanel title={this.pageName()} buttons={buttons} help={this.helpText()}/>; } private isPluginInstalled(vnode: m.Vnode<null, State>) { return vnode.state.pluginInfos().length !== 0; } private setPackageRepoOperations(vnode: m.Vnode<null, State>) { vnode.state.packageRepoOperations = new PackageRepoOperations(); vnode.state.packageRepoOperations.onAdd = (e: MouseEvent) => { e.stopPropagation(); const pluginId = vnode.state.pluginInfos()[0].id; const packageRepository = PackageRepository.default(); packageRepository.pluginMetadata().id(pluginId); new CreatePackageRepositoryModal(packageRepository, vnode.state.pluginInfos(), vnode.state.onSuccessfulSave) .render(); }; vnode.state.packageRepoOperations.onEdit = (pkgRepo: PackageRepository, e: MouseEvent) => { e.stopPropagation(); const copy = new PackageRepository(pkgRepo.repoId(), pkgRepo.name(), pkgRepo.pluginMetadata(), pkgRepo.configuration(), []); new EditPackageRepositoryModal(copy, vnode.state.pluginInfos(), vnode.state.onSuccessfulSave) .render(); }; vnode.state.packageRepoOperations.onClone = (pkgRepo: PackageRepository, e: MouseEvent) => { e.stopPropagation(); new ClonePackageRepositoryModal(pkgRepo, vnode.state.pluginInfos(), vnode.state.onSuccessfulSave) .render(); }; vnode.state.packageRepoOperations.onDelete = (pkgRepo: PackageRepository, e: MouseEvent) => { e.stopPropagation(); new DeletePackageRepositoryModal(pkgRepo, vnode.state.onSuccessfulSave) .render(); }; } private setPackageOperations(vnode: m.Vnode<null, State>) { vnode.state.packageOperations = new PackageOperations(); vnode.state.packageOperations.onAdd = (packageRepo: PackageRepository, e: MouseEvent) => { e.stopPropagation(); const pkg = Package.default(); pkg.packageRepo().id(packageRepo.repoId()); new CreatePackageModal(pkg, vnode.state.packageRepositories(), vnode.state.pluginInfos(), vnode.state.onSuccessfulSave) .render(); }; vnode.state.packageOperations.onEdit = (pkg: Package, e: MouseEvent) => { e.stopPropagation(); const copy = new Package(pkg.id(), pkg.name(), pkg.autoUpdate(), pkg.configuration(), pkg.packageRepo()); new EditPackageModal(copy, vnode.state.packageRepositories(), vnode.state.pluginInfos(), vnode.state.onSuccessfulSave) .render(); }; vnode.state.packageOperations.onClone = (pkg: Package, e: MouseEvent) => { e.stopPropagation(); new ClonePackageModal(pkg, vnode.state.packageRepositories(), vnode.state.pluginInfos(), vnode.state.onSuccessfulSave) .render(); }; vnode.state.packageOperations.onDelete = (pkg: Package, e: MouseEvent) => { e.stopPropagation(); new DeletePackageModal(pkg, vnode.state.onSuccessfulSave) .render(); }; vnode.state.packageOperations.showUsages = (pkg: Package, e: MouseEvent) => { e.stopPropagation(); PackagesCRUD.usages(pkg.id()) .then((result) => { result.do( (successResponse) => { new UsagePackageModal(pkg.name(), successResponse.body).render(); }, this.onOperationError(vnode) ); }); }; } private onOperationError(vnode: m.Vnode<null, State>): (errorResponse: ErrorResponse) => void { return (errorResponse: ErrorResponse) => { vnode.state.onError(JSON.parse(errorResponse.body!).message); }; } private parsePackageRepoLink(pkgRepoAnchorVm: ScrollManager, pkgAnchorVM: ScrollManager): PackageRepoScrollOptions { const repo_name = m.route.param().repo_name || ""; pkgRepoAnchorVm.setTarget(repo_name); const repo_operation = (m.route.param().repo_operation || "").toLowerCase(); const pkg_name = m.route.param().package_name || ""; pkgAnchorVM.setTarget(`${repo_name}:${pkg_name}`); const pkg_operation = (m.route.param().package_operation || "").toLowerCase(); return { package_repo_sm: { sm: pkgRepoAnchorVm, shouldOpenEditView: repo_operation === "edit", shouldOpenCreatePackageView: repo_operation === "create-package" }, package_sm: { sm: pkgAnchorVM, shouldOpenEditView: pkg_operation === "edit" } }; } }
the_stack
import * as React from 'react' import * as d3 from 'd3' import { layoutTextLabel, layoutGreedy, layoutLabel } from 'd3fc-label-layout' import { YtModel, ChannelData } from '../../common/YtModel' import { SelectableCell, DimQuery, Dim, ColEx } from '../../common/Dim' import { YtInteractiveChartHelper } from "../../common/YtInteractiveChartHelper" import * as _ from 'lodash' import { ChartProps, InteractiveDataState } from '../../common/Chart' import Select from 'react-select' import { renderToString } from 'react-dom/server' import { classNames, delay } from '../../common/Utils' import { range } from 'd3' import styled from 'styled-components' import { selectStyle, selectTheme } from '../MainLayout' const LegendStyle = styled.div` position: absolute; display: flex; flex-flow: column; padding: 5px; min-width: 150px; width: 20%; max-width: 250px; background-color: rgba(0, 0, 0, 0.5); top:0; > * { margin: 5px; } g.legend { cursor: pointer; margin: 5px; } g.legend text { fill: #eee; } ` interface State extends InteractiveDataState { } interface Props extends ChartProps<YtModel> { } interface Link extends d3.SimulationLinkDatum<Node> { strength: number color: string impressions: number } interface Node extends d3.SimulationNodeDatum, SelectableCell<Node> { channelId: string size: number row: ChannelData } export class ChannelRelations extends React.Component<Props, State> { svg: SVGSVGElement legendDiv: HTMLDivElement static source = 'relations' chart: YtInteractiveChartHelper = new YtInteractiveChartHelper(this, ChannelRelations.source) state: Readonly<State> = { selections: this.props.model.selectionState } componentDidMount() { this.loadChart() } componentDidUpdate(prevProps: Props, prevState: State) { this.stateRender(prevProps, prevState) } render() { return ( <> <svg ref={ref => (this.svg = ref)} /> {this.renderLegendHtml()} </>) } channelQuery(withColor: boolean): DimQuery<ChannelData> { return { group: ['channelId'], colorBy: withColor ? this.chart.selections.params().colorBy : null, labelBy: 'title' } } onColorBySelected = (option: { value: string }) => { this.chart.selections.setParam({ colorBy: option.value }) } private renderLegendHtml(): JSX.Element { let colorBy = this.chart.selections.params().colorBy const tagNodes = () => { let tagsCol = YtModel.channelDimStatic.col('tags') let tagsLabel = ColEx.labelFunc(tagsCol) let tagsColor = ColEx.colorFunc(tagsCol) const tags = tagsCol.values .filter(v => v.color) .map(v => v.value) // don't show some tags in the legend return _(tags).map(t => ({ keys: { tags: [t] }, label: tagsLabel(t), color: tagsColor(t), props: {}, measures: { dailyViews: this.props.model.tagViews[t] } } as SelectableCell<ChannelData>)) .orderBy(t => t.measures.dailyViews, 'desc') .value() } let legendNodes = colorBy == 'tags' ? tagNodes() : this.props.model.channels.cells({ group: [colorBy], // if the group has a color, it should be colored order: { col: 'dailyViews', order: 'desc' } }) as SelectableCell<ChannelData>[] let selections = this.chart.selections selections.updateSelectableCells(legendNodes) let dim = this.props.model.channels let options = YtModel.categoryCols.map(c => dim.col(c)).map(c => ({ value: c.name, label: c.label ?? c.name })) let selected = options.find(o => o.value == colorBy) return ( <LegendStyle> <Select options={options} value={selected} styles={selectStyle} theme={selectTheme} onChange={this.onColorBySelected} ></Select> <svg height={legendNodes.length * 21} onClick={() => selections.clearAll()}> <g className={'chart legend'}> {legendNodes.map((d, i) => { const className = classNames({ selected: d.selected, highlighted: d.highlighted, dimmed: d.dimmed }) const events = ({ click: (e: React.MouseEvent<Element, MouseEvent>) => { e.stopPropagation() return selections.select(d.keys) }, in: (e: React.MouseEvent<Element, MouseEvent>) => selections.highlight(d.keys), out: (e: React.MouseEvent<Element, MouseEvent>) => selections.clearHighlight() }) return (<g key={d.label} transform={`translate(10, ${10 + (i * 21)})`} onClick={events.click} onMouseEnter={events.in} onMouseLeave={events.out}> <circle r={8} fill={d.color} className={'node ' + className} ></circle> <text x={14} y={5} className={'label ' + className}>{d.label}</text> </g>) })} </g> </svg> </LegendStyle> ) } // a cheap render. Set by loadChat() so that it can use a bunch of context stateRender: (prevProps: Props, prevState: State) => void getData() { const coloredTags = YtModel.channelDimStatic.col('tags').values const channelCells = _(this.dim.rowCells(this.channelQuery(false))) .filter(c => c.row.tags.filter(t => coloredTags.find(v => v.value == t)).length > 0) .orderBy(c => c.row.relevantDailyViews, 'desc') .take(1000).value() let nodes: Node[] = _(channelCells) .filter(c => c.row.relevantDailyViews > 0) .map( c => ({ channelId: c.row.channelId, size: c.row.relevantDailyViews, row: c.row, ...c.cell } as Node) ).value() let links = _(this.props.model.recs.rows) .filter(l => l.toChannelId != l.fromChannelId && l.recommendsViewChannelPercent > 0.015) .map( l => ({ source: l.fromChannelId, target: l.toChannelId, strength: l.recommendsViewChannelPercent, impressions: l.relevantImpressionsDaily } as Link) ) .filter( l => (nodes.some(c => c.channelId == (l.source as string)) && nodes.some(c => c.channelId == (l.target as string))) ) .value() let keyedNodes = nodes.filter(n => links.some(l => n.channelId == (l.source as string) || n.channelId == (l.target as string))) let recMap = new Map() links.forEach(d => { recMap.set(d.source + '-' + d.target, true) recMap.set(d.target + '-' + d.source, true) }) let isConnected = (a: string, b: string) => a == b || recMap.get(a + '-' + b) return { nodes: keyedNodes, links: links, isConnected } } private get dim() { return this.props.model.channels as unknown as Dim<ChannelData> } getLayout(nodes: Node[], links: Link[]) { let simSize = 1024 let maxStrength = d3.max(links, l => l.strength) let maxImpressions = d3.max(links, l => l.impressions) let maxSize = d3.max(nodes, n => n.size) let getNodeRadius = (d: Node) => Math.sqrt(d.size > 0 ? d.size / maxSize : 1) * 40 let getLineWidth = (d: Link) => Math.sqrt(d.impressions / maxImpressions) * 200 let centerForce = d3.forceCenter(simSize / 2, simSize / 2) let force = d3 .forceSimulation<Node, Link>(nodes) .force('charge', d3.forceManyBody().strength(-60)) .force('center', centerForce) .force( 'link', d3 .forceLink<Node, Link>(links) .distance(1) .id(d => d.channelId) .strength(d => (d.strength / maxStrength) * 0.8) ) .force('collide', d3.forceCollide<Node>(getNodeRadius)) return { force, getLineWidth, getNodeRadius, simSize, maxSize } } async loadChart() { const { nodes, links, isConnected } = this.getData() const lay = this.getLayout(nodes, links) let svg = d3.select(this.svg) let container = this.chart.createContainer(svg, ChannelRelations.source) let linkEnter = container .append('g') .attr('class', 'links') .selectAll('line') .data(links) .enter() .append<SVGLineElement>('line') .attr('class', 'link') .attr('stroke-width', lay.getLineWidth) let nodesContainer = container.append<SVGGElement>('g').attr('class', 'node') let nodesEnter = nodesContainer .selectAll('g') .data<Node>(nodes, (n: Node) => n.channelId) .enter() .append('g') let nodesCircle = nodesEnter .append<SVGCircleElement>('circle') .attr('r', lay.getNodeRadius) this.chart.addShapeEvents(nodesCircle) let labelsGroup = container .append<SVGGElement>('g') .attr('class', 'labels') .datum(nodes) .attr('pointer-events', 'none') let textRatio: [number, number] = null let labelPadding = 2 let layoutLabels = layoutLabel<Node[]>(layoutGreedy()) .size((n: any, i, g) => { const node = n as Node if (!textRatio) { // render a label to know the size to calculate with let e = g[i] as Element let text = e.getElementsByTagName('text')[0] text.style.display = 'inherit' let box = text.getBBox() textRatio = [box.width / node.label.length, box.height] text.style.display = null } return [node.label.length * textRatio[0], textRatio[1]] }) .component( layoutTextLabel() .padding(labelPadding) .value((d: Node) => d.label) ) function updateLabels(fast: boolean) { if (fast) { labelsGroup.selectAll<SVGGElement, Node>('g.label') .attr('transform', d => `translate(${d.x + lay.getNodeRadius(d) + 3}, ${d.y - 10})`) } else { labelsGroup.call(layoutLabels) } } let updateColor = () => { let queryContext = this.dim.queryContext(this.channelQuery(true)) nodes.forEach(c => c.color = queryContext.getColor(c.row)) const nodeById = _.keyBy(nodes, n => n.channelId) links.forEach(l => l.color = nodeById[(l.source as Node).channelId].color) linkEnter.attr('stroke', (l: Link) => l.color) } let updateVisibility = () => { this.chart.selections.updateSelectableCells(nodes) let selectedOrHighlighted = nodes.filter(n => n.highlighted || n.selected) let selected = nodes.filter(n => n.selected) let highlighted = nodes.filter(n => n.highlighted) const related = (n: Node): boolean => selectedOrHighlighted.length <= 2 && selectedOrHighlighted.some(c => isConnected(n.channelId, c.channelId)) nodesCircle.classed('related', related) const labelText = labelsGroup.selectAll<SVGTextElement, Node>('text') labelText .style('display', d => { let zoomLabel = d3.zoomTransform(svg.node()).k > 2 let display = selectedOrHighlighted.length > 2 ? (d.selected && (zoomLabel || selected.length < 2)) || (d.highlighted && (zoomLabel || highlighted.length < 2)) // many selected - only show labels when zoomed : (d.selected || d.highlighted) || related(d) && zoomLabel// few selected - show labels of selected/highlighted, and also related when zoomed return display ? 'inherit' : 'none' }) linkEnter.classed('related', d => { let s = d.source as Node var t = d.target as Node return selectedOrHighlighted.some(n => s.channelId == n.channelId || t.channelId == n.channelId) }) linkEnter.style('opacity', selectedOrHighlighted.length > 2 ? 0.1 : 0.3) } const chart = this.chart const updateEffects = () => { let zoom = d3.zoomTransform(svg.node()) return chart.updateShapeEffects(nodesCircle, { unselectedGlow: d => d.size > lay.maxSize * 0.1 * zoom.k }) } function updatePositions() { nodesCircle.attr('cx', d => d.x).attr('cy', d => d.y) // faster than attr('transform', d => `translate(${d.x}, ${d.y})`) let safeLoc = (x?: number) => (x != null && isFinite(x) ? x : 0) linkEnter .attr('x1', d => safeLoc((d.source as Node).x)) .attr('y1', d => safeLoc((d.source as Node).y)) .attr('x2', d => safeLoc((d.target as Node).x)) .attr('y2', d => safeLoc((d.target as Node).y)) } // see here for good docs on d3 zooming https://www.datamake.io/blog/d3-zoom var zoomHandler = d3.zoom() .scaleExtent([0.2, 5]) .on("zoom", () => { const t = d3.zoomTransform(svg.node()) container.attr('transform', () => t.toString()) const labelsTrans = `scale(${1 / t.k})` const labelSelect = labelsGroup.select('text') const existingTrans = labelSelect.empty() ? null : labelSelect.attr('transform') if (labelsTrans != existingTrans) { labelsGroup.selectAll<SVGTextElement, Node>('text') .attr('transform', () => labelsTrans) // undo the zoom on labels updateVisibility() updateLabels(true) } }) let zoomToExpectedScale = (width: number, height: number) => zoom(width, height, new DOMRect(0, 0, 1400, 1400), 0) let zoom = (width: number, height: number, bounds: DOMRect, duration: number) => { let midX = bounds.x + bounds.width / 2 let midY = bounds.y + bounds.height / 2 var scale = 1 / Math.max(bounds.width / width, bounds.height / height) var t = { x: width / 2 - scale * midX, y: height / 2 - scale * midY, scale: scale } let trans = d3.zoomIdentity.translate(t.x, t.y).scale(t.scale) let s = svg.transition().duration(duration) s.call(zoomHandler.transform, trans) } zoomHandler(svg) zoomToExpectedScale(this.props.width, this.props.height) this.stateRender = (prevProps: Props, prevState: State) => { let svg = d3.select(this.svg) if (prevProps == null || prevProps.width != this.props.width || prevProps.height != this.props.height) { svg.attr('width', this.props.width) svg.attr('height', this.props.height) zoomToExpectedScale(this.props.width, this.props.height) } updateVisibility() updateColor() updateEffects() } await delay(1) this.stateRender(null, null) for (var i = 0; i < 150; i++) { lay.force.tick() updatePositions() await delay(4) } lay.force.stop() await delay(1) updatePositions() this.stateRender(this.props, this.state) await delay(1) updateLabels(false) } }
the_stack
import * as _ from 'underscore'; const d3Format: any = require('d3-format'); const d3TimeFormat: any = require('d3-time-format'); import { CellRenderer, TextRenderer, HyperlinkRenderer, } from '@lumino/datagrid'; import { Dict, WidgetModel, WidgetView, ISerializers, resolvePromisesDict, unpack_models, } from '@jupyter-widgets/base'; import { MODULE_NAME, MODULE_VERSION } from './version'; import { BarRenderer } from './core/barrenderer'; import { VegaExprView } from './vegaexpr'; import { Scalar, Theme } from './utils'; // Temporary, will be removed when the scales are exported from bqplot type Scale = any; type Processor = Scalar | VegaExprView | Scale; interface ICellRendererAttribute { // The name of the widget attribute name: string; // The name of the equivalent phosphor attribute, if null the CellRenderer attribute has no equivalent in phosphor phosphorName: string | null; // The default value for this attribute defaultValue: Scalar; } export abstract class CellRendererModel extends WidgetModel { defaults() { return { ...super.defaults(), _model_name: CellRendererModel.model_name, _model_module: CellRendererModel.model_module, _model_module_version: CellRendererModel.model_module_version, _view_name: CellRendererModel.view_name, _view_module: CellRendererModel.view_module, _view_module_version: CellRendererModel.view_module_version, }; } abstract get_attrs(): ICellRendererAttribute[]; static model_name = 'CellRendererModel'; static model_module = MODULE_NAME; static model_module_version = MODULE_VERSION; static view_name = 'CellRendererView'; static view_module = MODULE_NAME; static view_module_version = MODULE_VERSION; } export abstract class CellRendererView extends WidgetView { render() { return this.initializeRenderer().then(() => { this.updateRenderer(); this.on('renderer-needs-update', this.updateRenderer.bind(this)); }); } /** * Method that should be called when the theme has changed. */ onThemeChanged() { return this.initializeRenderer().then(() => { this.updateRenderer(); }); } /** * Initialize the CellRenderer widget. * * @return The promise to initialize the renderer */ protected initializeRenderer(): Promise<any> { const promises: Dict<PromiseLike<Processor>> = {}; const attr_names = this.model .get_attrs() .map((attr: ICellRendererAttribute) => { return attr.name; }); this.model.on_some_change( attr_names, this._on_some_processors_change, this, ); for (const name of attr_names) { promises[name] = this.updateProcessor(name); } return resolvePromisesDict(promises).then((processors: Dict<Processor>) => { this.processors = processors; }); } private _on_some_processors_change(event: any) { const promises: Dict<PromiseLike<Processor>> = {}; for (const name in event.changed) { promises[name] = this.updateProcessor(name); } resolvePromisesDict(promises).then((processors: Dict<Processor>) => { this.processors = { ...this.processors, ...processors, }; this.trigger('renderer-needs-update'); }); } /** * Update the phosphor renderer value, and trigger an event so that the DataGrid widget knows it has * changed. */ private updateRenderer() { const options: any = {}; for (const attr of this.model.get_attrs()) { if (attr.phosphorName) { options[attr.phosphorName] = (config: CellRenderer.CellConfig) => { return this.process(attr.name, config, attr.defaultValue); }; } } this.renderer = this.createRenderer(options); this.trigger('renderer-changed'); } /** * Update the processor associated with the given name. * * @param name - The name of the attribute to process. * * @return The PromiseLike to update the processor view. */ protected updateProcessor(name: string): any { const processor: any = this.model.get(name); if (Scalar.isScalar(processor)) { return processor; } // Assuming it is an VegaExprModel or a Scale model this.listenTo(processor, 'change', () => { this.trigger('renderer-needs-update'); }); return this.create_child_view(processor); } /** * Process a cell attribute given the cell config. * * @param name - The name of the attribute to process. * * @param config - The configuration data for the cell. * * @param defaultValue - The default attribute value. */ protected process( name: string, config: CellRenderer.CellConfig, defaultValue: Scalar, ): any { const processor = this.processors[name]; if (Scalar.isScalar(processor)) { if ( name === 'font' && typeof processor === 'string' && ((typeof config.value === 'number' && !Number.isFinite(config.value)) || (config.value instanceof Date && Number.isNaN(config.value.getTime()))) ) { return `italic ${processor}`; } return processor; } if (processor instanceof VegaExprView) { return processor.process(config, defaultValue); } // If it's a DateScale, convert the value to a Date object if ( processor.model.type == 'date' || processor.model.type == 'date_color_linear' ) { return processor.scale(new Date(config.value)); } // Assuming it is a Scale view return processor.scale(config.value); } protected abstract createRenderer( options: TextRenderer.IOptions, ): CellRenderer; model: CellRendererModel; renderer: CellRenderer; processors: Dict<Processor> = {}; } export class TextRendererModel extends CellRendererModel { defaults() { return { ...super.defaults(), _model_name: TextRendererModel.model_name, _view_name: TextRendererModel.view_name, font: '12px sans-serif', text_color: null, text_wrap: false, text_elide_direction: 'right', text_value: null, background_color: null, vertical_alignment: 'center', horizontal_alignment: 'left', format: null, format_type: 'number', missing: '', }; } get_attrs(): ICellRendererAttribute[] { return [ { name: 'font', phosphorName: 'font', defaultValue: '12px sans-serif' }, { name: 'text_wrap', phosphorName: 'wrapText', defaultValue: false }, { name: 'text_elide_direction', phosphorName: 'elideDirection', defaultValue: 'right', }, { name: 'text_color', phosphorName: 'textColor', defaultValue: Theme.getFontColor(), }, { name: 'text_value', phosphorName: null, defaultValue: null }, { name: 'background_color', phosphorName: 'backgroundColor', defaultValue: Theme.getBackgroundColor(), }, { name: 'vertical_alignment', phosphorName: 'verticalAlignment', defaultValue: 'center', }, { name: 'horizontal_alignment', phosphorName: 'horizontalAlignment', defaultValue: 'left', }, { name: 'format', phosphorName: null, defaultValue: null }, ]; } static serializers: ISerializers = { ...CellRendererModel.serializers, font: { deserialize: unpack_models as any }, text_color: { deserialize: unpack_models as any }, text_wrap: { deserialize: unpack_models as any }, text_elide_direction: { deserialize: unpack_models as any }, text_value: { deserialize: unpack_models as any }, background_color: { deserialize: unpack_models as any }, vertical_alignment: { deserialize: unpack_models as any }, horizontal_alignment: { deserialize: unpack_models as any }, format: { deserialize: unpack_models as any }, }; static model_name = 'TextRendererModel'; static view_name = 'TextRendererView'; } export class TextRendererView extends CellRendererView { render() { return super.render().then(() => { this.model.on_some_change( ['missing', 'format_type'], () => { this.trigger('renderer-needs-update'); }, this, ); }); } createRenderer(options: TextRenderer.IOptions) { return new TextRenderer({ ...options, format: this.getFormatter(), }); } getFormatter( options: TextRenderer.formatGeneric.IOptions = {}, ): TextRenderer.FormatFunc { return (config: CellRenderer.CellConfig) => { let formattedValue: string; if (config.value === null) { formattedValue = this.model.get('missing'); } else { const formattingRule = this.process('format', config, null); if (formattingRule === null) { formattedValue = String(config.value); } else { if (this.model.get('format_type') == 'time') { formattedValue = String( d3TimeFormat.timeFormat(formattingRule)(new Date(config.value)), ); } else { formattedValue = String( d3Format.format(formattingRule)(config.value), ); } } } return ( this.process('text_value', config, formattedValue) || formattedValue ); }; } renderer: TextRenderer; model: TextRendererModel; } export class BarRendererModel extends TextRendererModel { defaults() { return { ...super.defaults(), _model_name: BarRendererModel.model_name, _view_name: BarRendererModel.view_name, bar_color: '#4682b4', bar_value: 0, orientation: 'horizontal', bar_vertical_alignment: 'bottom', bar_horizontal_alignment: 'left', show_text: true, }; } get_attrs(): ICellRendererAttribute[] { return super.get_attrs().concat([ { name: 'bar_color', phosphorName: 'barColor', defaultValue: '#4682b4' }, { name: 'bar_value', phosphorName: 'barValue', defaultValue: 0 }, { name: 'orientation', phosphorName: 'orientation', defaultValue: 'horizontal', }, { name: 'bar_vertical_alignment', phosphorName: 'barVerticalAlignment', defaultValue: 'bottom', }, { name: 'bar_horizontal_alignment', phosphorName: 'barHorizontalAlignment', defaultValue: 'left', }, { name: 'show_text', phosphorName: 'showText', defaultValue: true }, ]); } static serializers: ISerializers = { ...TextRendererModel.serializers, bar_color: { deserialize: unpack_models as any }, bar_value: { deserialize: unpack_models as any }, orientation: { deserialize: unpack_models as any }, bar_vertical_alignment: { deserialize: unpack_models as any }, bar_horizontal_alignment: { deserialize: unpack_models as any }, show_text: { deserialize: unpack_models as any }, }; static model_name = 'BarRendererModel'; static view_name = 'BarRendererView'; } export class BarRendererView extends TextRendererView { createRenderer(options: BarRenderer.IOptions) { return new BarRenderer({ ...options, format: this.getFormatter(), }); } renderer: BarRenderer; model: BarRendererModel; } export class HyperlinkRendererModel extends TextRendererModel { defaults() { return { ...super.defaults(), _model_name: BarRendererModel.model_name, _view_name: BarRendererModel.view_name, url: {}, url_name: {}, }; } get_attrs(): ICellRendererAttribute[] { return super.get_attrs().concat([ { name: 'url', phosphorName: 'url', defaultValue: null }, { name: 'url_name', phosphorName: 'urlName', defaultValue: null }, ]); } static serializers: ISerializers = { ...TextRendererModel.serializers, url: { deserialize: unpack_models as any }, url_name: { deserialize: unpack_models as any }, }; static model_name = 'HyperlinkRendererModel'; static view_name = 'HyperlinkRendererView'; } export class HyperlinkRendererView extends TextRendererView { createRenderer(options: HyperlinkRenderer.IOptions) { return new HyperlinkRenderer({ ...options, format: this.getFormatter(), }); } renderer: HyperlinkRenderer; model: HyperlinkRendererModel; }
the_stack
// clang-format off import 'chrome://resources/cr_elements/cr_input/cr_input.m.js'; import {CrInputElement} from 'chrome://resources/cr_elements/cr_input/cr_input.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {assertEquals, assertFalse, assertNotEquals, assertThrows, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {eventToPromise, isChildVisible, whenAttributeIs} from 'chrome://webui-test/test_util.js'; // clang-format on suite('cr-input', function() { let crInput: CrInputElement; let input: HTMLInputElement; setup(function() { regenerateNewInput(); }); function regenerateNewInput() { document.body.innerHTML = ''; crInput = document.createElement('cr-input'); document.body.appendChild(crInput); input = crInput.inputElement; flush(); } test('AttributesCorrectlySupported', function() { // [externalName, internalName, defaultValue, testValue] type AttributeData = [ keyof CrInputElement, keyof HTMLInputElement, boolean | number | string, boolean | number | string ]; const attributesToTest: AttributeData[] = [ ['autofocus', 'autofocus', false, true], ['disabled', 'disabled', false, true], ['max', 'max', '', '100'], ['min', 'min', '', '1'], ['maxlength', 'maxLength', -1, 5], ['minlength', 'minLength', -1, 5], ['pattern', 'pattern', '', '[a-z]+'], ['readonly', 'readOnly', false, true], ['required', 'required', false, true], ['tabindex', 'tabIndex', 0, -1], ['type', 'type', 'text', 'password'], ['inputmode', 'inputMode', '', 'none'], ]; attributesToTest.forEach( ([externalName, internalName, defaultValue, testValue]: AttributeData) => { regenerateNewInput(); assertEquals(defaultValue, input[internalName]); crInput.setAttribute(externalName, testValue.toString()); assertEquals(testValue, input[internalName]); }); }); test('UnsupportedTypeThrows', function() { assertThrows(function() { crInput.type = 'checkbox'; }); }); test('togglingDisableModifiesTabIndexCorrectly', function() { // Do innerHTML instead of createElement to make sure it's correct right // after being attached, and not messed up by disabledChanged_. document.body.innerHTML = ` <cr-input tabindex="14"></cr-input> `; crInput = document.querySelector('cr-input')!; input = crInput.$.input; flush(); assertEquals('14', crInput.getAttribute('tabindex')); assertEquals(14, input.tabIndex); crInput.disabled = true; assertEquals(null, crInput.getAttribute('tabindex')); assertEquals(true, input.disabled); crInput.disabled = false; assertEquals('14', crInput.getAttribute('tabindex')); assertEquals(14, input.tabIndex); }); test('startingWithDisableSetsTabIndexCorrectly', function() { // Makes sure tabindex is recorded even if cr-input starts as disabled document.body.innerHTML = ` <cr-input tabindex="14" disabled></cr-input> `; crInput = document.querySelector('cr-input')!; input = crInput.$.input; flush(); return whenAttributeIs(input, 'tabindex', null).then(() => { assertEquals(null, crInput.getAttribute('tabindex')); assertEquals(true, input.disabled); crInput.disabled = false; assertEquals('14', crInput.getAttribute('tabindex')); assertEquals(14, input.tabIndex); }); }); test('pointerDownAndTabIndex', function() { crInput.fire('pointerdown'); assertEquals(null, crInput.getAttribute('tabindex')); return whenAttributeIs(crInput, 'tabindex', '0').then(() => { assertEquals(0, input.tabIndex); }); }); test('pointerdownWhileDisabled', function(done) { // pointerdown while disabled doesn't mess with tabindex. crInput.tabindex = 14; crInput.disabled = true; assertEquals(null, crInput.getAttribute('tabindex')); assertEquals(true, input.disabled); crInput.fire('pointerdown'); assertEquals(null, crInput.getAttribute('tabindex')); // Wait one cycle to make sure tabindex is still unchanged afterwards. setTimeout(() => { assertEquals(null, crInput.getAttribute('tabindex')); // Makes sure tabindex is correctly restored after reverting disabled. crInput.disabled = false; assertEquals('14', crInput.getAttribute('tabindex')); assertEquals(14, input.tabIndex); done(); }); }); test('pointerdownThenDisabledInSameCycle', function(done) { crInput.tabindex = 14; // Edge case: pointerdown and disabled are changed in the same cycle. crInput.fire('pointerdown'); crInput.disabled = true; assertEquals(null, crInput.getAttribute('tabindex')); // Wait one cycle to make sure tabindex is still unchanged afterwards. setTimeout(() => { assertEquals(null, crInput.getAttribute('tabindex')); // Makes sure tabindex is correctly restored after reverting disabled. crInput.disabled = false; assertEquals('14', crInput.getAttribute('tabindex')); assertEquals(14, input.tabIndex); done(); }); }); test('placeholderCorrectlyBound', function() { assertFalse(input.hasAttribute('placeholder')); crInput.placeholder = ''; assertTrue(input.hasAttribute('placeholder')); crInput.placeholder = 'hello'; assertEquals('hello', input.getAttribute('placeholder')); crInput.placeholder = null; assertFalse(input.hasAttribute('placeholder')); }); test('labelHiddenWhenEmpty', function() { const label = crInput.$.label; assertEquals('none', getComputedStyle(crInput.$.label).display); crInput.label = 'foobar'; assertEquals('block', getComputedStyle(crInput.$.label).display); assertEquals('foobar', label.textContent!.trim()); }); test('valueSetCorrectly', function() { crInput.value = 'hello'; assertEquals(crInput.value, input.value); // |value| is copied when typing triggers inputEvent. input.value = 'hello sir'; input.dispatchEvent(new InputEvent('input')); assertEquals(crInput.value, input.value); }); test('focusState', function() { assertFalse(crInput.hasAttribute('focused_')); const underline = crInput.$.underline; const label = crInput.$.label; const originalLabelColor = getComputedStyle(label).color; function waitForTransitions(): Promise<TransitionEvent[]> { const events: TransitionEvent[] = []; return eventToPromise('transitionend', underline) .then(e => { events.push(e); return eventToPromise('transitionend', underline); }) .then(e => { events.push(e); return events; }); } assertEquals('0', getComputedStyle(underline).opacity); assertEquals(0, underline.offsetWidth); let whenTransitionsEnd = waitForTransitions(); input.focus(); assertTrue(crInput.hasAttribute('focused_')); assertNotEquals(originalLabelColor, getComputedStyle(label).color); return whenTransitionsEnd .then(events => { // Ensure transitions finished in the expected order. assertEquals(2, events.length); assertEquals('opacity', events[0]!.propertyName); assertEquals('width', events[1]!.propertyName); assertEquals('1', getComputedStyle(underline).opacity); assertNotEquals(0, underline.offsetWidth); whenTransitionsEnd = waitForTransitions(); input.blur(); return whenTransitionsEnd; }) .then(events => { // Ensure transitions finished in the expected order. assertEquals(2, events.length); assertEquals('opacity', events[0]!.propertyName); assertEquals('width', events[1]!.propertyName); assertFalse(crInput.hasAttribute('focused_')); assertEquals('0', getComputedStyle(underline).opacity); assertEquals(0, underline.offsetWidth); }); }); test('invalidState', function() { crInput.errorMessage = 'error'; const errorLabel = crInput.$.error; const underline = crInput.$.underline; const label = crInput.$.label; const originalLabelColor = getComputedStyle(label).color; const originalLineColor = getComputedStyle(underline).borderBottomColor; assertEquals('', errorLabel.textContent); assertFalse(errorLabel.hasAttribute('role')); assertEquals('0', getComputedStyle(underline).opacity); assertEquals(0, underline.offsetWidth); assertEquals('hidden', getComputedStyle(errorLabel).visibility); const whenTransitionEnd = eventToPromise('transitionend', underline); crInput.invalid = true; flush(); assertTrue(crInput.hasAttribute('invalid')); assertEquals('alert', errorLabel.getAttribute('role')); assertEquals(crInput.errorMessage, errorLabel.textContent); assertEquals('visible', getComputedStyle(errorLabel).visibility); assertTrue(originalLabelColor !== getComputedStyle(label).color); assertTrue( originalLineColor !== getComputedStyle(underline).borderBottomColor); return whenTransitionEnd.then(() => { assertEquals('1', getComputedStyle(underline).opacity); assertTrue(0 !== underline.offsetWidth); }); }); test('validation', function() { crInput.value = 'FOO'; crInput.autoValidate = true; assertFalse(crInput.hasAttribute('required')); assertFalse(crInput.invalid); // Note that even with |autoValidate|, crInput.invalid only updates after // |value| is changed. crInput.setAttribute('required', ''); assertFalse(crInput.invalid); crInput.value = ''; assertTrue(crInput.invalid); crInput.value = 'BAR'; assertFalse(crInput.invalid); const testPattern = '[a-z]+'; crInput.setAttribute('pattern', testPattern); crInput.value = 'FOO'; assertTrue(crInput.invalid); crInput.value = 'foo'; assertFalse(crInput.invalid); // Without |autoValidate|, crInput.invalid should not change even if input // value is not valid. crInput.autoValidate = false; crInput.value = 'ALL CAPS'; assertFalse(crInput.invalid); assertFalse(input.checkValidity()); crInput.value = ''; assertFalse(crInput.invalid); assertFalse(input.checkValidity()); }); test('numberValidation', function() { crInput.type = 'number'; crInput.value = '50'; crInput.autoValidate = true; assertFalse(crInput.invalid); // Note that even with |autoValidate|, crInput.invalid only updates after // |value| is changed. const testMin = 1; const testMax = 100; crInput.setAttribute('min', testMin.toString()); crInput.setAttribute('max', testMax.toString()); crInput.value = '200'; assertTrue(crInput.invalid); crInput.value = '20'; assertFalse(crInput.invalid); crInput.value = '-2'; assertTrue(crInput.invalid); crInput.value = '40'; assertFalse(crInput.invalid); // Without |autoValidate|, crInput.invalid should not change even if input // value is not valid. crInput.autoValidate = false; crInput.value = '200'; assertFalse(crInput.invalid); assertFalse(input.checkValidity()); crInput.value = '-2'; assertFalse(crInput.invalid); assertFalse(input.checkValidity()); }); test('ariaDescriptionsCorrect', function() { assertEquals(crInput.inputElement.getAttribute('aria-description'), null); const ariaDescription = 'description'; crInput.ariaDescription = ariaDescription; flush(); assertEquals( crInput.inputElement.getAttribute('aria-description'), ariaDescription); crInput.ariaDescription = undefined; flush(); assertEquals(crInput.inputElement.getAttribute('aria-description'), null); }); test('ariaLabelsCorrect', function() { assertFalse(!!crInput.inputElement.getAttribute('aria-label')); /** * This function assumes attributes are passed in priority order. */ function testAriaLabel(attributes: string[]) { document.body.innerHTML = ''; crInput = document.createElement('cr-input'); attributes.forEach(attribute => { // Using their name as the value out of convenience. crInput.setAttribute(attribute, attribute); }); document.body.appendChild(crInput); flush(); // Assuming first attribute takes priority. assertEquals( attributes[0], crInput.inputElement.getAttribute('aria-label')); } testAriaLabel(['aria-label', 'label', 'placeholder']); testAriaLabel(['label', 'placeholder']); testAriaLabel(['placeholder']); }); test('select', function() { crInput.value = '0123456789'; assertFalse(input.matches(':focus')); crInput.select(); assertTrue(input.matches(':focus')); assertEquals('0123456789', window.getSelection()!.toString()); regenerateNewInput(); crInput.value = '0123456789'; assertFalse(input.matches(':focus')); crInput.select(2, 6); assertTrue(input.matches(':focus')); assertEquals('2345', window.getSelection()!.toString()); regenerateNewInput(); crInput.value = ''; assertFalse(input.matches(':focus')); crInput.select(); assertTrue(input.matches(':focus')); assertEquals('', window.getSelection()!.toString()); }); test('slots', function() { document.body.innerHTML = ` <cr-input> <div slot="inline-prefix" id="inline-prefix">One</div> <div slot="suffix" id="suffix">Two</div> <div slot="inline-suffix" id="inline-suffix">Three</div> </cr-input> `; flush(); crInput = document.querySelector('cr-input')!; assertTrue(isChildVisible(crInput, '#inline-prefix', true)); assertTrue(isChildVisible(crInput, '#suffix', true)); assertTrue(isChildVisible(crInput, '#inline-suffix', true)); }); });
the_stack
import { isArray } from '@antv/util'; import rectPath from './rect-path'; import path2Curve from './path-2-curve'; const base3 = function (t: number, p1: number, p2: number, p3: number, p4: number): number { const t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4; const t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; return t * t2 - 3 * p1 + 3 * p2; }; const bezlen = function (x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number, z: number): number { if (z === null) { z = 1; } z = z > 1 ? 1 : z < 0 ? 0 : z; const z2 = z / 2; const n = 12; const Tvalues = [ -0.1252, 0.1252, -0.3678, 0.3678, -0.5873, 0.5873, -0.7699, 0.7699, -0.9041, 0.9041, -0.9816, 0.9816 ]; const Cvalues = [ 0.2491, 0.2491, 0.2335, 0.2335, 0.2032, 0.2032, 0.1601, 0.1601, 0.1069, 0.1069, 0.0472, 0.0472 ]; let sum = 0; for (let i = 0; i < n; i++) { const ct = z2 * Tvalues[i] + z2; const xbase = base3(ct, x1, x2, x3, x4); const ybase = base3(ct, y1, y2, y3, y4); const comb = xbase * xbase + ybase * ybase; sum += Cvalues[i] * Math.sqrt(comb); } return z2 * sum; }; export interface Point { x: number; y: number; } export interface BoundPoint { min: Point; max: Point; } const curveDim = function (x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number): BoundPoint { const tvalues = []; const bounds = [ [], [], ]; let a; let b; let c; let t; for (let i = 0; i < 2; ++i) { if (i === 0) { b = 6 * x0 - 12 * x1 + 6 * x2; a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3; c = 3 * x1 - 3 * x0; } else { b = 6 * y0 - 12 * y1 + 6 * y2; a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3; c = 3 * y1 - 3 * y0; } if (Math.abs(a) < 1e-12) { if (Math.abs(b) < 1e-12) { continue; } t = -c / b; if (t > 0 && t < 1) { tvalues.push(t); } continue; } const b2ac = b * b - 4 * c * a; const sqrtb2ac = Math.sqrt(b2ac); if (b2ac < 0) { continue; } const t1 = (-b + sqrtb2ac) / (2 * a); if (t1 > 0 && t1 < 1) { tvalues.push(t1); } const t2 = (-b - sqrtb2ac) / (2 * a); if (t2 > 0 && t2 < 1) { tvalues.push(t2); } } let j = tvalues.length; const jlen = j; let mt; while (j--) { t = tvalues[j]; mt = 1 - t; bounds[0][j] = (mt * mt * mt * x0) + (3 * mt * mt * t * x1) + (3 * mt * t * t * x2) + (t * t * t * x3); bounds[1][j] = (mt * mt * mt * y0) + (3 * mt * mt * t * y1) + (3 * mt * t * t * y2) + (t * t * t * y3); } bounds[0][jlen] = x0; bounds[1][jlen] = y0; bounds[0][jlen + 1] = x3; bounds[1][jlen + 1] = y3; bounds[0].length = bounds[1].length = jlen + 2; return { min: { x: Math.min.apply(0, bounds[0]), y: Math.min.apply(0, bounds[1]), }, max: { x: Math.max.apply(0, bounds[0]), y: Math.max.apply(0, bounds[1]), }, }; }; const intersect = function (x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number): Point { if ( Math.max(x1, x2) < Math.min(x3, x4) || Math.min(x1, x2) > Math.max(x3, x4) || Math.max(y1, y2) < Math.min(y3, y4) || Math.min(y1, y2) > Math.max(y3, y4) ) { return; } const nx = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4); const ny = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4); const denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); if (!denominator) { return; } const px = nx / denominator; const py = ny / denominator; const px2 = +px.toFixed(2); const py2 = +py.toFixed(2); if ( px2 < +Math.min(x1, x2).toFixed(2) || px2 > +Math.max(x1, x2).toFixed(2) || px2 < +Math.min(x3, x4).toFixed(2) || px2 > +Math.max(x3, x4).toFixed(2) || py2 < +Math.min(y1, y2).toFixed(2) || py2 > +Math.max(y1, y2).toFixed(2) || py2 < +Math.min(y3, y4).toFixed(2) || py2 > +Math.max(y3, y4).toFixed(2) ) { return; } return { x: px, y: py, }; }; const isPointInsideBBox = function (bbox, x, y) { return x >= bbox.x && x <= bbox.x + bbox.width && y >= bbox.y && y <= bbox.y + bbox.height; }; const box = function (x, y, width, height) { if (x === null) { x = y = width = height = 0; } if (y === null) { y = x.y; width = x.width; height = x.height; x = x.x; } return { x, y, width, w: width, height, h: height, x2: x + width, y2: y + height, cx: x + width / 2, cy: y + height / 2, r1: Math.min(width, height) / 2, r2: Math.max(width, height) / 2, r0: Math.sqrt(width * width + height * height) / 2, path: rectPath(x, y, width, height), vb: [ x, y, width, height ].join(' '), }; }; const isBBoxIntersect = function (bbox1, bbox2) { // @ts-ignore bbox1 = box(bbox1); // @ts-ignore bbox2 = box(bbox2); return isPointInsideBBox(bbox2, bbox1.x, bbox1.y) || isPointInsideBBox(bbox2, bbox1.x2, bbox1.y) || isPointInsideBBox(bbox2, bbox1.x, bbox1.y2) || isPointInsideBBox(bbox2, bbox1.x2, bbox1.y2) || isPointInsideBBox(bbox1, bbox2.x, bbox2.y) || isPointInsideBBox(bbox1, bbox2.x2, bbox2.y) || isPointInsideBBox(bbox1, bbox2.x, bbox2.y2) || isPointInsideBBox(bbox1, bbox2.x2, bbox2.y2) || (bbox1.x < bbox2.x2 && bbox1.x > bbox2.x || bbox2.x < bbox1.x2 && bbox2.x > bbox1.x) && (bbox1.y < bbox2.y2 && bbox1.y > bbox2.y || bbox2.y < bbox1.y2 && bbox2.y > bbox1.y); }; const bezierBBox = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) { if (!isArray(p1x)) { p1x = [ p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y ]; } const bbox = curveDim.apply(null, p1x); return box( bbox.min.x, bbox.min.y, bbox.max.x - bbox.min.x, bbox.max.y - bbox.min.y, ); }; const findDotsAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { const t1 = 1 - t; const t13 = Math.pow(t1, 3); const t12 = Math.pow(t1, 2); const t2 = t * t; const t3 = t2 * t; const x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x; const y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y; const mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x); const my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y); const nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x); const ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y); const ax = t1 * p1x + t * c1x; const ay = t1 * p1y + t * c1y; const cx = t1 * c2x + t * p2x; const cy = t1 * c2y + t * p2y; const alpha = (90 - Math.atan2(mx - nx, my - ny) * 180 / Math.PI); // (mx > nx || my < ny) && (alpha += 180); return { x, y, m: { x: mx, y: my, }, n: { x: nx, y: ny, }, start: { x: ax, y: ay, }, end: { x: cx, y: cy, }, alpha, }; }; const interHelper = function (bez1, bez2, justCount) { // @ts-ignore const bbox1 = bezierBBox(bez1); // @ts-ignore const bbox2 = bezierBBox(bez2); if (!isBBoxIntersect(bbox1, bbox2)) { return justCount ? 0 : []; } const l1 = bezlen.apply(0, bez1); const l2 = bezlen.apply(0, bez2); const n1 = ~~(l1 / 8); const n2 = ~~(l2 / 8); const dots1 = []; const dots2 = []; const xy = {}; let res = justCount ? 0 : []; for (let i = 0; i < n1 + 1; i++) { const d = findDotsAtSegment.apply(0, bez1.concat(i / n1)); dots1.push({ x: d.x, y: d.y, t: i / n1, }); } for (let i = 0; i < n2 + 1; i++) { const d = findDotsAtSegment.apply(0, bez2.concat(i / n2)); dots2.push({ x: d.x, y: d.y, t: i / n2, }); } for (let i = 0; i < n1; i++) { for (let j = 0; j < n2; j++) { const di = dots1[i]; const di1 = dots1[i + 1]; const dj = dots2[j]; const dj1 = dots2[j + 1]; const ci = Math.abs(di1.x - di.x) < 0.001 ? 'y' : 'x'; const cj = Math.abs(dj1.x - dj.x) < 0.001 ? 'y' : 'x'; const is = intersect(di.x, di.y, di1.x, di1.y, dj.x, dj.y, dj1.x, dj1.y); if (is) { if (xy[is.x.toFixed(4)] === is.y.toFixed(4)) { continue; } xy[is.x.toFixed(4)] = is.y.toFixed(4); const t1 = di.t + Math.abs((is[ci] - di[ci]) / (di1[ci] - di[ci])) * (di1.t - di.t); const t2 = dj.t + Math.abs((is[cj] - dj[cj]) / (dj1[cj] - dj[cj])) * (dj1.t - dj.t); if (t1 >= 0 && t1 <= 1 && t2 >= 0 && t2 <= 1) { if (justCount) { // @ts-ignore res++; } else { // @ts-ignore res.push({ x: is.x, y: is.y, t1, t2, }); } } } } } return res; }; const interPathHelper = function (path1, path2, justCount) { // @ts-ignore path1 = path2Curve(path1); // @ts-ignore path2 = path2Curve(path2); let x1; let y1; let x2; let y2; let x1m; let y1m; let x2m; let y2m; let bez1; let bez2; let res = justCount ? 0 : []; for (let i = 0, ii = path1.length; i < ii; i++) { const pi = path1[i]; if (pi[0] === 'M') { x1 = x1m = pi[1]; y1 = y1m = pi[2]; } else { if (pi[0] === 'C') { bez1 = [ x1, y1 ].concat(pi.slice(1)); x1 = bez1[6]; y1 = bez1[7]; } else { bez1 = [ x1, y1, x1, y1, x1m, y1m, x1m, y1m ]; x1 = x1m; y1 = y1m; } for (let j = 0, jj = path2.length; j < jj; j++) { const pj = path2[j]; if (pj[0] === 'M') { x2 = x2m = pj[1]; y2 = y2m = pj[2]; } else { if (pj[0] === 'C') { bez2 = [ x2, y2 ].concat(pj.slice(1)); x2 = bez2[6]; y2 = bez2[7]; } else { bez2 = [ x2, y2, x2, y2, x2m, y2m, x2m, y2m ]; x2 = x2m; y2 = y2m; } const intr = interHelper(bez1, bez2, justCount); if (justCount) { // @ts-ignore res += intr; } else { // @ts-ignore for (let k = 0, kk = intr.length; k < kk; k++) { intr[k].segment1 = i; intr[k].segment2 = j; intr[k].bez1 = bez1; intr[k].bez2 = bez2; } // @ts-ignore res = res.concat(intr); } } } } } return res; }; export default function pathIntersection(path1, path2) { // @ts-ignore return interPathHelper(path1, path2); }
the_stack
import modalMixin from './modal-mixin' import ProgressBar from '../../vue/component/ProgressBar.vue' import TabSmall from '../../vue/component/TabSmall.vue' import InputRadio from '../../vue/component/InputRadio.vue' import InputText from '../../vue/component/InputText.vue' import privateStatus from './calculator-data' import Component, { mixins } from 'vue-class-component' import { Prop, Watch } from 'vue-property-decorator' // import { MasterData } from '../main/on-master-read' const { ipcRenderer } = window.node.electron @Component({ components: { ProgressBar, TabSmall, InputRadio, InputText } }) export default class extends mixins(modalMixin) { modalWidth = '920px' isCounting = false // 是否正在进行体力计时 currentEventTab = 'ATAPON' // 当前活动计算板块 stamina = 0 // 已恢复的stamina,以秒记 staminaSpeed = 300 // 恢复速度,以秒记 staminaTimer: NodeJS.Timer | number = 0 // 计时器开关 eventType: any = { 1: 'ATAPON', 2: 'CARAVAN', 3: 'MEDLEY', 5: 'TOUR' } publicStatus: any = { plv: '1', stamina: '0', exp: '0' } privateStatus: any = privateStatus // @Prop({ default: () => ({}), type: Object }) master: MasterData @Prop({ default: new Date().getTime() }) time: number get eventData (): any { return this.$store.state.master.eventData /* ? this.master.eventData : {} */ } get userLevel (): any[] { return this.$store.state.master.userLevel } get timeOffset (): number { return this.$store.state.master.timeOffset || 0 } get eventTimeTotal (): number { if (!this.eventData) return 1 return new Date(this.eventData.event_end).getTime() - new Date(this.eventData.event_start).getTime() } get eventTimeGone (): number { if (!this.eventData) return 0 return this.time - (new Date(this.eventData.event_start).getTime() - this.timeOffset) } get eventTimeLeft (): number { return this.eventTimeTotal - this.eventTimeGone > 0 ? this.eventTimeTotal - this.eventTimeGone : 0 } get eventTimePercent (): number { return this.eventTimeGone / this.eventTimeTotal > 1 ? 100 : 100 * this.eventTimeGone / this.eventTimeTotal } get maxStamina (): number { if (!this.publicStatus.plv || !this.userLevel) return 0 return this.userLevel.filter((level: any) => Number(level.level) === Number(this.publicStatus.plv))[0].stamina } get maxExp (): number { if (!this.publicStatus.plv || !this.userLevel || Number(this.publicStatus.plv) === 300) return Infinity return this.userLevel.filter((level) => Number(level.level) === Number(this.publicStatus.plv))[0].exp } get staminaPercent (): number { if (this.stamina && this.maxStamina) return 100 * this.stamina / (this.maxStamina * this.staminaSpeed) return 0 } get staminaTimeLeft (): string { if (this.stamina && this.maxStamina) return this.timeFormate(1000 * (this.maxStamina * this.staminaSpeed - this.stamina)) return '00:00' } @Watch('eventData') eventDataWatchHandler (v: any): void { if (v.type === 6) this.currentEventTab = 'ATAPON' else this.currentEventTab = this.eventType[v.type] } toggle (eventType: string): void { // console.log(eventType) this.currentEventTab = eventType } stopCount (): void { this.playSe(this.cancelSe) this.isCounting = false clearInterval(this.staminaTimer as NodeJS.Timer) this.stamina = 0 } startCount (): void { this.playSe(this.enterSe) if (!isNaN(this.publicStatus.stamina) && this.publicStatus.stamina < this.maxStamina * this.staminaSpeed) { this.stamina = this.publicStatus.stamina * this.staminaSpeed if (this.stamina >= this.maxStamina * this.staminaSpeed) return this.isCounting = true this.staminaTimer = setInterval(() => { this.stamina++ this.publicStatus.stamina = Math.floor(this.stamina / this.staminaSpeed) if (this.stamina >= this.maxStamina * this.staminaSpeed) { clearInterval(this.staminaTimer as NodeJS.Timer) this.isCounting = false ipcRenderer.send('flash') this.event.$emit('alert', this.$t('home.msg'), this.$t('home.stmnFull')) } }, 1000) } } calculate (): void { this.playSe(this.enterSe) if (this.currentEventTab === 'ATAPON') { this.ataponCal() } else if (this.currentEventTab === 'TOUR') { this.tourCal() } else if (this.currentEventTab === 'MEDLEY') { this.medleyCal() } else if (this.currentEventTab === 'CARAVAN') { this.caravanCal() } else { this.event.$emit('alert', this.$t('home.errorTitle'), this.$t('home.hope')) } } clear (): void { this.playSe(this.cancelSe) if (this.currentEventTab === 'ATAPON') { // clearInterval(this.privateStatus['1'].timer) for (const key in this.privateStatus['1'].output) { if (key === 'gameTime') this.privateStatus['1'].output[key] = '00:00' else this.privateStatus['1'].output[key] = 0 } } else if (this.currentEventTab === 'TOUR') { for (const key in this.privateStatus['5'].output) { if (key === 'gameTime') this.privateStatus['5'].output[key] = '00:00' else this.privateStatus['5'].output[key] = 0 } } else if (this.currentEventTab === 'MEDLEY') { for (const key in this.privateStatus['3'].output) { if (key === 'gameTime') this.privateStatus['3'].output[key] = '00:00' else this.privateStatus['3'].output[key] = 0 } } else if (this.currentEventTab === 'CARAVAN') { for (const key in this.privateStatus['2'].output) { if (key === 'gameTime') this.privateStatus['2'].output[key] = '00:00' else if (key === 'extraRewardOdds') this.privateStatus['2'].output[key] = '0/0/0/0/0' else if (key === 'cardRewardOdds') this.privateStatus['2'].output[key] = '0.00/0.00' else this.privateStatus['2'].output[key] = 0 } } else { this.event.$emit('alert', this.$t('home.errorTitle'), this.$t('home.hope')) } } timeFormate (t: number): string { const day = Math.floor(t / 1000 / 60 / 60 / 24) const hour = Math.floor(t / 1000 / 60 / 60 % 24) const minute = Math.floor(t / 1000 / 60 % 60) const second = Math.floor(t / 1000 % 60) return `${day ? `${day}日` : ''}${day ? (hour >= 10 ? `${hour}:` : `0${hour}:`) : (hour ? (hour >= 10 ? `${hour}:` : `0${hour}:`) : '')}${minute >= 10 ? minute : `0${minute}`}:${second >= 10 ? second : `0${second}`}` } getExp (plv: number | string): number { if (plv >= 300) return Infinity return this.userLevel.filter((level) => Number(level.level) === Number(plv))[0].exp } getMaxStamina (plv: number | string): number { return this.userLevel.filter((level) => Number(level.level) === Number(plv))[0].stamina } getLevelUpTimes (liveTimes: number, expPerTime: number, currentExp: number | string): number { let levelUp = 0 let gotExp = liveTimes * expPerTime + Number(currentExp) let tempLevel = this.publicStatus.plv // console.log('gotExp = ' + (liveTimes * expPerTime)) while (gotExp >= this.getExp(tempLevel)) { gotExp = gotExp - this.getExp(tempLevel) tempLevel++ levelUp++ } return levelUp } ptCount (times: number, use: number, levelUp: number, typeCode: string, loginStamina?: number): void { // console.log(times, use, levelUp, typeCode, loginStamina) let levelStamina = 0 let tempLevel = Number(this.publicStatus.plv) const speed = this.staminaSpeed const currentStaminaSeconds = this.stamina let stmn = 0 let seconds = 0 for (let i = 0; i < levelUp; i++) { tempLevel++ levelStamina = levelStamina + this.getMaxStamina(tempLevel) } if (loginStamina) { stmn = Math.ceil((times * use * speed - currentStaminaSeconds) / speed) - levelStamina - loginStamina seconds = times * use * speed - currentStaminaSeconds - levelStamina * speed - loginStamina * speed } else { stmn = Math.ceil((times * use * speed - currentStaminaSeconds) / speed) - levelStamina seconds = times * use * speed - currentStaminaSeconds - levelStamina * speed } this.privateStatus[typeCode].output.requireStamina = stmn > 0 ? stmn : 0 this.privateStatus[typeCode].output.gameTime = this.timeFormate(seconds > 0 ? seconds * 1000 : 0) let extraStamina = 0 if (seconds > this.eventTimeLeft / 1000) { extraStamina = Math.ceil((seconds - this.eventTimeLeft / 1000) / speed) } this.privateStatus[typeCode].output.extraStamina = extraStamina } mounted (): void { this.$nextTick(() => { this.event.$on('openCal', () => { this.show = true this.visible = true }) }) } ataponCal (): void { const curExp = Number(this.publicStatus.exp) const curItem = Number(this.privateStatus['1'].input.itemNumber.model) const curPt = Number(this.privateStatus['1'].input.currentPt.model) const tarPt = Number(this.privateStatus['1'].input.targetPt.model) const comDi = this.privateStatus['1'].input.commonDifficulty.model.split(' ') const evtDi = this.privateStatus['1'].input.eventDifficulty.model.split(' ') const cb = Number(this.privateStatus['1'].input.commonTimes.model) const eb = Number(this.privateStatus['1'].input.eventTimes.model) const cGet = Number(comDi[1]) const eUse = Number(evtDi[0]) const eGet = Number(evtDi[1]) let dateOffset = new Date(this.time + this.eventTimeLeft + this.timeOffset).getDate() - new Date(this.time + this.timeOffset).getDate() if (dateOffset < 0) dateOffset += new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate() const loginItem = 300 * dateOffset // console.log('loginItem = ' + loginItem) const reqPt = (tarPt - curPt) > 0 ? tarPt - curPt : 0 let eventLiveTimes = 0 let commonLiveTimes = 0 let reqItem = 0 // 对道具列方程:commonLiveTimes * cb * cGet + curItem + loginItem = eventLiveTimes * eUse * eb // 对pt列方程: commonLiveTimes * cGet + eventLiveTimes * eGet * eb = reqPt if (Math.floor((loginItem + Number(curItem)) / eUse / eb) >= Math.ceil(reqPt / eGet / eb)) { eventLiveTimes = Math.ceil(reqPt / eGet / eb) commonLiveTimes = 0 reqItem = 0 // console.log('pt = ' + (commonLiveTimes * cGet + eventLiveTimes * eGet * eb)) } else { commonLiveTimes = (reqPt * eUse - eGet * (Number(curItem) + loginItem)) / (cb * cGet * eGet + cGet * eUse) eventLiveTimes = (commonLiveTimes * cb * cGet + Number(curItem) + loginItem) / (eUse * eb) // 先向上取整eventLiveTimes,用取整后的eventLiveTimes再算一次commonLiveTimes,再对commonLiveTimes向上取整 eventLiveTimes = Math.ceil(eventLiveTimes) commonLiveTimes = Math.ceil((eventLiveTimes * eUse * eb - loginItem - Number(curItem)) / (cGet * cb)) // 修正eventLiveTimes溢出 if ((commonLiveTimes * cGet + eventLiveTimes * eGet * eb - reqPt) / eGet / eb >= 1) { eventLiveTimes = eventLiveTimes - 1 } reqItem = eventLiveTimes * eUse * eb - loginItem - curItem // 修正commonLiveTimes溢出 if ((commonLiveTimes * cGet + eventLiveTimes * eGet * eb - reqPt) / cGet >= 1 && (commonLiveTimes * cGet * cb - reqItem) / cGet / cb >= 1) { commonLiveTimes = commonLiveTimes - Math.floor((commonLiveTimes * cGet + eventLiveTimes * eGet * eb - reqPt) / cGet) } // console.log('pt = ' + (commonLiveTimes * cGet + eventLiveTimes * eGet * eb)) } // 算可升级次数及体力 let levelUp = 0 let gotExp = commonLiveTimes * Number(comDi[2]) + eventLiveTimes * Number(evtDi[2]) + Number(curExp) let tempLevel = Number(this.publicStatus.plv) // console.log('gotExp = ' + (gotExp - Number(curExp))) while (gotExp >= this.getExp(tempLevel)) { gotExp = gotExp - this.getExp(tempLevel) tempLevel++ levelUp++ } this.privateStatus['1'].output.levelUp = levelUp this.privateStatus['1'].output.requirePt = reqPt this.privateStatus['1'].output.requireItem = reqItem > 0 ? reqItem : 0 this.privateStatus['1'].output.commonLiveTimes = commonLiveTimes this.privateStatus['1'].output.eventLiveTimes = eventLiveTimes this.privateStatus['1'].output.bonusItem = loginItem this.ptCount(commonLiveTimes, comDi[0] * cb, levelUp, '1') /* clearInterval(this.privateStatus['1'].timer) this.privateStatus['1'].timer = setInterval(() => { this.ptCount(commonLiveTimes, comDi[0] * cb, levelUp, '1') }, 1000) */ } caravanCal (): void { const curExp = Number(this.publicStatus.exp) const curMdl = Number(this.privateStatus['2'].input.currentMedal.model) const tarMdl = Number(this.privateStatus['2'].input.targetMedal.model) const comDi = this.privateStatus['2'].input.commonDifficulty.model.split(' ') const starRank = this.privateStatus['2'].input.starRank.model let tsuikaritsu = 0 let dateOffset = new Date(this.time + this.eventTimeLeft + this.timeOffset).getDate() - new Date(this.time + this.timeOffset).getDate() if (dateOffset < 0) dateOffset += new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate() const loginStamina = 50 * dateOffset let zero = 0 let one = 0 let two = 0 let three = 0 let four = 0 let avrMdl = 0 let kaiSRshutsugen = 0 let jouiSRshutsugen = 0 if (starRank <= 15) { tsuikaritsu = Number(changeDecimal((starRank * 0.1 + 1.0) * 0.4 * comDi[2], 2, 'round')) zero = (1 - tsuikaritsu) * (1 - tsuikaritsu) one = 2 * tsuikaritsu * (1 - tsuikaritsu) two = tsuikaritsu * tsuikaritsu three = 0 four = 0 avrMdl = comDi[1] * one * 0.85 + comDi[1] * two * 1.37 kaiSRshutsugen = one * 0.02 + two * 0.12 jouiSRshutsugen = one * 0.01 + two * 0.03 } else { tsuikaritsu = Number(changeDecimal((0.2 * (starRank - 15)) * comDi[2], 2, 'round')) zero = 0 one = 0 two = (1 - tsuikaritsu) * (1 - tsuikaritsu) three = 2 * tsuikaritsu * (1 - tsuikaritsu) four = tsuikaritsu * tsuikaritsu avrMdl = comDi[1] * two * 1.37 + comDi[1] * three * 2.22 + comDi[1] * four * 2.74 kaiSRshutsugen = two * 0.12 + three * 0.14 + four * 0.24 jouiSRshutsugen = two * 0.03 + three * 0.04 + four * 0.06 } const reqMdl = (tarMdl - curMdl) > 0 ? tarMdl - curMdl : 0 let liveTimes = Math.ceil((tarMdl - curMdl) / avrMdl) if (liveTimes < 0) liveTimes = 0 zero = Math.round(zero * 100) one = Math.round(one * 100) two = Math.round(two * 100) three = Math.round(three * 100) four = Math.round(four * 100) avrMdl = Math.round(avrMdl) kaiSRshutsugen = Number(changeDecimal(kaiSRshutsugen * liveTimes, 2, 'round')) jouiSRshutsugen = Number(changeDecimal(jouiSRshutsugen * liveTimes, 2, 'round')) const levelUp = this.getLevelUpTimes(liveTimes, comDi[3], curExp) this.privateStatus['2'].output.levelUp = levelUp this.privateStatus['2'].output.extraRewardOdds = `${zero}/${one}/${two}/${three}/${four}` this.privateStatus['2'].output.cardRewardOdds = `${jouiSRshutsugen}/${kaiSRshutsugen}` this.privateStatus['2'].output.averageMedal = avrMdl this.privateStatus['2'].output.requireMedal = reqMdl this.privateStatus['2'].output.commonLiveTimes = liveTimes > 0 ? liveTimes : 0 this.privateStatus['2'].output.bonusStamina = loginStamina this.ptCount(liveTimes, Number(comDi[0]), levelUp, '2', loginStamina) } medleyCal (): void { const curExp = Number(this.publicStatus.exp) const curPt = Number(this.privateStatus['3'].input.currentPt.model) const tarPt = Number(this.privateStatus['3'].input.targetPt.model) const evtDi = this.privateStatus['3'].input.eventDifficulty.model.split(' ') const hkyr = this.privateStatus['3'].input.hakoyureLevel.model.split(' ') let dateOffset = new Date(this.time + this.eventTimeLeft + this.timeOffset).getDate() - new Date(this.time + this.timeOffset).getDate() if (dateOffset < 0) dateOffset += new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate() const loginStamina = 50 * dateOffset // console.log('loginItem = ' + loginItem) const reqPt = (tarPt - curPt) > 0 ? tarPt - curPt : 0 let liveTimes = Math.ceil((tarPt - curPt) / (Number(evtDi[2]) + Number(hkyr[evtDi[0]]))) if (liveTimes < 0) liveTimes = 0 const levelUp = this.getLevelUpTimes(liveTimes, evtDi[3], curExp) this.privateStatus['3'].output.levelUp = levelUp this.privateStatus['3'].output.requirePt = reqPt this.privateStatus['3'].output.eventLiveTimes = liveTimes > 0 ? liveTimes : 0 this.privateStatus['3'].output.bonusStamina = loginStamina this.ptCount(liveTimes, Number(evtDi[1]), levelUp, '3', loginStamina) } tourCal (): void { const curExp = Number(this.publicStatus.exp) const curAd = Number(this.privateStatus['5'].input.currentAudience.model) const tarAd = Number(this.privateStatus['5'].input.targetAudience.model) const useArr = this.privateStatus['5'].input.areaStamina.model.split(' ') const liveOption = this.privateStatus['5'].input.liveOption.model let dateOffset = new Date(this.time + this.eventTimeLeft + this.timeOffset).getDate() - new Date(this.time + this.timeOffset).getDate() if (dateOffset < 0) dateOffset += new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate() const loginStamina = 50 * dateOffset // console.log('loginItem = ' + loginItem) const reqAd = (tarAd - curAd) > 0 ? tarAd - curAd : 0 let liveTimes = Math.ceil(reqAd / (useArr[2] * (1 + 0.015 * useArr[1] + Number(liveOption)))) if (liveTimes < 0) liveTimes = 0 const levelUp = this.getLevelUpTimes(liveTimes, useArr[3], curExp) this.privateStatus['5'].output.levelUp = levelUp this.privateStatus['5'].output.requireAudience = reqAd this.privateStatus['5'].output.eventLiveTimes = liveTimes > 0 ? liveTimes : 0 this.privateStatus['5'].output.bonusStamina = loginStamina this.ptCount(liveTimes, Number(useArr[0]), levelUp, '5', loginStamina) } } function changeDecimal (x: string | number, n: number, op: string): string { x = parseFloat(x as string) let c = 1 if (isNaN(x)) { return '' } for (let i = 0; i < n; i++) { c = c * 10 } switch (op) { case 'round': x = Math.round(x * c) / c break case 'ceil': x = Math.ceil(x * c) / c break case 'floor': x = Math.floor(x * c) / c break default: x = Math.round(x * c) / c break } let xs = x.toString() let dp = xs.indexOf('.') if (dp < 0) { dp = xs.length xs += '.' } while (xs.length <= dp + n) { xs += '0' } return xs }
the_stack
import { mXparserConstants } from '../mXparserConstants'; /** * Random variables - mXparserConstants tokens definition. * * @author <b>Mariusz Gromada</b><br> * <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br> * <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser on GitHub</a><br> * * @version 4.1.0 * @class */ export class RandomVariable { public static TYPE_ID: number = 10; public static TYPE_DESC: string = "Random Variable"; public static UNIFORM_ID: number = 1; public static INT_ID: number = 2; public static INT1_ID: number = 3; public static INT2_ID: number = 4; public static INT3_ID: number = 5; public static INT4_ID: number = 6; public static INT5_ID: number = 7; public static INT6_ID: number = 8; public static INT7_ID: number = 9; public static INT8_ID: number = 10; public static INT9_ID: number = 11; public static NAT0_ID: number = 12; public static NAT0_1_ID: number = 13; public static NAT0_2_ID: number = 14; public static NAT0_3_ID: number = 15; public static NAT0_4_ID: number = 16; public static NAT0_5_ID: number = 17; public static NAT0_6_ID: number = 18; public static NAT0_7_ID: number = 19; public static NAT0_8_ID: number = 20; public static NAT0_9_ID: number = 21; public static NAT1_ID: number = 22; public static NAT1_1_ID: number = 23; public static NAT1_2_ID: number = 24; public static NAT1_3_ID: number = 25; public static NAT1_4_ID: number = 26; public static NAT1_5_ID: number = 27; public static NAT1_6_ID: number = 28; public static NAT1_7_ID: number = 29; public static NAT1_8_ID: number = 30; public static NAT1_9_ID: number = 31; public static NOR_ID: number = 32; public static UNIFORM_STR: string = "[Uni]"; public static INT_STR: string = "[Int]"; public static INT1_STR: string = "[Int1]"; public static INT2_STR: string = "[Int2]"; public static INT3_STR: string = "[Int3]"; public static INT4_STR: string = "[Int4]"; public static INT5_STR: string = "[Int5]"; public static INT6_STR: string = "[Int6]"; public static INT7_STR: string = "[Int7]"; public static INT8_STR: string = "[Int8]"; public static INT9_STR: string = "[Int9]"; public static NAT0_STR: string = "[nat]"; public static NAT0_1_STR: string = "[nat1]"; public static NAT0_2_STR: string = "[nat2]"; public static NAT0_3_STR: string = "[nat3]"; public static NAT0_4_STR: string = "[nat4]"; public static NAT0_5_STR: string = "[nat5]"; public static NAT0_6_STR: string = "[nat6]"; public static NAT0_7_STR: string = "[nat7]"; public static NAT0_8_STR: string = "[nat8]"; public static NAT0_9_STR: string = "[nat9]"; public static NAT1_STR: string = "[Nat]"; public static NAT1_1_STR: string = "[Nat1]"; public static NAT1_2_STR: string = "[Nat2]"; public static NAT1_3_STR: string = "[Nat3]"; public static NAT1_4_STR: string = "[Nat4]"; public static NAT1_5_STR: string = "[Nat5]"; public static NAT1_6_STR: string = "[Nat6]"; public static NAT1_7_STR: string = "[Nat7]"; public static NAT1_8_STR: string = "[Nat8]"; public static NAT1_9_STR: string = "[Nat9]"; public static NOR_STR: string = "[Nor]"; public static UNIFORM_SYN: string; public static UNIFORM_SYN_$LI$(): string { if (RandomVariable.UNIFORM_SYN == null) { RandomVariable.UNIFORM_SYN = RandomVariable.UNIFORM_STR; } return RandomVariable.UNIFORM_SYN; } public static INT_SYN: string; public static INT_SYN_$LI$(): string { if (RandomVariable.INT_SYN == null) { RandomVariable.INT_SYN = RandomVariable.INT_STR; } return RandomVariable.INT_SYN; } public static INT1_SYN: string; public static INT1_SYN_$LI$(): string { if (RandomVariable.INT1_SYN == null) { RandomVariable.INT1_SYN = RandomVariable.INT1_STR; } return RandomVariable.INT1_SYN; } public static INT2_SYN: string; public static INT2_SYN_$LI$(): string { if (RandomVariable.INT2_SYN == null) { RandomVariable.INT2_SYN = RandomVariable.INT2_STR; } return RandomVariable.INT2_SYN; } public static INT3_SYN: string; public static INT3_SYN_$LI$(): string { if (RandomVariable.INT3_SYN == null) { RandomVariable.INT3_SYN = RandomVariable.INT3_STR; } return RandomVariable.INT3_SYN; } public static INT4_SYN: string; public static INT4_SYN_$LI$(): string { if (RandomVariable.INT4_SYN == null) { RandomVariable.INT4_SYN = RandomVariable.INT4_STR; } return RandomVariable.INT4_SYN; } public static INT5_SYN: string; public static INT5_SYN_$LI$(): string { if (RandomVariable.INT5_SYN == null) { RandomVariable.INT5_SYN = RandomVariable.INT5_STR; } return RandomVariable.INT5_SYN; } public static INT6_SYN: string; public static INT6_SYN_$LI$(): string { if (RandomVariable.INT6_SYN == null) { RandomVariable.INT6_SYN = RandomVariable.INT6_STR; } return RandomVariable.INT6_SYN; } public static INT7_SYN: string; public static INT7_SYN_$LI$(): string { if (RandomVariable.INT7_SYN == null) { RandomVariable.INT7_SYN = RandomVariable.INT7_STR; } return RandomVariable.INT7_SYN; } public static INT8_SYN: string; public static INT8_SYN_$LI$(): string { if (RandomVariable.INT8_SYN == null) { RandomVariable.INT8_SYN = RandomVariable.INT8_STR; } return RandomVariable.INT8_SYN; } public static INT9_SYN: string; public static INT9_SYN_$LI$(): string { if (RandomVariable.INT9_SYN == null) { RandomVariable.INT9_SYN = RandomVariable.INT9_STR; } return RandomVariable.INT9_SYN; } public static NAT0_SYN: string; public static NAT0_SYN_$LI$(): string { if (RandomVariable.NAT0_SYN == null) { RandomVariable.NAT0_SYN = RandomVariable.NAT0_STR; } return RandomVariable.NAT0_SYN; } public static NAT0_1_SYN: string; public static NAT0_1_SYN_$LI$(): string { if (RandomVariable.NAT0_1_SYN == null) { RandomVariable.NAT0_1_SYN = RandomVariable.NAT0_1_STR; } return RandomVariable.NAT0_1_SYN; } public static NAT0_2_SYN: string; public static NAT0_2_SYN_$LI$(): string { if (RandomVariable.NAT0_2_SYN == null) { RandomVariable.NAT0_2_SYN = RandomVariable.NAT0_2_STR; } return RandomVariable.NAT0_2_SYN; } public static NAT0_3_SYN: string; public static NAT0_3_SYN_$LI$(): string { if (RandomVariable.NAT0_3_SYN == null) { RandomVariable.NAT0_3_SYN = RandomVariable.NAT0_3_STR; } return RandomVariable.NAT0_3_SYN; } public static NAT0_4_SYN: string; public static NAT0_4_SYN_$LI$(): string { if (RandomVariable.NAT0_4_SYN == null) { RandomVariable.NAT0_4_SYN = RandomVariable.NAT0_4_STR; } return RandomVariable.NAT0_4_SYN; } public static NAT0_5_SYN: string; public static NAT0_5_SYN_$LI$(): string { if (RandomVariable.NAT0_5_SYN == null) { RandomVariable.NAT0_5_SYN = RandomVariable.NAT0_5_STR; } return RandomVariable.NAT0_5_SYN; } public static NAT0_6_SYN: string; public static NAT0_6_SYN_$LI$(): string { if (RandomVariable.NAT0_6_SYN == null) { RandomVariable.NAT0_6_SYN = RandomVariable.NAT0_6_STR; } return RandomVariable.NAT0_6_SYN; } public static NAT0_7_SYN: string; public static NAT0_7_SYN_$LI$(): string { if (RandomVariable.NAT0_7_SYN == null) { RandomVariable.NAT0_7_SYN = RandomVariable.NAT0_7_STR; } return RandomVariable.NAT0_7_SYN; } public static NAT0_8_SYN: string; public static NAT0_8_SYN_$LI$(): string { if (RandomVariable.NAT0_8_SYN == null) { RandomVariable.NAT0_8_SYN = RandomVariable.NAT0_8_STR; } return RandomVariable.NAT0_8_SYN; } public static NAT0_9_SYN: string; public static NAT0_9_SYN_$LI$(): string { if (RandomVariable.NAT0_9_SYN == null) { RandomVariable.NAT0_9_SYN = RandomVariable.NAT0_9_STR; } return RandomVariable.NAT0_9_SYN; } public static NAT1_SYN: string; public static NAT1_SYN_$LI$(): string { if (RandomVariable.NAT1_SYN == null) { RandomVariable.NAT1_SYN = RandomVariable.NAT1_STR; } return RandomVariable.NAT1_SYN; } public static NAT1_1_SYN: string; public static NAT1_1_SYN_$LI$(): string { if (RandomVariable.NAT1_1_SYN == null) { RandomVariable.NAT1_1_SYN = RandomVariable.NAT1_1_STR; } return RandomVariable.NAT1_1_SYN; } public static NAT1_2_SYN: string; public static NAT1_2_SYN_$LI$(): string { if (RandomVariable.NAT1_2_SYN == null) { RandomVariable.NAT1_2_SYN = RandomVariable.NAT1_2_STR; } return RandomVariable.NAT1_2_SYN; } public static NAT1_3_SYN: string; public static NAT1_3_SYN_$LI$(): string { if (RandomVariable.NAT1_3_SYN == null) { RandomVariable.NAT1_3_SYN = RandomVariable.NAT1_3_STR; } return RandomVariable.NAT1_3_SYN; } public static NAT1_4_SYN: string; public static NAT1_4_SYN_$LI$(): string { if (RandomVariable.NAT1_4_SYN == null) { RandomVariable.NAT1_4_SYN = RandomVariable.NAT1_4_STR; } return RandomVariable.NAT1_4_SYN; } public static NAT1_5_SYN: string; public static NAT1_5_SYN_$LI$(): string { if (RandomVariable.NAT1_5_SYN == null) { RandomVariable.NAT1_5_SYN = RandomVariable.NAT1_5_STR; } return RandomVariable.NAT1_5_SYN; } public static NAT1_6_SYN: string; public static NAT1_6_SYN_$LI$(): string { if (RandomVariable.NAT1_6_SYN == null) { RandomVariable.NAT1_6_SYN = RandomVariable.NAT1_6_STR; } return RandomVariable.NAT1_6_SYN; } public static NAT1_7_SYN: string; public static NAT1_7_SYN_$LI$(): string { if (RandomVariable.NAT1_7_SYN == null) { RandomVariable.NAT1_7_SYN = RandomVariable.NAT1_7_STR; } return RandomVariable.NAT1_7_SYN; } public static NAT1_8_SYN: string; public static NAT1_8_SYN_$LI$(): string { if (RandomVariable.NAT1_8_SYN == null) { RandomVariable.NAT1_8_SYN = RandomVariable.NAT1_8_STR; } return RandomVariable.NAT1_8_SYN; } public static NAT1_9_SYN: string; public static NAT1_9_SYN_$LI$(): string { if (RandomVariable.NAT1_9_SYN == null) { RandomVariable.NAT1_9_SYN = RandomVariable.NAT1_9_STR; } return RandomVariable.NAT1_9_SYN; } public static NOR_SYN: string; public static NOR_SYN_$LI$(): string { if (RandomVariable.NOR_SYN == null) { RandomVariable.NOR_SYN = RandomVariable.NOR_STR; } return RandomVariable.NOR_SYN; } public static UNIFORM_DESC: string = "Random variable - Uniform continuous distribution U(0,1)"; public static INT_DESC: string = "Random variable - random integer"; public static INT1_DESC: string = "Random variable - random integer - Uniform discrete distribution U{-10^1, 10^1}"; public static INT2_DESC: string = "Random variable - random integer - Uniform discrete distribution U{-10^2, 10^2}"; public static INT3_DESC: string = "Random variable - random integer - Uniform discrete distribution U{-10^3, 10^3}"; public static INT4_DESC: string = "Random variable - random integer - Uniform discrete distribution U{-10^4, 10^4}"; public static INT5_DESC: string = "Random variable - random integer - Uniform discrete distribution U{-10^5, 10^5}"; public static INT6_DESC: string = "Random variable - random integer - Uniform discrete distribution U{-10^6, 10^6}"; public static INT7_DESC: string = "Random variable - random integer - Uniform discrete distribution U{-10^7, 10^7}"; public static INT8_DESC: string = "Random variable - random integer - Uniform discrete distribution U{-10^8, 10^8}"; public static INT9_DESC: string = "Random variable - random integer - Uniform discrete distribution U{-10^9, 10^9}"; public static NAT0_DESC: string = "Random variable - random natural number including 0"; public static NAT0_1_DESC: string = "Random variable - random natural number including 0 - Uniform discrete distribution U{0, 10^1}"; public static NAT0_2_DESC: string = "Random variable - random natural number including 0 - Uniform discrete distribution U{0, 10^2}"; public static NAT0_3_DESC: string = "Random variable - random natural number including 0 - Uniform discrete distribution U{0, 10^3}"; public static NAT0_4_DESC: string = "Random variable - random natural number including 0 - Uniform discrete distribution U{0, 10^4}"; public static NAT0_5_DESC: string = "Random variable - random natural number including 0 - Uniform discrete distribution U{0, 10^5}"; public static NAT0_6_DESC: string = "Random variable - random natural number including 0 - Uniform discrete distribution U{0, 10^6}"; public static NAT0_7_DESC: string = "Random variable - random natural number including 0 - Uniform discrete distribution U{0, 10^7}"; public static NAT0_8_DESC: string = "Random variable - random natural number including 0 - Uniform discrete distribution U{0, 10^8}"; public static NAT0_9_DESC: string = "Random variable - random natural number including 0 - Uniform discrete distribution U{0, 10^9}"; public static NAT1_DESC: string = "Random variable - random natural number"; public static NAT1_1_DESC: string = "Random variable - random natural number - Uniform discrete distribution U{1, 10^1}"; public static NAT1_2_DESC: string = "Random variable - random natural number - Uniform discrete distribution U{1, 10^2}"; public static NAT1_3_DESC: string = "Random variable - random natural number - Uniform discrete distribution U{1, 10^3}"; public static NAT1_4_DESC: string = "Random variable - random natural number - Uniform discrete distribution U{1, 10^4}"; public static NAT1_5_DESC: string = "Random variable - random natural number - Uniform discrete distribution U{1, 10^5}"; public static NAT1_6_DESC: string = "Random variable - random natural number - Uniform discrete distribution U{1, 10^6}"; public static NAT1_7_DESC: string = "Random variable - random natural number - Uniform discrete distribution U{1, 10^7}"; public static NAT1_8_DESC: string = "Random variable - random natural number - Uniform discrete distribution U{1, 10^8}"; public static NAT1_9_DESC: string = "Random variable - random natural number - Uniform discrete distribution U{1, 10^9}"; public static NOR_DESC: string = "Random variable - Normal distribution N(0,1)"; public static UNIFORM_SINCE: string; public static UNIFORM_SINCE_$LI$(): string { if (RandomVariable.UNIFORM_SINCE == null) { RandomVariable.UNIFORM_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.UNIFORM_SINCE; } public static INT_SINCE: string; public static INT_SINCE_$LI$(): string { if (RandomVariable.INT_SINCE == null) { RandomVariable.INT_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.INT_SINCE; } public static INT1_SINCE: string; public static INT1_SINCE_$LI$(): string { if (RandomVariable.INT1_SINCE == null) { RandomVariable.INT1_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.INT1_SINCE; } public static INT2_SINCE: string; public static INT2_SINCE_$LI$(): string { if (RandomVariable.INT2_SINCE == null) { RandomVariable.INT2_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.INT2_SINCE; } public static INT3_SINCE: string; public static INT3_SINCE_$LI$(): string { if (RandomVariable.INT3_SINCE == null) { RandomVariable.INT3_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.INT3_SINCE; } public static INT4_SINCE: string; public static INT4_SINCE_$LI$(): string { if (RandomVariable.INT4_SINCE == null) { RandomVariable.INT4_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.INT4_SINCE; } public static INT5_SINCE: string; public static INT5_SINCE_$LI$(): string { if (RandomVariable.INT5_SINCE == null) { RandomVariable.INT5_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.INT5_SINCE; } public static INT6_SINCE: string; public static INT6_SINCE_$LI$(): string { if (RandomVariable.INT6_SINCE == null) { RandomVariable.INT6_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.INT6_SINCE; } public static INT7_SINCE: string; public static INT7_SINCE_$LI$(): string { if (RandomVariable.INT7_SINCE == null) { RandomVariable.INT7_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.INT7_SINCE; } public static INT8_SINCE: string; public static INT8_SINCE_$LI$(): string { if (RandomVariable.INT8_SINCE == null) { RandomVariable.INT8_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.INT8_SINCE; } public static INT9_SINCE: string; public static INT9_SINCE_$LI$(): string { if (RandomVariable.INT9_SINCE == null) { RandomVariable.INT9_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.INT9_SINCE; } public static NAT0_SINCE: string; public static NAT0_SINCE_$LI$(): string { if (RandomVariable.NAT0_SINCE == null) { RandomVariable.NAT0_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT0_SINCE; } public static NAT0_1_SINCE: string; public static NAT0_1_SINCE_$LI$(): string { if (RandomVariable.NAT0_1_SINCE == null) { RandomVariable.NAT0_1_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT0_1_SINCE; } public static NAT0_2_SINCE: string; public static NAT0_2_SINCE_$LI$(): string { if (RandomVariable.NAT0_2_SINCE == null) { RandomVariable.NAT0_2_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT0_2_SINCE; } public static NAT0_3_SINCE: string; public static NAT0_3_SINCE_$LI$(): string { if (RandomVariable.NAT0_3_SINCE == null) { RandomVariable.NAT0_3_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT0_3_SINCE; } public static NAT0_4_SINCE: string; public static NAT0_4_SINCE_$LI$(): string { if (RandomVariable.NAT0_4_SINCE == null) { RandomVariable.NAT0_4_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT0_4_SINCE; } public static NAT0_5_SINCE: string; public static NAT0_5_SINCE_$LI$(): string { if (RandomVariable.NAT0_5_SINCE == null) { RandomVariable.NAT0_5_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT0_5_SINCE; } public static NAT0_6_SINCE: string; public static NAT0_6_SINCE_$LI$(): string { if (RandomVariable.NAT0_6_SINCE == null) { RandomVariable.NAT0_6_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT0_6_SINCE; } public static NAT0_7_SINCE: string; public static NAT0_7_SINCE_$LI$(): string { if (RandomVariable.NAT0_7_SINCE == null) { RandomVariable.NAT0_7_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT0_7_SINCE; } public static NAT0_8_SINCE: string; public static NAT0_8_SINCE_$LI$(): string { if (RandomVariable.NAT0_8_SINCE == null) { RandomVariable.NAT0_8_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT0_8_SINCE; } public static NAT0_9_SINCE: string; public static NAT0_9_SINCE_$LI$(): string { if (RandomVariable.NAT0_9_SINCE == null) { RandomVariable.NAT0_9_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT0_9_SINCE; } public static NAT1_SINCE: string; public static NAT1_SINCE_$LI$(): string { if (RandomVariable.NAT1_SINCE == null) { RandomVariable.NAT1_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT1_SINCE; } public static NAT1_1_SINCE: string; public static NAT1_1_SINCE_$LI$(): string { if (RandomVariable.NAT1_1_SINCE == null) { RandomVariable.NAT1_1_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT1_1_SINCE; } public static NAT1_2_SINCE: string; public static NAT1_2_SINCE_$LI$(): string { if (RandomVariable.NAT1_2_SINCE == null) { RandomVariable.NAT1_2_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT1_2_SINCE; } public static NAT1_3_SINCE: string; public static NAT1_3_SINCE_$LI$(): string { if (RandomVariable.NAT1_3_SINCE == null) { RandomVariable.NAT1_3_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT1_3_SINCE; } public static NAT1_4_SINCE: string; public static NAT1_4_SINCE_$LI$(): string { if (RandomVariable.NAT1_4_SINCE == null) { RandomVariable.NAT1_4_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT1_4_SINCE; } public static NAT1_5_SINCE: string; public static NAT1_5_SINCE_$LI$(): string { if (RandomVariable.NAT1_5_SINCE == null) { RandomVariable.NAT1_5_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT1_5_SINCE; } public static NAT1_6_SINCE: string; public static NAT1_6_SINCE_$LI$(): string { if (RandomVariable.NAT1_6_SINCE == null) { RandomVariable.NAT1_6_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT1_6_SINCE; } public static NAT1_7_SINCE: string; public static NAT1_7_SINCE_$LI$(): string { if (RandomVariable.NAT1_7_SINCE == null) { RandomVariable.NAT1_7_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT1_7_SINCE; } public static NAT1_8_SINCE: string; public static NAT1_8_SINCE_$LI$(): string { if (RandomVariable.NAT1_8_SINCE == null) { RandomVariable.NAT1_8_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT1_8_SINCE; } public static NAT1_9_SINCE: string; public static NAT1_9_SINCE_$LI$(): string { if (RandomVariable.NAT1_9_SINCE == null) { RandomVariable.NAT1_9_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NAT1_9_SINCE; } public static NOR_SINCE: string; public static NOR_SINCE_$LI$(): string { if (RandomVariable.NOR_SINCE == null) { RandomVariable.NOR_SINCE = mXparserConstants.NAMEv30; } return RandomVariable.NOR_SINCE; } } RandomVariable["__class"] = "org.mariuszgromada.math.mxparser.parsertokens.RandomVariable";
the_stack
import type * as I from '@apollo-elements/core/types'; import type { ApolloSubscriptionElement } from '@apollo-elements/core/types'; import { SetupFunction } from './types'; import { aTimeout, defineCE, expect, fixture, nextFrame } from '@open-wc/testing'; import { gql, ApolloClient, InMemoryCache } from '@apollo/client/core'; import { spy, SinonSpy } from 'sinon'; import { makeClient, setupClient, teardownClient } from './client'; import { restoreSpies, stringify, waitForRender } from './helpers'; import { TestableElement } from './types'; import * as S from './schema'; export interface DescribeSubscriptionComponentOptions<T extends ApolloSubscriptionElement<any, any> = ApolloSubscriptionElement<any, any>> { /** * Async function which returns an instance of the query element * The element must render a template which contains the following DOM structure * ```html * <output id="data"></output> * <output id="error"></output> * <output id="loading"></output> * ``` * On updates, each `<output>`'s text content should be * set to the `JSON.stringified` representation of it's associated value, * with 2 spaces as tabs. * The element must also implement a `stringify` method to perform that stringification, * as well as a `hasRendered` method which returns a promise that resolves when the element is finished rendering */ setupFunction: SetupFunction<T & TestableElement>; /** * Optional: the class which setup function uses to generate the component. * Only relevant to class-based libraries */ class?: I.Constructor<Omit<T, 'update'|'updated'> & TestableElement>; } export { setupSubscriptionClass } from './helpers'; export function describeSubscription(options: DescribeSubscriptionComponentOptions): void { const { setupFunction } = options; const Klass: I.Constructor<TestableElement> & typeof ApolloSubscriptionElement = options.class as unknown as I.Constructor<TestableElement> & typeof ApolloSubscriptionElement; describe(`ApolloSubscription interface`, function() { describe('when simply instantiating', function() { let element: ApolloSubscriptionElement & TestableElement|undefined; let spies: Record<keyof typeof element, SinonSpy>; beforeEach(async function setupElement() { ({ element, spies } = await setupFunction({ spy: ['subscribe'], })); }); afterEach(function teardownElement() { element?.remove?.(); element = undefined; }); afterEach(restoreSpies(() => spies)); it('has default properties', function() { // nullable fields expect(element?.data, 'data').to.be.null; expect(element?.error, 'error').to.be.null; expect(element?.subscription, 'subscription').to.be.null; expect(element?.variables, 'variables').to.be.null; // defined fields expect(element?.loading, 'loading').to.be.false; expect(element?.noAutoSubscribe, 'noAutoSubscribe').to.be.false; expect(element?.shouldResubscribe, 'shouldResubscribe').to.be.false; expect(element?.skip, 'skip').to.be.false; // options fields expect(element?.notifyOnNetworkStatusChange, 'notifyOnNetworkStatusChange').to.be.undefined; expect(element?.fetchPolicy, 'fetchPolicy').to.be.undefined; expect(element?.errorPolicy, 'errorPolicy').to.be.undefined; expect(element?.onError, 'onError').to.be.undefined; expect(element?.onSubscriptionComplete, 'onSubscriptionComplete').to.be.undefined; expect(element?.onSubscriptionData, 'onSubscriptionData').to.be.undefined; expect(element?.pollInterval, 'pollInterval').to.be.undefined; }); it('caches observed properties', function() { if (!element) throw new Error('No element'); const client = makeClient(); element.client = client; expect(element?.client, 'client').to.equal(client); element.client = null; expect(element?.client, 'client').to.be.null; element.data = { data: 'data' }; expect(element?.data, 'data').to.deep.equal({ data: 'data' }); let err: Error; try { throw new Error('error'); } catch (e) { err = e; } element.error = err; expect(element?.error, 'error').to.equal(err); element.loading = true; expect(element?.loading, 'loading').to.equal(true); element.loading = false; expect(element?.loading, 'loading').to.equal(false); const subscription = gql`{ __schema { __typename } }`; element.subscription = subscription; expect(element?.subscription, 'subscription').to.equal(subscription); element.subscription = null; expect(element?.subscription, 'subscription').to.be.null; }); describe('setting loading', function() { beforeEach(function setLoading() { element!.loading = true; }); beforeEach(waitForRender(() => element)); it('renders loading', async function() { expect(element?.shadowRoot?.getElementById('loading')?.textContent) .to.equal(stringify(true)); }); }); describe('calling subscribe without client', function() { it('throws', function() { expect(() => element!.subscribe()).to.throw('No Apollo client.'); }); describe('subscribe({ subscription, client })', async function() { let client: ApolloClient<any>|undefined; beforeEach(function() { client = new ApolloClient({ cache: new InMemoryCache() }); spy(client, 'subscribe'); element?.subscribe({ client, subscription: S.NullableParamSubscription }); }); afterEach(function() { (client?.subscribe as SinonSpy).restore(); client = undefined; delete window.__APOLLO_CLIENT__; }); it('calls client subscribe', function() { expect(client?.subscribe).to.have.been.calledWithMatch({ query: S.NullableParamSubscription, }); }); }); }); describe('setting NoParam subscription', function() { beforeEach(function setSubscription() { element!.subscription = S.NoParamSubscription; }); it('sets subscription property', function() { expect(element?.subscription).to.equal(S.NoParamSubscription); }); it('does not call subscribe', function() { // NB: haunted doesn't like spying on it's element methods expect(element?.subscribe).to.not.have.been.called; }); }); describe('setting malformed subscription', function() { it('throws', function() { // @ts-expect-error: we're testing the error expect(() => element.subscription = `subscription { foo }`) .to.throw('Subscription must be a parsed GraphQL document.'); expect(element?.subscription).to.not.be.ok; }); }); }); describe('with global client available', function() { let element: ApolloSubscriptionElement & TestableElement | undefined; let spies: Record<string|keyof ApolloSubscriptionElement, SinonSpy>; beforeEach(setupClient); beforeEach(async function setupElement() { ({ element, spies } = await setupFunction({ spy: ['subscribe'], })); }); beforeEach(function spyClientSubscribe() { spies['client.subscribe'] = spy(element!.client!, 'subscribe'); }); afterEach(restoreSpies(() => spies)); beforeEach(waitForRender(() => element)); afterEach(function teardownElement() { element?.remove?.(); element = undefined; }); afterEach(teardownClient); describe('with no-auto-subscribe attribute set', function() { describe('after setting NoParam subscription', function() { beforeEach(function setSubscription() { element!.subscription = S.NoParamSubscription; }); describe('subscribe()', function() { beforeEach(function() { element!.subscribe(); }); it('calls client subscribe once', function() { expect(element?.client?.subscribe).to.have.been.calledOnce; }); describe('then cancelling the subscription', function() { beforeEach(function() { element!.cancel(); }); describe('then setting element\'s shouldSubscribe to false', function() { beforeEach(function() { element!.shouldResubscribe = false; }); describe('and calling subscribe()', function() { beforeEach(function() { element!.subscribe(); }); it('calls client subscribe again', function() { expect(element?.client?.subscribe).to.have.been.calledTwice; }); }); describe('and calling subscribe({ shouldSubscribe: true })', function() { beforeEach(function() { element!.subscribe({ shouldResubscribe: true }); }); it('calls client subscribe again', function() { expect(element?.client?.subscribe).to.have.been.calledTwice; }); }); describe('and calling subscribe({ shouldSubscribe: false })', function() { beforeEach(function() { element!.subscribe({ shouldResubscribe: false }); }); it('calls client subscribe again', function() { expect(element?.client?.subscribe).to.have.been.calledTwice; }); }); }); describe('then setting element\'s shouldSubscribe to true', function() { beforeEach(function() { element!.shouldResubscribe = true; }); describe('and calling subscribe()', function() { beforeEach(function() { element!.subscribe(); }); it('calls client subscribe again', function() { expect(element?.client?.subscribe).to.have.been.calledTwice; }); }); describe('and calling subscribe({ shouldSubscribe: true })', function() { beforeEach(function() { element!.subscribe({ shouldResubscribe: true }); }); it('calls client subscribe again', function() { expect(element?.client?.subscribe).to.have.been.calledTwice; }); }); describe('and calling subscribe({ shouldSubscribe: false })', function() { beforeEach(function() { element!.subscribe({ shouldResubscribe: false }); }); it('calls client subscribe again', function() { expect(element?.client?.subscribe).to.have.been.calledTwice; }); }); }); }); describe('then calling subscribe({ shouldResubscribe })', function() { beforeEach(function() { element!.subscribe({ shouldResubscribe: true }); }); it('calls client subscribe again', function() { expect(element?.client?.subscribe).to.have.been.calledTwice; }); }); describe('then setting element\'s shouldSubscribe to false', function() { beforeEach(function() { element!.shouldResubscribe = false; }); describe('and calling subscribe({ shouldSubscribe: true })', function() { beforeEach(function() { element!.subscribe({ shouldResubscribe: true }); }); it('calls client subscribe again', function() { expect(element?.client?.subscribe).to.have.been.calledTwice; }); }); }); describe('then setting element\'s shouldSubscribe to true', function() { beforeEach(function() { element!.shouldResubscribe = true; }); describe('and calling subscribe({ shouldSubscribe: false })', function() { beforeEach(function() { element!.subscribe({ shouldResubscribe: false }); }); it('does not call client subscribe again', function() { expect(element?.client?.subscribe).to.have.been.calledOnce; }); }); describe('and calling subscribe({ shouldSubscribe: true })', function() { beforeEach(function() { element!.subscribe({ shouldResubscribe: true }); }); it('does call client subscribe again', function() { expect(element?.client?.subscribe).to.have.been.calledTwice; }); }); }); }); }); describe('and shouldResubscribe set', function() { beforeEach(function() { element!.shouldResubscribe = true; }); describe('subscribe({ subscription })', async function() { beforeEach(function() { element?.subscribe({ subscription: S.NullableParamSubscription }); }); it('calls client subscribe', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ query: S.NullableParamSubscription, }); }); }); describe('with element.skip true', function() { beforeEach(function() { element!.skip = true; }); describe('subscribe()', async function() { beforeEach(function() { element!.subscribe(); }); it('does not call client subscribe', function() { expect(element?.client?.subscribe).to.not.have.been.called; }); }); describe('subscribe({ subscription, skip: false })', async function() { beforeEach(function() { element!.subscribe({ subscription: S.NullableParamSubscription, skip: false, }); }); it('calls client subscribe', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ query: S.NullableParamSubscription, }); }); }); }); describe('subscribe({ subscription, client })', async function() { let client: ApolloClient<any>|undefined; beforeEach(function() { client = new ApolloClient({ cache: new InMemoryCache() }); spy(client, 'subscribe'); }); afterEach(function() { (client?.subscribe as SinonSpy).restore(); client = undefined; }); beforeEach(function() { element?.subscribe({ client, subscription: S.NullableParamSubscription }); }); it('calls client subscribe', function() { expect(client?.subscribe).to.have.been.calledWithMatch({ query: S.NullableParamSubscription, }); }); it('does not call element client subscribe', function() { expect(element?.client?.subscribe).to.not.have.been.called; }); }); describe('with element context', function() { const context = {}; beforeEach(function() { element!.context = context; }); describe('subscribe({ subscription })', function() { beforeEach(function() { element?.subscribe({ subscription: S.NullableParamSubscription }); }); it('calls client subscribe with element context', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ query: S.NullableParamSubscription, context, }); }); }); describe('subscribe({ subscription, context })', async function() { const context = {}; beforeEach(function() { element?.subscribe({ subscription: S.NullableParamSubscription, context }); }); it('calls client subscribe with context param', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ query: S.NullableParamSubscription, context, }); }); }); }); describe('subscribe({ subscription, context })', async function() { const context = {}; beforeEach(function() { element?.subscribe({ subscription: S.NullableParamSubscription, context }); }); it('calls client subscribe with context', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ query: S.NullableParamSubscription, context, }); }); }); describe('with element errorPolicy', function() { beforeEach(function() { element!.errorPolicy = 'none'; }); describe('subscribe({ subscription })', async function() { beforeEach(function() { element?.subscribe({ subscription: S.NullableParamSubscription }); }); it('calls client subscribe with element errorPolicy', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ query: S.NullableParamSubscription, errorPolicy: 'none', }); }); }); describe('subscribe({ subscription, errorPolicy })', async function() { beforeEach(function() { element?.subscribe({ subscription: S.NullableParamSubscription, errorPolicy: 'all' }); }); it('calls client subscribe with params errorPolicy', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ query: S.NullableParamSubscription, errorPolicy: 'all', }); }); }); }); describe('subscribe({ subscription, errorPolicy })', async function() { const errorPolicy = 'ignore'; beforeEach(function() { element?.subscribe({ subscription: S.NullableParamSubscription, errorPolicy }); }); it('calls client subscribe', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ query: S.NullableParamSubscription, errorPolicy, }); }); }); describe('with element fetchPolicy', function() { beforeEach(function() { element!.fetchPolicy = 'cache-first'; }); describe('subscribe({ subscription })', async function() { beforeEach(function() { element?.subscribe({ subscription: S.NullableParamSubscription }); }); it('calls client subscribe with element fetchPolicy', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ query: S.NullableParamSubscription, fetchPolicy: 'cache-first', }); }); }); describe('subscribe({ subscription, fetchPolicy })', async function() { beforeEach(function() { element?.subscribe({ subscription: S.NullableParamSubscription, fetchPolicy: 'network-only', }); }); it('calls client subscribe with params fetchPolicy', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ query: S.NullableParamSubscription, fetchPolicy: 'network-only', }); }); }); }); describe('subscribe({ subscription, fetchPolicy })', async function() { const fetchPolicy = 'no-cache'; beforeEach(function() { element?.subscribe({ subscription: S.NullableParamSubscription, fetchPolicy }); }); it('calls client subscribe', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ query: S.NullableParamSubscription, fetchPolicy, }); }); }); describe('subscribe({ subscription, variables })', async function() { const variables: S.NullableParamSubscriptionVariables = { nullable: 'params' }; beforeEach(function() { element?.subscribe({ subscription: S.NullableParamSubscription, variables }); }); it('calls client subscribe', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ query: S.NullableParamSubscription, variables, }); }); }); describe('with element variables', function() { beforeEach(function() { element!.variables = { nullable: 'with' }; }); describe('subscribe({ subscription })', async function() { beforeEach(function() { element?.subscribe({ subscription: S.NullableParamSubscription }); }); it('calls client subscribe with element variables', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ query: S.NullableParamSubscription, variables: { nullable: 'with' }, }); }); }); describe('subscribe({ subscription, variables })', async function() { beforeEach(function() { element?.subscribe({ subscription: S.NullableParamSubscription, variables: { nullable: 'else' }, }); }); it('calls client subscribe with params variables', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ query: S.NullableParamSubscription, variables: { nullable: 'else' }, }); }); }); }); }); }); describe('setting NoParam subscription', function() { beforeEach(function setSubscription() { element!.subscription = S.NoParamSubscription; }); it('calls subscribe', function() { expect(element?.client?.subscribe).to.have.been.called; }); describe('then setting NullableParam subscription', function() { beforeEach(function setNullableParamSubscription() { element!.subscription = S.NullableParamSubscription; }); beforeEach(waitForRender(() => element!)); beforeEach(() => aTimeout(50)); it('renders second subscription', async function() { const json = stringify({ 'nullableParam': { 'nullable': 'Hello World', '__typename': 'Nullable', }, }); expect(element).shadowDom.to.equal(` <output id="data">${json}</output> <output id="error">null</output> <output id="loading">false</output> `); }); describe('then setting variables', function() { beforeEach(function() { element!.variables = { nullable: 'quux' }; }); beforeEach(waitForRender(() => element)); beforeEach(() => aTimeout(50)); it('renders new variables', async function() { expect(element?.shadowRoot?.textContent).to.contain('quux'); }); }); }); }); describe('setting NullableParam subscription', function() { beforeEach(function setSubscription() { element!.subscription = S.NullableParamSubscription; }); beforeEach(waitForRender(() => element)); it('calls subscribe', function() { expect(element?.client?.subscribe).to.have.been.called; }); beforeEach(() => aTimeout(50)); it('renders data', function() { const json = stringify({ 'nullableParam': { 'nullable': 'Hello World', '__typename': 'Nullable', }, }); expect(element).shadowDom.to.equal(` <output id="data">${json}</output> <output id="error">null</output> <output id="loading">false</output> `); }); describe('then setting variables', function() { beforeEach(function setVariables() { element!.variables = { nullable: 'qux' }; }); beforeEach(waitForRender(() => element)); it('creates a new observable', function() { expect(element?.client?.subscribe).to.have.been.calledTwice; }); beforeEach(() => aTimeout(50)); it('renders the new data', function() { expect(element?.shadowRoot?.getElementById('data')?.textContent) .to.equal(stringify({ nullableParam: { nullable: 'qux', __typename: 'Nullable', }, })); }); }); describe('then setting variables that cause the subscription to error', function() { beforeEach(function setVariables() { element!.variables = { nullable: 'error' }; }); it('renders error', function() { expect(element?.shadowRoot?.getElementById('error')?.textContent) .to.equal(stringify(element?.error)); }); }); describe('then setting null subscription', function() { beforeEach(function nullifySubscription() { element!.subscription = null; }); it('does not create a new observable', function() { expect(element?.client?.subscribe).to.not.have.been.calledTwice; }); }); describe('when shouldResubscribe is set', function() { beforeEach(function setShouldResubscribe() { element!.shouldResubscribe = true; }); beforeEach(() => element?.controller.host.updateComplete); describe('subscribe({ fetchPolicy, variables })', function() { const fetchPolicy = 'network-only'; const variables = { nullable: 'bar' }; beforeEach(function() { element?.subscribe({ variables, fetchPolicy }); }); it('calls client subscribe with element subscription', function() { const { subscription } = element!; expect(element?.client?.subscribe).to.have.been.calledWithMatch({ query: subscription, }); }); it('calls client subscribe with specified FetchPolicy', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ fetchPolicy }); }); it('calls client subscribe with element variables', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ variables }); }); }); describe('subscribe({ subscription, fetchPolicy })', function() { const fetchPolicy = 'cache-only'; const subscription = S.NoParamSubscription; beforeEach(function setVariables() { element!.variables = { null: null }; }); beforeEach(function() { element?.subscribe({ subscription, fetchPolicy }); }); it('calls client subscribe with specified subscription', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ query: subscription, }); }); it('calls client subscribe with specified FetchPolicy', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ fetchPolicy }); }); it('calls client subscribe with element variables', function() { const { variables } = element!; expect(element?.client?.subscribe).to.have.been.calledWithMatch({ variables }); }); }); describe('subscribe({ subscription, variables })', function() { const subscription = S.NonNullableParamSubscription; const variables = { nonNull: 'bar' }; beforeEach(() => aTimeout(60)); beforeEach(function() { element?.subscribe({ subscription, variables }); }); it('calls client subscribe with specified subscription', function() { expect(element?.client?.subscribe) .to.have.been.calledTwice; const [operation] = (element?.client?.subscribe as SinonSpy).lastCall.args; expect(operation.query).to.equal(subscription); expect(operation.variables).to.equal(variables); }); it('calls client subscribe with element FetchPolicy', function() { const { fetchPolicy } = element!; expect(element?.client?.subscribe).to.have.been.calledWithMatch({ fetchPolicy }); }); it('calls client subscribe with specified variables', function() { expect(element?.client?.subscribe).to.have.been.calledWithMatch({ variables }); }); }); }); }); describe('setting malformed subscription', function() { let result: Error; beforeEach(function setBadSubscription() { try { // @ts-expect-error: we're testing the error element.subscription = `subscription { foo }`; expect.fail('should have thrown'); } catch (e) { result = e; } }); it('does not subscribe', function() { expect(element?.subscribe).to.not.have.been.called; }); it('does not set subscription', function() { expect(element?.subscription).to.not.be.ok; }); it('does not set error', function() { expect(element?.error).to.be.null; }); it('throws expected error', function() { expect(result.message).to.equal('Subscription must be a parsed GraphQL document.'); }); }); }); }); if (Klass) { describe('ApolloSubscription subclasses', function() { describe('with global client available', function() { beforeEach(setupClient); afterEach(teardownClient); describe('with subscription set as a class field', function() { let element: ApolloSubscriptionElement; beforeEach(async function() { class Test extends Klass { subscription = S.NoParamSubscription; } const tag = defineCE(Test); element = await fixture<Test>(`<${tag}></${tag}>`); }); it('caches subscription property', function() { expect(element?.subscription, 'subscription').to.equal(S.NoParamSubscription); }); }); describe('with shouldSubscribe overridden to return false', function() { let element: ApolloSubscriptionElement | undefined; beforeEach(() => spy(window.__APOLLO_CLIENT__!, 'subscribe')); afterEach(() => (window.__APOLLO_CLIENT__!.subscribe as SinonSpy).restore?.()); afterEach(function teardownElement() { element?.remove?.(); element = undefined; }); beforeEach(async function() { class Test extends Klass { subscription = S.NullableParamSubscription; shouldSubscribe() { return false; } } const tag = defineCE(Test); element = await fixture<Test>(`<${tag}></${tag}>`); }); it('does not subscribe on connect', function() { expect(element?.client?.subscribe).to.not.have.been.called; }); }); describe('with noAutoSubscribe set as a class field', function() { let element: ApolloSubscriptionElement; beforeEach(() => spy(window.__APOLLO_CLIENT__!, 'subscribe')); afterEach(() => (window.__APOLLO_CLIENT__!.subscribe as SinonSpy).restore?.()); afterEach(function teardownElement() { element?.remove?.(); // @ts-expect-error: fixture cleanup element = undefined; }); describe('when set before subscription field', function() { beforeEach(async function() { class Test extends Klass { noAutoSubscribe = true; subscription = S.NullableParamSubscription; } const tag = defineCE(Test); element = await fixture<Test>(`<${tag}></${tag}>`); }); it('does not subscribe on connect', function() { expect(element?.client?.subscribe).to.not.have.been.called; }); }); describe('when set after subscription field', function() { beforeEach(async function() { class Test extends Klass { subscription = S.NullableParamSubscription; noAutoSubscribe = true; } const tag = defineCE(Test); element = await fixture<Test>(`<${tag}></${tag}>`); }); it('does not subscribe on connect', function() { expect(element?.client?.subscribe).to.not.have.been.called; }); }); }); describe('with fetchPolicy set as a class field', function() { let element: ApolloSubscriptionElement<typeof S.NullableParamSubscription> | undefined; let spies: Record<string|Exclude<keyof ApolloSubscriptionElement, symbol>, SinonSpy>; beforeEach(function spyClientSubscribe() { spies = { 'client.subscribe': spy(window.__APOLLO_CLIENT__!, 'subscribe'), }; }); afterEach(function teardownElement() { element?.remove?.(); element = undefined; }); afterEach(restoreSpies(() => spies)); beforeEach(async function() { class Test extends Klass<typeof S.NullableParamSubscription> { subscription = S.NullableParamSubscription; variables = { nullable: 'quux' }; fetchPolicy = 'cache-only' as const; } const tag = defineCE(Test); element = await fixture<Test>(`<${tag}></${tag}>`); }); beforeEach(() => element?.controller.host.updateComplete); it('sets fetchPolicy', function() { expect(element?.fetchPolicy).to.equal('cache-only'); }); it('sets controller fetchPolicy', function() { expect(element?.controller?.options.fetchPolicy).to.equal('cache-only'); }); it('subscribes with the given FetchPolicy', function() { expect(element?.client?.subscribe).to.have.been .calledWithMatch({ fetchPolicy: 'cache-only' }); }); }); describe('with onComplete, onError, and onSubscriptionData set as class methods', function() { let element: TestableElement & ApolloSubscriptionElement<typeof S.NonNullableParamSubscription> | undefined; let spies: Record<string|Exclude<keyof ApolloSubscriptionElement, symbol>, SinonSpy> | undefined; beforeEach(function spyClientSubscribe() { spies = { 'client.subscribe': spy(window.__APOLLO_CLIENT__!, 'subscribe'), }; }); afterEach(function teardownElement() { element?.remove?.(); element = undefined; }); afterEach(restoreSpies(() => spies)); beforeEach(async function() { class Test extends Klass<typeof S.NonNullableParamSubscription> { subscription = S.NonNullableParamSubscription; noAutoSubscribe = true; onSubscriptionComplete(): void { null; } onSubscriptionData(x: unknown): void { x; } onError(x: unknown): void { x; } } const tag = defineCE(Test); element = await fixture<Test>(`<${tag}></${tag}>`); spies!['onSubscriptionComplete'] = spy(element, 'onSubscriptionComplete'); spies!['onSubscriptionData'] = spy(element, 'onSubscriptionData'); spies!['onError'] = spy(element, 'onError'); }); describe('with subscription that will resolve and immediately complete', function() { beforeEach(function setVariables() { element!.variables = { nonNull: 'hola' }; }); beforeEach(function subscribe() { element!.subscribe(); }); it('sets loading', function() { expect(element?.loading).to.be.true; }); describe('when subscription resolves', function() { beforeEach(nextFrame); beforeEach(waitForRender(() => element)); it('calls onSubscriptionData', function() { expect(element?.onSubscriptionData).to.have.been.called; }); it('does not call onError', function() { expect(element?.onError).to.not.have.been.called; }); it('calls onSubscriptionComplete', function() { expect(element?.onSubscriptionComplete).to.have.been.called; }); }); }); describe('with subscription that should error', function() { beforeEach(function setVariablesToError() { element!.variables = { nonNull: 'error' }; }); beforeEach(function subscribe() { element?.subscribe(); }); beforeEach(nextFrame); describe('when subscription rejects', function() { beforeEach(waitForRender(() => element)); it('does not call onSubscriptionData', function() { expect(element?.onSubscriptionData).to.not.have.been.called; }); it('calls onError', function() { expect(element?.onError).to.have.been.called; }); }); }); }); }); }); } }
the_stack
import * as cp from 'child_process'; import * as minimatch from 'minimatch'; import { dirname, join, normalize, relative, sep } from 'path'; import type * as tslint from 'tslint'; import type { IConfigurationFile } from 'tslint/lib/configuration'; import type * as typescript from 'typescript'; import * as util from 'util'; import * as server from 'vscode-languageserver'; import { MruCache } from './mruCache'; export type PackageManager = 'npm' | 'pnpm' | 'yarn'; export function toPackageManager(manager: string | undefined): PackageManager | undefined { switch (manager && manager.toLowerCase()) { case 'npm': return 'npm'; case 'pnpm': return 'pnpm'; case 'yarn': return 'yarn'; default: return undefined; } } export interface RunConfiguration { readonly jsEnable: boolean; readonly rulesDirectory?: string | string[]; readonly configFile?: string; readonly ignoreDefinitionFiles: boolean; readonly exclude: string[]; readonly validateWithDefaultConfig?: boolean; readonly packageManager?: PackageManager; readonly traceLevel?: 'verbose' | 'normal'; readonly workspaceFolderPath?: string; /** * Controls where TSlint and other scripts can be loaded from. */ readonly workspaceLibraryExecution: WorkspaceLibraryExecution; } /** * Controls where TSlint and other scripts can be loaded from. */ export enum WorkspaceLibraryExecution { /** * Block executing TSLint, linter rules, and other scripts from the current workspace. */ Disallow = 1, /** * Enable loading TSLint and rules from the workspace. */ Allow = 2, /** * The workspace library execution has not yet been configured or cannot be determined. */ Unknown = 3, } interface Configuration { readonly linterConfiguration: tslint.Configuration.IConfigurationFile | undefined; isDefaultLinterConfig: boolean; readonly path?: string; } class ConfigCache { public configuration: Configuration | undefined; private filePath: string | undefined; constructor() { this.filePath = undefined; this.configuration = undefined; } public set(filePath: string, configuration: Configuration) { this.filePath = filePath; this.configuration = configuration; } public get(forPath: string): Configuration | undefined { return forPath === this.filePath ? this.configuration : undefined; } public isDefaultLinterConfig(): boolean { return !!(this.configuration && this.configuration.isDefaultLinterConfig); } public flush() { this.filePath = undefined; this.configuration = undefined; } } export interface RunResult { readonly lintResult: tslint.LintResult; readonly warnings: string[]; readonly workspaceFolderPath?: string; readonly configFilePath?: string; } const emptyLintResult: tslint.LintResult = { errorCount: 0, warningCount: 0, failures: [], fixes: [], format: '', output: '', }; const emptyResult: RunResult = { lintResult: emptyLintResult, warnings: [], }; export class TsLintRunner { private readonly tslintPath2Library = new Map<string, { tslint: typeof tslint, path: string } | undefined>(); private readonly document2LibraryCache = new MruCache<{ readonly workspaceTslintPath: string | undefined, readonly globalTsLintPath: string | undefined, getTSLint(isTrusted: boolean): { tslint: typeof tslint, path: string } | undefined }>(100); // map stores undefined values to represent failed resolutions private readonly globalPackageManagerPath = new Map<PackageManager, string | undefined>(); private readonly configCache = new ConfigCache(); constructor( private readonly trace: (data: string) => void, ) { } public runTsLint( filePath: string, contents: string | typescript.Program, configuration: RunConfiguration, ): RunResult { this.traceMethod('runTsLint', 'start'); const warnings: string[] = []; if (!this.document2LibraryCache.has(filePath)) { this.loadLibrary(filePath, configuration); } this.traceMethod('runTsLint', 'Loaded tslint library'); if (!this.document2LibraryCache.has(filePath)) { return emptyResult; } const cacheEntry = this.document2LibraryCache.get(filePath)!; let library: { tslint: typeof tslint, path: string } | undefined; switch (configuration.workspaceLibraryExecution) { case WorkspaceLibraryExecution.Disallow: library = cacheEntry.getTSLint(false); break; case WorkspaceLibraryExecution.Allow: library = cacheEntry.getTSLint(true); break; default: if (cacheEntry.workspaceTslintPath) { if (this.isWorkspaceImplicitlyTrusted(cacheEntry.workspaceTslintPath)) { configuration = { ...configuration, workspaceLibraryExecution: WorkspaceLibraryExecution.Allow }; library = cacheEntry.getTSLint(true); break; } // If the user has not explicitly trusted/not trusted the workspace AND we have a workspace TS version // show a special error that lets the user trust/untrust the workspace return { lintResult: emptyLintResult, warnings: [ getWorkspaceNotTrustedMessage(filePath), ], }; } else if (cacheEntry.globalTsLintPath) { library = cacheEntry.getTSLint(false); } break; } if (!library) { return { lintResult: emptyLintResult, warnings: [ getInstallFailureMessage( filePath, configuration.packageManager || 'npm'), ], }; } this.traceMethod('runTsLint', 'About to validate ' + filePath); return this.doRun(filePath, contents, library, configuration, warnings); } public onConfigFileChange(_tsLintFilePath: string) { this.configCache.flush(); } private traceMethod(method: string, message: string) { this.trace(`(${method}) ${message}`); } private loadLibrary(filePath: string, configuration: RunConfiguration): void { this.traceMethod('loadLibrary', `trying to load ${filePath}`); const directory = dirname(filePath); const tsLintPaths = this.getTsLintPaths(directory, configuration.packageManager); this.traceMethod('loadLibrary', `Resolved tslint to workspace: '${tsLintPaths.workspaceTsLintPath}' global: '${tsLintPaths.globalTsLintPath}'`); this.document2LibraryCache.set(filePath, { workspaceTslintPath: tsLintPaths.workspaceTsLintPath || undefined, globalTsLintPath: tsLintPaths.globalTsLintPath || undefined, getTSLint: (allowWorkspaceLibraryExecution: boolean) => { const tsLintPath = allowWorkspaceLibraryExecution ? tsLintPaths.workspaceTsLintPath || tsLintPaths.globalTsLintPath : tsLintPaths.globalTsLintPath; if (!tsLintPath) { return; } let library; if (!this.tslintPath2Library.has(tsLintPath)) { try { library = require(tsLintPath); } catch (e) { this.tslintPath2Library.set(tsLintPath, undefined); return; } this.tslintPath2Library.set(tsLintPath, { tslint: library, path: tsLintPath }); } return this.tslintPath2Library.get(tsLintPath); } }); } private getTsLintPaths(directory: string, packageManager: PackageManager | undefined) { const globalPath = this.getGlobalPackageManagerPath(packageManager); let workspaceTsLintPath: string | undefined; try { workspaceTsLintPath = this.resolveTsLint({ nodePath: undefined, cwd: directory }) || undefined; } catch { // noop } let globalTSLintPath: string | undefined; try { globalTSLintPath = this.resolveTsLint({ nodePath: undefined, cwd: globalPath }) || this.resolveTsLint({ nodePath: globalPath, cwd: globalPath }); } catch { // noop } return { workspaceTsLintPath, globalTsLintPath: globalTSLintPath }; } private getGlobalPackageManagerPath(packageManager: PackageManager = 'npm'): string | undefined { this.traceMethod('getGlobalPackageManagerPath', `Begin - Resolve Global Package Manager Path for: ${packageManager}`); if (!this.globalPackageManagerPath.has(packageManager)) { let path: string | undefined; if (packageManager === 'npm') { path = server.Files.resolveGlobalNodePath(this.trace); } else if (packageManager === 'yarn') { path = server.Files.resolveGlobalYarnPath(this.trace); } else if (packageManager === 'pnpm') { path = cp.execSync('pnpm root -g').toString().trim(); } this.globalPackageManagerPath.set(packageManager, path); } this.traceMethod('getGlobalPackageManagerPath', `Done - Resolve Global Package Manager Path for: ${packageManager}`); return this.globalPackageManagerPath.get(packageManager); } private doRun( filePath: string, contents: string | typescript.Program, library: { tslint: typeof tslint, path: string }, configuration: RunConfiguration, warnings: string[], ): RunResult { this.traceMethod('doRun', `starting validation for ${filePath}`); let cwd = configuration.workspaceFolderPath; if (!cwd && typeof contents === "object") { cwd = contents.getCurrentDirectory(); } if (this.fileIsExcluded(configuration, filePath, cwd)) { this.traceMethod('doRun', `No linting: file ${filePath} is excluded`); return emptyResult; } let cwdToRestore: string | undefined; if (cwd && configuration.workspaceLibraryExecution === WorkspaceLibraryExecution.Allow) { this.traceMethod('doRun', `Changed directory to ${cwd}`); cwdToRestore = process.cwd(); process.chdir(cwd); } try { const configFile = configuration.configFile || null; let linterConfiguration: Configuration | undefined; this.traceMethod('doRun', 'About to getConfiguration'); try { linterConfiguration = this.getConfiguration(filePath, filePath, library.tslint, configFile); } catch (err) { this.traceMethod('doRun', `No linting: exception when getting tslint configuration for ${filePath}, configFile= ${configFile}`); warnings.push(getConfigurationFailureMessage(err)); return { lintResult: emptyLintResult, warnings, }; } if (!linterConfiguration) { this.traceMethod('doRun', `No linting: no tslint configuration`); return emptyResult; } this.traceMethod('doRun', 'Configuration fetched'); if (isJsDocument(filePath) && !configuration.jsEnable) { this.traceMethod('doRun', `No linting: a JS document, but js linting is disabled`); return emptyResult; } if (configuration.validateWithDefaultConfig === false && this.configCache.configuration!.isDefaultLinterConfig) { this.traceMethod('doRun', `No linting: linting with default tslint configuration is disabled`); return emptyResult; } if (isExcludedFromLinterOptions(linterConfiguration.linterConfiguration, filePath)) { this.traceMethod('doRun', `No linting: file is excluded using linterOptions.exclude`); return emptyResult; } let result: tslint.LintResult; const isTrustedWorkspace = configuration.workspaceLibraryExecution === WorkspaceLibraryExecution.Allow; // Only allow using a custom rules directory if the workspace has been trusted by the user const rulesDirectory = isTrustedWorkspace ? configuration.rulesDirectory : []; const options: tslint.ILinterOptions = { formatter: "json", fix: false, rulesDirectory, formattersDirectory: undefined, }; if (configuration.traceLevel && configuration.traceLevel === 'verbose') { this.traceConfigurationFile(linterConfiguration.linterConfiguration); } // tslint writes warnings using console.warn, capture these warnings and send them to the client const originalConsoleWarn = console.warn; const captureWarnings = (message?: any) => { warnings.push(message); originalConsoleWarn(message); }; console.warn = captureWarnings; const sanitizedLintConfiguration = { ...linterConfiguration.linterConfiguration } as IConfigurationFile; // Only allow using a custom rules directory if the workspace has been trusted by the user if (!isTrustedWorkspace) { sanitizedLintConfiguration.rulesDirectory = []; } try { // clean up if tslint crashes const linter = new library.tslint.Linter(options, typeof contents === 'string' ? undefined : contents); this.traceMethod('doRun', `Linting: start linting`); linter.lint(filePath, typeof contents === 'string' ? contents : '', sanitizedLintConfiguration); result = linter.getResult(); this.traceMethod('doRun', `Linting: ended linting`); } finally { console.warn = originalConsoleWarn; } return { lintResult: result, warnings, workspaceFolderPath: configuration.workspaceFolderPath, configFilePath: linterConfiguration.path, }; } finally { if (typeof cwdToRestore === 'string') { process.chdir(cwdToRestore); } } } /** * Check if `tslintPath` is next to the running TS version. This indicates that the user has * implicitly trusted the workspace since they are already running TS from it. */ private isWorkspaceImplicitlyTrusted(tslintPath: string): boolean { const tsPath = process.argv[1]; const nodeModulesPath = join(tsPath, '..', '..', '..'); const rel = relative(nodeModulesPath, normalize(tslintPath)); if (rel === `tslint${sep}lib${sep}index.js`) { return true; } return false; } private getConfiguration(uri: string, filePath: string, library: typeof tslint, configFileName: string | null): Configuration | undefined { this.traceMethod('getConfiguration', `Starting for ${uri}`); const config = this.configCache.get(filePath); if (config) { return config; } let isDefaultConfig = false; let linterConfiguration: tslint.Configuration.IConfigurationFile | undefined; const linter = library.Linter; if (linter.findConfigurationPath) { isDefaultConfig = linter.findConfigurationPath(configFileName, filePath) === undefined; } const configurationResult = linter.findConfiguration(configFileName, filePath); linterConfiguration = configurationResult.results; // In tslint version 5 the 'no-unused-variable' rules breaks the TypeScript language service plugin. // See https://github.com/Microsoft/TypeScript/issues/15344 // Therefore we remove the rule from the configuration. if (linterConfiguration) { if (linterConfiguration.rules) { linterConfiguration.rules.delete('no-unused-variable'); } if (linterConfiguration.jsRules) { linterConfiguration.jsRules.delete('no-unused-variable'); } } const configuration: Configuration = { isDefaultLinterConfig: isDefaultConfig, linterConfiguration, path: configurationResult.path, }; this.configCache.set(filePath, configuration); return this.configCache.configuration; } private fileIsExcluded(settings: RunConfiguration, filePath: string, cwd: string | undefined): boolean { if (settings.ignoreDefinitionFiles && filePath.endsWith('.d.ts')) { return true; } return settings.exclude.some(pattern => testForExclusionPattern(filePath, pattern, cwd)); } private traceConfigurationFile(configuration: tslint.Configuration.IConfigurationFile | undefined) { if (!configuration) { this.trace("no tslint configuration"); return; } this.trace("tslint configuration:" + util.inspect(configuration, undefined, 4)); } private resolveTsLint(options: { nodePath: string | undefined; cwd: string | undefined; }): string | undefined { const nodePathKey = 'NODE_PATH'; const app = [ "console.log(require.resolve('tslint'));", ].join(''); const env = process.env; const newEnv = Object.create(null); Object.keys(env).forEach(key => newEnv[key] = env[key]); if (options.nodePath) { newEnv[nodePathKey] = options.nodePath; } newEnv.ELECTRON_RUN_AS_NODE = '1'; const spawnResults = cp.spawnSync(process.argv0, ['-e', app], { cwd: options.cwd, env: newEnv }); return spawnResults.stdout.toString().trim() || undefined; } } function testForExclusionPattern(filePath: string, pattern: string, cwd: string | undefined): boolean { if (cwd) { // try first as relative const relPath = relative(cwd, filePath); if (minimatch(relPath, pattern, { dot: true })) { return true; } if (relPath === filePath) { return false; } } return minimatch(filePath, pattern, { dot: true }); } function getInstallFailureMessage(filePath: string, packageManager: PackageManager): string { const localCommands = { npm: 'npm install tslint', pnpm: 'pnpm install tslint', yarn: 'yarn add tslint', }; const globalCommands = { npm: 'npm install -g tslint', pnpm: 'pnpm install -g tslint', yarn: 'yarn global add tslint', }; return [ `Failed to load the TSLint library for '${filePath}'`, `To use TSLint, please install tslint using \'${localCommands[packageManager]}\' or globally using \'${globalCommands[packageManager]}\'.`, 'Be sure to restart your editor after installing tslint.', ].join('\n'); } function getWorkspaceNotTrustedMessage(filePath: string) { return [ `Not using the local TSLint version found for '${filePath}'`, 'To enable code execution from the current workspace you must enable workspace library execution.', ].join('\n'); } function isJsDocument(filePath: string): boolean { return /\.(jsx?|mjs)$/i.test(filePath); } function isExcludedFromLinterOptions( config: tslint.Configuration.IConfigurationFile | undefined, fileName: string, ): boolean { if (config === undefined || config.linterOptions === undefined || config.linterOptions.exclude === undefined) { return false; } return config.linterOptions.exclude.some(pattern => testForExclusionPattern(fileName, pattern, undefined)); } function getConfigurationFailureMessage(err: any): string { let errorMessage = `unknown error`; if (typeof err.message === 'string' || err.message instanceof String) { errorMessage = err.message; } return `Cannot read tslint configuration - '${errorMessage}'`; }
the_stack
import { should, expect } from 'chai'; import sinon from 'sinon'; import { HealthEndpoint, ReadinessEndpoint, LivenessEndpoint, HealthChecker, StartupCheck, LivenessCheck, ReadinessCheck, ShutdownCheck } from '../../index'; import {NextFunction} from 'connect'; import * as http from "http"; should(); describe('Connect Cloud Health test suite', () => { it('Liveness returns 200 OK on startup check starting', (done) => { let cloudHealth = new HealthChecker(); const StartPromise = () => new Promise<void>((resolve,_reject) => { setTimeout(resolve, 100, 'foo'); }) let StartCheck = new StartupCheck("StartCheck",StartPromise); cloudHealth.registerStartupCheck(StartCheck); const reqStub: Partial<http.IncomingMessage> = {}; const nextStub: Partial<NextFunction> = {}; const resStub: Partial<http.ServerResponse> = { write: sinon.fake(), end: function () { let expectedStatus = 200; let code = resStub.statusCode ? resStub.statusCode : 0 code.should.equals(expectedStatus, `Should return: ${expectedStatus}, but returned: ${code}`); done(); } }; LivenessEndpoint(cloudHealth)(<http.IncomingMessage>reqStub, <http.ServerResponse>resStub, <NextFunction>nextStub) }); it('Liveness returns 200 OK and UP on liveness success', (done) => { let cloudHealth = new HealthChecker(); cloudHealth.registerLivenessCheck( // tslint:disable-next-line:no-shadowed-variable new LivenessCheck("test1", () => new Promise<void>((resolve, _reject) => { resolve(); })) ) const reqStub: Partial<http.IncomingMessage> = {}; const nextStub: Partial<NextFunction> = {}; const resStub: Partial<http.ServerResponse> = { write: sinon.fake(), //write: sinon.stub(), end: function () { let expectedStatus = 200; let code = resStub.statusCode ? resStub.statusCode : 0 code.should.equals(expectedStatus, `Should return: ${expectedStatus}, but returned: ${code}`); let expectedBody = "{\"status\":\"UP\",\"checks\":[{\"name\":\"test1\",\"state\":\"UP\",\"data\":{\"reason\":\"\"}}]}"; sinon.assert.calledWith(resStub.write as sinon.SinonStub, expectedBody) done(); } }; LivenessEndpoint(cloudHealth)(<http.IncomingMessage>reqStub, <http.ServerResponse>resStub, <NextFunction>nextStub) }); it('Liveness returns 503 Unavailable and DOWN on liveness fail', function(done) { let cloudHealth = new HealthChecker(); cloudHealth.registerLivenessCheck( // tslint:disable-next-line:no-shadowed-variable new LivenessCheck("test1", () => new Promise<void>(function(resolve, reject){ throw new Error("Liveness Failure"); })) ) const reqStub: Partial<http.IncomingMessage> = {}; const nextStub: Partial<NextFunction> = {}; const resStub: Partial<http.ServerResponse> = { write: sinon.fake(), end: function () { let expectedStatus = 503; let code = resStub.statusCode ? resStub.statusCode : 0 code.should.equals(expectedStatus, `Should return: ${expectedStatus}, but returned: ${code}`); let expectedBody = "{\"status\":\"DOWN\",\"checks\":[{\"name\":\"test1\",\"state\":\"DOWN\",\"data\":{\"reason\":\"Liveness Failure\"}}]}"; sinon.assert.calledWith(resStub.write as sinon.SinonStub, expectedBody) done(); } }; LivenessEndpoint(cloudHealth)(<http.IncomingMessage>reqStub, <http.ServerResponse>resStub, <NextFunction>nextStub) }); it('Liveness returns 503 OK and STOPPING on STOPPING', function(done) { process.removeAllListeners('SIGTERM'); let cloudHealth = new HealthChecker(); cloudHealth.registerShutdownCheck( // tslint:disable-next-line:no-shadowed-variable new ShutdownCheck("test1", () => new Promise<void>(function(resolve, reject){ // tslint:disable-next-line:no-shadowed-variable no-unused-expression new Promise(function(resolve, _reject){ setTimeout(resolve, 1000, 'foo'); }) })) ) const reqStub: Partial<http.IncomingMessage> = {}; const nextStub: Partial<NextFunction> = {}; const resStub: Partial<http.ServerResponse> = { write: sinon.fake(), end: function () { let expectedStatus = 503; let code = resStub.statusCode ? resStub.statusCode : 0 code.should.equals(expectedStatus, `Should return: ${expectedStatus}, but returned: ${code}`); let expectedBody = "{\"status\":\"STOPPING\",\"checks\":[{\"name\":\"test1\",\"state\":\"STOPPING\",\"data\":{\"reason\":\"\"}}]}"; sinon.assert.calledWith(resStub.write as sinon.SinonStub, expectedBody) done(); } }; process.once('SIGTERM', () => { LivenessEndpoint(cloudHealth)(<http.IncomingMessage>reqStub, <http.ServerResponse>resStub, <NextFunction>nextStub) }); process.kill(process.pid, 'SIGTERM') }); it('Liveness returns 503 OK and STOPPED on STOPPED', function(done) { process.removeAllListeners('SIGTERM'); let cloudHealth = new HealthChecker(); const promiseone = () => new Promise<void>((resolve, _reject) => { setTimeout(resolve, 1); }); let checkone = new ShutdownCheck("test1", promiseone) cloudHealth.registerShutdownCheck(checkone) const reqStub: Partial<http.IncomingMessage> = {}; const nextStub: Partial<NextFunction> = {}; const resStub: Partial<http.ServerResponse> = { write: sinon.fake(), end: function () { let expectedStatus = 503; let code = resStub.statusCode ? resStub.statusCode : 0 code.should.equals(expectedStatus, `Should return: ${expectedStatus}, but returned: ${code}`); let expectedBody = "{\"status\":\"STOPPED\",\"checks\":[{\"name\":\"test1\",\"state\":\"STOPPED\",\"data\":{\"reason\":\"\"}}]}"; sinon.assert.calledWith(resStub.write as sinon.SinonStub, expectedBody) done(); } }; process.once('SIGTERM', async () => { await setTimeout(async () => { LivenessEndpoint(cloudHealth)(<http.IncomingMessage>reqStub, <http.ServerResponse>resStub, <NextFunction>nextStub) }, 100); }); process.kill(process.pid, 'SIGTERM') }); it('Readiness returns 503 Unavailable and DOWN on startup fail', function(done) { let cloudHealth = new HealthChecker(); cloudHealth.registerStartupCheck( // tslint:disable-next-line:no-shadowed-variable new StartupCheck("test1", () => new Promise<void>(function(resolve, reject){ throw new Error("Startup Failure"); })) ) .then(() => { ReadinessEndpoint(cloudHealth)(<http.IncomingMessage>reqStub, <http.ServerResponse>resStub, <NextFunction>nextStub) }); const reqStub: Partial<http.IncomingMessage> = {}; const nextStub: Partial<NextFunction> = {}; const resStub: Partial<http.ServerResponse> = { write: sinon.fake(), end: function () { let expectedStatus = 503; let code = resStub.statusCode ? resStub.statusCode : 0 code.should.equals(expectedStatus, `Should return: ${expectedStatus}, but returned: ${code}`); let expectedBody = "{\"status\":\"DOWN\",\"checks\":[{\"name\":\"test1\",\"state\":\"DOWN\",\"data\":{\"reason\":\"Startup Failure\"}}]}"; sinon.assert.calledWith(resStub.write as sinon.SinonStub, expectedBody) done(); } }; }); it('Readiness returns 503 Unavailable on startup check starting', (done) => { let cloudHealth = new HealthChecker(); const StartPromise = () => new Promise<void>((resolve,reject) => { setTimeout(reject, 100, 'foo'); }) let StartCheck = new StartupCheck("StartCheck",StartPromise); cloudHealth.registerStartupCheck(StartCheck); const reqStub: Partial<http.IncomingMessage> = {}; const nextStub: Partial<NextFunction> = {}; const resStub: Partial<http.ServerResponse> = { write: sinon.fake(), end: function () { let expectedStatus = 503; let code = resStub.statusCode ? resStub.statusCode : 0 code.should.equals(expectedStatus, `Should return: ${expectedStatus}, but returned: ${code}`); done(); } }; ReadinessEndpoint(cloudHealth)(<http.IncomingMessage>reqStub, <http.ServerResponse>resStub, <NextFunction>nextStub) }); it('Readiness returns 200 OK and UP on startup and liveness checks', function(done) { let cloudHealth = new HealthChecker(); cloudHealth.registerStartupCheck( // tslint:disable-next-line:no-shadowed-variable new StartupCheck("startup", () => new Promise<void>(function(resolve, reject){ resolve(); })) ) .then(() => { ReadinessEndpoint(cloudHealth)(<http.IncomingMessage>reqStub, <http.ServerResponse>resStub, <NextFunction>nextStub) }) cloudHealth.registerReadinessCheck( // tslint:disable-next-line:no-shadowed-variable new LivenessCheck("readiness", () => new Promise<void>(function(resolve, reject){ resolve(); })) ) const reqStub: Partial<http.IncomingMessage> = {}; const nextStub: Partial<NextFunction> = {}; const resStub: Partial<http.ServerResponse> = { write: sinon.fake(), end: function () { let expectedStatus = 200; let code = resStub.statusCode ? resStub.statusCode : 0 code.should.equals(expectedStatus, `Should return: ${expectedStatus}, but returned: ${code}`); let expectedBody = "{\"status\":\"UP\",\"checks\":[{\"name\":\"readiness\",\"state\":\"UP\",\"data\":{\"reason\":\"\"}}]}"; sinon.assert.calledWith(resStub.write as sinon.SinonStub, expectedBody) done(); } }; }); it('Readiness returns 503 OK and STOPPING on STOPPING', function(done) { process.removeAllListeners('SIGTERM'); let cloudHealth = new HealthChecker(); cloudHealth.registerShutdownCheck( // tslint:disable-next-line:no-shadowed-variable new ShutdownCheck("test1", () => new Promise<void>(function(resolve, reject){ // tslint:disable-next-line:no-shadowed-variable no-unused-expression new Promise(function(resolve, _reject){ setTimeout(resolve, 1000, 'foo'); }) })) ) const reqStub: Partial<http.IncomingMessage> = {}; const nextStub: Partial<NextFunction> = {}; const resStub: Partial<http.ServerResponse> = { write: sinon.fake(), end: function () { let expectedStatus = 503; let code = resStub.statusCode ? resStub.statusCode : 0 code.should.equals(expectedStatus, `Should return: ${expectedStatus}, but returned: ${code}`); let expectedBody = "{\"status\":\"STOPPING\",\"checks\":[{\"name\":\"test1\",\"state\":\"STOPPING\",\"data\":{\"reason\":\"\"}}]}"; sinon.assert.calledWith(resStub.write as sinon.SinonStub, expectedBody) done(); } }; process.once('SIGTERM', () => { ReadinessEndpoint(cloudHealth)(<http.IncomingMessage>reqStub, <http.ServerResponse>resStub, <NextFunction>nextStub) }); process.kill(process.pid, 'SIGTERM') }); it('Readiness returns 503 OK and STOPPED on STOPPED', function(done) { process.removeAllListeners('SIGTERM'); let cloudHealth = new HealthChecker(); const promiseone = () => new Promise<void>((resolve, _reject) => { setTimeout(resolve, 1); }); let checkone = new ShutdownCheck("test1", promiseone) cloudHealth.registerShutdownCheck(checkone) const reqStub: Partial<http.IncomingMessage> = {}; const nextStub: Partial<NextFunction> = {}; const resStub: Partial<http.ServerResponse> = { write: sinon.fake(), end: function () { let expectedStatus = 503; let code = resStub.statusCode ? resStub.statusCode : 0 code.should.equals(expectedStatus, `Should return: ${expectedStatus}, but returned: ${code}`); let expectedBody = "{\"status\":\"STOPPED\",\"checks\":[{\"name\":\"test1\",\"state\":\"STOPPED\",\"data\":{\"reason\":\"\"}}]}"; sinon.assert.calledWith(resStub.write as sinon.SinonStub, expectedBody) done(); } }; process.once('SIGTERM', async () => { await setTimeout(async () => { ReadinessEndpoint(cloudHealth)(<http.IncomingMessage>reqStub, <http.ServerResponse>resStub, <NextFunction>nextStub) }, 100); }); process.kill(process.pid, 'SIGTERM') }); it('Health returns 503 Unavailable and STARTING on startup check starting', (done) => { let cloudHealth = new HealthChecker(); const StartPromise = () => new Promise<void>((resolve,_reject) => { setTimeout(resolve, 100, 'foo'); }) let StartCheck = new StartupCheck("StartCheck",StartPromise); cloudHealth.registerStartupCheck(StartCheck); const reqStub: Partial<http.IncomingMessage> = {}; const nextStub: Partial<NextFunction> = {}; const resStub: Partial<http.ServerResponse> = { write: sinon.fake(), end: function () { let expectedStatus = 503; let code = resStub.statusCode ? resStub.statusCode : 0 code.should.equals(expectedStatus, `Should return: ${expectedStatus}, but returned: ${code}`); let expectedBody = "{\"status\":\"STARTING\",\"checks\":[{\"name\":\"StartCheck\",\"state\":\"STARTING\",\"data\":{\"reason\":\"\"}}]}"; sinon.assert.calledWith(resStub.write as sinon.SinonStub, expectedBody) done(); } }; HealthEndpoint(cloudHealth)(<http.IncomingMessage>reqStub, <http.ServerResponse>resStub, <NextFunction>nextStub) }); it('Health returns 200 OK and UP on liveness success', function(done) { let cloudHealth = new HealthChecker(); cloudHealth.registerLivenessCheck( // tslint:disable-next-line:no-shadowed-variable new LivenessCheck("test1", () => new Promise<void>(function(resolve, reject){ resolve(); })) ) const reqStub: Partial<http.IncomingMessage> = {}; const nextStub: Partial<NextFunction> = {}; const resStub: Partial<http.ServerResponse> = { write: sinon.fake(), //write: sinon.stub(), end: function () { let expectedStatus = 200; let code = resStub.statusCode ? resStub.statusCode : 0 code.should.equals(expectedStatus, `Should return: ${expectedStatus}, but returned: ${code}`); let expectedBody = "{\"status\":\"UP\",\"checks\":[{\"name\":\"test1\",\"state\":\"UP\",\"data\":{\"reason\":\"\"}}]}"; sinon.assert.calledWith(resStub.write as sinon.SinonStub, expectedBody) done(); } }; HealthEndpoint(cloudHealth)(<http.IncomingMessage>reqStub, <http.ServerResponse>resStub, <NextFunction>nextStub) }); it('Health returns 503 Unavailable and DOWN on liveness fail', function(done) { let cloudHealth = new HealthChecker(); cloudHealth.registerLivenessCheck( // tslint:disable-next-line:no-shadowed-variable new LivenessCheck("test1", () => new Promise<void>(function(resolve, reject){ throw new Error("Liveness Failure"); })) ) const reqStub: Partial<http.IncomingMessage> = {}; const nextStub: Partial<NextFunction> = {}; const resStub: Partial<http.ServerResponse> = { write: sinon.fake(), end: function () { let expectedStatus = 503; let code = resStub.statusCode ? resStub.statusCode : 0 code.should.equals(expectedStatus, `Should return: ${expectedStatus}, but returned: ${code}`); let expectedBody = "{\"status\":\"DOWN\",\"checks\":[{\"name\":\"test1\",\"state\":\"DOWN\",\"data\":{\"reason\":\"Liveness Failure\"}}]}"; sinon.assert.calledWith(resStub.write as sinon.SinonStub, expectedBody) done(); } }; HealthEndpoint(cloudHealth)(<http.IncomingMessage>reqStub, <http.ServerResponse>resStub, <NextFunction>nextStub) }); it('Health returns 503 OK and STOPPING on STOPPING', function(done) { process.removeAllListeners('SIGTERM'); let cloudHealth = new HealthChecker(); cloudHealth.registerShutdownCheck( // tslint:disable-next-line:no-shadowed-variable new ShutdownCheck("test1", () => new Promise<void>(function(resolve, reject){ // tslint:disable-next-line:no-shadowed-variable no-unused-expression new Promise(function(resolve, _reject){ setTimeout(resolve, 1000, 'foo'); }) })) ) const reqStub: Partial<http.IncomingMessage> = {}; const nextStub: Partial<NextFunction> = {}; const resStub: Partial<http.ServerResponse> = { write: sinon.fake(), end: function () { let expectedStatus = 503; let code = resStub.statusCode ? resStub.statusCode : 0 code.should.equals(expectedStatus, `Should return: ${expectedStatus}, but returned: ${code}`); let expectedBody = "{\"status\":\"STOPPING\",\"checks\":[{\"name\":\"test1\",\"state\":\"STOPPING\",\"data\":{\"reason\":\"\"}}]}"; sinon.assert.calledWith(resStub.write as sinon.SinonStub, expectedBody) done(); } }; process.once('SIGTERM', () => { HealthEndpoint(cloudHealth)(<http.IncomingMessage>reqStub, <http.ServerResponse>resStub, <NextFunction>nextStub) }); process.kill(process.pid, 'SIGTERM') }); it('Health returns 503 OK and STOPPED on STOPPED', function(done) { process.removeAllListeners('SIGTERM'); let cloudHealth = new HealthChecker(); const promiseone = () => new Promise<void>((resolve, _reject) => { setTimeout(resolve, 1); }); let checkone = new ShutdownCheck("test1", promiseone) cloudHealth.registerShutdownCheck(checkone) const reqStub: Partial<http.IncomingMessage> = {}; const nextStub: Partial<NextFunction> = {}; const resStub: Partial<http.ServerResponse> = { write: sinon.fake(), end: function () { let expectedStatus = 503; let code = resStub.statusCode ? resStub.statusCode : 0 code.should.equals(expectedStatus, `Should return: ${expectedStatus}, but returned: ${code}`); let expectedBody = "{\"status\":\"STOPPED\",\"checks\":[{\"name\":\"test1\",\"state\":\"STOPPED\",\"data\":{\"reason\":\"\"}}]}"; sinon.assert.calledWith(resStub.write as sinon.SinonStub, expectedBody) done(); } }; process.once('SIGTERM', async () => { await setTimeout(async () => { HealthEndpoint(cloudHealth)(<http.IncomingMessage>reqStub, <http.ServerResponse>resStub, <NextFunction>nextStub) }, 100); }); process.kill(process.pid, 'SIGTERM') }); });
the_stack
interface Window { mapsforge: MapsforgePlugin; } declare var mapsforge: MapsforgePlugin; interface MapsforgePlugin { embedded: MapsforgeEmbeddedPlugin; cache: MapsforgeCachePlugin; } interface MapsforgeEmbeddedPlugin { COLOR_DKGRAY: number|string; COLOR_CYAN: number|string; COLOR_BLACK: number|string; COLOR_BLUE: number|string; COLOR_GREEN: number|string; COLOR_RED: number|string; COLOR_WHITE: number|string; COLOR_TRANSPARENT: number|string; COLOR_YELLOW: number|string; MARKER_RED: number|string; MARKER_GREEN: number|string; MARKER_BLUE: number|string; MARKER_YELLOW: number|string; MARKER_BLACK: number|string; MARKER_WHITE: number|string; /** * The map file path provided must be the absolute file path. You can specify the width and height values for the view that will be added, * or you can set them to 0 for set the value to MATCH_PARENT. You must call this method before any other method. * @param args Array in the following form: [String mapFilePath, int viewWidth, int viewHeight]. * @param success Success callback. * @param error Error callback */ initialize(args: any[], success?: () => void, error?: (message: string) => void): void; /** * To show the map view. * @param success Success callback. * @param error Error callback */ show(success?: () => void, error?: (message: string) => void): void; /** * To hide the map view. * @param success Success callback. * @param error Error callback */ hide(success?: () => void, error?: (message: string) => void): void; /** * Sets the center of the map to the given coordinates. * @param lat Latitude of the new center. * @param lng Longitude of the new center. * @param success Success callback. * @param error Error callback */ setCenter(lat: number, lng: number, success?: () => void, error?: (message: string) => void): void; /** * Sets the zoom to the specified value (if it is between the zoom limits). * @param zoomLevel New zoom level. * @param success Success callback. * @param error Error callback */ setZoom(zoomLevel: number, success?: () => void, error?: (message: string) => void): void; /** * Sets the maximum zoom level. * @param maxZoom New maximum zoom level. * @param success Success callback. * @param error Error callback */ setMaxZoom(maxZoom: number, success?: () => void, error?: (message: string) => void): void; /** * Sets the minimum zoom level. * @param minZoom New minimum zoom level. * @param success Success callback. * @param error Error callback */ setMinZoom(minZoom: number, success?: () => void, error?: (message: string) => void): void; /** * The path to the map ile is required, and the path to the render theme may be null in order to apply the default render theme. * @param args Array in the following form: [String mapFilePath, String renderThemePath] * @param success Success callback. * @param error Error callback */ setOfflineTileLayer(args: any[], success?: () => void, error?: (message: string) => void): void; /** * * @param args Array in the following form: [String providerName, String host, String baseUrl, String extension, int port] * @param success Success callback. * @param error Error callback */ setOnlineTileLayer(args: any[], success?: () => void, error?: (message: string) => void): void; /** * Adds a marker to the map in the specified coordinates and returns the key for that marker to the success function. * @param arg Array in the following form: [String marker_color, double lat, double lng]. * The color of the marker should be one of the constants from mapsforge.embedded object; if the marker doesn't exist a green marker will be used instead. * @param success Success callback. Gets the key of created marker. That key is the one you have to use if you want to delete it. * @param error Error callback */ addMarker(arg: any[], success?: (key: number) => void, error?: (message: string) => void): void; /** * * @param arg Array in the following form: [int color, int strokeWidth,[double points]]. * The color can be one of the constants specified before, or the new color you want. * This function will use the odd positions of the array of points for the latitudes and the even positions for the longitudes. * Example: [lat1, lng1, lat2, lng2, lat3, lng3]. * If the length of the array is not even, the function will throw an exception and return the error message to the error function. * @param success Success callback. Gets the key of created polyline. * @param error Error callback */ addPolyline(arg: any[], success?: (key: number) => void, error?: (message: string) => void): void; /** * Deletes the layer(markers or polylines) with the specified key from the map. * @param key Key of marker or polyline. * @param success Success callback. * @param error Error callback */ deleteLayer(key: number, success?: () => void, error?: (message: string) => void): void; /** * Initializes again the map if the onStop method was called. * @param success Success callback. * @param error Error callback */ onStart(success?: () => void, error?: (message: string) => void): void; /** * Stops the rendering. Useful for when the app goes to the background. You have to call the onStart method to restart it. * @param success Success callback. * @param error Error callback */ onStop(success?: () => void, error?: (message: string) => void): void; /** * Stops and cleans the resources that have been used. * @param success Success callback. * @param error Error callback */ onDestroy(success?: () => void, error?: (message: string) => void): void; } interface MapsforgeCachePlugin { /** * You should call this method before any other one, and provide it with the absolute map file path. * @param mapFilePath Absolute map file path. * @param success Success callback. * @param error Error callback */ initialize(mapFilePath: string, success?: () => void, error?: (message: string) => void): void; /** * This method is the one that provides the tiles, generating them if their are not in the cache. * @param args Array in the following form: [double lat, double lng, byte zoom] * @param success Success callback. Gets the tile path. * @param error Error callback */ getTile(args: any[], success?: (tilePath: string) => void, error?: (message: string) => void): void; /** * Enables or disables the cache. If disabled, the plugin will generate the tiles always from scratch. Cache is enabled by default. * @param enabled Cache enabled or disabled. * @param success Success callback. * @param error Error callback */ setCacheEnabled(enabled: boolean, success?: () => void, error?: (message: string) => void): void; /** * Sets whether or not the cache should be placed in the internal memory or in the SD card. * By default it is placed in SD card, so devices with not too much memory have a better performance. * @param external Cache external or internal. * @param success Success callback. * @param error Error callback */ setExternalCache(external: boolean, success?: () => void, error?: (message: string) => void): void; /** * Sets the map file to be used for rendering to the map specified by its absolute path. * @param absolutePath Absolute map file path. * @param success Success callback. * @param error Error callback */ setMapFile(absolutePath: string, success?: () => void, error?: (message: string) => void): void; /** * Sets the age for the generated images. This means that when the cache is being cleaned, all images younger than the specified value will be kept in the cache in order to avoid deleting images that are being used at the moment. * @param milliseconds Max cache age in milliseconds. * @param success Success callback. * @param error Error callback */ setMaxCacheAge(milliseconds: number, success?: () => void, error?: (message: string) => void): void; /** * Sets the maximum size for the cache. This size must be specified in megabytes. If there is not that space available, the cache will fit the maximum size. * @param sizeInMB Max cache size in megabytes. * @param success Success callback. * @param error Error callback */ setMaxCacheSize(sizeInMB: number, success?: () => void, error?: (message: string) => void): void; /** * Sets the tile size. By default the tile size is set to 256. * @param size Tile size. * @param success Success callback. * @param error Error callback */ setMaxCacheSize(size: number, success?: () => void, error?: (message: string) => void): void; /** * This method sets the size in megabytes that will remain always available in memory in order to avoid that the application uses all space available. * @param sizeInMB Size in megabytes that will remain always available in memory. * @param success Success callback. * @param error Error callback */ setCacheCleaningTrigger(sizeInMB: number, success?: () => void, error?: (message: string) => void): void; /** * Sets a flag to destroy the cache when the onDestroy method is called. * @param destroy If true, cache will be destroyed when the onDestroy method will be called. * @param success Success callback. * @param error Error callback */ destroyCacheOnExit(destroy: boolean, success?: () => void, error?: (message: string) => void): void; /** * Deletes the cache depending on the flag state. * @param success Success callback. * @param error Error callback */ onDestroy(success?: () => void, error?: (message: string) => void): void; }
the_stack
declare global { interface EventTarget { attachEvent?: (type: string, fn: EventListenerOrEventListenerObject) => void; } } /** * The criteria which will be used to filter results to specific classes or elements */ export interface FilterCriterion<T> { /** A collection of class names to include */ allowlist?: string[]; /** A collector of class names to exclude */ denylist?: string[]; /** A callback which returns a boolean as to whether the element should be included */ filter?: (elt: T) => boolean; } /** * Checks if an object is a string * @param str - The object to check */ export function isString(str: Object): str is string { if (str && typeof str.valueOf() === 'string') { return true; } return false; } /** * Checks if an object is an integer * @param int - The object to check */ export function isInteger(int: Object): int is number { return ( (Number.isInteger && Number.isInteger(int)) || (typeof int === 'number' && isFinite(int) && Math.floor(int) === int) ); } /** * Checks if the input parameter is a function * @param func - The object to check */ export function isFunction(func: unknown) { if (func && typeof func === 'function') { return true; } return false; } /** * Cleans up the page title */ export function fixupTitle(title: string | { text: string }) { if (!isString(title)) { title = title.text || ''; var tmp = document.getElementsByTagName('title'); if (tmp && tmp[0] != null) { title = tmp[0].text; } } return title; } /** * Extract hostname from URL */ export function getHostName(url: string) { // scheme : // [username [: password] @] hostname [: port] [/ [path] [? query] [# fragment]] var e = new RegExp('^(?:(?:https?|ftp):)/*(?:[^@]+@)?([^:/#]+)'), matches = e.exec(url); return matches ? matches[1] : url; } /** * Fix-up domain */ export function fixupDomain(domain: string) { var dl = domain.length; // remove trailing '.' if (domain.charAt(--dl) === '.') { domain = domain.slice(0, dl); } // remove leading '*' if (domain.slice(0, 2) === '*.') { domain = domain.slice(1); } return domain; } /** * Get page referrer. In the case of a single-page app, * if the URL changes without the page reloading, pass * in the old URL. It will be returned unless overriden * by a "refer(r)er" parameter in the querystring. * * @param string - oldLocation Optional. * @returns string The referrer */ export function getReferrer(oldLocation?: string) { let windowAlias = window, referrer = '', fromQs = fromQuerystring('referrer', windowAlias.location.href) || fromQuerystring('referer', windowAlias.location.href); // Short-circuit if (fromQs) { return fromQs; } // In the case of a single-page app, return the old URL if (oldLocation) { return oldLocation; } try { referrer = windowAlias.top.document.referrer; } catch (e) { if (windowAlias.parent) { try { referrer = windowAlias.parent.document.referrer; } catch (e2) { referrer = ''; } } } if (referrer === '') { referrer = document.referrer; } return referrer; } /** * Cross-browser helper function to add event handler */ export function addEventListener( element: HTMLElement | EventTarget, eventType: string, eventHandler: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions ) { if (element.addEventListener) { element.addEventListener(eventType, eventHandler, options); return true; } // IE Support if (element.attachEvent) { return element.attachEvent('on' + eventType, eventHandler); } (element as any)['on' + eventType] = eventHandler; } /** * Return value from name-value pair in querystring */ export function fromQuerystring(field: string, url: string) { var match = new RegExp('^[^#]*[?&]' + field + '=([^&#]*)').exec(url); if (!match) { return null; } return decodeURIComponent(match[1].replace(/\+/g, ' ')); } /** * Add a name-value pair to the querystring of a URL * * @param string - url URL to decorate * @param string - name Name of the querystring pair * @param string - value Value of the querystring pair */ export function decorateQuerystring(url: string, name: string, value: string) { var initialQsParams = name + '=' + value; var hashSplit = url.split('#'); var qsSplit = hashSplit[0].split('?'); var beforeQuerystring = qsSplit.shift(); // Necessary because a querystring may contain multiple question marks var querystring = qsSplit.join('?'); if (!querystring) { querystring = initialQsParams; } else { // Whether this is the first time the link has been decorated var initialDecoration = true; var qsFields = querystring.split('&'); for (var i = 0; i < qsFields.length; i++) { if (qsFields[i].substr(0, name.length + 1) === name + '=') { initialDecoration = false; qsFields[i] = initialQsParams; querystring = qsFields.join('&'); break; } } if (initialDecoration) { querystring = initialQsParams + '&' + querystring; } } hashSplit[0] = beforeQuerystring + '?' + querystring; return hashSplit.join('#'); } /** * Attempt to get a value from localStorage * * @param string - key * @returns string The value obtained from localStorage, or * undefined if localStorage is inaccessible */ export function attemptGetLocalStorage(key: string) { try { const localStorageAlias = window.localStorage, exp = localStorageAlias.getItem(key + '.expires'); if (exp === null || +exp > Date.now()) { return localStorageAlias.getItem(key); } else { localStorageAlias.removeItem(key); localStorageAlias.removeItem(key + '.expires'); } return undefined; } catch (e) { return undefined; } } /** * Attempt to write a value to localStorage * * @param string - key * @param string - value * @param number - ttl Time to live in seconds, defaults to 2 years from Date.now() * @returns boolean Whether the operation succeeded */ export function attemptWriteLocalStorage(key: string, value: string, ttl = 63072000) { try { const localStorageAlias = window.localStorage, t = Date.now() + ttl * 1000; localStorageAlias.setItem(`${key}.expires`, t.toString()); localStorageAlias.setItem(key, value); return true; } catch (e) { return false; } } /** * Attempt to delete a value from localStorage * * @param string - key * @returns boolean Whether the operation succeeded */ export function attemptDeleteLocalStorage(key: string) { try { const localStorageAlias = window.localStorage; localStorageAlias.removeItem(key); localStorageAlias.removeItem(key + '.expires'); return true; } catch (e) { return false; } } /** * Attempt to get a value from sessionStorage * * @param string - key * @returns string The value obtained from sessionStorage, or * undefined if sessionStorage is inaccessible */ export function attemptGetSessionStorage(key: string) { try { return window.sessionStorage.getItem(key); } catch (e) { return undefined; } } /** * Attempt to write a value to sessionStorage * * @param string - key * @param string - value * @returns boolean Whether the operation succeeded */ export function attemptWriteSessionStorage(key: string, value: string) { try { window.sessionStorage.setItem(key, value); return true; } catch (e) { return false; } } /** * Finds the root domain */ export function findRootDomain(sameSite: string, secure: boolean) { const windowLocationHostnameAlias = window.location.hostname, cookiePrefix = '_sp_root_domain_test_', cookieName = cookiePrefix + new Date().getTime(), cookieValue = '_test_value_' + new Date().getTime(); var split = windowLocationHostnameAlias.split('.'); var position = split.length - 1; while (position >= 0) { var currentDomain = split.slice(position, split.length).join('.'); cookie(cookieName, cookieValue, 0, '/', currentDomain, sameSite, secure); if (cookie(cookieName) === cookieValue) { // Clean up created cookie(s) deleteCookie(cookieName, currentDomain, sameSite, secure); var cookieNames = getCookiesWithPrefix(cookiePrefix); for (var i = 0; i < cookieNames.length; i++) { deleteCookie(cookieNames[i], currentDomain, sameSite, secure); } return currentDomain; } position -= 1; } // Cookies cannot be read return windowLocationHostnameAlias; } /** * Checks whether a value is present within an array * * @param val - The value to check for * @param array - The array to check within * @returns boolean Whether it exists */ export function isValueInArray<T>(val: T, array: T[]) { for (var i = 0; i < array.length; i++) { if (array[i] === val) { return true; } } return false; } /** * Deletes an arbitrary cookie by setting the expiration date to the past * * @param cookieName - The name of the cookie to delete * @param domainName - The domain the cookie is in */ export function deleteCookie(cookieName: string, domainName?: string, sameSite?: string, secure?: boolean) { cookie(cookieName, '', -1, '/', domainName, sameSite, secure); } /** * Fetches the name of all cookies beginning with a certain prefix * * @param cookiePrefix - The prefix to check for * @returns array The cookies that begin with the prefix */ export function getCookiesWithPrefix(cookiePrefix: string) { var cookies = document.cookie.split('; '); var cookieNames = []; for (var i = 0; i < cookies.length; i++) { if (cookies[i].substring(0, cookiePrefix.length) === cookiePrefix) { cookieNames.push(cookies[i]); } } return cookieNames; } /** * Get and set the cookies associated with the current document in browser * This implementation always returns a string, returns the cookie value if only name is specified * * @param name - The cookie name (required) * @param value - The cookie value * @param ttl - The cookie Time To Live (seconds) * @param path - The cookies path * @param domain - The cookies domain * @param samesite - The cookies samesite attribute * @param secure - Boolean to specify if cookie should be secure * @returns string The cookies value */ export function cookie( name: string, value?: string, ttl?: number, path?: string, domain?: string, samesite?: string, secure?: boolean ) { if (arguments.length > 1) { return (document.cookie = name + '=' + encodeURIComponent(value ?? '') + (ttl ? '; Expires=' + new Date(+new Date() + ttl * 1000).toUTCString() : '') + (path ? '; Path=' + path : '') + (domain ? '; Domain=' + domain : '') + (samesite ? '; SameSite=' + samesite : '') + (secure ? '; Secure' : '')); } return decodeURIComponent((('; ' + document.cookie).split('; ' + name + '=')[1] || '').split(';')[0]); } /** * Parses an object and returns either the * integer or undefined. * * @param obj - The object to parse * @returns the result of the parse operation */ export function parseAndValidateInt(obj: unknown) { var result = parseInt(obj as string); return isNaN(result) ? undefined : result; } /** * Parses an object and returns either the * number or undefined. * * @param obj - The object to parse * @returns the result of the parse operation */ export function parseAndValidateFloat(obj: unknown) { var result = parseFloat(obj as string); return isNaN(result) ? undefined : result; } /** * Convert a criterion object to a filter function * * @param object - criterion Either {allowlist: [array of allowable strings]} * or {denylist: [array of allowable strings]} * or {filter: function (elt) {return whether to track the element} * @param boolean - byClass Whether to allowlist/denylist based on an element's classes (for forms) * or name attribute (for fields) */ export function getFilterByClass(criterion?: FilterCriterion<HTMLElement> | null): (elt: HTMLElement) => boolean { // If the criterion argument is not an object, add listeners to all elements if (criterion == null || typeof criterion !== 'object' || Array.isArray(criterion)) { return function () { return true; }; } const inclusive = Object.prototype.hasOwnProperty.call(criterion, 'allowlist'); const specifiedClassesSet = getSpecifiedClassesSet(criterion); return getFilter(criterion, function (elt: HTMLElement) { return checkClass(elt, specifiedClassesSet) === inclusive; }); } /** * Convert a criterion object to a filter function * * @param object - criterion Either {allowlist: [array of allowable strings]} * or {denylist: [array of allowable strings]} * or {filter: function (elt) {return whether to track the element} */ export function getFilterByName<T extends { name: string }>(criterion?: FilterCriterion<T>): (elt: T) => boolean { // If the criterion argument is not an object, add listeners to all elements if (criterion == null || typeof criterion !== 'object' || Array.isArray(criterion)) { return function () { return true; }; } const inclusive = criterion.hasOwnProperty('allowlist'); const specifiedClassesSet = getSpecifiedClassesSet(criterion); return getFilter(criterion, function (elt: T) { return elt.name in specifiedClassesSet === inclusive; }); } /** * List the classes of a DOM element without using elt.classList (for compatibility with IE 9) */ export function getCssClasses(elt: Element) { return elt.className.match(/\S+/g) || []; } /** * Check whether an element has at least one class from a given list */ function checkClass(elt: Element, classList: Record<string, boolean>) { var classes = getCssClasses(elt); for (const className of classes) { if (classList[className]) { return true; } } return false; } function getFilter<T>(criterion: FilterCriterion<T>, fallbackFilter: (elt: T) => boolean) { if (criterion.hasOwnProperty('filter') && criterion.filter) { return criterion.filter; } return fallbackFilter; } function getSpecifiedClassesSet<T>(criterion: FilterCriterion<T>) { // Convert the array of classes to an object of the form {class1: true, class2: true, ...} var specifiedClassesSet: Record<string, boolean> = {}; var specifiedClasses = criterion.allowlist || criterion.denylist; if (specifiedClasses) { if (!Array.isArray(specifiedClasses)) { specifiedClasses = [specifiedClasses]; } for (var i = 0; i < specifiedClasses.length; i++) { specifiedClassesSet[specifiedClasses[i]] = true; } } return specifiedClassesSet; }
the_stack
import * as React from 'react' import { Colors } from '@xstyled/system' import { toCustomPropertiesDeclarations, toCustomPropertiesReferences, } from './customProperties' type ColorModeState = [string | null, (mode: string | null) => void] interface ColorModes { [key: string]: Colors } interface ITheme { useCustomProperties?: boolean useColorSchemeMediaQuery?: boolean initialColorModeName?: string defaultColorModeName?: string colors?: Colors & { modes?: ColorModes } } interface IColorModeTheme extends ITheme { colors: Colors & { modes: ColorModes } } const STORAGE_KEY = 'xstyled-color-mode' const isLocalStorageAvailable: boolean = typeof window !== 'undefined' && (() => { try { const key = 'xstyled-test-key' window.localStorage.setItem(key, key) window.localStorage.removeItem(key) return true } catch (err) { return false } })() interface Storage { get(): string | null set(value: string): void clear(): void } const storage: Storage = isLocalStorageAvailable ? { get: () => window.localStorage.getItem(STORAGE_KEY), set: (value: string) => { window.localStorage.setItem(STORAGE_KEY, value) }, clear: () => window.localStorage.removeItem(STORAGE_KEY), } : { get: () => null, set: () => {}, clear: () => {}, } const COLOR_MODE_CLASS_PREFIX = 'xstyled-color-mode-' const getColorModeClassName = (mode: string) => `${COLOR_MODE_CLASS_PREFIX}${mode}` const XSTYLED_COLORS_PREFIX = 'xstyled-colors' const SYSTEM_MODES = ['light', 'dark'] function getModeTheme(theme: IColorModeTheme, mode: string): IColorModeTheme { return { ...theme, colors: { ...theme.colors, ...theme.colors.modes[mode] }, } } const getMediaQuery = (query: string): string => `@media ${query}` const getColorModeQuery = (mode: string): string => `(prefers-color-scheme: ${mode})` function checkHasColorModes(theme: ITheme | null): theme is IColorModeTheme { return Boolean(theme && theme.colors && theme.colors.modes) } function checkHasCustomPropertiesEnabled(theme: ITheme | null): boolean { return Boolean( theme && (theme.useCustomProperties === undefined || theme.useCustomProperties), ) } function checkHasMediaQueryEnabled(theme: ITheme | null): boolean { return Boolean( theme && (theme.useColorSchemeMediaQuery === undefined || theme.useColorSchemeMediaQuery), ) } function getInitialColorModeName(theme: ITheme): string { return theme.initialColorModeName || 'default' } function getDefaultColorModeName(theme: ITheme): string { return theme.defaultColorModeName || getInitialColorModeName(theme) } function getUsedColorKeys(modes: ColorModes) { let keys: string[] = [] for (const key in modes) { keys = [...keys, ...Object.keys(modes[key])] } return keys } export function createColorStyles( theme: ITheme, { targetSelector = 'body' } = {}, ): string | null { if (!checkHasColorModes(theme)) return null const { modes, ...colors } = theme.colors const colorKeys = getUsedColorKeys(modes) let styles = toCustomPropertiesDeclarations( colors, theme, colorKeys, XSTYLED_COLORS_PREFIX, ) function getModePropertiesDeclarations(mode: string) { const modeTheme = getModeTheme(theme as IColorModeTheme, mode) const { modes, ...colors } = modeTheme.colors return toCustomPropertiesDeclarations( { ...colors, ...modes[mode] }, modeTheme, colorKeys, XSTYLED_COLORS_PREFIX, ) } if (theme.useColorSchemeMediaQuery !== false) { SYSTEM_MODES.forEach((mode) => { if (modes[mode]) { const mediaQuery = getMediaQuery(getColorModeQuery(mode)) styles += `${mediaQuery}{${getModePropertiesDeclarations(mode)}}` } }) } const initialModeName = getInitialColorModeName(theme) ;[initialModeName, ...Object.keys(modes)].forEach((mode) => { const key = `&.${getColorModeClassName(mode)}` styles += `${key}{${getModePropertiesDeclarations(mode)}}` }) return `${targetSelector}{${styles}}` } function getSystemModeMql(mode: string) { if (typeof window === 'undefined' || window.matchMedia === undefined) { return null } const query = getColorModeQuery(mode) return window.matchMedia(query) } function useSystemMode(theme: ITheme) { const configs: { mode: string; mql: MediaQueryList }[] = React.useMemo(() => { if (!checkHasMediaQueryEnabled(theme)) return [] return SYSTEM_MODES.map((mode) => { if (!checkHasColorModes(theme)) return null if (!theme.colors.modes[mode]) return null const mql = getSystemModeMql(mode) return mql ? { mode, mql } : null }).filter(Boolean) as { mode: string; mql: MediaQueryList }[] }, [theme]) const [systemMode, setSystemMode] = React.useState(() => { const config = configs.find((config) => config.mql.matches) return config ? config.mode : null }) React.useEffect(() => { const cleans = configs.map(({ mode, mql }) => { const handler = ({ matches }: MediaQueryListEvent) => { if (matches) { setSystemMode(mode) } else { setSystemMode((previousMode) => (previousMode === mode ? null : mode)) } } mql.addEventListener('change', handler) return () => mql.removeEventListener('change', handler) }) return () => cleans.forEach((clean) => clean()) }) return systemMode } const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? React.useLayoutEffect : React.useEffect export function useColorModeState( theme: ITheme, { target }: { target?: Element } = {}, ): ColorModeState { const systemMode = useSystemMode(theme) const defaultColorMode = getDefaultColorModeName(theme) const initialColorMode = getInitialColorModeName(theme) const [mode, setMode] = React.useState(() => { if (!checkHasColorModes(theme)) return null return defaultColorMode }) // Add mode className const customPropertiesEnabled = checkHasCustomPropertiesEnabled(theme) const manualSetRef = React.useRef(false) const manuallySetMode = React.useCallback((value) => { manualSetRef.current = true setMode(value) }, []) // Set initial color mode in lazy useIsomorphicLayoutEffect(() => { if (!checkHasColorModes(theme)) return const storedMode = storage.get() const initialMode = storedMode || systemMode || defaultColorMode if (mode !== initialMode) { setMode(storedMode || systemMode || defaultColorMode) } }, []) // Store mode preference useIsomorphicLayoutEffect(() => { if (manualSetRef.current) { if (mode) { storage.set(mode) } else { storage.clear() } } }, [mode]) // Sync system mode useIsomorphicLayoutEffect(() => { const storedMode = storage.get() if (storedMode) return const targetMode = systemMode || defaultColorMode if (targetMode === mode) return setMode(targetMode) }, [mode, systemMode, defaultColorMode]) // Add and remove class names useIsomorphicLayoutEffect(() => { if (!mode) return undefined if (!customPropertiesEnabled) return undefined const stored = storage.get() const initial = initialColorMode !== mode if (!stored && !initial) return undefined const className = getColorModeClassName(mode) const usedTarget = target || document.body usedTarget.classList.add(className) return () => { usedTarget.classList.remove(className) } }, [customPropertiesEnabled, target, mode, initialColorMode]) return [mode, manuallySetMode] } export function useColorModeTheme( theme: ITheme, mode: string | null, ): ITheme | null { const [initialMode] = React.useState(mode) const customPropertiesTheme = React.useMemo(() => { if (!initialMode) return null if (!checkHasCustomPropertiesEnabled(theme)) return null if (!checkHasColorModes(theme)) return theme const { modes, ...colors } = theme.colors const colorKeys = getUsedColorKeys(modes) return { ...theme, colors: { ...colors, ...toCustomPropertiesReferences( colors, theme, colorKeys, XSTYLED_COLORS_PREFIX, ), modes, }, __rawColors: theme.colors, } }, [initialMode, theme]) const swapModeTheme = React.useMemo(() => { if (!mode) return null if (checkHasCustomPropertiesEnabled(theme)) return null if (!checkHasColorModes(theme)) return theme if (mode === getInitialColorModeName(theme)) { return { ...theme, __colorMode: mode } } return { ...theme, colors: { ...theme.colors, ...theme.colors.modes[mode], }, __colorMode: mode, __rawColors: theme.colors, } }, [theme, mode]) return (customPropertiesTheme || swapModeTheme) as ITheme } export const ColorModeContext = React.createContext<ColorModeState | null>(null) export function useColorMode(): ColorModeState { const colorModeState = React.useContext(ColorModeContext) if (!colorModeState) { throw new Error(`[useColorMode] requires the ColorModeProvider component`) } return colorModeState } export interface ColorModeProviderProps { children: React.ReactNode target?: Element targetSelector?: string } export function createColorModeProvider({ ThemeContext, ThemeProvider, ColorModeStyle, }: { ThemeContext: React.Context<any> ThemeProvider: React.ComponentType<any> ColorModeStyle: React.ComponentType<any> }): React.FC<ColorModeProviderProps> { function ColorModeProvider({ children, target, targetSelector, }: ColorModeProviderProps) { const theme = React.useContext(ThemeContext) if (!theme) { throw new Error( '[ColorModeProvider] requires ThemeProvider upper in the tree', ) } const colorState = useColorModeState(theme, { target }) const colorModeTheme = useColorModeTheme(theme, colorState[0]) return ( <> <ColorModeStyle targetSelector={targetSelector} /> <ThemeProvider theme={colorModeTheme}> <ColorModeContext.Provider value={colorState}> {children} </ColorModeContext.Provider> </ThemeProvider> </> ) } return ColorModeProvider } interface GetInitScriptOptions { target?: string } function getInitScript({ target = 'document.body', }: GetInitScriptOptions = {}) { return `(function() { try { var mode = localStorage.getItem('${STORAGE_KEY}'); if (mode) ${target}.classList.add('${COLOR_MODE_CLASS_PREFIX}' + mode); } catch (e) {} })();` } export function getColorModeInitScriptElement( options?: GetInitScriptOptions, ): JSX.Element { return ( <script key="xstyled-color-mode-init" dangerouslySetInnerHTML={{ __html: getInitScript(options) }} /> ) } export function getColorModeInitScriptTag( options?: GetInitScriptOptions, ): string { return `<script>${getInitScript(options)}</script>` }
the_stack
import { DefaultLogEvent, DI, IContainer, ILogger, ISink, LoggerConfiguration, LogLevel, pascalCase, Registration, sink, optional, Task, TaskStatus, Class, } from '@aurelia/kernel'; import { bindingBehavior, BindingBehaviorInstance, Controller, customElement, CustomElement, IBinding, Scope, LifecycleFlags, Switch, Aurelia, IPlatform, ICustomElementViewModel, PromiseTemplateController, valueConverter, ValueConverter, If, ISyntheticView, ICustomElementController, } from '@aurelia/runtime-html'; import { assert, TestContext, } from '@aurelia/testing'; import { createSpecFunction, TestExecutionContext, TestFunction, } from '../util.js'; describe('promise template-controller', function () { const phost = 'pending-host'; const fhost = 'fulfilled-host'; const rhost = 'rejected-host'; type PromiseWithId<TValue extends unknown = unknown> = Promise<TValue> & { id?: number }; class Config { public constructor( public hasPromise: boolean, public wait: (name: string) => Promise<void> | void, ) { } public toString(): string { return `{${this.hasPromise ? this.wait.toString() : 'noWait'}}`; } } const configLookup = DI.createInterface<Map<string, Config>>(); let nameIdMap: Map<string, number>; function createComponentType(name: string, template: string = '', bindables: string[] = []) { @customElement({ name, template, bindables, isStrictBinding: true }) class Component { private readonly logger: ILogger; public constructor( @optional(Config) private readonly config: Config, @ILogger logger: ILogger, @IContainer container: IContainer, ) { let id = nameIdMap.get(name) ?? 1; this.logger = logger.scopeTo(`${name}-${id}`); nameIdMap.set(name, ++id); if (config == null) { const lookup = container.get(configLookup); this.config = lookup.get(name); } } public async binding(): Promise<void> { if (this.config.hasPromise) { await this.config.wait('binding'); } this.logger.debug('binding'); } public async bound(): Promise<void> { if (this.config.hasPromise) { await this.config.wait('bound'); } this.logger.debug('bound'); } public async attaching(): Promise<void> { if (this.config.hasPromise) { await this.config.wait('attaching'); } this.logger.debug('attaching'); } public async attached(): Promise<void> { if (this.config.hasPromise) { await this.config.wait('attached'); } this.logger.debug('attached'); } public async detaching(): Promise<void> { if (this.config.hasPromise) { await this.config.wait('detaching'); } this.logger.debug('detaching'); } public async unbinding(): Promise<void> { if (this.config.hasPromise) { await this.config.wait('unbinding'); } this.logger.debug('unbinding'); } } Reflect.defineProperty(Component, 'name', { writable: false, enumerable: false, configurable: true, value: pascalCase(name), }); return Component; } @sink({ handles: [LogLevel.debug] }) class DebugLog implements ISink { public readonly log: string[] = []; public handleEvent(event: DefaultLogEvent): void { const scope = event.scope.join('.'); if (scope.includes('-host')) { this.log.push(`${scope}.${event.message}`); } } public clear() { this.log.length = 0; } } interface TestSetupContext<TApp> { template: string; registrations: any[]; expectedStopLog: string[]; verifyStopCallsAsSet: boolean; promise: Promise<unknown> | (() => Promise<unknown>) | null; delayPromise: DelayPromise | null; appType: Class<TApp>; } class PromiseTestExecutionContext<TApp = App> implements TestExecutionContext<TApp> { private _scheduler: IPlatform; private readonly _log: DebugLog; public constructor( public ctx: TestContext, public container: IContainer, public host: HTMLElement, public app: TApp, public controller: Controller, public error: Error | null, ) { this._log = (container.get(ILogger)['debugSinks'] as ISink[]).find((s) => s instanceof DebugLog) as DebugLog; } public get platform(): IPlatform { return this._scheduler ?? (this._scheduler = this.container.get(IPlatform)); } public get log() { return this._log?.log ?? []; } public clear() { this._log?.clear(); } public assertCalls(expected: string[], message: string = '') { assert.deepStrictEqual(this.log, expected, message); } public assertCallSet(expected: string[], message: string = '') { const actual = this.log; assert.strictEqual(actual.length, expected.length, `${message} - calls.length - ${actual}`); assert.strictEqual(actual.filter((c) => !expected.includes(c)).length, 0, `${message} - calls set equality - ${actual}`); } } enum DelayPromise { binding = 'binding', } const seedPromise = DI.createInterface<Promise<unknown>>(); const delaySeedPromise = DI.createInterface<DelayPromise>(); async function testPromise<TApp>( testFunction: TestFunction<PromiseTestExecutionContext<TApp>>, { template, registrations = [], expectedStopLog, verifyStopCallsAsSet = false, promise, delayPromise = null, appType, }: Partial<TestSetupContext<TApp>> = {} ) { nameIdMap = new Map<string, number>(); const ctx = TestContext.create(); const host = ctx.doc.createElement('div'); ctx.doc.body.appendChild(host); const container = ctx.container; const au = new Aurelia(container); let error: Error | null = null; let app: TApp | null = null; let controller: Controller = null!; try { await au .register( LoggerConfiguration.create({ level: LogLevel.trace, sinks: [DebugLog] }), ...registrations, Promisify, Double, NoopBindingBehavior, typeof promise === 'function' ? Registration.callback(seedPromise, promise) : Registration.instance(seedPromise, promise), Registration.instance(delaySeedPromise, delayPromise), ) .app({ host, component: CustomElement.define({ name: 'app', isStrictBinding: true, template }, appType ?? App) }) .start(); app = au.root.controller.viewModel as TApp; controller = au.root.controller! as unknown as Controller; } catch (e) { error = e; } const testCtx = new PromiseTestExecutionContext(ctx, container, host, app, controller, error); await testFunction(testCtx); if (error === null) { testCtx.clear(); await au.stop(); assert.html.innerEqual(host, '', 'post-detach innerHTML'); if (verifyStopCallsAsSet) { testCtx.assertCallSet(expectedStopLog); } else { testCtx.assertCalls(expectedStopLog, 'stop lifecycle calls'); } } ctx.doc.body.removeChild(host); } const $it = createSpecFunction(testPromise); @valueConverter('promisify') class Promisify { public toView(value: unknown, resolve: boolean = true, ticks: number = 0): Promise<unknown> { if (ticks === 0) { return Object.assign(resolve ? Promise.resolve(value) : Promise.reject(new Error(String(value))), { id: 0 }); } return Object.assign( createMultiTickPromise(ticks, () => resolve ? Promise.resolve(value) : Promise.reject(new Error(String(value))))(), { id: 0 } ); } } @valueConverter('double') class Double { public fromView(value: unknown): unknown { return value instanceof Error ? (value.message = `${value.message} ${value.message}`, value) : `${value} ${value}`; } } @bindingBehavior('noop') class NoopBindingBehavior implements BindingBehaviorInstance { public bind(_flags: LifecycleFlags, _scope: Scope, _binding: IBinding): void { return; } public unbind(_flags: LifecycleFlags, _scope: Scope, _binding: IBinding): void { return; } } class App { public promise: PromiseWithId; public constructor( @IContainer private readonly container: IContainer, @delaySeedPromise private readonly delaySeedPromise: DelayPromise, ) { if (delaySeedPromise === null) { this.init(); } } public binding(): void { if (this.delaySeedPromise !== DelayPromise.binding) { return; } this.init(); } private init() { this.promise = this.container.get(seedPromise); } private updateError(err: Error) { err.message += '1'; return err; } } function getActivationSequenceFor(name: string | string[]) { return typeof name === 'string' ? [`${name}.binding`, `${name}.bound`, `${name}.attaching`, `${name}.attached`] : ['binding', 'bound', 'attaching', 'attached'].flatMap(x => name.map(n => `${n}.${x}`)); } function getDeactivationSequenceFor(name: string | string[]) { return typeof name === 'string' ? [`${name}.detaching`, `${name}.unbinding`] : ['detaching', 'unbinding'].flatMap(x => name.map(n => `${n}.${x}`)); } class TestData<TApp = App> implements TestSetupContext<TApp> { public readonly template: string; public readonly registrations: any[]; public readonly verifyStopCallsAsSet: boolean; public readonly name: string; public readonly delayPromise: DelayPromise | null; public readonly appType: Class<TApp>; public constructor( name: string, public promise: Promise<unknown> | (() => Promise<unknown>) | null, { registrations = [], template, verifyStopCallsAsSet = false, delayPromise = null, appType, }: Partial<TestSetupContext<TApp>>, public readonly config: Config, public readonly expectedInnerHtml: string, public readonly expectedStartLog: string[], public readonly expectedStopLog: string[], public readonly additionalAssertions: ((ctx: PromiseTestExecutionContext<TApp>) => Promise<void> | void) | null = null, public readonly only: boolean = false, ) { this.name = `${name} - config: ${String(config)} - delayPromise: ${delayPromise}`; this.registrations = [ ...(config !== null ? [Registration.instance(Config, config)] : []), createComponentType(phost, `pending\${p.id}`, ['p']), createComponentType(fhost, `resolved with \${data}`, ['data']), createComponentType(rhost, `rejected with \${err.message}`, ['err']), ...registrations, ]; this.template = template; this.verifyStopCallsAsSet = verifyStopCallsAsSet; this.delayPromise = delayPromise; this.appType = appType as unknown as Class<TApp>; } } function createWaiter(ms: number): (name: string) => Promise<void> { function wait(_name: string): Promise<void> { return new Promise(function (resolve) { setTimeout(resolve, ms); }); } wait.toString = function () { return `setTimeout(cb,${JSON.stringify(ms)})`; }; return wait; } function noop(): Promise<void> { return; } noop.toString = function () { return 'Promise.resolve()'; }; function createMultiTickPromise(ticks: number, cb: () => Promise<unknown>) { const wait = () => { if (ticks === 0) { return cb(); } ticks--; return new Promise((r) => setTimeout(function () { r(wait()); }, 0)); }; return wait; } function createWaiterWithTicks(ticks: Record<string, number>): (name?: string) => Promise<void> | void { const lookup: Record<string, () => Promise<void> | void> = Object.create(null); for (const [key, numTicks] of Object.entries(ticks)) { const fn: (() => Promise<void> | void) & { ticks: number } = () => { if (fn.ticks === 0) { return; } fn.ticks--; return new Promise((r) => setTimeout(function () { void r(fn()); }, 0)); }; fn.ticks = numTicks; lookup[key] = fn; } const wait = (name: string) => { return lookup[name]?.() ?? Promise.resolve(); }; wait.toString = function () { return `waitWithTicks(cb,${JSON.stringify(ticks)})`; }; return wait; } function *getTestData() { function wrap(content: string, type: 'p' | 'f' | 'r', debugMode = false) { switch (type) { case 'p': return `<${phost} ${debugMode ? `p.bind="promise" ` : ''}class="au">${content}</${phost}>`; case 'f': return `<${fhost} ${debugMode ? `data.bind="data" ` : ''}class="au">${content}</${fhost}>`; case 'r': return `<${rhost} ${debugMode ? `err.bind="err" ` : ''}class="au">${content}</${rhost}>`; } } const configFactories = [ function () { return new Config(false, noop); }, function () { return new Config(true, createWaiter(0)); }, function () { return new Config(true, createWaiter(5)); }, ]; for (const [pattribute, fattribute, rattribute] of [ ['promise.bind', 'then.from-view', 'catch.from-view'], // TODO: activate after the attribute parser and/or interpreter such that for `t`, `then` is not picked up. // ['promise.resolve', 'then', 'catch'] ]) { const templateDiv = ` <div ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </div>`; const template1 = ` <template> <template ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template> </template>`; for (const delayPromise of [null, ...(Object.values(DelayPromise))]) { for (const config of configFactories) { { let resolve: (value: unknown) => void; yield new TestData( 'shows content as per promise status - non-template promise-host - fulfilled', Object.assign(new Promise((r) => resolve = r), { id: 0 }), { delayPromise, template: templateDiv, }, config(), `<div> ${wrap('pending0', 'p')} </div>`, getActivationSequenceFor(`${phost}-1`), getDeactivationSequenceFor(`${fhost}-1`), async (ctx) => { ctx.clear(); resolve(42); const p = ctx.platform; // one tick to call back the fulfill delegate, and queue task await p.domWriteQueue.yield(); // on the next tick wait the queued task await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, `<div> ${wrap('resolved with 42', 'f')} </div>`); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor(`${fhost}-1`)]); } ); } { let reject: (value: unknown) => void; yield new TestData( 'shows content as per promise status #1 - rejected', Object.assign(new Promise((_, r) => reject = r), { id: 0 }), { delayPromise, template: templateDiv }, config(), `<div> ${wrap('pending0', 'p')} </div>`, getActivationSequenceFor(`${phost}-1`), getDeactivationSequenceFor(`${rhost}-1`), async (ctx) => { ctx.clear(); reject(new Error('foo-bar')); const p = ctx.platform; await p.domWriteQueue.yield(); await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, `<div> ${wrap('rejected with foo-bar', 'r')} </div>`); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor(`${rhost}-1`)]); } ); } { let resolve: (value: unknown) => void; yield new TestData( 'shows content as per promise status #1 - fulfilled', Object.assign(new Promise((r) => resolve = r), { id: 0 }), { delayPromise, template: template1, }, config(), wrap('pending0', 'p'), getActivationSequenceFor(`${phost}-1`), getDeactivationSequenceFor(`${fhost}-1`), async (ctx) => { ctx.clear(); resolve(42); const p = ctx.platform; // one tick to call back the fulfill delegate, and queue task await p.domWriteQueue.yield(); // on the next tick wait the queued task await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('resolved with 42', 'f')); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor(`${fhost}-1`)]); } ); } { let reject: (value: unknown) => void; yield new TestData( 'shows content as per promise status #1 - rejected', Object.assign(new Promise((_, r) => reject = r), { id: 0 }), { delayPromise, template: template1 }, config(), wrap('pending0', 'p'), getActivationSequenceFor(`${phost}-1`), getDeactivationSequenceFor(`${rhost}-1`), async (ctx) => { ctx.clear(); reject(new Error('foo-bar')); const p = ctx.platform; await p.domWriteQueue.yield(); await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar', 'r')); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor(`${rhost}-1`)]); } ); } yield new TestData( 'shows content for resolved promise', Promise.resolve(42), { delayPromise, template: template1 }, config(), wrap('resolved with 42', 'f'), getActivationSequenceFor(`${fhost}-1`), getDeactivationSequenceFor(`${fhost}-1`), ); yield new TestData( 'shows content for rejected promise', () => Promise.reject(new Error('foo-bar')), { delayPromise, template: template1 }, config(), wrap('rejected with foo-bar', 'r'), getActivationSequenceFor(`${rhost}-1`), getDeactivationSequenceFor(`${rhost}-1`), ); yield new TestData( 'reacts to change in promise value - fulfilled -> fulfilled', Promise.resolve(42), { delayPromise, template: template1 }, config(), wrap('resolved with 42', 'f'), getActivationSequenceFor(`${fhost}-1`), getDeactivationSequenceFor(`${fhost}-1`), async (ctx) => { ctx.clear(); const p = ctx.platform; ctx.app.promise = Promise.resolve(24); await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('resolved with 24', 'f')); ctx.assertCallSet([]); } ); yield new TestData( 'reacts to change in promise value - fulfilled -> rejected', Promise.resolve(42), { delayPromise, template: template1 }, config(), wrap('resolved with 42', 'f'), getActivationSequenceFor(`${fhost}-1`), getDeactivationSequenceFor(`${rhost}-1`), async (ctx) => { ctx.clear(); const p = ctx.platform; ctx.app.promise = Promise.reject(new Error('foo-bar')); await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar', 'r')); ctx.assertCallSet([...getDeactivationSequenceFor(`${fhost}-1`), ...getActivationSequenceFor(`${rhost}-1`)]); } ); yield new TestData( 'reacts to change in promise value - fulfilled -> (pending -> fulfilled)', Promise.resolve(42), { delayPromise, template: template1 }, config(), wrap('resolved with 42', 'f'), getActivationSequenceFor(`${fhost}-1`), getDeactivationSequenceFor(`${fhost}-1`), async (ctx) => { ctx.clear(); const p = ctx.platform; let resolve: (value: unknown) => void; const promise: PromiseWithId = new Promise((r) => resolve = r); promise.id = 0; ctx.app.promise = promise; await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('pending0', 'p')); ctx.assertCallSet([...getDeactivationSequenceFor(`${fhost}-1`), ...getActivationSequenceFor(`${phost}-1`)]); ctx.clear(); resolve(84); await p.domWriteQueue.yield(); await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('resolved with 84', 'f')); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor(`${fhost}-1`)]); } ); yield new TestData( 'reacts to change in promise value - fulfilled -> (pending -> rejected)', Promise.resolve(42), { delayPromise, template: template1 }, config(), wrap('resolved with 42', 'f'), getActivationSequenceFor(`${fhost}-1`), getDeactivationSequenceFor(`${rhost}-1`), async (ctx) => { ctx.clear(); const p = ctx.platform; let reject: (value: unknown) => void; const promise: PromiseWithId = new Promise((_, r) => reject = r); promise.id = 0; ctx.app.promise = promise; await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('pending0', 'p')); ctx.assertCallSet([...getDeactivationSequenceFor(`${fhost}-1`), ...getActivationSequenceFor(`${phost}-1`)]); ctx.clear(); reject(new Error('foo-bar')); await p.domWriteQueue.yield(); await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar', 'r')); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor(`${rhost}-1`)]); } ); yield new TestData( 'reacts to change in promise value - rejected -> rejected', () => Promise.reject(new Error('foo-bar')), { delayPromise, template: template1 }, config(), wrap('rejected with foo-bar', 'r'), getActivationSequenceFor(`${rhost}-1`), getDeactivationSequenceFor(`${rhost}-1`), async (ctx) => { ctx.clear(); const p = ctx.platform; ctx.app.promise = Promise.reject(new Error('fizz-bazz')); await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('rejected with fizz-bazz', 'r')); ctx.assertCallSet([]); } ); yield new TestData( 'reacts to change in promise value - rejected -> fulfilled', () => Promise.reject(new Error('foo-bar')), { delayPromise, template: template1 }, config(), wrap('rejected with foo-bar', 'r'), getActivationSequenceFor(`${rhost}-1`), getDeactivationSequenceFor(`${fhost}-1`), async (ctx) => { ctx.clear(); const p = ctx.platform; ctx.app.promise = Promise.resolve(42); await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('resolved with 42', 'f')); ctx.assertCallSet([...getDeactivationSequenceFor(`${rhost}-1`), ...getActivationSequenceFor(`${fhost}-1`)]); } ); yield new TestData( 'reacts to change in promise value - rejected -> (pending -> fulfilled)', () => Promise.reject(new Error('foo-bar')), { delayPromise, template: template1 }, config(), wrap('rejected with foo-bar', 'r'), getActivationSequenceFor(`${rhost}-1`), getDeactivationSequenceFor(`${fhost}-1`), async (ctx) => { ctx.clear(); const p = ctx.platform; let resolve: (value: unknown) => void; const promise: PromiseWithId = new Promise((r) => resolve = r); promise.id = 0; ctx.app.promise = promise; await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('pending0', 'p')); ctx.assertCallSet([...getDeactivationSequenceFor(`${rhost}-1`), ...getActivationSequenceFor(`${phost}-1`)]); ctx.clear(); resolve(84); await p.domWriteQueue.yield(); await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('resolved with 84', 'f')); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor(`${fhost}-1`)]); } ); yield new TestData( 'reacts to change in promise value - rejected -> (pending -> rejected)', () => Promise.reject(new Error('foo-bar')), { delayPromise, template: template1 }, config(), wrap('rejected with foo-bar', 'r'), getActivationSequenceFor(`${rhost}-1`), getDeactivationSequenceFor(`${rhost}-1`), async (ctx) => { ctx.clear(); const p = ctx.platform; let reject: (value: unknown) => void; const promise: PromiseWithId = new Promise((_, r) => reject = r); promise.id = 0; ctx.app.promise = promise; await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('pending0', 'p')); ctx.assertCallSet([...getDeactivationSequenceFor(`${rhost}-1`), ...getActivationSequenceFor(`${phost}-1`)]); ctx.clear(); reject(new Error('foo-bar')); await p.domWriteQueue.yield(); await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar', 'r')); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor(`${rhost}-1`)]); } ); yield new TestData( 'reacts to change in promise value - pending -> pending', Object.assign(new Promise(() => {/* noop */ }), { id: 0 }), { delayPromise, template: template1 }, config(), wrap('pending0', 'p'), getActivationSequenceFor(`${phost}-1`), getDeactivationSequenceFor(`${phost}-1`), async (ctx) => { ctx.clear(); const p = ctx.platform; ctx.app.promise = Object.assign(new Promise(() => {/* noop */ }), { id: 1 }); await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('pending1', 'p')); ctx.assertCallSet([]); } ); yield new TestData( 'reacts to change in promise value - pending -> fulfilled', Object.assign(new Promise(() => {/* noop */ }), { id: 0 }), { delayPromise, template: template1 }, config(), wrap('pending0', 'p'), getActivationSequenceFor(`${phost}-1`), getDeactivationSequenceFor(`${fhost}-1`), async (ctx) => { ctx.clear(); const p = ctx.platform; ctx.app.promise = Promise.resolve(42); await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('resolved with 42', 'f')); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor(`${fhost}-1`)]); } ); yield new TestData( 'reacts to change in promise value - pending -> rejected', Object.assign(new Promise(() => {/* noop */ }), { id: 0 }), { delayPromise, template: template1 }, config(), wrap('pending0', 'p'), getActivationSequenceFor(`${phost}-1`), getDeactivationSequenceFor(`${rhost}-1`), async (ctx) => { ctx.clear(); const p = ctx.platform; ctx.app.promise = Promise.reject(new Error('foo-bar')); await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar', 'r')); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor(`${rhost}-1`)]); } ); yield new TestData( 'reacts to change in promise value - pending -> (pending -> fulfilled)', Object.assign(new Promise(() => {/* noop */ }), { id: 0 }), { delayPromise, template: template1 }, config(), wrap('pending0', 'p'), getActivationSequenceFor(`${phost}-1`), getDeactivationSequenceFor(`${fhost}-1`), async (ctx) => { ctx.clear(); const p = ctx.platform; let resolve: (value: unknown) => void; ctx.app.promise = Object.assign(new Promise((r) => resolve = r), { id: 1 }); await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('pending1', 'p')); ctx.assertCallSet([]); resolve(42); await p.domWriteQueue.yield(); await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('resolved with 42', 'f')); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor(`${fhost}-1`)]); } ); yield new TestData( 'reacts to change in promise value - pending -> (pending -> rejected)', Object.assign(new Promise(() => {/* noop */ }), { id: 0 }), { delayPromise, template: template1 }, config(), wrap('pending0', 'p'), getActivationSequenceFor(`${phost}-1`), getDeactivationSequenceFor(`${rhost}-1`), async (ctx) => { ctx.clear(); const p = ctx.platform; let reject: (value: unknown) => void; ctx.app.promise = Object.assign(new Promise((_, r) => reject = r), { id: 1 }); await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('pending1', 'p')); ctx.assertCallSet([]); reject(new Error('foo-bar')); await p.domWriteQueue.yield(); await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar', 'r')); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor(`${rhost}-1`)]); } ); yield new TestData( 'can be used in isolation without any of the child template controllers', new Promise(() => {/* noop */ }), { delayPromise, template: `<template><template ${pattribute}="promise">this is shown always</template></template>` }, config(), 'this is shown always', [], [], ); const pTemplt = `<template> <template ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> </template> </template>`; { let resolve: (value: unknown) => void; yield new TestData( 'supports combination: promise>pending - resolved', Object.assign(new Promise((r) => resolve = r), { id: 0 }), { delayPromise, template: pTemplt }, config(), wrap('pending0', 'p'), getActivationSequenceFor(`${phost}-1`), [], async (ctx) => { ctx.clear(); resolve(42); const q = ctx.platform.domWriteQueue; await q.yield(); await q.yield(); assert.html.innerEqual(ctx.host, ''); ctx.assertCallSet(getDeactivationSequenceFor(`${phost}-1`)); } ); } { let reject: (value: unknown) => void; yield new TestData( 'supports combination: promise>pending - rejected', Object.assign(new Promise((_, r) => reject = r), { id: 0 }), { delayPromise, template: pTemplt }, config(), wrap('pending0', 'p'), getActivationSequenceFor(`${phost}-1`), [], async (ctx) => { ctx.clear(); reject(new Error('foo-bar')); const q = ctx.platform.domWriteQueue; await q.yield(); await q.yield(); assert.html.innerEqual(ctx.host, ''); ctx.assertCallSet(getDeactivationSequenceFor(`${phost}-1`)); } ); } const pfCombTemplt = `<template> <template ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> </template> </template>`; { let resolve: (value: unknown) => void; yield new TestData( 'supports combination: promise>(pending+then) - resolved', Object.assign(new Promise((r) => resolve = r), { id: 0 }), { delayPromise, template: pfCombTemplt }, config(), wrap('pending0', 'p'), getActivationSequenceFor(`${phost}-1`), getDeactivationSequenceFor(`${fhost}-1`), async (ctx) => { ctx.clear(); resolve(42); const q = ctx.platform.domWriteQueue; await q.yield(); await q.yield(); assert.html.innerEqual(ctx.host, wrap('resolved with 42', 'f')); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor(`${fhost}-1`)]); } ); } { let reject: (value: unknown) => void; yield new TestData( 'supports combination: promise>(pending+then) - rejected', Object.assign(new Promise((_, r) => reject = r), { id: 0 }), { delayPromise, template: pfCombTemplt }, config(), wrap('pending0', 'p'), getActivationSequenceFor(`${phost}-1`), [], async (ctx) => { ctx.clear(); reject(new Error('foo-bar')); const q = ctx.platform.domWriteQueue; await q.yield(); await q.yield(); assert.html.innerEqual(ctx.host, ''); ctx.assertCallSet(getDeactivationSequenceFor(`${phost}-1`)); } ); } const prCombTemplt = `<template> <template ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template> </template>`; { let resolve: (value: unknown) => void; yield new TestData( 'supports combination: promise>(pending+catch) - resolved', Object.assign(new Promise((r) => resolve = r), { id: 0 }), { delayPromise, template: prCombTemplt }, config(), wrap('pending0', 'p'), getActivationSequenceFor(`${phost}-1`), [], async (ctx) => { ctx.clear(); resolve(42); const q = ctx.platform.domWriteQueue; await q.yield(); await q.yield(); assert.html.innerEqual(ctx.host, ''); ctx.assertCallSet(getDeactivationSequenceFor(`${phost}-1`)); } ); } { let reject: (value: unknown) => void; yield new TestData( 'supports combination: promise>(pending+catch) - rejected', Object.assign(new Promise((_, r) => reject = r), { id: 0 }), { delayPromise, template: prCombTemplt }, config(), wrap('pending0', 'p'), getActivationSequenceFor(`${phost}-1`), getDeactivationSequenceFor(`${rhost}-1`), async (ctx) => { ctx.clear(); reject(new Error('foo-bar')); const q = ctx.platform.domWriteQueue; await q.yield(); await q.yield(); assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar', 'r')); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor(`${rhost}-1`)]); } ); } const fTemplt = `<template> <template ${pattribute}="promise"> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> </template> </template>`; { let resolve: (value: unknown) => void; yield new TestData( 'supports combination: promise>then - resolved', Object.assign(new Promise((r) => resolve = r), { id: 0 }), { delayPromise, template: fTemplt }, config(), '', [], getDeactivationSequenceFor(`${fhost}-1`), async (ctx) => { ctx.clear(); resolve(42); const q = ctx.platform.domWriteQueue; await q.yield(); await q.yield(); assert.html.innerEqual(ctx.host, wrap('resolved with 42', 'f')); ctx.assertCallSet(getActivationSequenceFor(`${fhost}-1`)); } ); } { let reject: (value: unknown) => void; yield new TestData( 'supports combination: promise>then - rejected', Object.assign(new Promise((_, r) => reject = r), { id: 0 }), { delayPromise, template: fTemplt }, config(), '', [], [], async (ctx) => { ctx.clear(); reject(new Error('foo-bar')); const q = ctx.platform.domWriteQueue; await q.yield(); await q.yield(); assert.html.innerEqual(ctx.host, ''); ctx.assertCallSet([]); } ); } const rTemplt = `<template> <template ${pattribute}="promise"> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template> </template>`; { let resolve: (value: unknown) => void; yield new TestData( 'supports combination: promise>catch - resolved', new Promise((r) => resolve = r), { delayPromise, template: rTemplt }, config(), '', [], [], async (ctx) => { ctx.clear(); resolve(42); const q = ctx.platform.domWriteQueue; await q.yield(); await q.yield(); assert.html.innerEqual(ctx.host, ''); ctx.assertCallSet([]); } ); } { let reject: (value: unknown) => void; yield new TestData( 'supports combination: promise>catch - rejected', new Promise((_, r) => reject = r), { delayPromise, template: rTemplt }, config(), '', [], getDeactivationSequenceFor(`${rhost}-1`), async (ctx) => { ctx.clear(); reject(new Error('foo-bar')); const q = ctx.platform.domWriteQueue; await q.yield(); await q.yield(); assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar', 'r')); ctx.assertCallSet(getActivationSequenceFor(`${rhost}-1`)); } ); } const frTemplt = `<template> <template ${pattribute}="promise"> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template> </template>`; { let resolve: (value: unknown) => void; yield new TestData( 'supports combination: promise>then+catch - resolved', new Promise((r) => resolve = r), { delayPromise, template: frTemplt }, config(), '', [], getDeactivationSequenceFor(`${fhost}-1`), async (ctx) => { ctx.clear(); resolve(42); const q = ctx.platform.domWriteQueue; await q.yield(); await q.yield(); assert.html.innerEqual(ctx.host, wrap('resolved with 42', 'f')); ctx.assertCallSet(getActivationSequenceFor(`${fhost}-1`)); } ); } { let reject: (value: unknown) => void; yield new TestData( 'supports combination: promise>then+catch - rejected', new Promise((_, r) => reject = r), { delayPromise, template: frTemplt }, config(), '', [], getDeactivationSequenceFor(`${rhost}-1`), async (ctx) => { ctx.clear(); reject(new Error('foo-bar')); const q = ctx.platform.domWriteQueue; await q.yield(); await q.yield(); assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar', 'r')); ctx.assertCallSet(getActivationSequenceFor(`${rhost}-1`)); } ); } yield new TestData( 'shows static elements', Promise.resolve(42), { delayPromise, template: ` <template> <template ${pattribute}="promise"> <div>foo</div> </template> </template>` }, config(), '<div>foo</div>', [], [], ); const template2 = ` <template> <template ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <fulfilled-host1 then></fulfilled-host1> <rejected-host1 catch></rejected-host1> </template> </template>`; { let resolve: (value: unknown) => void; yield new TestData( 'shows content as per promise status #2 - fulfilled', Object.assign(new Promise((r) => resolve = r), { id: 0 }), { delayPromise, template: template2, registrations: [ createComponentType('fulfilled-host1', 'resolved'), createComponentType('rejected-host1', 'rejected'), ] }, config(), wrap('pending0', 'p'), getActivationSequenceFor(`${phost}-1`), getDeactivationSequenceFor('fulfilled-host1-1'), async (ctx) => { ctx.clear(); resolve(42); const p = ctx.platform; // one tick to call back the fulfill delegate, and queue task await p.domWriteQueue.yield(); // on the next tick wait the queued task await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, '<fulfilled-host1 class="au">resolved</fulfilled-host1>'); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor('fulfilled-host1-1')]); } ); } { let reject: (value: unknown) => void; yield new TestData( 'shows content as per promise status #2 - rejected', Object.assign(new Promise((_, r) => reject = r), { id: 0 }), { delayPromise, template: template2, registrations: [ createComponentType('fulfilled-host1', 'resolved'), createComponentType('rejected-host1', 'rejected'), ] }, config(), wrap('pending0', 'p'), getActivationSequenceFor(`${phost}-1`), getDeactivationSequenceFor('rejected-host1-1'), async (ctx) => { ctx.clear(); reject(new Error()); const p = ctx.platform; // one tick to call back the fulfill delegate, and queue task await p.domWriteQueue.yield(); // on the next tick wait the queued task await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, '<rejected-host1 class="au">rejected</rejected-host1>'); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor('rejected-host1-1')]); } ); } yield new TestData( 'works in nested template - fulfilled>fulfilled', Promise.resolve({ json() { return Promise.resolve(42); } }), { delayPromise, template: ` <template> <template ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <template ${fattribute}="response" ${pattribute}="response.json()"> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> </template> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template> </template>` }, config(), wrap('resolved with 42', 'f'), getActivationSequenceFor(`${fhost}-1`), getDeactivationSequenceFor(`${fhost}-1`), ); yield new TestData( 'works in nested template - fulfilled>rejected', Promise.resolve({ json() { return Promise.reject(new Error('foo-bar')); } }), { delayPromise, template: ` <template> <template ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <template ${fattribute}="response" ${pattribute}="response.json()"> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="updateError(err)"></rejected-host> </template> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template> </template>` }, config(), '<rejected-host class="au">rejected with foo-bar1</rejected-host>', getActivationSequenceFor(`${rhost}-1`), getDeactivationSequenceFor(`${rhost}-1`), ); yield new TestData( 'works in nested template - rejected>fulfilled', () => Promise.reject({ json() { return Promise.resolve(42); } }), { delayPromise, template: ` <template> <template ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <template ${rattribute}="response" ${pattribute}="response.json()"> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template> </template> </template>` }, config(), wrap('resolved with 42', 'f'), getActivationSequenceFor(`${fhost}-2`), getDeactivationSequenceFor(`${fhost}-2`), ); yield new TestData( 'works in nested template - rejected>rejected', () => Promise.reject({ json() { return Promise.reject(new Error('foo-bar')); } }), { delayPromise, template: ` <template> <template ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <template ${rattribute}="response" ${pattribute}="response.json()"> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template> </template> </template>` }, config(), wrap('rejected with foo-bar', 'r'), getActivationSequenceFor(`${rhost}-1`), getDeactivationSequenceFor(`${rhost}-1`), ); for (const $resolve of [true, false]) { yield new TestData( `works with value converter on - settled promise - ${$resolve ? 'fulfilled' : 'rejected'}`, null, { delayPromise, template: ` <template> <template ${pattribute}="42|promisify:${$resolve}"> <pending-host pending></pending-host> <fulfilled-host ${fattribute}="data | double" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err | double" err.bind="err"></rejected-host> </template> </template>` }, config(), $resolve ? wrap('resolved with 42 42', 'f') : wrap('rejected with 42 42', 'r'), getActivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`), getDeactivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`), ); yield new TestData( `works with value converter - longer running promise - ${$resolve ? 'fulfilled' : 'rejected'}`, null, { delayPromise, template: ` <template> <template ${pattribute}="42|promisify:${$resolve}:25"> <pending-host pending></pending-host> <fulfilled-host ${fattribute}="data | double" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err | double" err.bind="err"></rejected-host> </template> </template>` }, config(), null, null, getDeactivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`), async (ctx) => { const q = ctx.platform.domWriteQueue; await q.yield(); const tc = (ctx.app as ICustomElementViewModel).$controller.children.find((c) => c.viewModel instanceof PromiseTemplateController).viewModel as PromiseTemplateController; try { await tc.value; } catch { // ignore rejection } await q.yield(); if ($resolve) { assert.html.innerEqual(ctx.host, wrap('resolved with 42 42', 'f'), 'fulfilled'); } else { assert.html.innerEqual(ctx.host, wrap('rejected with 42 42', 'r'), 'rejected'); } ctx.assertCallSet([...getActivationSequenceFor(`${phost}-1`), ...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`)]); }, ); yield new TestData( `works with binding behavior - settled promise - ${$resolve ? 'fulfilled' : 'rejected'}`, () => $resolve ? Promise.resolve(42) : Promise.reject(new Error('foo-bar')), { delayPromise, template: ` <template> <template ${pattribute}="promise & noop"> <pending-host pending></pending-host> <fulfilled-host ${fattribute}="data & noop" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err & noop" err.bind="err"></rejected-host> </template> </template>` }, config(), $resolve ? wrap('resolved with 42', 'f') : wrap('rejected with foo-bar', 'r'), getActivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`), getDeactivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`), ); yield new TestData( `works with binding behavior - longer running promise - ${$resolve ? 'fulfilled' : 'rejected'}`, () => Object.assign( createMultiTickPromise(20, () => $resolve ? Promise.resolve(42) : Promise.reject(new Error('foo-bar')))(), { id: 0 } ), { delayPromise, template: ` <template> <template ${pattribute}="promise & noop"> <pending-host pending p.bind="promise"></pending-host> <fulfilled-host ${fattribute}="data & noop" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err & noop" err.bind="err"></rejected-host> </template> </template>` }, config(), wrap('pending0', 'p'), getActivationSequenceFor(`${phost}-1`), getDeactivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`), async (ctx) => { ctx.clear(); const q = ctx.platform.domWriteQueue; const tc = (ctx.app as ICustomElementViewModel).$controller.children.find((c) => c.viewModel instanceof PromiseTemplateController).viewModel as PromiseTemplateController; try { await tc.value; } catch { // ignore rejection } await q.yield(); if ($resolve) { assert.html.innerEqual(ctx.host, wrap('resolved with 42', 'f'), 'fulfilled'); } else { assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar', 'r'), 'rejected'); } ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`)]); }, ); { const staticPart = '<my-el class="au">Fizz Bazz</my-el>'; let resolve: (value: unknown) => void; let reject: (value: unknown) => void; yield new TestData( `enables showing rest of the content although the promise is no settled - ${$resolve ? 'fulfilled' : 'rejected'}`, Object.assign(new Promise((rs, rj) => { resolve = rs; reject = rj; }), { id: 0 }), { delayPromise, template: ` <let foo-bar.bind="'Fizz Bazz'"></let> <my-el prop.bind="fooBar"></my-el> <template ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template>`, registrations: [ CustomElement.define({ name: 'my-el', template: `\${prop}`, bindables: ['prop'] }, class MyEl { }), ] }, config(), `${staticPart} ${wrap('pending0', 'p')}`, getActivationSequenceFor(`${phost}-1`), getDeactivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`), async (ctx) => { ctx.clear(); if ($resolve) { resolve(42); } else { reject(new Error('foo-bar')); } const p = ctx.platform; // one tick to call back the fulfill delegate, and queue task await p.domWriteQueue.yield(); // on the next tick wait the queued task await p.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, `${staticPart} ${$resolve ? wrap('resolved with 42', 'f') : wrap('rejected with foo-bar', 'r')}`); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`)]); } ); } } yield new TestData( `shows content specific to promise`, null, { delayPromise, template: ` <template> <template ${pattribute}="42|promisify:true"> <pending-host pending></pending-host> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template> <template ${pattribute}="'forty-two'|promisify:false"> <pending-host pending></pending-host> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template> </template>` }, config(), `${wrap('resolved with 42', 'f')} ${wrap('rejected with forty-two', 'r')}`, getActivationSequenceFor([`${fhost}-1`, `${rhost}-2`]), getDeactivationSequenceFor([`${fhost}-1`, `${rhost}-2`]), ); yield new TestData( `[repeat.for] > [${pattribute}] works`, null, { delayPromise, template: ` <template> <let items.bind="[[42, true], ['foo-bar', false], ['forty-two', true], ['fizz-bazz', false]]"></let> <template repeat.for="item of items"> <template ${pattribute}="item[0] | promisify:item[1]"> <let data.bind="null" err.bind="null"></let> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template> </template> </template>`, }, config(), `${wrap('resolved with 42', 'f')} ${wrap('rejected with foo-bar', 'r')} ${wrap('resolved with forty-two', 'f')} ${wrap('rejected with fizz-bazz', 'r')}`, // getActivationSequenceFor([`${fhost}-1`, `${rhost}-2`, `${fhost}-3`, `${rhost}-4`]), getDeactivationSequenceFor([`${fhost}-1`, `${rhost}-2`, `${fhost}-3`, `${rhost}-4`]), ); yield new TestData( `[repeat.for,${pattribute}] works`, null, { delayPromise, template: ` <template> <let items.bind="[[42, true], ['foo-bar', false], ['forty-two', true], ['fizz-bazz', false]]"></let> <template repeat.for="item of items" ${pattribute}="item[0] | promisify:item[1]"> <let data.bind="null" err.bind="null"></let> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template> </template>`, }, config(), `${wrap('resolved with 42', 'f')} ${wrap('rejected with foo-bar', 'r')} ${wrap('resolved with forty-two', 'f')} ${wrap('rejected with fizz-bazz', 'r')}`, getActivationSequenceFor([`${fhost}-1`, `${rhost}-2`, `${fhost}-3`, `${rhost}-4`]), getDeactivationSequenceFor([`${fhost}-1`, `${rhost}-2`, `${fhost}-3`, `${rhost}-4`]), ); yield new TestData( `[then,repeat.for] works`, null, { delayPromise, template: ` <template> <template ${pattribute}="[42, 'forty-two'] | promisify:true"> <fulfilled-host ${fattribute}="items" repeat.for="data of items" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template> </template>`, }, config(), `${wrap('resolved with 42', 'f')}${wrap('resolved with forty-two', 'f')}`, getActivationSequenceFor([`${fhost}-1`, `${fhost}-2`]), getDeactivationSequenceFor([`${fhost}-1`, `${fhost}-2`]), ); yield new TestData( `[then] > [repeat.for] works`, null, { delayPromise, template: ` <template> <template ${pattribute}="[42, 'forty-two'] | promisify:true"> <template ${fattribute}="items"> <fulfilled-host repeat.for="data of items" data.bind="data"></fulfilled-host> </template> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template> </template>`, }, config(), `${wrap('resolved with 42', 'f')}${wrap('resolved with forty-two', 'f')}`, getActivationSequenceFor([`${fhost}-1`, `${fhost}-2`]), getDeactivationSequenceFor([`${fhost}-1`, `${fhost}-2`]), ); { const registrations = [ createComponentType('rej-host', `rejected with \${err}`, ['err']), ValueConverter.define( 'parseError', class ParseError { public toView(value: Error): string[] { return value.message.split(','); } } ) ]; yield new TestData( `[catch,repeat.for] works`, null, { delayPromise, template: ` <template> <template ${pattribute}="[42, 'forty-two'] | promisify:false"> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rej-host ${rattribute}="error" repeat.for="err of error | parseError" err.bind="err"></rej-host> </template> </template>`, registrations, }, config(), '<rej-host class="au">rejected with 42</rej-host><rej-host class="au">rejected with forty-two</rej-host>', getActivationSequenceFor(['rej-host-1', 'rej-host-2']), getDeactivationSequenceFor(['rej-host-1', 'rej-host-2']), ); yield new TestData( `[catch] > [repeat.for] works`, null, { delayPromise, template: ` <template> <template ${pattribute}="[42, 'forty-two'] | promisify:false"> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <template ${rattribute}="error"> <rej-host repeat.for="err of error | parseError" err.bind="err"></rej-host> </template> </template> </template>`, registrations, }, config(), '<rej-host class="au">rejected with 42</rej-host><rej-host class="au">rejected with forty-two</rej-host>', getActivationSequenceFor(['rej-host-1', 'rej-host-2']), getDeactivationSequenceFor(['rej-host-1', 'rej-host-2']), ); } yield new TestData( `[if,${pattribute}], [else,${pattribute}] works`, null, { delayPromise, template: ` <let flag.bind="false"></let> <template if.bind="flag" ${pattribute}="42 | promisify:true"> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template> <template else ${pattribute}="'forty-two' | promisify:false"> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template>`, }, config(), wrap('rejected with forty-two', 'r'), getActivationSequenceFor(`${rhost}-1`), getDeactivationSequenceFor(`${fhost}-2`), async (ctx) => { const q = ctx.platform.domWriteQueue; const app = ctx.app; const controller = (app as ICustomElementViewModel).$controller; const $if = controller.children.find((c) => c.viewModel instanceof If).viewModel as If; ctx.clear(); controller.scope.overrideContext.flag = true; await $if['pending']; const ptc1 = $if.ifView.children.find((c) => c.viewModel instanceof PromiseTemplateController).viewModel as PromiseTemplateController; try { await ptc1.value; } catch { // ignore rejection } await q.yield(); assert.html.innerEqual(ctx.host, wrap('resolved with 42', 'f')); ctx.assertCallSet([...getDeactivationSequenceFor(`${rhost}-1`), ...getActivationSequenceFor(`${fhost}-2`)]); }, ); yield new TestData( `[pending,if] works`, Object.assign(new Promise(() => {/* noop */ }), { id: 0 }), { delayPromise, template: ` <let flag.bind="false"></let> <template ${pattribute}="promise"> <pending-host pending p.bind="promise" if.bind="flag"></pending-host> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template>`, }, config(), '', [], getDeactivationSequenceFor(`${phost}-1`), async (ctx) => { ctx.clear(); const q = ctx.platform.domWriteQueue; const app = ctx.app; const controller = (app as ICustomElementViewModel).$controller; const tc = controller.children.find((c) => c.viewModel instanceof PromiseTemplateController).viewModel as PromiseTemplateController; controller.scope.overrideContext.flag = true; await ((tc['pending']['view'] as ISyntheticView).children.find((c) => c.viewModel instanceof If).viewModel as If)['pending']; await q.yield(); assert.html.innerEqual(ctx.host, wrap('pending0', 'p')); ctx.assertCallSet(getActivationSequenceFor(`${phost}-1`)); }, ); yield new TestData( `[then,if] works- #1`, Object.assign(Promise.resolve(42), { id: 0 }), { delayPromise, template: ` <let flag.bind="false"></let> <template ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <fulfilled-host ${fattribute}="data" if.bind="flag" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template>`, }, config(), '', [], getDeactivationSequenceFor(`${fhost}-1`), async (ctx) => { ctx.clear(); const app = ctx.app; const controller = (app as ICustomElementViewModel).$controller; const tc = controller.children.find((c) => c.viewModel instanceof PromiseTemplateController).viewModel as PromiseTemplateController; controller.scope.overrideContext.flag = true; await ((tc['fulfilled']['view'] as ISyntheticView).children.find((c) => c.viewModel instanceof If).viewModel as If)['pending']; assert.html.innerEqual(ctx.host, wrap('resolved with 42', 'f')); ctx.assertCallSet(getActivationSequenceFor(`${fhost}-1`)); }, ); yield new TestData( `[then,if] works- #2`, Object.assign(Promise.resolve(24), { id: 0 }), { delayPromise, template: ` <template> <template ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <fulfilled-host ${fattribute}="data" if.bind="data === 42" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template> </template>`, }, config(), '', [], getDeactivationSequenceFor(`${fhost}-1`), async (ctx) => { ctx.clear(); const q = ctx.platform.domWriteQueue; const app = ctx.app; await (app.promise = Promise.resolve(42)); await q.yield(); const controller = (app as ICustomElementViewModel).$controller; const tc = controller.children.find((c) => c.viewModel instanceof PromiseTemplateController).viewModel as PromiseTemplateController; controller.scope.overrideContext.flag = true; await ((tc['fulfilled']['view'] as ISyntheticView).children.find((c) => c.viewModel instanceof If).viewModel as If)['pending']; assert.html.innerEqual(ctx.host, wrap('resolved with 42', 'f')); ctx.assertCallSet(getActivationSequenceFor(`${fhost}-1`)); }, ); yield new TestData( `[catch,if] works- #1`, () => Object.assign(Promise.reject(new Error('foo-bar')), { id: 0 }), { delayPromise, template: ` <let flag.bind="false"></let> <template ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" if.bind="flag" err.bind="err"></rejected-host> </template>`, }, config(), '', [], getDeactivationSequenceFor(`${rhost}-1`), async (ctx) => { ctx.clear(); const app = ctx.app; const controller = (app as ICustomElementViewModel).$controller; const tc = controller.children.find((c) => c.viewModel instanceof PromiseTemplateController).viewModel as PromiseTemplateController; controller.scope.overrideContext.flag = true; await ((tc['rejected']['view'] as ISyntheticView).children.find((c) => c.viewModel instanceof If).viewModel as If)['pending']; assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar', 'r')); ctx.assertCallSet(getActivationSequenceFor(`${rhost}-1`)); }, ); yield new TestData( `[catch,if] works- #2`, () => Object.assign(Promise.reject(new Error('foo')), { id: 0 }), { delayPromise, template: ` <template> <template ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" if.bind="err.message === 'foo-bar'" err.bind="err"></rejected-host> </template> </template>`, }, config(), '', [], getDeactivationSequenceFor(`${rhost}-1`), async (ctx) => { ctx.clear(); const q = ctx.platform.domWriteQueue; const app = ctx.app; try { await (app.promise = Promise.reject(new Error('foo-bar'))); } catch { // ignore rejection } await q.yield(); const controller = (app as ICustomElementViewModel).$controller; const tc = controller.children.find((c) => c.viewModel instanceof PromiseTemplateController).viewModel as PromiseTemplateController; controller.scope.overrideContext.flag = true; await ((tc['rejected']['view'] as ISyntheticView).children.find((c) => c.viewModel instanceof If).viewModel as If)['pending']; assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar', 'r')); ctx.assertCallSet(getActivationSequenceFor(`${rhost}-1`)); }, ); const waitSwitch: ($switch: Switch) => Promise<void> = async ($switch) => { const promise = $switch.promise; await promise; if ($switch.promise !== promise) { await waitSwitch($switch); } }; for (const $resolve of [true, false]) { yield new TestData( `[case,${pattribute}] works - ${$resolve ? 'fulfilled' : 'rejected'}`, () => $resolve ? Promise.resolve(42) : Promise.reject(new Error('foo-bar')), { delayPromise, template: ` <let status.bind="'unknown'"></let> <template switch.bind="status"> <template case="unknown">Unknown</template> <template case="processing" ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" if.bind="err.message === 'foo-bar'" err.bind="err"></rejected-host> </template> </template>`, }, config(), 'Unknown', [], getDeactivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`), async (ctx) => { ctx.clear(); const q = ctx.platform.domWriteQueue; const app = ctx.app; const controller = (app as ICustomElementViewModel).$controller; controller.scope.overrideContext.status = 'processing'; await waitSwitch(controller.children.find((c) => c.viewModel instanceof Switch).viewModel as Switch); try { await app.promise; } catch { // ignore rejection } await q.yield(); assert.html.innerEqual(ctx.host, $resolve ? wrap('resolved with 42', 'f') : wrap('rejected with foo-bar', 'r')); ctx.assertCallSet(getActivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`)); }, ); } yield new TestData( `[then,switch] works - #1`, Promise.resolve('foo'), { delayPromise, template: ` <template> <template ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <template ${fattribute}="status" switch.bind="status"> <fulfilled-host case='processing' data="processing"></fulfilled-host> <fulfilled-host default-case data="unknown"></fulfilled-host> </template> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template> </template>`, }, config(), '<fulfilled-host class="au">resolved with unknown</fulfilled-host>', getActivationSequenceFor(`${fhost}-2`), getDeactivationSequenceFor(`${fhost}-1`), async (ctx) => { ctx.clear(); const q = ctx.platform.domWriteQueue; const app = ctx.app; const controller = (app as ICustomElementViewModel).$controller; const tc = controller.children.find((c) => c.viewModel instanceof PromiseTemplateController).viewModel as PromiseTemplateController; const $switch = tc['fulfilled'].view.children.find((c) => c.viewModel instanceof Switch).viewModel as Switch; await (app.promise = Promise.resolve('processing')); await q.yield(); await waitSwitch($switch); assert.html.innerEqual(ctx.host, '<fulfilled-host class="au">resolved with processing</fulfilled-host>'); ctx.assertCallSet([...getDeactivationSequenceFor(`${fhost}-2`), ...getActivationSequenceFor(`${fhost}-1`)]); }, ); yield new TestData( `[then,switch] works - #2`, Promise.resolve('foo'), { delayPromise, template: ` <let status.bind="'processing'"></let> <template ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <template then switch.bind="status"> <fulfilled-host case='processing' data="processing"></fulfilled-host> <fulfilled-host default-case data="unknown"></fulfilled-host> </template> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </template>`, }, config(), '<fulfilled-host class="au">resolved with processing</fulfilled-host>', getActivationSequenceFor(`${fhost}-1`), getDeactivationSequenceFor(`${fhost}-2`), async (ctx) => { ctx.clear(); const app = ctx.app; const controller = (app as ICustomElementViewModel).$controller; const tc = controller.children.find((c) => c.viewModel instanceof PromiseTemplateController).viewModel as PromiseTemplateController; const $switch = tc['fulfilled'].view.children.find((c) => c.viewModel instanceof Switch).viewModel as Switch; controller.scope.overrideContext.status = 'foo'; await waitSwitch($switch); assert.html.innerEqual(ctx.host, '<fulfilled-host class="au">resolved with unknown</fulfilled-host>'); ctx.assertCallSet([...getDeactivationSequenceFor(`${fhost}-1`), ...getActivationSequenceFor(`${fhost}-2`)]); } ); yield new TestData( `[catch,switch] works - #1`, () => Promise.reject(new Error('foo')), { delayPromise, template: ` <template> <template ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <template ${rattribute}="err" switch.bind="err.message"> <rejected-host case='processing' err.bind="{message: 'processing'}"></rejected-host> <rejected-host default-case err.bind="{message: 'unknown'}"></rejected-host> </template> </template> </template>`, }, config(), '<rejected-host class="au">rejected with unknown</rejected-host>', getActivationSequenceFor(`${rhost}-2`), getDeactivationSequenceFor(`${rhost}-1`), async (ctx) => { ctx.clear(); const q = ctx.platform.domWriteQueue; const app = ctx.app; const controller = (app as ICustomElementViewModel).$controller; const tc = controller.children.find((c) => c.viewModel instanceof PromiseTemplateController).viewModel as PromiseTemplateController; const $switch = tc['rejected'].view.children.find((c) => c.viewModel instanceof Switch).viewModel as Switch; try { await (app.promise = Promise.reject(new Error('processing'))); } catch { // ignore rejection } await q.yield(); await waitSwitch($switch); assert.html.innerEqual( ctx.host, '<rejected-host class="au">rejected with processing</rejected-host>' ); ctx.assertCallSet([...getDeactivationSequenceFor(`${rhost}-2`), ...getActivationSequenceFor(`${rhost}-1`)]); }, ); yield new TestData( `[catch,switch] works - #2`, () => Promise.reject(new Error('foo')), { delayPromise, template: ` <let status.bind="'processing'"></let> <template ${pattribute}="promise"> <pending-host pending p.bind="promise"></pending-host> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <template catch switch.bind="status"> <rejected-host case='processing' err.bind="{message: 'processing'}"></rejected-host> <rejected-host default-case err.bind="{message: 'unknown'}"></rejected-host> </template> </template>`, }, config(), '<rejected-host class="au">rejected with processing</rejected-host>', getActivationSequenceFor(`${rhost}-1`), getDeactivationSequenceFor(`${rhost}-2`), async (ctx) => { ctx.clear(); const app = ctx.app; const controller = (app as ICustomElementViewModel).$controller; const tc = controller.children.find((c) => c.viewModel instanceof PromiseTemplateController).viewModel as PromiseTemplateController; const $switch = tc['rejected'].view.children.find((c) => c.viewModel instanceof Switch).viewModel as Switch; controller.scope.overrideContext.status = 'foo'; await waitSwitch($switch); assert.html.innerEqual(ctx.host, '<rejected-host class="au">rejected with unknown</rejected-host>'); ctx.assertCallSet([...getDeactivationSequenceFor(`${rhost}-1`), ...getActivationSequenceFor(`${rhost}-2`)]); } ); yield new TestData( `au-slot use-case`, () => Promise.reject(new Error('foo')), { delayPromise, template: ` <foo-bar p.bind="42|promisify:true"> <div au-slot>f1</div> <div au-slot="rejected">r1</div> </foo-bar> <foo-bar p.bind="'forty-two'|promisify:false"> <div au-slot>f2</div> <div au-slot="rejected">r2</div> </foo-bar> <template as-custom-element="foo-bar"> <bindable property="p"></bindable> <template ${pattribute}="p"> <au-slot name="pending" pending></au-slot> <au-slot then></au-slot> <au-slot name="rejected" catch></au-slot> </template> </template>`, }, config(), '<foo-bar class="au"> <div>f1</div> </foo-bar> <foo-bar class="au"> <div>r2</div> </foo-bar>', [], [], ); { let resolve: (value: unknown) => void; yield new TestData( `*[promise]>div>*[pending|then|catch] works`, Object.assign(new Promise((r) => { resolve = r; }), { id: 0 }), { delayPromise, template: ` <template> <template ${pattribute}="promise"> <div> <pending-host pending p.bind="promise"></pending-host> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </div> </template> </template>`, }, config(), `<div> ${wrap('pending0', 'p')} </div>`, getActivationSequenceFor(`${phost}-1`), getDeactivationSequenceFor(`${rhost}-1`), async (ctx) => { ctx.clear(); const q = ctx.platform.domWriteQueue; resolve(42); await q.yield(); await q.yield(); assert.html.innerEqual(ctx.host, `<div> ${wrap('resolved with 42', 'f')} </div>`, 'fulfilled'); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor(`${fhost}-1`)]); ctx.clear(); ctx.app.promise = Promise.reject(new Error('foo-bar')); await q.yield(); await q.yield(); assert.html.innerEqual(ctx.host, `<div> ${wrap('rejected with foo-bar', 'r')} </div>`, 'rejected'); ctx.assertCallSet([...getDeactivationSequenceFor(`${fhost}-1`), ...getActivationSequenceFor(`${rhost}-1`)]); } ); } { let resolve: (value: unknown) => void; yield new TestData( `*[promise]>CE>*[pending|then|catch] produces output`, Object.assign(new Promise((r) => { resolve = r; }), { id: 0 }), { delayPromise, template: ` <template as-custom-element="foo-bar"> foo bar </template> <template ${pattribute}="promise"> <foo-bar> <pending-host pending p.bind="promise"></pending-host> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </foo-bar> </template>`, }, config(), `<foo-bar class="au"> ${wrap('pending0', 'p')} foo bar </foo-bar>`, getActivationSequenceFor(`${phost}-1`), getDeactivationSequenceFor(`${rhost}-1`), async (ctx) => { ctx.clear(); const q = ctx.platform.domWriteQueue; resolve(42); await q.yield(); await q.yield(); assert.html.innerEqual(ctx.host, `<foo-bar class="au"> ${wrap('resolved with 42', 'f')} foo bar </foo-bar>`, 'fulfilled'); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor(`${fhost}-1`)]); ctx.clear(); ctx.app.promise = Promise.reject(new Error('foo-bar')); await q.yield(); await q.yield(); assert.html.innerEqual(ctx.host, `<foo-bar class="au"> ${wrap('rejected with foo-bar', 'r')} foo bar </foo-bar>`, 'rejected'); ctx.assertCallSet([...getDeactivationSequenceFor(`${fhost}-1`), ...getActivationSequenceFor(`${rhost}-1`)]); } ); } { let resolve: (value: unknown) => void; yield new TestData( `*[promise]>CE>CE>*[pending|then|catch] produces output`, Object.assign(new Promise((r) => { resolve = r; }), { id: 0 }), { delayPromise, template: ` <template as-custom-element="foo-bar"> foo bar </template> <template as-custom-element="fiz-baz"> fiz baz </template> <template ${pattribute}="promise"> <foo-bar> <fiz-baz> <pending-host pending p.bind="promise"></pending-host> <fulfilled-host ${fattribute}="data" data.bind="data"></fulfilled-host> <rejected-host ${rattribute}="err" err.bind="err"></rejected-host> </fiz-baz> </foo-bar> </template>`, }, config(), `<foo-bar class="au"> <fiz-baz class="au"> ${wrap('pending0', 'p')} fiz baz </fiz-baz> foo bar </foo-bar>`, getActivationSequenceFor(`${phost}-1`), getDeactivationSequenceFor(`${rhost}-1`), async (ctx) => { ctx.clear(); const q = ctx.platform.domWriteQueue; resolve(42); await q.yield(); await q.yield(); assert.html.innerEqual(ctx.host, `<foo-bar class="au"> <fiz-baz class="au"> ${wrap('resolved with 42', 'f')} fiz baz </fiz-baz> foo bar </foo-bar>`, 'fulfilled'); ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor(`${fhost}-1`)]); ctx.clear(); ctx.app.promise = Promise.reject(new Error('foo-bar')); await q.yield(); await q.yield(); assert.html.innerEqual(ctx.host, `<foo-bar class="au"> <fiz-baz class="au"> ${wrap('rejected with foo-bar', 'r')} fiz baz </fiz-baz> foo bar </foo-bar>`, 'rejected'); ctx.assertCallSet([...getDeactivationSequenceFor(`${fhost}-1`), ...getActivationSequenceFor(`${rhost}-1`)]); } ); } } // #region timings for (const $resolve of [true, false]) { const getPromise = (ticks: number) => () => Object.assign( createMultiTickPromise(ticks, () => $resolve ? Promise.resolve(42) : Promise.reject(new Error('foo-bar')))(), { id: 0 } ); yield new TestData( `pending activation duration < promise settlement duration - ${$resolve ? 'fulfilled' : 'rejected'}`, getPromise(20), { delayPromise, template: template1, registrations: [ Registration.instance(configLookup, new Map<string, Config>([ [phost, new Config(true, createWaiterWithTicks({ binding: 1, bound: 1, attaching: 1, attached: 1 }))], [fhost, new Config(true, createWaiterWithTicks(Object.create(null)))], [rhost, new Config(true, createWaiterWithTicks(Object.create(null)))], ])), ], }, null, null, null, getDeactivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`), async (ctx) => { const q = ctx.platform.domWriteQueue; await q.yield(); try { await ctx.app.promise; } catch (e) { // ignore rejection } await q.yield(); if ($resolve) { assert.html.innerEqual(ctx.host, wrap('resolved with 42', 'f'), 'fulfilled'); } else { assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar', 'r'), 'rejected'); } ctx.assertCallSet([...getActivationSequenceFor(`${phost}-1`), ...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`)]); }, ); // These tests are more like sanity checks rather than asserting the lifecycle hooks invocation timings and sequence of those. // These rather assert that under varied configurations of promise and hook timings, the template controllers still work. for (const [name, promiseTick, config] of [ ['pending activation duration == promise settlement duration', 4, { binding: 1, bound: 1, attaching: 1, attached: 1 }], ['pending "binding" duration == promise settlement duration', 2, { binding: 2 }], ['pending "binding" duration > promise settlement duration', 1, { binding: 2 }], ['pending "binding" duration > promise settlement duration (longer running promise and hook)', 4, { binding: 6 }], ['pending "binding+bound" duration > promise settlement duration', 2, { binding: 1, bound: 2 }], ['pending "binding+bound" duration > promise settlement duration (longer running promise and hook)', 4, { binding: 3, bound: 3 }], ['pending "binding+bound+attaching" duration > promise settlement duration', 2, { binding: 1, bound: 1, attaching: 1 }], ['pending "binding+bound+attaching" duration > promise settlement duration (longer running promise and hook)', 5, { binding: 2, bound: 2, attaching: 2 }], ['pending "binding+bound+attaching+attached" duration > promise settlement duration', 3, { binding: 1, bound: 1, attaching: 1, attached: 1 }], ['pending "binding+bound+attaching+attached" duration > promise settlement duration (longer running promise and hook)', 6, { binding: 2, bound: 2, attaching: 2, attached: 2 }], ] as const) { yield new TestData( `${name} - ${$resolve ? 'fulfilled' : 'rejected'}`, getPromise(promiseTick), { delayPromise, template: template1, registrations: [ Registration.instance(configLookup, new Map<string, Config>([ [phost, new Config(true, createWaiterWithTicks(config))], [fhost, new Config(true, createWaiterWithTicks(Object.create(null)))], [rhost, new Config(true, createWaiterWithTicks(Object.create(null)))], ])), ], }, null, null, null, getDeactivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`), async (ctx) => { const q = ctx.platform.domWriteQueue; await q.yield(); const app = ctx.app; // Note: If the ticks are close to each other, we cannot avoid a race condition for the purpose of deterministic tests. // Therefore, the expected logs are constructed dynamically to ensure certain level of confidence. const tc = (app as ICustomElementViewModel).$controller.children.find((c) => c.viewModel instanceof PromiseTemplateController).viewModel as PromiseTemplateController; const task = tc['preSettledTask'] as (Task<void | Promise<void>> | null); const logs = task.status === TaskStatus.running || task.status === TaskStatus.completed ? [...getActivationSequenceFor(`${phost}-1`), ...getDeactivationSequenceFor(`${phost}-1`)] : []; try { await app.promise; } catch { // ignore rejection } await q.yield(); if ($resolve) { assert.html.innerEqual(ctx.host, wrap('resolved with 42', 'f'), 'fulfilled'); } else { assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar', 'r'), 'rejected'); } ctx.assertCallSet([...logs, ...getActivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`)], `calls mismatch; presettled task status: ${task.status}`); } ); } yield new TestData( `change of promise in quick succession - final promise is settled - ${$resolve ? 'fulfilled' : 'rejected'}`, Promise.resolve(42), { delayPromise, template: template1, registrations: [ Registration.instance(configLookup, new Map<string, Config>([ [phost, new Config(true, createWaiterWithTicks(Object.create(null)))], [fhost, new Config(true, createWaiterWithTicks(Object.create(null)))], [rhost, new Config(true, createWaiterWithTicks(Object.create(null)))], ])), ], }, null, wrap(`resolved with 42`, 'f'), getActivationSequenceFor(`${fhost}-1`), getDeactivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`), async (ctx) => { ctx.clear(); const app = ctx.app; app.promise = Object.assign(new Promise(() => { /* unsettled */ }), { id: 0 }); const q = ctx.platform.domWriteQueue; await q.yield(); assert.html.innerEqual(ctx.host, wrap('pending0', 'p'), 'pending'); ctx.assertCallSet([...getDeactivationSequenceFor(`${fhost}-1`), ...getActivationSequenceFor(`${phost}-1`)], `calls mismatch1`); ctx.clear(); try { // interrupt await (app.promise = $resolve ? Promise.resolve(4242) : Promise.reject(new Error('foo-bar foo-bar'))); } catch { // ignore rejection } // wait for the next tick await q.yield(); if ($resolve) { assert.html.innerEqual(ctx.host, wrap('resolved with 4242', 'f'), 'fulfilled'); } else { assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar foo-bar', 'r'), 'rejected'); } ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`)], `calls mismatch2`); }, ); yield new TestData( `change of promise in quick succession - final promise is of shorter duration - ${$resolve ? 'fulfilled' : 'rejected'}`, Promise.resolve(42), { delayPromise, template: template1, registrations: [ Registration.instance(configLookup, new Map<string, Config>([ [phost, new Config(true, createWaiterWithTicks(Object.create(null)))], [fhost, new Config(true, createWaiterWithTicks(Object.create(null)))], [rhost, new Config(true, createWaiterWithTicks(Object.create(null)))], ])), ], }, null, wrap(`resolved with 42`, 'f'), getActivationSequenceFor(`${fhost}-1`), getDeactivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`), async (ctx) => { ctx.clear(); const app = ctx.app; app.promise = Object.assign(new Promise(() => { /* unsettled */ }), { id: 0 }); const q = ctx.platform.domWriteQueue; await q.yield(); assert.html.innerEqual(ctx.host, wrap('pending0', 'p'), 'pending0'); ctx.assertCallSet([...getDeactivationSequenceFor(`${fhost}-1`), ...getActivationSequenceFor(`${phost}-1`)], `calls mismatch1`); ctx.clear(); // interrupt; the previous promise is of longer duration because it is never settled. const promise = app.promise = Object.assign( createMultiTickPromise(5, () => $resolve ? Promise.resolve(4242) : Promise.reject(new Error('foo-bar foo-bar')))(), { id: 1 } ); await q.queueTask(() => { assert.html.innerEqual(ctx.host, wrap('pending1', 'p'), 'pending1'); }).result; ctx.assertCallSet([], `calls mismatch2`); ctx.clear(); try { await promise; } catch { // ignore rejection } // wait for the next tick await q.yield(); if ($resolve) { assert.html.innerEqual(ctx.host, wrap('resolved with 4242', 'f'), 'fulfilled'); } else { assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar foo-bar', 'r'), 'rejected'); } ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`)], `calls mismatch2`); }, ); yield new TestData( `change of promise in quick succession - changed after previous promise is settled but the post-settlement activation is pending - ${$resolve ? 'fulfilled' : 'rejected'}`, Promise.resolve(42), { delayPromise, template: template1, registrations: [ Registration.instance(configLookup, new Map<string, Config>([ [phost, new Config(true, createWaiterWithTicks(Object.create(null)))], [fhost, new Config(true, createWaiterWithTicks($resolve ? { binding: 1, bound: 2, attaching: 2, attached: 2 } : Object.create(null)))], [rhost, new Config(true, createWaiterWithTicks($resolve ? Object.create(null) : { binding: 1, bound: 2, attaching: 2, attached: 2 }))], ])), ], }, null, wrap(`resolved with 42`, 'f'), getActivationSequenceFor(`${fhost}-1`), getDeactivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`), async (ctx) => { ctx.clear(); const app = ctx.app; let resolve: (value: unknown) => void; let reject: (value: unknown) => void; let promise = app.promise = Object.assign(new Promise((rs, rj) => [resolve, reject] = [rs, rj]), { id: 0 }); const q = ctx.platform.domWriteQueue; await q.yield(); assert.html.innerEqual(ctx.host, wrap('pending0', 'p'), 'pending0'); ctx.assertCallSet([...getDeactivationSequenceFor(`${fhost}-1`), ...getActivationSequenceFor(`${phost}-1`)], `calls mismatch1`); ctx.clear(); try { if ($resolve) { resolve(84); } else { reject(new Error('fizz bazz')); } await promise; } catch { // ignore rejection } // attempt interrupt promise = app.promise = Object.assign( createMultiTickPromise(20, () => $resolve ? Promise.resolve(4242) : Promise.reject(new Error('foo-bar foo-bar')))(), { id: 1 } ); await q.yield(); assert.html.innerEqual(ctx.host, wrap('pending1', 'p'), 'pending1'); ctx.assertCallSet([], `calls mismatch3`); ctx.clear(); try { await promise; } catch { // ignore rejection } await q.yield(); if ($resolve) { assert.html.innerEqual(ctx.host, wrap('resolved with 4242', 'f'), 'fulfilled 2'); } else { assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar foo-bar', 'r'), 'rejected 2'); } ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`)], `calls mismatch4`); }, ); yield new TestData( `change of promise in quick succession - changed after the post-settlement activation is running - ${$resolve ? 'fulfilled' : 'rejected'}`, Promise.resolve(42), { delayPromise, template: template1, registrations: [ Registration.instance(configLookup, new Map<string, Config>([ [phost, new Config(true, createWaiterWithTicks(Object.create(null)))], [fhost, new Config(true, createWaiterWithTicks($resolve ? { binding: 1, bound: 2, attaching: 2, attached: 2 } : Object.create(null)))], [rhost, new Config(true, createWaiterWithTicks($resolve ? Object.create(null) : { binding: 1, bound: 2, attaching: 2, attached: 2 }))], ])), ], }, null, wrap(`resolved with 42`, 'f'), getActivationSequenceFor(`${fhost}-1`), getDeactivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`), async (ctx) => { ctx.clear(); const app = ctx.app; let resolve: (value: unknown) => void; let reject: (value: unknown) => void; let promise = app.promise = Object.assign(new Promise((rs, rj) => [resolve, reject] = [rs, rj]), { id: 0 }); const q = ctx.platform.domWriteQueue; await q.yield(); assert.html.innerEqual(ctx.host, wrap('pending0', 'p'), 'pending0'); ctx.assertCallSet([...getDeactivationSequenceFor(`${fhost}-1`), ...getActivationSequenceFor(`${phost}-1`)], `calls mismatch1`); ctx.clear(); try { if ($resolve) { resolve(84); } else { reject(new Error('foo-bar')); } await promise; } catch { // ignore rejection } // run the post-settled task q.flush(); promise = app.promise = Object.assign(new Promise((rs, rj) => [resolve, reject] = [rs, rj]), { id: 1 }); await q.yield(); if ($resolve) { assert.html.innerEqual(ctx.host, wrap('resolved with 84', 'f'), 'fulfilled 1'); } else { assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar', 'r'), 'rejected 1'); } ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`)], `calls mismatch2`); ctx.clear(); await q.yield(); assert.html.innerEqual(ctx.host, wrap('pending1', 'p'), 'pending1'); ctx.assertCallSet([...getDeactivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`), ...getActivationSequenceFor(`${phost}-1`)], `calls mismatch3`); ctx.clear(); try { if ($resolve) { resolve(4242); } else { reject(new Error('foo-bar foo-bar')); } await promise; } catch { // ignore rejection } await q.yield(); if ($resolve) { assert.html.innerEqual(ctx.host, wrap('resolved with 4242', 'f'), 'fulfilled 2'); } else { assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar foo-bar', 'r'), 'rejected 2'); } ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`)], `calls mismatch4`); }, ); yield new TestData( `change of promise in quick succession - previous promise is settled after the new promise is settled - ${$resolve ? 'fulfilled' : 'rejected'}`, Promise.resolve(42), { delayPromise, template: template1, registrations: [ Registration.instance(configLookup, new Map<string, Config>([ [phost, new Config(true, createWaiterWithTicks(Object.create(null)))], [fhost, new Config(true, createWaiterWithTicks($resolve ? { binding: 1, bound: 2, attaching: 2, attached: 2 } : Object.create(null)))], [rhost, new Config(true, createWaiterWithTicks($resolve ? Object.create(null) : { binding: 1, bound: 2, attaching: 2, attached: 2 }))], ])), ], }, null, wrap(`resolved with 42`, 'f'), getActivationSequenceFor(`${fhost}-1`), getDeactivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`), async (ctx) => { ctx.clear(); const app = ctx.app; let resolve1: (value: unknown) => void; let reject1: (value: unknown) => void; const promise1 = app.promise = Object.assign(new Promise((rs, rj) => [resolve1, reject1] = [rs, rj]), { id: 0 }); const q = ctx.platform.domWriteQueue; await q.yield(); assert.html.innerEqual(ctx.host, wrap('pending0', 'p'), 'pending0'); ctx.assertCallSet([...getDeactivationSequenceFor(`${fhost}-1`), ...getActivationSequenceFor(`${phost}-1`)], `calls mismatch1`); ctx.clear(); try { await (app.promise = Object.assign($resolve ? Promise.resolve(84) : Promise.reject(new Error('foo-bar')), { id: 1 })); } catch { // ignore rejection } try { if ($resolve) { resolve1(4242); } else { reject1(new Error('fiz baz')); } await promise1; } catch { // ignore rejection } await q.yield(); if ($resolve) { assert.html.innerEqual(ctx.host, wrap('resolved with 84', 'f'), 'fulfilled 1'); } else { assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar', 'r'), 'rejected 1'); } ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`)], `calls mismatch2`); }, ); yield new TestData( `change of promise in quick succession - previous promise is settled after the new post-settled work is finished - ${$resolve ? 'fulfilled' : 'rejected'}`, Promise.resolve(42), { delayPromise, template: template1, registrations: [ Registration.instance(configLookup, new Map<string, Config>([ [phost, new Config(true, createWaiterWithTicks(Object.create(null)))], [fhost, new Config(true, createWaiterWithTicks($resolve ? { binding: 1, bound: 2, attaching: 2, attached: 2 } : Object.create(null)))], [rhost, new Config(true, createWaiterWithTicks($resolve ? Object.create(null) : { binding: 1, bound: 2, attaching: 2, attached: 2 }))], ])), ], }, null, wrap(`resolved with 42`, 'f'), getActivationSequenceFor(`${fhost}-1`), getDeactivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`), async (ctx) => { ctx.clear(); const app = ctx.app; let resolve1: (value: unknown) => void; let reject1: (value: unknown) => void; const promise1 = app.promise = Object.assign(new Promise((rs, rj) => [resolve1, reject1] = [rs, rj]), { id: 0 }); const q = ctx.platform.domWriteQueue; await q.yield(); assert.html.innerEqual(ctx.host, wrap('pending0', 'p'), 'pending0'); ctx.assertCallSet([...getDeactivationSequenceFor(`${fhost}-1`), ...getActivationSequenceFor(`${phost}-1`)], `calls mismatch1`); ctx.clear(); try { await (app.promise = Object.assign($resolve ? Promise.resolve(84) : Promise.reject(new Error('foo-bar')), { id: 1 })); } catch { // ignore rejection } await q.yield(); if ($resolve) { assert.html.innerEqual(ctx.host, wrap('resolved with 84', 'f'), 'fulfilled 1'); } else { assert.html.innerEqual(ctx.host, wrap('rejected with foo-bar', 'r'), 'rejected 1'); } ctx.assertCallSet([...getDeactivationSequenceFor(`${phost}-1`), ...getActivationSequenceFor($resolve ? `${fhost}-1` : `${rhost}-1`)], `calls mismatch2`); const tc = (ctx.app as ICustomElementViewModel).$controller.children.find((c) => c.viewModel instanceof PromiseTemplateController).viewModel as PromiseTemplateController; const postSettleTask = tc['postSettledTask']; // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access const taskNums = [q['pending'].length, q['processing'].length, q['delayed'].length]; try { if ($resolve) { resolve1(4242); } else { reject1(new Error('fiz baz')); } await promise1; } catch { // ignore rejection } await q.yield(); assert.strictEqual(tc['postSettledTask'], postSettleTask); // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access assert.deepStrictEqual([q['pending'].length, q['processing'].length, q['delayed'].length], taskNums); }, ); } // #endregion } // #region scope for (const $resolve of [true, false]) { { class App1 { public readonly promise: Promise<number>; public data: number; public err: Error; public constructor() { this.promise = $resolve ? Promise.resolve(42) : Promise.reject(new Error('foo-bar')); } public async binding(): Promise<void> { try { this.data = (await this.promise) ** 2; } catch (e) { this.err = new Error(`modified ${e.message}`); } } } yield new TestData<App1>( `shows scoped content correctly #1 - ${$resolve ? 'fulfilled' : 'rejected'}`, null, { template: ` <div ${pattribute}="promise"> <let data.bind="null" err.bind="null"></let> <div ${fattribute}="data">\${data} \${$parent.data}</div> <div ${rattribute}="err">'\${err.message}' '\${$parent.err.message}'</div> </div>`, appType: App1, }, null, $resolve ? `<div> <div>42 1764</div> </div>` : `<div> <div>'foo-bar' 'modified foo-bar'</div> </div>`, [], [], ); yield new TestData<App1>( `shows scoped content correctly #2 - ${$resolve ? 'fulfilled' : 'rejected'}`, null, { template: ` <div ${pattribute}="promise"> <div ${fattribute}>\${data}</div> <div ${rattribute}>\${err.message}</div> </div>`, appType: App1, }, null, $resolve ? `<div> <div>1764</div> </div>` : `<div> <div>modified foo-bar</div> </div>`, [], [], ); } { class App1 implements ICustomElementViewModel { public readonly promise: Promise<number>; public data: number; public err: Error; public $controller: ICustomElementController<this>; public constructor() { this.promise = $resolve ? Promise.resolve(42) : Promise.reject(new Error('foo-bar')); } } yield new TestData<App1>( `shows scoped content correctly #3 - ${$resolve ? 'fulfilled' : 'rejected'}`, null, { template: ` <div ${pattribute}="promise"> <div ${fattribute}="$parent.data">\${data} \${$parent.data}</div> <div ${rattribute}="$parent.err">'\${err.message}' '\${$parent.err.message}'</div> </div> \${data} \${err.message}`, appType: App1, }, null, $resolve ? `<div> <div>42 42</div> </div> 42 undefined` : `<div> <div>'foo-bar' 'foo-bar'</div> </div> undefined foo-bar`, [], [], (ctx) => { const app = ctx.app; const s = app.$controller.scope; const bc = s.bindingContext; const oc = s.overrideContext; if ($resolve) { assert.strictEqual(bc.data, 42, 'bc.data'); assert.strictEqual(bc.err, undefined, 'bc.err'); } else { assert.strictEqual(bc.data, undefined, 'bc.data'); assert.strictEqual((bc.err as Error).message, 'foo-bar', 'bc.err'); } assert.strictEqual('data' in oc, false, 'data in oc'); assert.strictEqual('err' in oc, false, 'err in oc'); }, ); yield new TestData<App1>( `shows scoped content correctly #4 - ${$resolve ? 'fulfilled' : 'rejected'}`, null, { template: ` <div ${pattribute}="promise"> <div ${fattribute}="data">\${data}</div> <div ${rattribute}="err">\${err.message}</div> </div>`, appType: App1, }, null, $resolve ? `<div> <div>42</div> </div>` : `<div> <div>foo-bar</div> </div>`, [], [], (ctx) => { const app = ctx.app; const s = app.$controller.scope; const bc = s.bindingContext; const oc = s.overrideContext; assert.strictEqual('data' in bc, true, 'data in bc'); assert.strictEqual('err' in bc, true, 'err in bc'); assert.strictEqual('data' in oc, false, 'data in oc'); assert.strictEqual('err' in oc, false, 'err in oc'); }, ); } } // #endregion } } for (const data of getTestData()) { (data.only ? $it.only : $it)(data.name, async function (ctx: PromiseTestExecutionContext<any>) { assert.strictEqual(ctx.error, null); const expectedContent = data.expectedInnerHtml; if (expectedContent !== null) { await ctx.platform.domWriteQueue.yield(); assert.html.innerEqual(ctx.host, expectedContent, 'innerHTML'); } const expectedLog = data.expectedStartLog; if (expectedLog !== null) { ctx.assertCallSet(expectedLog, 'start lifecycle calls'); } const additionalAssertions = data.additionalAssertions; if (additionalAssertions !== null) { await additionalAssertions(ctx); } }, data); } class NegativeTestData implements TestSetupContext<App> { public readonly registrations: any[] = []; public readonly expectedStopLog: string[] = []; public readonly verifyStopCallsAsSet: boolean = false; public readonly promise: Promise<unknown> = Promise.resolve(42); public readonly delayPromise: DelayPromise = null; public readonly appType: Class<App> = App; public constructor( public readonly name: string, public readonly template: string, ) { } } function *getNegativeTestData() { yield new NegativeTestData( `pending cannot be used in isolation`, `<template><template pending>pending</template></template>` ); yield new NegativeTestData( `then cannot be used in isolation`, `<template><template then>fulfilled</template></template>` ); yield new NegativeTestData( `catch cannot be used in isolation`, `<template><template catch>rejected</template></template>` ); yield new NegativeTestData( `pending cannot be nested inside an if.bind`, `<template><template if.bind="true"><template pending>pending</template></template></template>` ); yield new NegativeTestData( `then cannot be nested inside an if.bind`, `<template><template if.bind="true"><template then>fulfilled</template></template></template>` ); yield new NegativeTestData( `catch cannot be nested inside an if.bind`, `<template><template if.bind="true"><template catch>rejected</template></template></template>` ); yield new NegativeTestData( `pending cannot be nested inside an else`, `<template><template if.bind="false"></template><template else><template pending>pending</template></template></template>` ); yield new NegativeTestData( `then cannot be nested inside an else`, `<template><template if.bind="false"></template><template else><template then>fulfilled</template></template></template>` ); yield new NegativeTestData( `catch cannot be nested inside an else`, `<template><template if.bind="false"></template><template else><template catch>rejected</template></template></template>` ); yield new NegativeTestData( `pending cannot be nested inside a repeater`, `<template><template repeat.for="i of 1"><template pending>pending</template></template></template>` ); yield new NegativeTestData( `then cannot be nested inside a repeater`, `<template><template repeat.for="i of 1"><template then>fulfilled</template></template></template>` ); yield new NegativeTestData( `catch cannot be nested inside a repeater`, `<template><template repeat.for="i of 1"><template catch>rejected</template></template></template>` ); } for (const data of getNegativeTestData()) { $it(data.name, async function (ctx: PromiseTestExecutionContext) { // assert.match(ctx.error.message, /The parent promise\.resolve not found; only `\*\[promise\.resolve\] > \*\[pending\|then\|catch\]` relation is supported\./); assert.match(ctx.error.message, /AUR0813/); }, data); } });
the_stack
import * as coreClient from "@azure/core-client"; /** High-level information about a Template Spec version. */ export interface TemplateSpecVersionInfo { /** * Template Spec version description. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly description?: string; /** * The timestamp of when the version was created. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly timeCreated?: Date; /** * The timestamp of when the version was last modified. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly timeModified?: Date; } /** Common properties for all Azure resources. */ export interface AzureResourceBase { /** * String Id used to locate any resource on Azure. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly id?: string; /** * Name of this resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly name?: string; /** * Type of this resource. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** * Azure Resource Manager metadata containing createdBy and modifiedBy information. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly systemData?: SystemData; } /** Metadata pertaining to creation and last modification of the resource. */ export interface SystemData { /** The identity that created the resource. */ createdBy?: string; /** The type of identity that created the resource. */ createdByType?: CreatedByType; /** The timestamp of resource creation (UTC). */ createdAt?: Date; /** The identity that last modified the resource. */ lastModifiedBy?: string; /** The type of identity that last modified the resource. */ lastModifiedByType?: CreatedByType; /** The timestamp of resource last modification (UTC) */ lastModifiedAt?: Date; } /** Template Specs error response. */ export interface TemplateSpecsError { /** Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.) */ error?: ErrorResponse; } /** Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData error response format.) */ export interface ErrorResponse { /** * The error code. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly code?: string; /** * The error message. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly message?: string; /** * The error target. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly target?: string; /** * The error details. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly details?: ErrorResponse[]; /** * The error additional info. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly additionalInfo?: ErrorAdditionalInfo[]; } /** The resource management error additional info. */ export interface ErrorAdditionalInfo { /** * The additional info type. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly type?: string; /** * The additional info. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly info?: Record<string, unknown>; } /** List of Template Specs. */ export interface TemplateSpecsListResult { /** An array of Template Specs. */ value?: TemplateSpec[]; /** * The URL to use for getting the next set of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Represents a Template Spec artifact containing an embedded Azure Resource Manager template for use as a linked template. */ export interface LinkedTemplateArtifact { /** A filesystem safe relative path of the artifact. */ path: string; /** The Azure Resource Manager template. */ template: Record<string, unknown>; } /** List of Template Specs versions */ export interface TemplateSpecVersionsListResult { /** An array of Template Spec versions. */ value?: TemplateSpecVersion[]; /** * The URL to use for getting the next set of results. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly nextLink?: string; } /** Template Spec object. */ export type TemplateSpec = AzureResourceBase & { /** The location of the Template Spec. It cannot be changed after Template Spec creation. It must be one of the supported Azure locations. */ location: string; /** Resource tags. */ tags?: { [propertyName: string]: string }; /** Template Spec description. */ description?: string; /** Template Spec display name. */ displayName?: string; /** The Template Spec metadata. Metadata is an open-ended object and is typically a collection of key-value pairs. */ metadata?: Record<string, unknown>; /** * High-level information about the versions within this Template Spec. The keys are the version names. Only populated if the $expand query parameter is set to 'versions'. * NOTE: This property will not be serialized. It can only be populated by the server. */ readonly versions?: { [propertyName: string]: TemplateSpecVersionInfo }; }; /** Template Spec properties to be updated (only tags are currently supported). */ export type TemplateSpecUpdateModel = AzureResourceBase & { /** Resource tags. */ tags?: { [propertyName: string]: string }; }; /** Template Spec Version object. */ export type TemplateSpecVersion = AzureResourceBase & { /** The location of the Template Spec Version. It must match the location of the parent Template Spec. */ location: string; /** Resource tags. */ tags?: { [propertyName: string]: string }; /** Template Spec version description. */ description?: string; /** An array of linked template artifacts. */ linkedTemplates?: LinkedTemplateArtifact[]; /** The version metadata. Metadata is an open-ended object and is typically a collection of key-value pairs. */ metadata?: Record<string, unknown>; /** The main Azure Resource Manager template content. */ mainTemplate?: Record<string, unknown>; /** The Azure Resource Manager template UI definition content. */ uiFormDefinition?: Record<string, unknown>; }; /** Template Spec Version properties to be updated (only tags are currently supported). */ export type TemplateSpecVersionUpdateModel = AzureResourceBase & { /** Resource tags. */ tags?: { [propertyName: string]: string }; }; /** Known values of {@link CreatedByType} that the service accepts. */ export enum KnownCreatedByType { User = "User", Application = "Application", ManagedIdentity = "ManagedIdentity", Key = "Key" } /** * Defines values for CreatedByType. \ * {@link KnownCreatedByType} can be used interchangeably with CreatedByType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **User** \ * **Application** \ * **ManagedIdentity** \ * **Key** */ export type CreatedByType = string; /** Known values of {@link TemplateSpecExpandKind} that the service accepts. */ export enum KnownTemplateSpecExpandKind { /** Includes version information with the Template Spec. */ Versions = "versions" } /** * Defines values for TemplateSpecExpandKind. \ * {@link KnownTemplateSpecExpandKind} can be used interchangeably with TemplateSpecExpandKind, * this enum contains the known values that the service supports. * ### Known values supported by the service * **versions**: Includes version information with the Template Spec. */ export type TemplateSpecExpandKind = string; /** Optional parameters. */ export interface TemplateSpecsCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type TemplateSpecsCreateOrUpdateResponse = TemplateSpec; /** Optional parameters. */ export interface TemplateSpecsUpdateOptionalParams extends coreClient.OperationOptions { /** Template Spec resource with the tags to be updated. */ templateSpec?: TemplateSpecUpdateModel; } /** Contains response data for the update operation. */ export type TemplateSpecsUpdateResponse = TemplateSpec; /** Optional parameters. */ export interface TemplateSpecsGetOptionalParams extends coreClient.OperationOptions { /** Allows for expansion of additional Template Spec details in the response. Optional. */ expand?: TemplateSpecExpandKind; } /** Contains response data for the get operation. */ export type TemplateSpecsGetResponse = TemplateSpec; /** Optional parameters. */ export interface TemplateSpecsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface TemplateSpecsListBySubscriptionOptionalParams extends coreClient.OperationOptions { /** Allows for expansion of additional Template Spec details in the response. Optional. */ expand?: TemplateSpecExpandKind; } /** Contains response data for the listBySubscription operation. */ export type TemplateSpecsListBySubscriptionResponse = TemplateSpecsListResult; /** Optional parameters. */ export interface TemplateSpecsListByResourceGroupOptionalParams extends coreClient.OperationOptions { /** Allows for expansion of additional Template Spec details in the response. Optional. */ expand?: TemplateSpecExpandKind; } /** Contains response data for the listByResourceGroup operation. */ export type TemplateSpecsListByResourceGroupResponse = TemplateSpecsListResult; /** Optional parameters. */ export interface TemplateSpecsListBySubscriptionNextOptionalParams extends coreClient.OperationOptions { /** Allows for expansion of additional Template Spec details in the response. Optional. */ expand?: TemplateSpecExpandKind; } /** Contains response data for the listBySubscriptionNext operation. */ export type TemplateSpecsListBySubscriptionNextResponse = TemplateSpecsListResult; /** Optional parameters. */ export interface TemplateSpecsListByResourceGroupNextOptionalParams extends coreClient.OperationOptions { /** Allows for expansion of additional Template Spec details in the response. Optional. */ expand?: TemplateSpecExpandKind; } /** Contains response data for the listByResourceGroupNext operation. */ export type TemplateSpecsListByResourceGroupNextResponse = TemplateSpecsListResult; /** Optional parameters. */ export interface TemplateSpecVersionsCreateOrUpdateOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the createOrUpdate operation. */ export type TemplateSpecVersionsCreateOrUpdateResponse = TemplateSpecVersion; /** Optional parameters. */ export interface TemplateSpecVersionsUpdateOptionalParams extends coreClient.OperationOptions { /** Template Spec Version resource with the tags to be updated. */ templateSpecVersionUpdateModel?: TemplateSpecVersionUpdateModel; } /** Contains response data for the update operation. */ export type TemplateSpecVersionsUpdateResponse = TemplateSpecVersion; /** Optional parameters. */ export interface TemplateSpecVersionsGetOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get operation. */ export type TemplateSpecVersionsGetResponse = TemplateSpecVersion; /** Optional parameters. */ export interface TemplateSpecVersionsDeleteOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface TemplateSpecVersionsListOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the list operation. */ export type TemplateSpecVersionsListResponse = TemplateSpecVersionsListResult; /** Optional parameters. */ export interface TemplateSpecVersionsListNextOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the listNext operation. */ export type TemplateSpecVersionsListNextResponse = TemplateSpecVersionsListResult; /** Optional parameters. */ export interface TemplateSpecsClientOptionalParams extends coreClient.ServiceClientOptions { /** server parameter */ $host?: string; /** Api Version */ apiVersion?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import { createConnection, TextDocuments, ProposedFeatures, InitializeParams, DidChangeConfigurationNotification, CompletionItem, CompletionItemKind, ClientCapabilities, Command, Range, MarkedString, MarkupContent, Location, DocumentSymbol, SymbolKind, WorkspaceEdit, TextEdit, ColorPresentation, Color, ColorInformation, TextDocumentSyncKind, MarkupKind } from "vscode-languageserver/node"; import { TextDocument } from 'vscode-languageserver-textdocument'; import { CompletionList, InsertTextFormat, Position } from 'vscode-languageserver-types'; import * as emmet from './emmet'; import { getCSSLanguageService } from 'vscode-css-languageservice'; import { getLanguageService as getHTMLLanguageService, HTMLFormatConfiguration } from 'vscode-html-languageservice'; import "process"; import { ISvgJsonRoot, ISvgJsonElement, ISvgJsonAttribute, SvgEnum } from "./svgjson"; import { getSvgJson } from "./svg"; import { buildActiveToken, getParentTagName, getOwnerTagName, getAllAttributeNames, getOwnerAttributeName, TokenType, Token, getTokenLen, IActiveToken } from "./token"; import * as pc from './pc-info'; import { parsePath, PathDataCommandItem } from './path-grammar'; import { getModes, getModeAtOffset, DocumentRangeMode, getModeDocument } from "./modes"; let svg: ISvgJsonRoot = getSvgJson(''); const svgDocUrl = { attribute: 'https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/', element: 'https://developer.mozilla.org/en-US/docs/Web/SVG/Element/' }; function rgb(r: number, g: number, b: number) { return Color.create(r / 255, g / 255, b / 255, 1); } const colors: { [name: string]: Color } = { "lightsalmon": rgb(255, 160, 122), "salmon": rgb(250, 128, 114), "darksalmon": rgb(233, 150, 122), "lightcoral": rgb(240, 128, 128), "indianred": rgb(205, 92, 92), "crimson": rgb(220, 20, 60), "firebrick": rgb(178, 34, 34), "red": rgb(255, 0, 0), "darkred": rgb(139, 0, 0), "coral": rgb(255, 127, 80), "tomato": rgb(255, 99, 71), "orangered": rgb(255, 69, 0), "gold": rgb(255, 215, 0), "orange": rgb(255, 165, 0), "darkorange": rgb(255, 140, 0), "lightyellow": rgb(255, 255, 224), "lemonchiffon": rgb(255, 250, 205), "lightgoldenrodyellow": rgb(250, 250, 210), "papayawhip": rgb(255, 239, 213), "moccasin": rgb(255, 228, 181), "peachpuff": rgb(255, 218, 185), "palegoldenrod": rgb(238, 232, 170), "khaki": rgb(240, 230, 140), "darkkhaki": rgb(189, 183, 107), "yellow": rgb(255, 255, 0), "lawngreen": rgb(124, 252, 0), "chartreuse": rgb(127, 255, 0), "limegreen": rgb(50, 205, 50), "lime": rgb(0, 255, 0), "forestgreen": rgb(34, 139, 34), "green": rgb(0, 128, 0), "darkgreen": rgb(0, 100, 0), "greenyellow": rgb(173, 255, 47), "yellowgreen": rgb(154, 205, 50), "springgreen": rgb(0, 255, 127), "mediumspringgreen": rgb(0, 250, 154), "lightgreen": rgb(144, 238, 144), "palegreen": rgb(152, 251, 152), "darkseagreen": rgb(143, 188, 143), "mediumseagreen": rgb(60, 179, 113), "seagreen": rgb(46, 139, 87), "olive": rgb(128, 128, 0), "darkolivegreen": rgb(85, 107, 47), "olivedrab": rgb(107, 142, 35), "lightcyan": rgb(224, 255, 255), "cyan": rgb(0, 255, 255), "aqua": rgb(0, 255, 255), "aquamarine": rgb(127, 255, 212), "mediumaquamarine": rgb(102, 205, 170), "paleturquoise": rgb(175, 238, 238), "turquoise": rgb(64, 224, 208), "mediumturquoise": rgb(72, 209, 204), "darkturquoise": rgb(0, 206, 209), "lightseagreen": rgb(32, 178, 170), "cadetblue": rgb(95, 158, 160), "darkcyan": rgb(0, 139, 139), "teal": rgb(0, 128, 128), "powderblue": rgb(176, 224, 230), "lightblue": rgb(173, 216, 230), "lightskyblue": rgb(135, 206, 250), "skyblue": rgb(135, 206, 235), "deepskyblue": rgb(0, 191, 255), "lightsteelblue": rgb(176, 196, 222), "dodgerblue": rgb(30, 144, 255), "cornflowerblue": rgb(100, 149, 237), "steelblue": rgb(70, 130, 180), "royalblue": rgb(65, 105, 225), "blue": rgb(0, 0, 255), "mediumblue": rgb(0, 0, 205), "darkblue": rgb(0, 0, 139), "navy": rgb(0, 0, 128), "midnightblue": rgb(25, 25, 112), "mediumslateblue": rgb(123, 104, 238), "slateblue": rgb(106, 90, 205), "darkslateblue": rgb(72, 61, 139), "lavender": rgb(230, 230, 250), "thistle": rgb(216, 191, 216), "plum": rgb(221, 160, 221), "violet": rgb(238, 130, 238), "orchid": rgb(218, 112, 214), "fuchsia": rgb(255, 0, 255), "magenta": rgb(255, 0, 255), "mediumorchid": rgb(186, 85, 211), "mediumpurple": rgb(147, 112, 219), "blueviolet": rgb(138, 43, 226), "darkviolet": rgb(148, 0, 211), "darkorchid": rgb(153, 50, 204), "darkmagenta": rgb(139, 0, 139), "purple": rgb(128, 0, 128), "indigo": rgb(75, 0, 130), "pink": rgb(255, 192, 203), "lightpink": rgb(255, 182, 193), "hotpink": rgb(255, 105, 180), "deeppink": rgb(255, 20, 147), "palevioletred": rgb(219, 112, 147), "mediumvioletred": rgb(199, 21, 133), "white": rgb(255, 255, 255), "snow": rgb(255, 250, 250), "honeydew": rgb(240, 255, 240), "mintcream": rgb(245, 255, 250), "azure": rgb(240, 255, 255), "aliceblue": rgb(240, 248, 255), "ghostwhite": rgb(248, 248, 255), "whitesmoke": rgb(245, 245, 245), "seashell": rgb(255, 245, 238), "beige": rgb(245, 245, 220), "oldlace": rgb(253, 245, 230), "floralwhite": rgb(255, 250, 240), "ivory": rgb(255, 255, 240), "antiquewhite": rgb(250, 235, 215), "linen": rgb(250, 240, 230), "lavenderblush": rgb(255, 240, 245), "mistyrose": rgb(255, 228, 225), "gainsboro": rgb(220, 220, 220), "lightgray": rgb(211, 211, 211), "silver": rgb(192, 192, 192), "darkgray": rgb(169, 169, 169), "gray": rgb(128, 128, 128), "dimgray": rgb(105, 105, 105), "lightslategray": rgb(119, 136, 153), "slategray": rgb(112, 128, 144), "darkslategray": rgb(47, 79, 79), "black": rgb(0, 0, 0), "cornsilk": rgb(255, 248, 220), "blanchedalmond": rgb(255, 235, 205), "bisque": rgb(255, 228, 196), "navajowhite": rgb(255, 222, 173), "wheat": rgb(245, 222, 179), "burlywood": rgb(222, 184, 135), "tan": rgb(210, 180, 140), "rosybrown": rgb(188, 143, 143), "sandybrown": rgb(244, 164, 96), "goldenrod": rgb(218, 165, 32), "peru": rgb(205, 133, 63), "chocolate": rgb(210, 105, 30), "saddlebrown": rgb(139, 69, 19), "sienna": rgb(160, 82, 45), "brown": rgb(165, 42, 42), "maroon": rgb(128, 0, 0) }; interface SVGSettings { completion: { showAdvanced: boolean; showDeprecated: boolean; emmet: boolean; elementsActionAsSimple: string[]; }; } const defaultSettings: SVGSettings = { completion: { showAdvanced: false, showDeprecated: false, emmet: false, elementsActionAsSimple: [] } }; let langauge: string = ''; let globalSettings: SVGSettings = defaultSettings; // Cache the settings of all open documents let documentSettings: Map<string, Thenable<SVGSettings>> = new Map(); let connection = createConnection(ProposedFeatures.all); let documents: TextDocuments<TextDocument> = new TextDocuments(TextDocument); let hasConfigurationCapability: boolean = false; let hasWorkspaceFolderCapability: boolean = false; connection.onInitialize((params: InitializeParams) => { let capabilities: ClientCapabilities = params.capabilities; hasConfigurationCapability = !!( capabilities.workspace && !!capabilities.workspace.configuration ); hasWorkspaceFolderCapability = !!( capabilities.workspace && !!capabilities.workspace.workspaceFolders ); return { capabilities: { textDocumentSync: TextDocumentSyncKind.Incremental, completionProvider: { triggerCharacters: '<|.| |=|"|}|0|1|2|3|4|5|6|7|8|9|a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z'.split('|'), resolveProvider: false }, hoverProvider: true, signatureHelpProvider: { triggerCharacters: '"|M|m|L|l|H|h|V|v|C|c|S|s|Q|q|T|t|A|a|Z|z|0|1|2|3|4|5|6|7|8|9|.|,|-| '.split('|') }, definitionProvider: true, referencesProvider: true, documentSymbolProvider: true, documentFormattingProvider: true, renameProvider: { prepareProvider: true }, colorProvider: true } }; }); connection.onInitialized(() => { if (hasConfigurationCapability) { connection.client.register(DidChangeConfigurationNotification.type, undefined); } if (hasWorkspaceFolderCapability) { connection.workspace.onDidChangeWorkspaceFolders(_event => { }); } reloadSvgConfiguration(); connection.workspace.getConfiguration('html.format').then(a => { if (a) { htmlFormatOptions = <HTMLFormatConfiguration>a; } }); }); connection.onNotification("_svg_init", p => { if (p && p.language) { langauge = p.language; if (langauge) { svg = getSvgJson(langauge.toLowerCase()); } } }); // 使用 vscode-html-langservice 作为格式化工具 connection.onDocumentFormatting(e => { let doc = documents.get(e.textDocument.uri); if (doc) { let options = { tabSize: e.options.tabSize, insertSpaces: e.options.insertSpaces, ...htmlFormatOptions }; let edits = htmlLangService.format(doc, undefined, options); return edits; } }); function reloadSvgConfiguration() { connection.workspace.getConfiguration("svg").then(settings => { if (settings) { globalSettings = <SVGSettings>settings; } }); } connection.onDidChangeConfiguration(change => { if (hasConfigurationCapability) { // Reset all cached document settings documentSettings.clear(); } if (change && change.settings) { globalSettings = <SVGSettings>( (change.settings.svg || defaultSettings) ); } else { reloadSvgConfiguration(); } }); function posInPath(pgs: PathDataCommandItem[], offset: number) { connection.console.log('posInPath: ' + pgs.length + ', ' + offset); for (let pg of pgs) { connection.console.log('posInPath of: ' + pg.start + ', ' + pg.end); if (pg.start <= offset && pg.end >= offset) { connection.console.log(pg.commandType); let cmd = pc.pathCommandFromChar(pg.commandType); if (cmd) { let argFull = !cmd.parameters ? true : (pg.args.length % cmd.parameters.length === 0); for (let pi = 0; pi < pg.args.length; pi++) { let p = pg.args[pi]; if (p.start <= offset && p.end >= offset) { return { cmd, pi }; } } if (!argFull) { return { cmd, pi: pg.args.length }; } } } } if (pgs.length) { let pg = pgs[pgs.length - 1]; let cmd = pc.pathCommandFromChar(pg.commandType); if (cmd) { let argFull = !cmd.parameters ? true : (pg.args.length % cmd.parameters.length === 0); if (!argFull) { return { cmd, pi: pg.args.length }; } } } return null; } connection.onSignatureHelp(e => { let uri = e.textDocument.uri; let doc = documents.get(uri); if (doc) { let content = doc.getText(); let offset = doc.offsetAt(e.position); let triggerChar = offset > 0 ? content.charAt(offset - 1) : ''; let token = buildActiveToken(connection, doc, content, offset); if (token && token.token && token.token.type === TokenType.String) { let attrToken = getOwnerAttributeName(token.all, token.index); if (attrToken && attrToken.type === TokenType.AttributeName) { if (getTokenText(content, attrToken) === 'd') { let eleToken = getOwnerTagName(token.all, token.index); if (eleToken && ['path', 'glyph', 'missing-glyph'].indexOf(getTokenText(content, eleToken)) > -1) { // @ts-ignore TS2554 let pathData = getTokenText(content, token.token); pathData = pathData.length > 2 ? pathData.substring(1, pathData.length - 1) : ''; const pgs = parsePath(pathData); const inPathDataOffset = offset - token.token.startIndex - 1; let pos = posInPath(pgs, inPathDataOffset); let tpc = (!!pos) ? pos.cmd : pc.pathCommandFromChar(triggerChar); if (tpc) { return { signatures: [ pc.signatureFromPathCommand(tpc), pc.PathDataSignature ], activeSignature: 0, // @ts-ignore TS2554 activeParameter: pos != null ? (pos.pi % tpc.parameters.length) : null }; } else { return { signatures: [pc.PathDataSignature], activeSignature: 0, activeParameter: null }; } } } } } // connection.console.log('onSignatureHelp token ' + JSON.stringify(token.token)); } return null; }); function getDocumentSettings(resource: string): Thenable<SVGSettings> { if (!hasConfigurationCapability) { return Promise.resolve(globalSettings); } let result = documentSettings.get(resource); if (!result) { result = connection.workspace.getConfiguration({ scopeUri: resource, section: 'svg' }); documentSettings.set(resource, result); } return result; } interface ICompletionData<T> { item: T; insertFullTag: boolean; firstAppend: string; uri: string; position: number; } function createCompletionFromElement(uri: string, position: number, name: string, element: ISvgJsonElement, insertFullTag: boolean, firstAppend: string): CompletionItem { let item: CompletionItem = { label: name, kind: CompletionItemKind.Module, commitCharacters: [' '], data: { item: element, insertFullTag, firstAppend, uri, position } }; return item; } function createCompletionFromAttribute(uri: string, position: number, attribute: ISvgJsonAttribute, insertFullTag: boolean, firstAppend: string): CompletionItem { let item: CompletionItem = { label: attribute.name, kind: CompletionItemKind.Property, data: { item: attribute, insertFullTag, firstAppend, uri, position } }; return item; } function createCompletionFromEnum(uri: string, position: number, svgEnum: SvgEnum, insertFullTag: boolean, firstAppend: string): CompletionItem { if (typeof svgEnum == "string") { svgEnum = { name: svgEnum, documentation: '' }; } let item: CompletionItem = { label: svgEnum.name, kind: CompletionItemKind.Enum, data: { item: svgEnum, insertFullTag, firstAppend, uri, position } }; return item; } let cssLangService = getCSSLanguageService(); let htmlLangService = getHTMLLanguageService(); let htmlFormatOptions: HTMLFormatConfiguration = {}; function onCompletionInCss(doc: TextDocument, content: string, position: Position, modes: Array<DocumentRangeMode>) { var cssDoc = getModeDocument(doc, content, modes, 'css'); var styleSheet = cssLangService.parseStylesheet(cssDoc); return cssLangService.doComplete(cssDoc, position, styleSheet); } interface CompletionTargetAttrCallback { (label: string, context: string, kind?: CompletionItemKind):void; } function onCompletionPaintAttr(doc: TextDocument, appendQute: boolean, addCallback: CompletionTargetAttrCallback) { // 快速找到有 ID 的 linearGradient, pattern, radialGradient let reg = /<(linearGradient|pattern|radialGradient)[^>]*id="([^"]+)"/g; let text = doc.getText(); let match: RegExpExecArray | null = null; let qute = appendQute ? '"' : ''; while (match = reg.exec(text)) { let id = match[2]; addCallback('#' + id, qute + 'url(#' + id + ')' + qute); } } function onCompletionClassAttr(doc: TextDocument, content: string, modes: Array<DocumentRangeMode>, appendQute: boolean, addCallback: CompletionTargetAttrCallback) { var cssDoc = getModeDocument(doc, content, modes, 'css'); var css = cssDoc.getText(); let reg = /\s\.([-a-z_][-a-z0-9_]*)/gi; let match = null; let writed: any = {}; while (match = reg.exec(css)) { let name = match[1]; if (name in writed) { continue; } writed[name] = true; addCallback(name, appendQute ? `"${name}"` : name, CompletionItemKind.Class); } } enum CompletionMeanType { Element, Attribute, Value, Other, } function getMeanAttributeName(token: IActiveToken, content: string, index: number) { while (index > 0) { let t = token.all[index]; if (t.type == TokenType.AttributeName) { return content.substring(t.startIndex, t.endIndex); } index--; } return null; } function getMeanParentTagName(token: IActiveToken, content: string, index: number, level = 1) { let tagName: Token | null = null; let tagNameSu = false; while (index > 0) { let t = token.all[index]; if (t.type == TokenType.TagName) { tagName = t; tagNameSu = true; } else if (tagNameSu) { if (t.type == TokenType.StartEndTag) { level++; } else if (t.type == TokenType.StartTag) { level--; if (level <= 0) { break; } } tagNameSu = false; } else if (t.type == TokenType.SimpleEndTag) { level++; } index--; } return tagName && content.substring(tagName.startIndex, tagName.endIndex) || null; } interface CompletionMean { type: CompletionMeanType; start: string; end: string; startOffset: number; endOffset: number; parent?: string | null; /** Current tag for completion, only for `CompletionMeanType.Value` */ tag?: string | null; hasAttributes?: Array<string>; } function fillHasAttributeNext(token: IActiveToken, index: number, attrs: Array<string>, content: string, step: -1 | 1 = 1) { while (index >= 0 && index < token.all.length) { let t = token.all[index]; index += step; switch (t.type) { case TokenType.AttributeName: attrs.push(content.substring(t.startIndex, t.endIndex)); break; case TokenType.EndTag: case TokenType.StartEndTag: case TokenType.SimpleEndTag: case TokenType.StartTag: return; } } } function fastGetCompletionMean(token: IActiveToken, content: string, offset: number): CompletionMean | null { try { // const endOfToken = token.all.find(t=>t.endIndex == offset); // const startOfToken = token.all.find(t=>t.startIndex == offset); const inToken = token.all.find(t => t.startIndex < offset && t.endIndex >= offset); const prevToken = inToken && inToken.index > 0 && token.all[inToken.index - 1] || undefined; if (!prevToken) { if (inToken) { if (inToken.type == TokenType.TagName) { return { type: CompletionMeanType.Element, start: content.substring(inToken.startIndex, offset), end: content.substring(offset, inToken.endIndex), startOffset: offset, endOffset: offset, }; } if (inToken.type == TokenType.StartTag) { return { type: CompletionMeanType.Element, start: '', end: '', startOffset: offset, endOffset: offset }; } } return null; } if (!inToken) { return null; } let start = ''; let end = ''; let startOffset = offset; let endOffset = offset; // 元素名 if (inToken.type == TokenType.StartTag) { return { type: CompletionMeanType.Element, start, end, startOffset, endOffset, parent: getMeanParentTagName(token, content, prevToken.index) }; } if (inToken.type == TokenType.TagName) { return { type: CompletionMeanType.Element, start: content.substring(inToken.startIndex, offset), end: content.substring(offset, inToken.endIndex), startOffset: inToken.startIndex, endOffset: inToken.endIndex, parent: getMeanParentTagName(token, content, prevToken.index - 1) }; } // 属性名 if (inToken.type == TokenType.Whitespace && prevToken.type == TokenType.TagName) { let hasAttributes: Array<string> = []; fillHasAttributeNext(token, inToken.index, hasAttributes, content); return { type: CompletionMeanType.Attribute, start, end, startOffset, endOffset, hasAttributes, parent: getMeanParentTagName(token, content, inToken.index) }; } if (inToken.type == TokenType.Whitespace && prevToken.type == TokenType.String) { let hasAttributes: Array<string> = []; fillHasAttributeNext(token, inToken.index, hasAttributes, content); fillHasAttributeNext(token, inToken.index, hasAttributes, content, -1); return { type: CompletionMeanType.Attribute, start, end, startOffset, endOffset, hasAttributes, parent: getMeanParentTagName(token, content, inToken.index) }; } if(inToken.type == TokenType.AttributeName) { let hasAttributes: Array<string> = []; fillHasAttributeNext(token, inToken.index, hasAttributes, content); fillHasAttributeNext(token, inToken.index, hasAttributes, content, -1); return { type: CompletionMeanType.Attribute, start: content.substring(inToken.startIndex, offset), end: content.substring(offset, inToken.endIndex), startOffset: inToken.startIndex, endOffset: inToken.endIndex, hasAttributes, parent: getMeanParentTagName(token, content, inToken.index) }; } // 属性值 if (inToken.type == TokenType.String && prevToken.type == TokenType.Equal) { return { type: CompletionMeanType.Value, start: content.substring(inToken.startIndex, offset), end: content.substring(offset, inToken.endIndex), startOffset: inToken.startIndex, endOffset: inToken.endIndex, parent: getMeanAttributeName(token, content, inToken.index), tag: getMeanParentTagName(token, content, inToken.index) }; } if(inToken.type == TokenType.Equal) { return { type: CompletionMeanType.Value, start, end, startOffset, endOffset, parent: getMeanAttributeName(token, content, inToken.index), tag: getMeanParentTagName(token, content, inToken.index) }; } } catch (e) { console.error(e); } return null; } function appendCompletion(doc: TextDocument, offset: number, document: string, items: Array<CompletionItem>, label: string, mean: CompletionMean, content: string, kind: CompletionItemKind, help?: string, triggerSuggest = false, deprecated?: boolean|string) { let endOffset = mean.endOffset; let eatContentStart = 0; // let start = content.substring(0, eatContentStart + 1); // let hasStart = document.substring(offset - eatContentStart - 1, offset); // while (mean.startOffset != mean.endOffset && start != hasStart) { // eatContentStart++; // if (eatContentStart > 20) { // return; // } // start = content.substring(0, eatContentStart + 1); // hasStart = document.substring(offset - eatContentStart - 1, offset); // } if(mean.start) { eatContentStart = offset - mean.startOffset; } if (content.startsWith('<')) { eatContentStart++; } content = content.substring(eatContentStart); const range = Range.create(doc.positionAt(offset), doc.positionAt(endOffset)); // console.log(`replace range:${JSON.stringify(range)} ${context}`); const completionItem: CompletionItem = { label, kind, insertTextFormat: InsertTextFormat.Snippet, insertText: content, textEdit: TextEdit.replace(range, content) }; completionItem.documentation = { kind: MarkupKind.Markdown, value: '' }; let needNewLine = false; if (deprecated) { completionItem.documentation.value += '*Deprecated*'; if(typeof deprecated === 'string') { completionItem.documentation.value += ' - ' + MarkedString.fromPlainText(deprecated); } needNewLine = true; } if (help) { if(needNewLine){ completionItem.documentation.value += '\n\n'; } completionItem.documentation.value += help.replace(/\<[^\>]\>/gi, n=>'`' + n + '`'); needNewLine = true; } if(kind == CompletionItemKind.Module) { if(needNewLine){ completionItem.documentation.value += '\n\n'; } completionItem.documentation.value += '[MDN References](' + svgDocUrl.element + label + ')'; } if(kind == CompletionItemKind.Property) { if(needNewLine){ completionItem.documentation.value += '\n\n'; } completionItem.documentation.value += '[MDN References](' + svgDocUrl.attribute + label + ')'; } if (triggerSuggest) { // completionItem.insertTextFormat = InsertTextFormat.PlainText; // delete completionItem.insertText; // delete completionItem.textEdit; completionItem.command = Command.create('Show Suggest', 'editor.action.triggerSuggest'); // console.debug(JSON.stringify(completionItem)); } items.push(completionItem); } function getLocalOrGlobalAttr(mean: CompletionMean) : ISvgJsonAttribute | undefined { if(mean && mean.parent) { // global attr let attr = svg.attributes[mean.parent]; // try get local attr if(mean.tag && svg.elements[mean.tag]) { const ele = svg.elements[mean.tag]; if(ele.attributes) { const localAttr = <ISvgJsonAttribute | undefined>ele.attributes.find(p=>typeof p !== 'string' && p.name == mean.parent); if(localAttr) { return localAttr; } } } return attr; } } connection.onCompletion(async e => { // connection.console.log("onCompletion " + e.textDocument.uri); let uri = e.textDocument.uri; let doc = documents.get(uri); // let triggerCharacter = e.context && e.context.triggerCharacter; if (doc) { let isIncomplete = true; let settings = await getDocumentSettings(doc.uri); let items: Array<CompletionItem> = []; let content = doc.getText(); let modes = getModes(content); let offset = doc.offsetAt(e.position); let mode = getModeAtOffset(modes, offset); if (mode) { if (mode.languageId == 'css') { return onCompletionInCss(doc, content, e.position, modes); } } let token = buildActiveToken(connection, doc, content, offset); let mean = fastGetCompletionMean(token, content, offset); if (mean) { // console.debug(`mean ${JSON.stringify(mean)}`); switch (mean.type) { case CompletionMeanType.Element: if (mean.parent) { isIncomplete = false; let parentElement = svg.elements[mean.parent]; if (parentElement && parentElement.subElements) { for (var name of parentElement.subElements) { if (mean.start && !name.startsWith(mean.start)) { continue; } let element = svg.elements[name]; if (element.advanced && !settings.completion.showAdvanced) { continue; } if (element.deprecated && !settings.completion.showDeprecated) { continue; } //items.push(createCompletionFromElement(uri, offset, name, element, !triggerCharacter, '')); let output: Array<string> = []; output.push(`<${name}`); if (element.defaultAttributes) { let inputIndex = 1; for (var pn in element.defaultAttributes) { output.push(` ${pn}="$\{${inputIndex++}:${element.defaultAttributes[pn]}\}"`); } } if (element.simple || globalSettings.completion.elementsActionAsSimple.includes(name)) { output.push(`$0 />`); } else if (element.inline) { output.push('>$0</'); output.push(name); output.push('>'); } else { output.push('>\n\t$0\n</'); output.push(name); output.push('>'); } appendCompletion(doc, offset, content, items, name, mean, output.join(''), CompletionItemKind.Module, element.documentation, false, element.deprecated); } } } else { appendCompletion(doc, offset, content, items, 'SVG Root Element', mean, '<svg xmlns="http://www.w3.org/2000/svg">\n\t$0\n</svg>', CompletionItemKind.Snippet); } break; case CompletionMeanType.Attribute: if (mean.parent) { isIncomplete = false; let parent = svg.elements[mean.parent]; if (parent && parent.attributes) { for (let attr of parent.attributes) { if (typeof attr === 'string') { let attr2 = svg.attributes[attr]; if(attr2) { attr = attr2; } else { attr = { name: attr}; } } if (mean.start && !attr.name.startsWith(mean.start)) { continue; } if (mean.hasAttributes && mean.hasAttributes.includes(attr.name)) { continue; } if ((!!attr.enum) || (!!attr.enums) || attr.type && /^(color|fill|stroke|paint|class)$/.test(attr.type)) { appendCompletion(doc, offset, content, items, attr.name, mean, `${attr.name}="$0"`, CompletionItemKind.Property, attr.documentation, true, attr.deprecated); } else { appendCompletion(doc, offset, content, items, attr.name, mean, `${attr.name}="$0"`, CompletionItemKind.Property, attr.documentation, false, attr.deprecated); } } } } break; case CompletionMeanType.Value: if (mean.parent) { isIncomplete = false; let attr = getLocalOrGlobalAttr(mean); if (attr) { if (attr.enum) { for (var a of attr.enum) { let name = typeof a === 'string' ? a : a.name; let help = typeof a === 'string' ? undefined : a.documentation; if (mean.start) { let start = mean.start; if (start.startsWith('"')) { start = start.substr(1); } if (start && !name.startsWith(start)) { continue; } } appendCompletion(doc, offset, content, items, name, mean, `"${name}"`, CompletionItemKind.Enum, help); } } if(attr.enums) { for (var a of attr.enums) { let name = typeof a === 'string' ? a : a.name; let help = typeof a === 'string' ? undefined : a.documentation; if (mean.start) { let start = mean.start; if (start.startsWith('"')) { start = start.substr(1); } if (start && !name.startsWith(start)) { continue; } } appendCompletion(doc, offset, content, items, name, mean, `"${name}"`, CompletionItemKind.Enum, help); } } if (attr.type && /^(color|fill|stroke|paint)$/.test(attr.type)) { for (let color in colors) { if(mean.start && (!color.startsWith(mean.start) && !('"' + color).startsWith(mean.start))) { continue; } appendCompletion(doc, offset, content, items, color, mean, `"${color}"`, CompletionItemKind.Color); } if (attr.type == 'paint') { onCompletionPaintAttr(doc, true, (label, text)=>{ appendCompletion(doc!, offset, content, items, label, mean!, text, CompletionItemKind.Variable); }); } } else if(attr.name == 'class') { onCompletionClassAttr(doc, content, modes, true, (label, text, kind)=>{ appendCompletion(doc!, offset, content, items, label, mean!, text, kind || CompletionItemKind.Variable); }); } } } } } // Emmet 风格自动提示 else if (globalSettings.completion.emmet) { const completionList = emmet.doComplete(doc, e.position, 'svg', svg); if (completionList && completionList.items) { items.push(...completionList.items); } // console.debug(`items: ${items.length}`); } return CompletionList.create(items, isIncomplete); } }); function createDocumentation(item: CompletionItem, deprecated?: boolean | string, documentation?: string): string | MarkupContent | undefined { let docUrlPart = ''; if (item.kind == CompletionItemKind.Module) { docUrlPart = '\n\n[MDN Reference](' + svgDocUrl.element + item.label + ')'; } else if (item.kind == CompletionItemKind.Property) { docUrlPart = '\n\n[MDN Reference](' + svgDocUrl.attribute + item.label + ')'; } if (deprecated) { if (typeof deprecated == 'string') { if (documentation) { return { kind: MarkupKind.Markdown, value: '*Deprecated* - ' + MarkedString.fromPlainText(deprecated) + '\n' + MarkedString.fromPlainText(documentation) + docUrlPart }; } else { return { kind: MarkupKind.Markdown, value: '**Deprecated** - ' + MarkedString.fromPlainText(deprecated) + docUrlPart }; } } else { if (documentation) { return { kind: MarkupKind.Markdown, value: '**Deprecated**\n' + MarkedString.fromPlainText(documentation) + docUrlPart }; } else { return { kind: MarkupKind.Markdown, value: '**Deprecated**' + docUrlPart }; } } } if (documentation) { return { kind: MarkupKind.Markdown, value: MarkedString.fromPlainText(documentation) + docUrlPart }; } return { kind: MarkupKind.Markdown, value: docUrlPart.substring(1) }; } // connection.onCompletionResolve(item => { // connection.console.log("onCompletionResolve " + item); // if(item.data) { // if(item.kind == CompletionItemKind.Module) { // let data : ICompletionData<ISvgJsonElement> = item.data; // let svgElement: ISvgJsonElement = data.item; // item.documentation = createDocumentation(item, svgElement.deprecated, svgElement.documentation); // item.insertTextFormat = 2; // let insertText : Array<string> = []; // if(data.insertFullTag) { // insertText.push("<"); // } // if(data.firstAppend) { // insertText.push(item.label.substr(data.firstAppend.length)); // } // else // { // insertText.push(item.label); // } // let index = 1; // if(svgElement.defaultAttributes) { // for(var pn in svgElement.defaultAttributes) { // let pv = svgElement.defaultAttributes[pn]; // insertText.push(` ${pn}="\${${index++}:${pv}}"`); // } // } // if(svgElement.simple) { // insertText.push("$0 />"); // } // else { // insertText.push(">\n\t$0\n</" + item.label + ">"); // } // item.insertText = insertText.join(''); // } // else if(item.kind == CompletionItemKind.Property) { // let data : ICompletionData<ISvgJsonAttribute> = item.data; // let svgAttr: ISvgJsonAttribute = data.item; // item.documentation = createDocumentation(item, svgAttr.deprecated, svgAttr.documentation); // item.insertTextFormat = 2; // let insertText : Array<string> = []; // if(!data.firstAppend && data.insertFullTag) { // insertText.push(' '); // } // // else if(data.firstAppend) { // // insertText.push(item.label.substr(data.firstAppend.length)); // // } // else // { // insertText.push(item.label); // } // insertText.push("=\"$0\""); // if(svgAttr.enum || svgAttr.enums || (svgAttr.type && /^(color|fill|stroke|paint)$/.test(svgAttr.type))) { // item.command = Command.create("Show Enum Completion List", "editor.action.triggerSuggest"); // } // item.insertText = insertText.join(''); // } // else if(item.kind == CompletionItemKind.Enum) { // let data : ICompletionData<SvgEnum> = item.data; // let svgEnum: SvgEnum = data.item; // if(typeof svgEnum == 'string') { // svgEnum = {name: svgEnum, documentation: ''}; // } // item.documentation = svgEnum.documentation; // if(data.insertFullTag) { // item.insertText = `"${item.label}"`; // } // else if(data.firstAppend) { // item.insertText = item.label.substr(data.firstAppend.length); // } // } // } // return item; // }); function replaceDocumentationToMarkedString(documentation: string, label?: string): string | MarkedString | MarkupContent { if (label && label.toLowerCase() in svg.elements) { return { kind: MarkupKind.Markdown, //language: 'xml', value: MarkedString.fromPlainText(documentation) + '\n\n[MDN Reference](' + svgDocUrl.element + label + ')' }; } if (label && label.toLowerCase() in svg.attributes) { return { kind: MarkupKind.Markdown, //language: 'xml', value: MarkedString.fromPlainText(documentation) + '\n\n[MDN Reference](' + svgDocUrl.attribute + label + ')' }; } return MarkedString.fromPlainText(documentation); } connection.onHover(e => { let doc = documents.get(e.textDocument.uri); if (doc) { let offset = doc.offsetAt(e.position); let token = buildActiveToken(connection, doc, doc.getText(), offset); if (token && token.token && (token.token.type == TokenType.TagName || token.token.type == TokenType.AttributeName)) { let content = doc.getText(); // try find tag element if (token.token.type == TokenType.TagName) { var tagName = content.substring(token.token.startIndex, token.token.endIndex); var range = Range.create( doc.positionAt(token.token.startIndex), doc.positionAt(token.token.endIndex)); if (tagName in svg.elements) { var tag = svg.elements[tagName]; if (tag && tag.documentation) { return { contents: replaceDocumentationToMarkedString(tag.documentation, tagName), range }; } } } // tag attribute else { let ownerTagName = getOwnerTagName(token.all, token.index); if (ownerTagName) { var attrName = content.substring(token.token.startIndex, token.token.endIndex); var range = Range.create( doc.positionAt(token.token.startIndex), doc.positionAt(token.token.endIndex)); if (attrName in svg.attributes) { var attr = svg.attributes[attrName]; if (attr && attr.documentation) { return { contents: replaceDocumentationToMarkedString(attr.documentation, attrName), range }; } } } } } } }); connection.onDefinition(e => { let doc = documents.get(e.textDocument.uri); if (doc) { let content = doc.getText(); let offset = doc.offsetAt(e.position); let token = buildActiveToken(connection, doc, content, offset); if (token && token.token && token.token.type == TokenType.String) { let val = content.substring(token.token.startIndex, token.token.endIndex); let urlMatch = val.match(/url\(#(.*?)\)/i); if (urlMatch && urlMatch.length) { let id = urlMatch[1]; let idAttrStartIndex = content.indexOf(`id="${id}"`); if (idAttrStartIndex > -1) { let range = Range.create(doc.positionAt(idAttrStartIndex), doc.positionAt(idAttrStartIndex + 5 + id.length)); return Location.create(e.textDocument.uri, range); } } urlMatch = val.match(/"#(.*?)"/i); if (urlMatch && urlMatch.length) { let id = urlMatch[1]; let idAttrStartIndex = content.indexOf(`id="${id}"`); if (idAttrStartIndex > -1) { let range = Range.create(doc.positionAt(idAttrStartIndex), doc.positionAt(idAttrStartIndex + 5 + id.length)); return Location.create(e.textDocument.uri, range); } } else { if (token.index > 2 && token.prevToken && token.prevToken.type == TokenType.Equal) { let attrNameToken = token.all[token.index - 2]; let result = getTokenText(content, token.token); let attrName = getTokenText(content, attrNameToken); if (attrNameToken.type == TokenType.AttributeName && (attrName == 'in' || attrName == 'in2')) { let resultStartIndex = content.indexOf(`result=${result}`); if (resultStartIndex > -1) { let range = Range.create(doc.positionAt(resultStartIndex), doc.positionAt(resultStartIndex + 7 + result.length)); return Location.create(e.textDocument.uri, range); } } } } } } }); connection.onReferences(e => { let doc = documents.get(e.textDocument.uri); if (doc) { let content = doc.getText(); let offset = doc.offsetAt(e.position); let token = buildActiveToken(connection, doc, content, offset); if (token && token.token && token.token.type == TokenType.String && token.prevToken && token.prevToken.type == TokenType.Equal) { let ownerAttrName = getOwnerAttributeName(token.all, token.index); if (ownerAttrName) { let ownerAttr = content.substring(ownerAttrName.startIndex, ownerAttrName.endIndex); if (ownerAttr.toUpperCase() == "ID") { let id = content.substring(token.token.startIndex + 1, token.token.endIndex - 1); if (id) { let refRegx = /(url\(#(.*?)\))/ig; let result: RegExpExecArray | null = null; let locations = []; while (result = refRegx.exec(content)) { if (result[2] == id) { let start = doc.positionAt(result.index); let end = doc.positionAt(result.index + result[0].length); locations.push(Location.create(e.textDocument.uri, Range.create(start, end))); } } refRegx = /xlink:href="#(.*?)"/ig; while (result = refRegx.exec(content)) { if (result[1] == id) { let start = doc.positionAt(result.index); let end = doc.positionAt(result.index + result[0].length); locations.push(Location.create(e.textDocument.uri, Range.create(start, end))); } } return locations; } } else if (ownerAttr.toUpperCase() == "RESULT") { let id = content.substring(token.token.startIndex + 1, token.token.endIndex - 1); if (id) { let refRegx = /in2?="(.*?)"/ig; let result: RegExpExecArray | null = null; let locations = []; while (result = refRegx.exec(content)) { if (result[1] == id) { let start = doc.positionAt(result.index); let end = doc.positionAt(result.index + result[0].length); locations.push(Location.create(e.textDocument.uri, Range.create(start, end))); } } return locations; } } } } } }); interface ASTNODE { start?: Token; name?: string; end?: Token; parent?: ASTNODE | null; children: Array<ASTNODE>; } function buildAstTree(all: Array<Token>, content: string) { let node: ASTNODE = { children: [], parent: null }; let root = node; let rp = 0; // 1 - starttag 2 - name 3 - endtag 4 - startendtag 5 - name 6 - endtag for (let t of all) { switch (t.type) { case TokenType.StartTag: rp = 1; node = { parent: node, children: [], start: t }; node.parent!.children.push(node); break; case TokenType.TagName: if (rp == 1) { rp = 2; node.name = content.substring(t.startIndex, t.endIndex); } else if (rp == 4) { let endname = content.substring(t.startIndex, t.endIndex); if (endname == node.name) { rp = 5; } } break; case TokenType.StartEndTag: rp = 4; break; case TokenType.EndTag: if (rp == 2) { rp = 3; } else if (rp == 5) { rp = 6; node.end = t; if (node.parent) { node = node.parent; } } break; case TokenType.SimpleEndTag: node.end = t; if (node.parent) { node = node.parent; } break; } } return root; } function findAstNode(ast: ASTNODE, index: number): ASTNODE | null { if (ast.children && ast.children.length) { for (let child of ast.children) { let childFindNode = findAstNode(child, index); if (childFindNode) { return childFindNode; } } } if (ast.start && ast.end) { if (index >= ast.start.startIndex && index < ast.end.endIndex) { return ast; } } return null; } function createRange(doc: TextDocument, token: Token, startOffset = 0, endOffset = 0): Range { return Range.create(doc.positionAt(token.startIndex + startOffset), doc.positionAt(token.endIndex + endOffset)); } function getTokenText(content: string, token: Token) { return content.substring(token.startIndex, token.endIndex); } connection.onDocumentSymbol(e => { let doc = documents.get(e.textDocument.uri); if (doc) { let content = doc.getText(); let token = buildActiveToken(connection, doc, content, 0); let root = buildAstTree(token.all, content); let result: Array<DocumentSymbol> = []; function buildResult(symbols: Array<DocumentSymbol>, nodes: Array<ASTNODE>) { for (let node of nodes) { if (node.start && node.end) { let range = Range.create(doc!.positionAt(node.start.startIndex), doc!.positionAt(node.end.endIndex)); let symbol: DocumentSymbol = { name: '' + node.name, kind: SymbolKind.Module, range: range, selectionRange: Range.create(range.start, range.start) }; if (node.children.length) { symbol.children = []; buildResult(symbol.children, node.children); } symbols.push(symbol); } } } buildResult(result, root.children); return result; } }); function renameID(doc: TextDocument, content: string, oldId: string, newId: string) { let changes: Array<TextEdit> = []; let idRegex = /id="(.+?)"/gi; let re: RegExpExecArray | null = null; while (re = idRegex.exec(content)) { if (re[1] == oldId) { changes.push(TextEdit.replace(Range.create(doc.positionAt(re.index + 4), doc.positionAt(re.index + 4 + oldId.length)), newId)); } } idRegex = /url\(#(.+?)\)/gi; while (re = idRegex.exec(content)) { if (re[1] == oldId) { changes.push(TextEdit.replace(Range.create(doc.positionAt(re.index + 5), doc.positionAt(re.index + 5 + oldId.length)), newId)); } } let result: WorkspaceEdit = { changes: {} }; result.changes![doc.uri] = changes; return result; } connection.onRenameRequest(e => { let doc = documents.get(e.textDocument.uri); if (doc) { let content = doc.getText(); let offset = doc.offsetAt(e.position); let token = buildActiveToken(connection, doc, content, offset); if (token && token.token && token.prevToken) { if (token.token.type == TokenType.TagName || token.token.type == TokenType.AttributeName) { let ast = buildAstTree(token.all, content); let node = findAstNode(ast, token.token.startIndex); if (node) { let changes: Array<TextEdit> = []; let startTagName = token.all[node.start!.index + 1]; changes.push(TextEdit.replace(createRange(doc, startTagName), e.newName)); if (node.end && node.end.type == TokenType.EndTag) { let endTagName = token.all[node.end.index - 1]; if (endTagName.type == TokenType.TagName) { changes.push(TextEdit.replace(createRange(doc, endTagName), e.newName)); } } let result: WorkspaceEdit = { changes: {} }; result.changes![e.textDocument.uri] = changes; return result; } } if (token.token.type == TokenType.String && token.prevToken.type == TokenType.Equal) { if (token.prevToken.index > 0) { let attrVal = getTokenText(content, token.token); let attNameToken = token.all[token.prevToken.index - 1]; if (getTokenText(content, attNameToken).toUpperCase() == "ID") { return renameID(doc, content, attrVal.substr(1, attrVal.length - 2), e.newName); } let idUrlMatch = attrVal.match(/url\(#(.+?)\)/i); if (idUrlMatch && idUrlMatch.length > 1) { return renameID(doc, content, idUrlMatch[1], e.newName); } } } } } return null; }); connection.onPrepareRename(e => { let doc = documents.get(e.textDocument.uri); if (doc) { let content = doc.getText(); let offset = doc.offsetAt(e.position); let token = buildActiveToken(connection, doc, content, offset); if (token && token.token && token.prevToken) { if (token.token.type == TokenType.TagName) { if (token.prevToken.type == TokenType.StartTag) { return createRange(doc, token.token); } else if (token.prevToken.type == TokenType.StartEndTag) { return createRange(doc, token.token); } } if (token.token.type == TokenType.String && token.prevToken.type == TokenType.Equal) { if (token.prevToken.index > 0) { let attNameToken = token.all[token.prevToken.index - 1]; if (getTokenText(content, attNameToken).toUpperCase() == "ID") { return createRange(doc, token.token, 1, -1); } let attrVal = getTokenText(content, token.token); let idUrlMatch = attrVal.match(/url\(#(.+?)\)/i); if (idUrlMatch && idUrlMatch.length > 1) { let endIndex = token.token.startIndex + idUrlMatch.index! + idUrlMatch[0].length - 1; return createRange(doc, token.token, idUrlMatch.index! + 5, endIndex - token.token.endIndex); } } } } } }); function tryConvertColor(str: string): Color | null { if (str.length <= 2) return null; let match: RegExpExecArray | null = null; if (/^#[0-9A-Fa-f]{3}$/.test(str)) { let r = Number.parseInt(str.substr(1, 1), 16); let g = Number.parseInt(str.substr(2, 1), 16); let b = Number.parseInt(str.substr(3, 1), 16); r = r * 17; g = g * 17; b = b * 17; return Color.create(r / 255, g / 255, b / 255, 1); } else if (/^#[0-9A-Fa-f]{6}$/.test(str)) { let r = Number.parseInt(str.substr(1, 2), 16); let g = Number.parseInt(str.substr(3, 2), 16); let b = Number.parseInt(str.substr(5, 2), 16); return Color.create(r / 255, g / 255, b / 255, 1); } else if (match = /^rgb\(\s*(\d+),\s*(\d+),\s*(\d+)\)/.exec(str)) { let r = Number.parseInt(match[1]); let g = Number.parseInt(match[2]); let b = Number.parseInt(match[3]); return Color.create(r / 255, g / 255, b / 255, 1); } else if (match = /^rgb\(\s*(\d+)%,\s*(\d+)%,\s*(\d+)%\)/.exec(str)) { let r = Number.parseFloat(match[1]); let g = Number.parseFloat(match[2]); let b = Number.parseFloat(match[3]); return Color.create(r / 100, g / 100, b / 100, 1); } else if (match = /^rgba\(\s*(\d+),\s*(\d+),\s*(\d+),\s*(\d+(\.\d*)?)\)/.exec(str)) { let r = Number.parseFloat(match[1]); let g = Number.parseFloat(match[2]); let b = Number.parseFloat(match[3]); let a = Number.parseFloat(match[4]); return Color.create(r / 255, g / 255, b / 255, a); } else if (match = /^rgba\(\s*(\d+)%,\s*(\d+)%,\s*(\d+)%,\s*(\d+(\.\d*)?)\)/.exec(str)) { let r = Number.parseFloat(match[1]); let g = Number.parseFloat(match[2]); let b = Number.parseFloat(match[3]); let a = Number.parseFloat(match[4]); return Color.create(r / 100, g / 100, b / 100, a); } if (str in colors) { return colors[str]; } return null; } function toHex2(num: number | string): string { if (typeof num == 'string') { num = parseInt(num); } let str = num.toString(16); if (str.length == 1) { str = '0' + str; } return str; } function toColorString(color: Color): string { if (color.alpha >= 1) { return `#${toHex2("" + color.red * 255)}${toHex2("" + color.green * 255)}${toHex2("" + color.blue * 255)}`; } else { return `rgba(${parseInt("" + color.red * 255)},${parseInt("" + color.green * 255)},${parseInt("" + color.blue * 255)},${color.alpha})`; } } connection.onDocumentColor(e => { let doc = documents.get(e.textDocument.uri); if (doc != null) { let content = doc.getText(); let token = buildActiveToken(connection, doc, content, 0); let colors: Array<ColorInformation> = []; let index = 3; for (; index < token.all.length; index++) { if (token.all[index].type == TokenType.String && token.all[index - 1].type == TokenType.Equal) { let attrNameToken = getOwnerAttributeName(token.all, index); if (attrNameToken) { let attr = getTokenText(content, attrNameToken); if (attr in svg.attributes) { let svgAttr = svg.attributes[attr]; if (svgAttr && svgAttr.type && /^(color|fill|stroke|paint)$/.test(svgAttr.type)) { let colorText = getTokenText(content, token.all[index]); let color = tryConvertColor(colorText.substring(1, colorText.length - 1)); if (color) { colors.push(ColorInformation.create(createRange(doc, token.all[index], 1, -1), color)); } } } } } } return colors; } }); function isSameColor(colorStr: string, color: Color): boolean { let colorCov = tryConvertColor(colorStr); if (colorCov) { return colorCov.alpha == color.alpha && colorCov.blue == color.blue && colorCov.green == color.green && colorCov.red == color.red; } else { return false; } } connection.onColorPresentation(e => { let doc = documents.get(e.textDocument.uri); if (doc != null) { let currentStr = doc.getText(e.range); if (e.color) { if (!isSameColor(currentStr, e.color)) { let newString = toColorString(e.color); return [ColorPresentation.create(newString, TextEdit.replace(e.range, newString))]; } } } return null; }); documents.onDidClose(() => { }); documents.onDidChangeContent(() => { // connection.console.log("onDidChangeContent"); }); documents.listen(connection); connection.listen();
the_stack
import "./matchers"; import { Production, RightHandSideList, RightHandSide, Nonterminal } from "../nodes"; import { Parser } from "../parser"; import { NodeNavigator } from "../navigator"; import { SyntaxKind } from "../tokens"; import { makeExpectToken } from "./navigatorUtils"; describe("Navigator", () => { const es6GrammarText: string = ` // A.1 - Lexical Grammar SourceCharacter :: > any Unicode code point InputElementDiv :: WhiteSpace LineTerminator Comment CommonToken DivPunctuator RightBracePunctuator InputElementRegExp :: WhiteSpace LineTerminator Comment CommonToken RightBracePunctuator RegularExpressionLiteral // ... ExportSpecifier : IdentifierName IdentifierName \`as\` IdentifierName `.trim(); it("initial state", () => { const { sourceFile, navigator } = getNavigator(); expect(navigator.getRoot()).toStrictEqual(sourceFile); expect(navigator.getNode()).toStrictEqual(sourceFile); expect(navigator.getParent()).toStrictEqual(undefined); expect(navigator.getKind()).toStrictEqual(SyntaxKind.SourceFile); expect(navigator.getDepth()).toStrictEqual(0); expect(navigator.getName()).toStrictEqual(undefined); expect(navigator.getOffset()).toStrictEqual(0); expect(navigator.getArray()).toStrictEqual(undefined); expect(navigator.isArray()).toStrictEqual(false); expect(navigator.hasChildren()).toStrictEqual(true); }); it("moveToFirstChild", () => { const { sourceFile, navigator } = getNavigator(); const moved = navigator.moveToFirstChild(); expect(moved).toEqual(true); expect(navigator.getRoot()).toStrictEqual(sourceFile); expect(navigator.getNode()).toStrictEqual(sourceFile.elements[0]); expect(navigator.getParent()).toStrictEqual(sourceFile); expect(navigator.getKind()).toStrictEqual(SyntaxKind.Production); expect(navigator.getDepth()).toStrictEqual(1); expect(navigator.getName()).toStrictEqual("elements"); expect(navigator.getOffset()).toStrictEqual(0); expect(navigator.getArray()).toBeDefined(); expect(navigator.isArray()).toStrictEqual(true); expect(navigator.hasChildren()).toStrictEqual(true); }); it("moveToLastChild", () => { const { sourceFile, navigator } = getNavigator(); const moved = navigator.moveToLastChild(); expect(moved).toEqual(true); expect(navigator.getRoot()).toStrictEqual(sourceFile); expect(navigator.getNode()).toStrictEqual(sourceFile.elements[sourceFile.elements.length - 1]); expect(navigator.getParent()).toStrictEqual(sourceFile); expect(navigator.getKind()).toStrictEqual(SyntaxKind.Production); expect(navigator.getDepth()).toStrictEqual(1); expect(navigator.getName()).toStrictEqual("elements"); expect(navigator.getOffset()).toStrictEqual(sourceFile.elements.length - 1); expect(navigator.getArray()).toBeDefined(); expect(navigator.isArray()).toStrictEqual(true); expect(navigator.hasChildren()).toStrictEqual(true); }); it("moveToNextSibling (in array)", () => { const { sourceFile, navigator } = getNavigator(); navigator.moveToFirstChild(); const moved = navigator.moveToNextSibling(); expect(moved).toEqual(true); expect(navigator.getRoot()).toStrictEqual(sourceFile); expect(navigator.getNode()).toStrictEqual(sourceFile.elements[1]); expect(navigator.getParent()).toStrictEqual(sourceFile); expect(navigator.getKind()).toStrictEqual(SyntaxKind.Production); expect(navigator.getDepth()).toStrictEqual(1); expect(navigator.getName()).toStrictEqual("elements"); expect(navigator.getOffset()).toStrictEqual(1); expect(navigator.getArray()).toBeDefined(); expect(navigator.isArray()).toStrictEqual(true); expect(navigator.hasChildren()).toStrictEqual(true); }); it("moveToNextSibling (in object)", () => { const { navigator } = getNavigator(); navigator.moveToFirstChild(); const movedToFirstChild = navigator.moveToFirstChild(); const production = <Production>navigator.getParent(); const firstChild = navigator.getNode(); const firstChildName = navigator.getName(); const movedToSibling = navigator.moveToNextSibling(); const nextSibling = navigator.getNode(); const nextSiblingName = navigator.getName(); expect(movedToFirstChild).toBe(true); expect(movedToSibling).toBe(true); expect(production.kind).toBe(SyntaxKind.Production); expect(firstChildName).toBe("name"); expect(firstChild).toBe(production.name); expect(nextSiblingName).toBe("colonToken"); expect(nextSibling).toBe(production.colonToken); }); it("moveTopPreviousSibling (in array)", () => { const { sourceFile, navigator } = getNavigator(); navigator.moveToLastChild(); const moved = navigator.moveToPreviousSibling(); expect(moved).toEqual(true); expect(navigator.getRoot()).toStrictEqual(sourceFile); expect(navigator.getNode()).toStrictEqual(sourceFile.elements[sourceFile.elements.length - 2]); expect(navigator.getParent()).toStrictEqual(sourceFile); expect(navigator.getKind()).toStrictEqual(SyntaxKind.Production); expect(navigator.getDepth()).toStrictEqual(1); expect(navigator.getName()).toStrictEqual("elements"); expect(navigator.getOffset()).toStrictEqual(sourceFile.elements.length - 2); expect(navigator.getArray()).toBeDefined(); expect(navigator.isArray()).toStrictEqual(true); expect(navigator.hasChildren()).toStrictEqual(true); }); it("moveTopPreviousSibling (in object)", () => { const { navigator } = getNavigator(); navigator.moveToFirstChild(); const movedToLastChild = navigator.moveToLastChild(); const production = <Production>navigator.getParent(); const lastChild = navigator.getNode(); const lastChildName = navigator.getName(); const movedToSibling = navigator.moveToPreviousSibling(); const previousSibling = navigator.getNode(); const previousSiblingName = navigator.getName(); expect(movedToLastChild).toBe(true); expect(movedToSibling).toBe(true); expect(production.kind).toBe(SyntaxKind.Production); expect(lastChildName).toBe("body"); expect(lastChild).toBe(production.body); expect(previousSiblingName).toBe("colonToken"); expect(previousSibling).toBe(production.colonToken); }); it("moveToPosition", () => { const { sourceFile, navigator } = getNavigator(); const moved = navigator.moveToPosition({ line: 14, character: 9 }); expect(moved).toEqual(true); expect(navigator.getKind()).toStrictEqual(SyntaxKind.Identifier); expect(navigator.getName()).toStrictEqual("name"); const production = <Production>sourceFile.elements[2]; const list = <RightHandSideList>production.body; const rhs = <RightHandSide>(list.elements && list.elements[0]); const symbol = <Nonterminal>rhs.head!.symbol; expect(navigator.getNode()).toStrictEqual(symbol.name); }); describe("moveToTouchingToken", () => { it("at start", () => { const { navigator } = getNavigator(); expect(navigator.moveToTouchingToken({ line: 6, character: 1 })).toBe(true); expect(navigator.getKind()).toBeSyntaxKind(SyntaxKind.Identifier); expect(navigator.getTextContent()).toBe("WhiteSpace"); }); it("in leading trivia", () => { const { navigator } = getNavigator(); expect(navigator.moveToTouchingToken({ line: 6, character: 0 })).toBe(true); expect(navigator.getKind()).toBeSyntaxKind(SyntaxKind.ColonColonToken); }); it("in middle", () => { const { navigator } = getNavigator(); expect(navigator.moveToTouchingToken({ line: 6, character: 5 })).toBe(true); expect(navigator.getKind()).toBeSyntaxKind(SyntaxKind.Identifier); expect(navigator.getTextContent()).toBe("WhiteSpace"); }); it("at end", () => { const { navigator } = getNavigator(); expect(navigator.moveToTouchingToken({ line: 6, character: 11 })).toBe(true); expect(navigator.getKind()).toBeSyntaxKind(SyntaxKind.Identifier); expect(navigator.getTextContent()).toBe("WhiteSpace"); }); it("at bof", () => { const { navigator } = getNavigator(); expect(navigator.moveToTouchingToken({ line: 0, character: 0 })).toBe(false); }); it("at eof", () => { const { navigator } = getNavigator(); expect(navigator.moveToTouchingToken({ line: 25, character: 36 })).toBe(true); expect(navigator.getKind()).toBeSyntaxKind(SyntaxKind.Identifier); expect(navigator.getTextContent()).toBe("IdentifierName"); }); }); describe("moveToFirstToken", () => { it("when token in AST", () => { const { sourceFile, navigator, firstToken } = getNavigator(); firstToken(); expect(navigator.getNode()).toStrictEqual((sourceFile.elements[0] as Production).name); }); it("when token not in AST", () => { const { navigator, firstToken } = getNavigator(","); firstToken(); expect(navigator.getParent()).toBe(navigator.getRoot()); }); it("moves to first token in node", () => { const { navigator, firstToken } = getNavigator("A : B? C?"); expect(navigator.moveToFirstChild(SyntaxKind.Production)).toBe(true); expect(navigator.moveToLastChild(SyntaxKind.RightHandSide)).toBe(true); expect(navigator.moveToFirstChild(SyntaxKind.SymbolSpan)).toBe(true); expect(navigator.moveToFirstChild(SyntaxKind.Nonterminal)).toBe(true); firstToken(SyntaxKind.Identifier, "B"); }); }); describe("moveToLastToken", () => { it("when in ast", () => { const { sourceFile, navigator, lastToken } = getNavigator(); lastToken(SyntaxKind.Identifier); expect(navigator.getNode().end === sourceFile.end) }); it("when not in ast", () => { const { navigator, lastToken, bof } = getNavigator(","); lastToken(SyntaxKind.CommaToken); expect(navigator.getParent()).toBe(navigator.getRoot()); bof(); }); it("moves to last token in node", () => { const { navigator, lastToken, prevToken } = getNavigator("A : B? C?"); expect(navigator.moveToFirstChild(SyntaxKind.Production)).toBe(true); expect(navigator.moveToLastChild(SyntaxKind.RightHandSide)).toBe(true); expect(navigator.moveToFirstChild(SyntaxKind.SymbolSpan)).toBe(true); expect(navigator.moveToFirstChild(SyntaxKind.Nonterminal)).toBe(true); lastToken(SyntaxKind.QuestionToken); prevToken(SyntaxKind.Identifier, "B"); }); }); describe("moveToNextToken", () => { it("when in ast", () => { const { firstToken, nextToken, eof } = getNavigator(); firstToken(SyntaxKind.Identifier, "SourceCharacter"); // SourceCharacter nextToken(SyntaxKind.ColonColonToken); // :: nextToken(SyntaxKind.GreaterThanToken); // > nextToken(SyntaxKind.ProseFull, "any Unicode code point"); // any Unicode code point nextToken(SyntaxKind.Identifier, "InputElementDiv"); // InputElementDiv nextToken(SyntaxKind.ColonColonToken); // :: nextToken(SyntaxKind.Identifier, "WhiteSpace"); // WhiteSpace nextToken(SyntaxKind.Identifier, "LineTerminator"); // LineTerminator nextToken(SyntaxKind.Identifier, "Comment"); // Comment nextToken(SyntaxKind.Identifier, "CommonToken"); // CommonToken nextToken(SyntaxKind.Identifier, "DivPunctuator"); // DivPunctuator nextToken(SyntaxKind.Identifier, "RightBracePunctuator"); // RightBracePunctuator nextToken(SyntaxKind.Identifier, "InputElementRegExp"); // InputElementRegExp nextToken(SyntaxKind.ColonColonToken); // :: nextToken(SyntaxKind.Identifier, "WhiteSpace"); // WhiteSpace nextToken(SyntaxKind.Identifier, "LineTerminator"); // LineTerminator nextToken(SyntaxKind.Identifier, "Comment"); // Comment nextToken(SyntaxKind.Identifier, "CommonToken"); // CommonToken nextToken(SyntaxKind.Identifier, "RightBracePunctuator"); // RightBracePunctuator nextToken(SyntaxKind.Identifier, "RegularExpressionLiteral"); // RegularExpressionLiteral nextToken(SyntaxKind.Identifier, "ExportSpecifier"); // ExportSpecifier nextToken(SyntaxKind.ColonToken); // : nextToken(SyntaxKind.Identifier, "IdentifierName"); // IdentifierName nextToken(SyntaxKind.Identifier, "IdentifierName"); // IdentifierName nextToken(SyntaxKind.TerminalLiteral, "as"); // `as` nextToken(SyntaxKind.Identifier, "IdentifierName"); // IdentifierName eof(); }); it("when not in ast", () => { const { navigator, firstToken, nextToken, eof } = getNavigator("A[B, C] : `a`"); firstToken(SyntaxKind.Identifier, "A"); nextToken(SyntaxKind.OpenBracketToken); // [ nextToken(SyntaxKind.Identifier, "B"); // B nextToken(SyntaxKind.CommaToken); // , expect(navigator.getParent()?.kind).toBe(SyntaxKind.Parameter); nextToken(SyntaxKind.Identifier, "C"); // C nextToken(SyntaxKind.CloseBracketToken); // ] nextToken(SyntaxKind.ColonToken); // : nextToken(SyntaxKind.TerminalLiteral); // `a` eof(); }); it("in one of symbol", () => { const { firstToken, nextToken, eof } = getNavigator("A :: B but not one of C or D"); firstToken(SyntaxKind.Identifier, "A"); nextToken(SyntaxKind.ColonColonToken); nextToken(SyntaxKind.Identifier); nextToken(SyntaxKind.ButKeyword); nextToken(SyntaxKind.NotKeyword); nextToken(SyntaxKind.OneKeyword); nextToken(SyntaxKind.OfKeyword); nextToken(SyntaxKind.Identifier, "C"); nextToken(SyntaxKind.OrKeyword); nextToken(SyntaxKind.Identifier, "D"); eof(); }); it("in InvalidAssertion", () => { const { firstToken, nextToken, eof } = getNavigator("A :: B [,@]"); firstToken(SyntaxKind.Identifier, "A"); nextToken(SyntaxKind.ColonColonToken); nextToken(SyntaxKind.Identifier, "B"); nextToken(SyntaxKind.OpenBracketToken); nextToken(SyntaxKind.CommaToken); nextToken(SyntaxKind.AtToken); nextToken(SyntaxKind.CloseBracketToken); eof(); }); it("moves to next token following current node", () => { const { navigator, nextToken, eof } = getNavigator("A :: B? `c`"); expect(navigator.moveToFirstChild(SyntaxKind.Production)).toBe(true); expect(navigator.moveToLastChild(SyntaxKind.RightHandSide)).toBe(true); expect(navigator.moveToFirstChild(SyntaxKind.SymbolSpan)).toBe(true); expect(navigator.moveToFirstChild(SyntaxKind.Nonterminal)).toBe(true); nextToken(SyntaxKind.TerminalLiteral, "c"); eof(); }); }); describe("moveToPreviousToken", () => { it("when in ast", () => { const { lastToken, prevToken } = getNavigator(); lastToken(SyntaxKind.Identifier, "IdentifierName"); // IdentifierName prevToken(SyntaxKind.TerminalLiteral, "as"); // `as` prevToken(SyntaxKind.Identifier, "IdentifierName"); // IdentifierName prevToken(SyntaxKind.Identifier, "IdentifierName"); // IdentifierName prevToken(SyntaxKind.ColonToken); // : prevToken(SyntaxKind.Identifier, "ExportSpecifier"); // ExportSpecifier prevToken(SyntaxKind.Identifier, "RegularExpressionLiteral"); // RegularExpressionLiteral }); it("when not in ast", () => { const { lastToken, prevToken, bof } = getNavigator("A[B, C] : `a`"); lastToken(SyntaxKind.TerminalLiteral); prevToken(SyntaxKind.ColonToken); prevToken(SyntaxKind.CloseBracketToken); prevToken(SyntaxKind.Identifier); prevToken(SyntaxKind.CommaToken); prevToken(SyntaxKind.Identifier); prevToken(SyntaxKind.OpenBracketToken); prevToken(SyntaxKind.Identifier); bof(); }); it("moves to previous token preceding current node", () => { const { navigator, lastToken, prevToken } = getNavigator("A :: B? `c`"); lastToken(); expect(navigator.moveToAncestor(SyntaxKind.SymbolSpan)).toBe(true); prevToken(SyntaxKind.QuestionToken); }); }); function getNavigator(text = es6GrammarText) { const parser = new Parser(); const sourceFile = parser.parseSourceFile("file.grammar", text); const navigator = new NodeNavigator(sourceFile); return { sourceFile, navigator, ...makeExpectToken(navigator) }; } });
the_stack
import { TreeGrid } from '../base/treegrid'; import { Grid, InfiniteScroll as GridInfiniteScroll, ActionEventArgs, NotifyArgs } from '@syncfusion/ej2-grids'; import { InfiniteScrollArgs, Column, Row, RowRenderer, ServiceLocator, resetRowIndex } from '@syncfusion/ej2-grids'; import { getValue, isNullOrUndefined, remove } from '@syncfusion/ej2-base'; import * as events from '../base/constant'; import { ITreeData, RowCollapsedEventArgs } from '../base'; import { DataManager, Predicate, Query } from '@syncfusion/ej2-data'; import { findChildrenRecords, getExpandStatus } from '../utils'; /** * TreeGrid Infinite Scroll module will handle Infinite Scrolling. * * @hidden */ export class InfiniteScroll { private parent: TreeGrid; private visualData: ITreeData[]; /** * Constructor for VirtualScroll module * * @param {TreeGrid} parent - Tree Grid instance */ constructor(parent?: TreeGrid) { this.parent = parent; Grid.Inject(GridInfiniteScroll); this.addEventListener(); } /** * For internal use only - Get the module name. * * @private * @returns {string} - Returns Logger module name */ protected getModuleName(): string { return 'infiniteScroll'; } /** * @hidden * @returns {void} */ public addEventListener(): void { this.parent.on(events.pagingActions, this.infinitePageAction, this); this.parent.on('infinite-remote-expand', this.infiniteRemoteExpand, this); this.parent.grid.on('delete-complete', this.infiniteDeleteHandler, this); this.parent.grid.on('infinite-edit-handler', this.infiniteEditHandler, this); this.parent.grid.on('infinite-crud-cancel', this.createRows, this); this.parent.grid.on('content-ready', this.contentready, this); this.parent.on(events.localPagedExpandCollapse, this.collapseExpandInfinitechilds, this); } /** * @hidden * @returns {void} */ public removeEventListener(): void { if (this.parent.isDestroyed) { return; } this.parent.off('infinite-remote-expand', this.infiniteRemoteExpand); this.parent.grid.off('delete-complete', this.infiniteDeleteHandler); this.parent.grid.off('infinite-edit-handler', this.infiniteEditHandler); this.parent.off(events.pagingActions, this.infinitePageAction); this.parent.grid.off('infinite-crud-cancel', this.createRows); this.parent.grid.off('content-ready', this.contentready); this.parent.off(events.localPagedExpandCollapse, this.collapseExpandInfinitechilds); } /** * Handles the Expand Collapse action for Remote data with infinite scrolling. * * @param {{ index: number, childData: ITreeData[] }} args - expanded row index and its child data * @param { number } args.index - expanded row index * @param { ITreeData[] } args.childData - child data of expanded row * @returns {void} */ private infiniteRemoteExpand(args: { index: number, childData: ITreeData[] }): void { const rowObjects: Row<Column>[] = this.parent.grid.getRowsObject(); const locator: string = 'serviceLocator'; const generateRows: string = 'generateRows'; const serviceLocator: ServiceLocator = this.parent.grid.infiniteScrollModule[locator]; const rowRenderer: RowRenderer<Column> = new RowRenderer<Column>(serviceLocator, null, this.parent.grid); const rows: Element[] = this.parent.getRows(); const position: string = args.index === rows.length - 1 ? 'after' : 'before'; const cols: Column[] = this.parent.grid.getColumns(); const childRowObjects: Row<Column>[] = this.parent.grid.infiniteScrollModule[generateRows](args.childData, args); const childRowElements: Element[] = []; for (let i: number = 0; i < childRowObjects.length; i++) { childRowElements.push(rowRenderer.render(childRowObjects[i], cols)); } rowObjects.splice(args.index + 1, 0, ...childRowObjects); for (let i: number = 0; i < childRowElements.length; i++) { if (position === 'after') { rows[args.index + i][position](childRowElements[i]); } else { rows[args.index + i + 1][position](childRowElements[i]); } rows.splice(args.index + 1 + i, 0, childRowElements[i]); } resetRowIndex(this.parent.grid, this.parent.grid.getRowsObject(), this.parent.grid.getRows() as HTMLTableRowElement[], 0); } /** * Resetted the row index for expand collapse action for cache support. * * @returns {void} */ private contentready (): void { if (this.parent.infiniteScrollSettings.enableCache && !isNullOrUndefined(this.parent.editModule)) { const updateIndex: string = 'updateIndex'; this.parent.editModule[updateIndex](this.parent.grid.dataSource, this.parent.getRows(), this.parent.getCurrentViewRecords()); if (this.parent.getFrozenColumns()) { this.parent.editModule[updateIndex](this.parent.grid.dataSource, this.parent.getMovableDataRows(), this.parent.getCurrentViewRecords()); } } } private collapseExpandInfinitechilds(row: { action: string, row: HTMLTableRowElement, record: ITreeData, args: RowCollapsedEventArgs }): void { row.record.expanded = row.action === 'collapse' ? false : true; const ret: Object = { result: this.parent.flatData, row: row.row, action: row.action, record: row.record, count: this.parent.flatData.length }; const requestType: string = getValue('isCollapseAll', this.parent) ? 'collapseAll' : 'refresh'; getValue('grid.renderModule', this.parent).dataManagerSuccess(ret, <NotifyArgs>{ requestType: requestType }); } /** * Handles the page query for Data operations and CRUD actions. * * @param {{ result: ITreeData[], count: number, actionArgs: object }} pageingDetails - data, its count and action details * @param {ITreeData[]} pageingDetails.result - data on scroll action * @param {number} pageingDetails.count - data count on scroll action * @param {Object} pageingDetails.actionArgs - scroll action details * @returns {void} */ private infinitePageAction(pageingDetails: { result: ITreeData[], count: number, actionArgs: Object }): void { const dm: DataManager = new DataManager(pageingDetails.result); const expanded: Predicate = new Predicate('expanded', 'notequal', null).or('expanded', 'notequal', undefined); const infiniteParents: ITreeData[] = dm.executeLocal(new Query().where(expanded)); const visualData: ITreeData[] = infiniteParents.filter((e: ITreeData) => { return getExpandStatus(this.parent, e, infiniteParents); }); const actionArgs: ActionEventArgs = getValue('actionArgs', pageingDetails.actionArgs); const actions: string[] = getValue('actions', this.parent.grid.infiniteScrollModule); const initial: boolean = actions.some((value: string): boolean => { return value === actionArgs.requestType; }); const initialRender: boolean = initial ? true : this.parent.initialRender ? true : false; this.visualData = visualData; pageingDetails.count = visualData.length; if (getValue('isPrinting', pageingDetails.actionArgs)) { pageingDetails.result = visualData; } else { let query: Query = new Query(); const isCache: boolean = this.parent.infiniteScrollSettings.enableCache; if (isCache && this.parent.infiniteScrollSettings.initialBlocks > this.parent.infiniteScrollSettings.maxBlocks) { this.parent.infiniteScrollSettings.initialBlocks = this.parent.infiniteScrollSettings.maxBlocks; } let size: number = initialRender ? this.parent.pageSettings.pageSize * this.parent.infiniteScrollSettings.initialBlocks : this.parent.pageSettings.pageSize; let current: number = this.parent.grid.pageSettings.currentPage; if (!isNullOrUndefined(actionArgs)) { const lastIndex: number = getValue('lastIndex', this.parent.grid.infiniteScrollModule); const firstIndex: number = getValue('firstIndex', this.parent.grid.infiniteScrollModule); if (!isCache && actionArgs.requestType === 'delete') { const skip: number = lastIndex - (<Object[]>actionArgs.data).length + 1; const take: number = (<Object[]>actionArgs.data).length; query = query.skip(skip).take(take); } else if (isCache && actionArgs.requestType === 'delete' || (actionArgs.requestType === 'save' && actionArgs.action === 'add')) { query = query.skip(firstIndex); query = query.take(this.parent.infiniteScrollSettings.initialBlocks * this.parent.pageSettings.pageSize); } else { if ((pageingDetails.actionArgs['action'] === 'expand' || pageingDetails.actionArgs['action'] === 'collapse') && this.parent.grid.pageSettings.currentPage !== 1) { current = 1; size = this.parent.pageSettings.pageSize * this.parent.grid.pageSettings.currentPage; } query = query.page(current, size); } } else { query = query.page(current, size); } dm.dataSource.json = visualData; if (!isCache && !isNullOrUndefined(actionArgs) && actionArgs.requestType === 'save' && actionArgs.action === 'add') { pageingDetails.result = [actionArgs.data]; } else { pageingDetails.result = dm.executeLocal(query); } } this.parent.notify('updateAction', pageingDetails); } /** * Handles the currentviewdata for delete operation. * * @param {{ e: InfiniteScrollArgs, result: Object[] }} args - Scroller and data details * @param {InfiniteScrollArgs} args.e - scroller details while CRUD * @param {Object[]} args.result - data details while CRUD * @returns {void} */ private infiniteEditHandler(args: { e: InfiniteScrollArgs, result: Object[] }): void { const infiniteData: string = 'infiniteCurrentViewData'; const infiniteCurrentViewData: { [x: number]: Object[] } = this.parent.grid.infiniteScrollModule[infiniteData]; const keys: string[] = Object.keys(infiniteCurrentViewData); if (args.e.requestType === 'delete' && args.result.length > 1) { for (let i: number = 1; i < args.result.length; i++) { infiniteCurrentViewData[keys[keys.length - 1]].push(args.result[i]); } } } /** * Handles the row objects for delete operation. * * @param {ActionEventArgs} args - crud action details * @returns {void} */ private infiniteDeleteHandler(args: ActionEventArgs): void { if (args.requestType === 'delete') { const rows: Row<Column>[] = this.parent.grid.getRowsObject(); const rowElms: Element[] = this.parent.getRows(); const data: Object[] = args.data instanceof Array ? args.data : [args.data]; const keyField: string = this.parent.grid.getPrimaryKeyFieldNames()[0]; this.removeRows(rowElms, rows, data, keyField, true); if (this.parent.getFrozenColumns() > 0) { const mRows: Row<Column>[] = this.parent.grid.getMovableRowsObject(); const mRowElms: Element[] = this.parent.grid.getMovableRows(); this.removeRows(mRowElms, mRows, data, keyField); } } } /** * Handles the row objects for delete operation. * * @param {Element[]} rowElms - row elements * @param {Row<Column>[]} rows - Row object collection * @param {Object[]} data - data collection * @param {string} keyField - primary key name * @param { boolean} isFrozen - Specifies whether frozen column enabled * @returns {void} */ private removeRows(rowElms: Element[], rows: Row<Column>[], data: Object[], keyField: string, isFrozen?: boolean): void { const resetInfiniteCurrentViewData: string = 'resetInfiniteCurrentViewData'; for (let i: number = 0; i < data.length; i++) { rows.filter((e: Row<Column>, index: number) => { if (e.data[keyField] === data[i][keyField]) { if (isFrozen) { const page: number = Math.ceil((index + 1) / this.parent.grid.pageSettings.pageSize); this.parent.grid.infiniteScrollModule[resetInfiniteCurrentViewData](page, index); } rows.splice(index, 1); remove(rowElms[index]); rowElms.splice(index, 1); } }); } } /** * Handles the row objects for Add operation. */ private createRows(eventArgs: { rows: Row<Column>[], row: Row<Column>[], cancel: boolean, args: { e: ActionEventArgs, result: Object[] }, isMovable?: boolean, isFrozenRows?: boolean, isFrozenRight?: boolean }): void { const locator: string = 'serviceLocator'; const actionArgs: ActionEventArgs = eventArgs.args.e; const row: Row<Column>[] = eventArgs.row; const serviceLocator: ServiceLocator = this.parent.grid.infiniteScrollModule[locator]; const rowRenderer: RowRenderer<Column> = new RowRenderer<Column>(serviceLocator, null, this.parent.grid); let tbody: HTMLElement; const currentData: ITreeData[] = this.parent.getCurrentViewRecords(); const currentRows: HTMLTableRowElement[] = eventArgs.isMovable ? <HTMLTableRowElement[]>this.parent.grid.getMovableRows() : <HTMLTableRowElement[]>this.parent.grid.getDataRows(); if (eventArgs.isFrozenRight) { tbody = this.parent.element.querySelector('.e-frozen-right-content').querySelector('tbody'); } else { tbody = !this.parent.grid.isFrozenGrid() ? this.parent.getContent().querySelector('tbody') : eventArgs.isMovable ? this.parent.grid.getMovableVirtualContent().querySelector('tbody') : this.parent.grid.getFrozenVirtualContent().querySelector('tbody'); } if (this.parent.frozenRows) { tbody = eventArgs.isFrozenRows && this.parent.grid.infiniteScrollModule.requestType !== 'add' || !eventArgs.isFrozenRows && this.parent.grid.infiniteScrollModule.requestType === 'add' ? !this.parent.grid.isFrozenGrid() ? this.parent.getHeaderContent().querySelector('tbody') : eventArgs.isMovable ? this.parent.grid.getMovableVirtualHeader().querySelector('tbody') : eventArgs.isFrozenRight ? this.parent.element.querySelector('.e-frozen-right-header').querySelector('tbody') : this.parent.grid.getFrozenVirtualHeader().querySelector('tbody') : tbody; } let position: string; const addRowIndex: string = 'addRowIndex'; let newRowIndex: number = this.parent.editModule[addRowIndex]; for (let i: number = 0; i < row.length; i++) { const newRow: HTMLTableRowElement = <HTMLTableRowElement>rowRenderer.render(row[i], this.parent.grid.getColumns()); if (actionArgs.requestType === 'save' && actionArgs.action === 'add') { if (getValue('selectedIndex', this.parent.editModule) !== -1 && this.parent.editSettings.newRowPosition !== 'Top') { if (this.parent.editSettings.newRowPosition === 'Below' || this.parent.editSettings.newRowPosition === 'Child') { position = 'after'; newRowIndex += findChildrenRecords(currentData[newRowIndex + 1]).length; if (this.parent.editSettings.newRowPosition === 'Child') { newRowIndex -= 1; //// for child position already child record is added in childRecords so subtracting 1 } currentRows[newRowIndex][position](newRow); } else if (this.parent.editSettings.newRowPosition === 'Above') { position = 'before'; currentRows[this.parent.editModule[addRowIndex]][position](newRow); } } else if (this.parent.editSettings.newRowPosition === 'Bottom') { tbody.appendChild(newRow); } else { tbody.insertBefore(newRow, tbody.firstElementChild); } } else if (actionArgs.requestType === 'delete') { tbody.appendChild(newRow); } } eventArgs.cancel = true; } /** * To destroy the infiniteScroll module * * @returns {void} * @hidden */ public destroy(): void { this.removeEventListener(); } }
the_stack
import { Component, OnDestroy, OnInit } from '@angular/core'; import { AbstractTrackableComponent } from '../../../shared/trackable/abstract-trackable.component'; import { DynamicFormControlModel, DynamicFormGroupModel, DynamicFormLayout, DynamicFormService, DynamicInputModel, DynamicOptionControlModel, DynamicRadioGroupModel, DynamicSelectModel, DynamicTextAreaModel } from '@ng-dynamic-forms/core'; import { Location } from '@angular/common'; import { TranslateService } from '@ngx-translate/core'; import { ObjectUpdatesService } from '../../../core/data/object-updates/object-updates.service'; import { NotificationsService } from '../../../shared/notifications/notifications.service'; import { FormGroup } from '@angular/forms'; import { hasNoValue, hasValue, isNotEmpty } from '../../../shared/empty.util'; import { ContentSource, ContentSourceHarvestType } from '../../../core/shared/content-source.model'; import { Observable, Subscription } from 'rxjs'; import { RemoteData } from '../../../core/data/remote-data'; import { Collection } from '../../../core/shared/collection.model'; import { first, map, switchMap, take } from 'rxjs/operators'; import { ActivatedRoute, Router } from '@angular/router'; import { FieldUpdate, FieldUpdates } from '../../../core/data/object-updates/object-updates.reducer'; import { cloneDeep } from 'lodash'; import { CollectionDataService } from '../../../core/data/collection-data.service'; import { getFirstSucceededRemoteData, getFirstCompletedRemoteData } from '../../../core/shared/operators'; import { MetadataConfig } from '../../../core/shared/metadata-config.model'; import { INotification } from '../../../shared/notifications/models/notification.model'; import { RequestService } from '../../../core/data/request.service'; import { environment } from '../../../../environments/environment'; /** * Component for managing the content source of the collection */ @Component({ selector: 'ds-collection-source', templateUrl: './collection-source.component.html', }) export class CollectionSourceComponent extends AbstractTrackableComponent implements OnInit, OnDestroy { /** * The current collection's remote data */ collectionRD$: Observable<RemoteData<Collection>>; /** * The collection's content source */ contentSource: ContentSource; /** * The current update to the content source */ update$: Observable<FieldUpdate>; /** * The initial harvest type we started off with * Used to compare changes */ initialHarvestType: ContentSourceHarvestType; /** * @type {string} Key prefix used to generate form labels */ LABEL_KEY_PREFIX = 'collection.edit.tabs.source.form.'; /** * @type {string} Key prefix used to generate form error messages */ ERROR_KEY_PREFIX = 'collection.edit.tabs.source.form.errors.'; /** * @type {string} Key prefix used to generate form option labels */ OPTIONS_KEY_PREFIX = 'collection.edit.tabs.source.form.options.'; /** * The Dynamic Input Model for the OAI Provider */ oaiSourceModel = new DynamicInputModel({ id: 'oaiSource', name: 'oaiSource', required: true, validators: { required: null }, errorMessages: { required: 'You must provide a set id of the target collection.' } }); /** * The Dynamic Input Model for the OAI Set */ oaiSetIdModel = new DynamicInputModel({ id: 'oaiSetId', name: 'oaiSetId' }); /** * The Dynamic Input Model for the Metadata Format used */ metadataConfigIdModel = new DynamicSelectModel({ id: 'metadataConfigId', name: 'metadataConfigId' }); /** * The Dynamic Input Model for the type of harvesting */ harvestTypeModel = new DynamicRadioGroupModel<string>({ id: 'harvestType', name: 'harvestType', options: [ { value: ContentSourceHarvestType.Metadata }, { value: ContentSourceHarvestType.MetadataAndRef }, { value: ContentSourceHarvestType.MetadataAndBitstreams } ] }); /** * All input models in a simple array for easier iterations */ inputModels = [this.oaiSourceModel, this.oaiSetIdModel, this.metadataConfigIdModel, this.harvestTypeModel]; /** * The dynamic form fields used for editing the content source of a collection * @type {(DynamicInputModel | DynamicTextAreaModel)[]} */ formModel: DynamicFormControlModel[] = [ new DynamicFormGroupModel({ id: 'oaiSourceContainer', group: [ this.oaiSourceModel ] }), new DynamicFormGroupModel({ id: 'oaiSetContainer', group: [ this.oaiSetIdModel, this.metadataConfigIdModel ] }), new DynamicFormGroupModel({ id: 'harvestTypeContainer', group: [ this.harvestTypeModel ] }) ]; /** * Layout used for structuring the form inputs */ formLayout: DynamicFormLayout = { oaiSource: { grid: { host: 'col-12 d-inline-block' } }, oaiSetId: { grid: { host: 'col col-sm-6 d-inline-block' } }, metadataConfigId: { grid: { host: 'col col-sm-6 d-inline-block' } }, harvestType: { grid: { host: 'col-12', option: 'btn-outline-secondary' } }, oaiSetContainer: { grid: { host: 'row' } }, oaiSourceContainer: { grid: { host: 'row' } }, harvestTypeContainer: { grid: { host: 'row' } } }; /** * The form group of this form */ formGroup: FormGroup; /** * Subscription to update the current form */ updateSub: Subscription; /** * The content harvesting type used when harvesting is disabled */ harvestTypeNone = ContentSourceHarvestType.None; /** * The previously selected harvesting type * Used for switching between ContentSourceHarvestType.None and the previously selected value when enabling / disabling harvesting * Defaults to ContentSourceHarvestType.Metadata */ previouslySelectedHarvestType = ContentSourceHarvestType.Metadata; /** * Notifications displayed after clicking submit * These are cleaned up every time a user submits the form to prevent error or other notifications from staying active * while they shouldn't be. */ displayedNotifications: INotification[] = []; public constructor(public objectUpdatesService: ObjectUpdatesService, public notificationsService: NotificationsService, protected location: Location, protected formService: DynamicFormService, protected translate: TranslateService, protected route: ActivatedRoute, protected router: Router, protected collectionService: CollectionDataService, protected requestService: RequestService) { super(objectUpdatesService, notificationsService, translate); } /** * Initialize properties to setup the Field Update and Form */ ngOnInit(): void { this.notificationsPrefix = 'collection.edit.tabs.source.notifications.'; this.discardTimeOut = environment.collection.edit.undoTimeout; this.url = this.router.url; if (this.url.indexOf('?') > 0) { this.url = this.url.substr(0, this.url.indexOf('?')); } this.formGroup = this.formService.createFormGroup(this.formModel); this.collectionRD$ = this.route.parent.data.pipe(first(), map((data) => data.dso)); this.collectionRD$.pipe( getFirstSucceededRemoteData(), map((col) => col.payload.uuid), switchMap((uuid) => this.collectionService.getContentSource(uuid)), getFirstCompletedRemoteData(), ).subscribe((rd: RemoteData<ContentSource>) => { this.initializeOriginalContentSource(rd.payload); }); this.updateFieldTranslations(); this.translate.onLangChange .subscribe(() => { this.updateFieldTranslations(); }); } /** * Initialize the Field Update and subscribe on it to fire updates to the form whenever it changes */ initializeOriginalContentSource(contentSource: ContentSource) { this.contentSource = contentSource; this.initialHarvestType = contentSource.harvestType; this.initializeMetadataConfigs(); const initialContentSource = cloneDeep(this.contentSource); this.objectUpdatesService.initialize(this.url, [initialContentSource], new Date()); this.update$ = this.objectUpdatesService.getFieldUpdates(this.url, [initialContentSource]).pipe( map((updates: FieldUpdates) => updates[initialContentSource.uuid]) ); this.updateSub = this.update$.subscribe((update: FieldUpdate) => { if (update) { const field = update.field as ContentSource; let configId; if (hasValue(this.contentSource) && isNotEmpty(this.contentSource.metadataConfigs)) { configId = this.contentSource.metadataConfigs[0].id; } if (hasValue(field) && hasValue(field.metadataConfigId)) { configId = field.metadataConfigId; } if (hasValue(field)) { this.formGroup.patchValue({ oaiSourceContainer: { oaiSource: field.oaiSource }, oaiSetContainer: { oaiSetId: field.oaiSetId, metadataConfigId: configId }, harvestTypeContainer: { harvestType: field.harvestType } }); this.contentSource = cloneDeep(field); } this.contentSource.metadataConfigId = configId; } }); } /** * Fill the metadataConfigIdModel's options using the contentSource's metadataConfigs property */ initializeMetadataConfigs() { this.metadataConfigIdModel.options = this.contentSource.metadataConfigs .map((metadataConfig: MetadataConfig) => Object.assign({ value: metadataConfig.id, label: metadataConfig.label })); if (this.metadataConfigIdModel.options.length > 0) { this.formGroup.patchValue({ oaiSetContainer: { metadataConfigId: this.metadataConfigIdModel.options[0].value } }); } } /** * Used the update translations of errors and labels on init and on language change */ private updateFieldTranslations() { this.inputModels.forEach( (fieldModel: DynamicFormControlModel) => { this.updateFieldTranslation(fieldModel); } ); } /** * Update the translations of a DynamicInputModel * @param fieldModel */ private updateFieldTranslation(fieldModel: DynamicFormControlModel) { fieldModel.label = this.translate.instant(this.LABEL_KEY_PREFIX + fieldModel.id); if (isNotEmpty(fieldModel.validators)) { fieldModel.errorMessages = {}; Object.keys(fieldModel.validators).forEach((key) => { fieldModel.errorMessages[key] = this.translate.instant(this.ERROR_KEY_PREFIX + fieldModel.id + '.' + key); }); } if (fieldModel instanceof DynamicOptionControlModel) { if (isNotEmpty(fieldModel.options)) { fieldModel.options.forEach((option) => { if (hasNoValue(option.label)) { option.label = this.translate.instant(this.OPTIONS_KEY_PREFIX + fieldModel.id + '.' + option.value); } }); } } } /** * Fired whenever the form receives an update and makes sure the Content Source and field update is up-to-date with the changes * @param event */ onChange(event) { this.updateContentSourceField(event.model, true); this.saveFieldUpdate(); } /** * Submit the edited Content Source to the REST API, re-initialize the field update and display a notification */ onSubmit() { // Remove cached harvester request to allow for latest harvester to be displayed when switching tabs this.collectionRD$.pipe( getFirstSucceededRemoteData(), map((col) => col.payload.uuid), switchMap((uuid) => this.collectionService.getHarvesterEndpoint(uuid)), take(1) ).subscribe((endpoint) => this.requestService.removeByHrefSubstring(endpoint)); this.requestService.setStaleByHrefSubstring(this.contentSource._links.self.href); // Update harvester this.collectionRD$.pipe( getFirstSucceededRemoteData(), map((col) => col.payload.uuid), switchMap((uuid) => this.collectionService.updateContentSource(uuid, this.contentSource)), take(1) ).subscribe((result: ContentSource | INotification) => { if (hasValue((result as any).harvestType)) { this.clearNotifications(); this.initializeOriginalContentSource(result as ContentSource); this.displayedNotifications.push(this.notificationsService.success(this.getNotificationTitle('saved'), this.getNotificationContent('saved'))); } else { this.displayedNotifications.push(result as INotification); } }); } /** * Cancel the edit and return to the previous page */ onCancel() { this.location.back(); } /** * Is the current form valid to be submitted ? */ isValid(): boolean { return (this.contentSource.harvestType === ContentSourceHarvestType.None) || this.formGroup.valid; } /** * Switch the external source on or off and fire a field update */ changeExternalSource() { if (this.contentSource.harvestType === ContentSourceHarvestType.None) { this.contentSource.harvestType = this.previouslySelectedHarvestType; } else { this.previouslySelectedHarvestType = this.contentSource.harvestType; this.contentSource.harvestType = ContentSourceHarvestType.None; } this.updateContentSource(false); } /** * Loop over all inputs and update the Content Source with their value * @param updateHarvestType When set to false, the harvestType of the contentSource will be ignored in the update */ updateContentSource(updateHarvestType: boolean) { this.inputModels.forEach( (fieldModel: DynamicInputModel) => { this.updateContentSourceField(fieldModel, updateHarvestType); } ); this.saveFieldUpdate(); } /** * Update the Content Source with the value from a DynamicInputModel * @param fieldModel The fieldModel to fetch the value from and update the contentSource with * @param updateHarvestType When set to false, the harvestType of the contentSource will be ignored in the update */ updateContentSourceField(fieldModel: DynamicInputModel, updateHarvestType: boolean) { if (hasValue(fieldModel.value) && !(fieldModel.id === this.harvestTypeModel.id && !updateHarvestType)) { this.contentSource[fieldModel.id] = fieldModel.value; } } /** * Save the current Content Source to the Object Updates cache */ saveFieldUpdate() { this.objectUpdatesService.saveAddFieldUpdate(this.url, cloneDeep(this.contentSource)); } /** * Clear possible active notifications */ clearNotifications() { this.displayedNotifications.forEach((notification: INotification) => { this.notificationsService.remove(notification); }); this.displayedNotifications = []; } /** * Make sure open subscriptions are closed */ ngOnDestroy(): void { if (this.updateSub) { this.updateSub.unsubscribe(); } } }
the_stack
import { IServer } from "./IServer.interface"; import { ISocket } from "./ISocket.interface"; import { EventEmitter } from "./EventEmitter"; import { Stub } from "./Stub"; import { Transport } from "./Transport"; import { Util } from "./Util.class"; import { Contract } from "./Contract.class"; import { Protocol } from "./Protocol.static"; import { InvokeContext } from "./InvokeContext.class"; import * as Transports from './transport/index'; /** @ignore */ declare var _eureca_host: any; declare var _eureca_uri: any; /** * Eureca client class * This constructor takes an optional settings object * @constructor Client * @param {object} [settings] - have the following properties <br /> * @property {uri} settings.uri - Eureca server WS uri, browser client can automatically guess the server URI if you are using a single Eureca server but Nodejs client need this parameter. * @property {string} [settings.prefix=eureca.io] - This determines the websocket path, it's unvisible to the user but if for some reason you want to rename this path use this parameter. * @property {int} [settings.retry=20] - Determines max retries to reconnect to the server if the connection is lost. * @property {boolean} [settings.autoConnect=true] - Estabilish connection automatically after instantiation.<br />if set to False you'll need to call client.connect() explicitly. * @property {object} [settings.transportSettings] - If defined, all parameters passed here will be sent to the underlying transport settings, this can be used to finetune, or override transport settings. * * @example * **Example of a nodejs client** * ```javascript * var Eureca = require('eureca.io'); * var client = new Eureca.Client({ uri: 'ws://localhost:8000/', prefix: 'eureca.io', retry: 3 }); * client.ready(function (serverProxy) { * // ... * }); * ``` * * @example * **Equivalent browser client** * ```html * &lt;!doctype html&gt; * &lt;html&gt; * &lt;head&gt; * &lt;script src=&quot;/eureca.js&quot;&gt;&lt;/script&gt; * &lt;/head&gt; * &lt;body&gt; * &lt;script&gt; * var client = new Eureca.Client({prefix: 'eureca.io', retry: 3 }); * //uri is optional in browser client * client.ready(function (serverProxy) { * // ... * }); * &lt;/script&gt; * &lt;/body&gt; * &lt;/html&gt; * ``` * * @see authenticate * @see connect * @see disconnect * @see send * @see isReady * * */ export class Client extends EventEmitter { public transport; public exports = {}; public stub: Stub; public contract = []; /** @ignore */ private __eureca_exports__: any = {}; /** @ignore */ //this variable keeps track of received name spaces list private __eureca_imports__: any = {}; /** @ignore */ //this variable checks if we received the initial namespaces list from the server private __eureca_imports_received__ = false; private socket: ISocket; private state: string; public serverProxy: any = {}; /** @ignore */ private serialize = (v) => v; /** @ignore */ private deserialize = (v) => v; constructor(public settings: any = {}) { super(); if (!settings.transport) settings.transport = 'engine.io'; if (!settings.prefix) settings.prefix = 'eureca.io'; if (!settings.clientScript) settings.clientScript = '/eureca.js'; this.loadTransports(); this.transport = Transport.get(settings.transport); if (this.transport.serialize) this.serialize = this.transport.serialize; if (this.transport.deserialize) this.deserialize = this.transport.deserialize; settings.serialize = settings.serialize || this.serialize; settings.deserialize = settings.deserialize || this.deserialize; settings.retries = settings.retries || 20; settings.autoConnect = !(settings.autoConnect === false); //if (this.settings.autoConnect !== false) this.stub = new Stub(settings); if (this.settings.autoConnect) setTimeout(this.connect.bind(this), 100); } private loadTransports() { for (let tr in Transports) if (typeof Transports[tr].register === 'function') Transports[tr].register(); } public ready(callback) { if (callback) { if (this.state === 'ready') callback(); else this.on('ready', callback); return null; } return new Promise(resolve => { this.on('ready', resolve); }) } /** * Send authentication request to the server. <br /> * this can take an arbitrary number of arguments depending on what you defined in the server side <br /> * when the server receive an auth request it'll handle it and return null on auth success, or an error message if something goes wrong <br /> * you need to listed to auth result throught authResponse event * ** Important ** : it's up to you to define the authenticationmethod in the server side * @function Client#authenticate * * @example * var client = new Eureca.Client({..}); * //listen to auth response * client.authResponse(function(result) { * if (result == null) { * // ... Auth OK * } * else { * // ... Auth failed * } * }); * * client.ready(function(){ * * //send auth request * client.authenticate('your_auth_token'); * }); */ public authenticate(...args: any[]) { var authRequest = {}; authRequest[Protocol.authReq] = args; this.socket.send(this.settings.serialize(authRequest)); } /** * connect client * * * @function Client#connect * */ public connect() { const prefix = this.settings.prefix || _eureca_prefix; const uri = this.settings.uri || (prefix ? _eureca_host + '/' + prefix : (_eureca_uri || undefined)); this.state = 'connecting'; this.socket = this.transport.createClient(uri, this.settings); //this.socket.proxy = this.serverProxy; this._handleClient(this.socket); } /** * close client connection * * * @function Client#disconnect * */ public disconnect() { //this.tries = this.maxRetries + 1; this.socket.close(); } public _export(obj, name, update = true) { if (typeof name !== 'string') throw new Error('invalid object name'); if (name !== '__default__' && this.__eureca_exports__[name]) { console.warn(`Export name "${name}" already used, will be overwritten`); } const cexport = { exports: obj, contract: Contract.ensureContract(obj), context: undefined } this.__eureca_exports__[name] = cexport; if (update) { const sendObj = {}; sendObj[Protocol.contractFnList] = cexport.contract; sendObj[Protocol.contractObjId] = name; this.socket.send(this.settings.serialize(sendObj)); } } public import(name: string = '__default__') { return this.socket.import(name); } private _handleClient(clientSocket: ISocket) { const proxy = clientSocket.proxy; clientSocket.on('open', () => this.emit('connect', clientSocket)); clientSocket.on('message', (data) => { this.emit('message', data); const jobj: any = this.deserialize.call(clientSocket, data); if (typeof jobj != 'object') { this.emit('unhandledMessage', data); return; } if (jobj[Protocol.contractFnList]) { const update = this.contract && this.contract.length > 0; this.contract = jobj[Protocol.contractFnList]; /** dynamic client contract*/ if (jobj[Protocol.command]) { this._export(this.exports, '__default__', false); for (let name in this.__eureca_exports__) { const cexport = this.__eureca_exports__[name]; const sendObj = {}; sendObj[Protocol.contractFnList] = cexport.contract; sendObj[Protocol.contractObjId] = name; clientSocket.send(this.settings.serialize(sendObj)); } //this.contract = contract; } /*****************************************************/ const importName = jobj[Protocol.contractObjId] ? jobj[Protocol.contractObjId] : '__default__'; this.stub.importRemoteFunction(clientSocket, jobj[Protocol.contractFnList], importName); this.serverProxy = this.socket.proxy || {}; //var next = function () { this.__eureca_imports__[importName] = true; if (jobj[Protocol.nsListId]) { this.__eureca_imports_received__ = true; for (let ns of jobj[Protocol.nsListId]) { if (!this.__eureca_imports__[ns]) this.__eureca_imports__[ns] = false; } } if (this.state === 'ready' && update) { /** * ** Experimental ** Triggered when the server explicitly notify the client about remote functions change.<br /> * you'll need this for example, if the server define some functions dynamically and need to make them available to clients. * */ this.emit('update', this.serverProxy, this.contract); } else { const allNS = this.__eureca_imports_received__ && [...Object.values(this.__eureca_imports__)].reduce((cumul, v) => cumul && v); if (allNS) { this.state = 'ready'; this.emit('ready', this.serverProxy, this.contract); } } return; } //Handle auth response if (jobj[Protocol.authResp] !== undefined) { clientSocket.eureca.authenticated = true; var callArgs = ['authResponse'].concat(jobj[Protocol.authResp]); this.emit.apply(this, callArgs); return; } // /!\ order is important we have to check invoke BEFORE callback if (jobj[Protocol.functionId] !== undefined) //server invoking client { if (clientSocket.context == undefined) { clientSocket.context = new InvokeContext(clientSocket, jobj); clientSocket.context.serialize = this.serialize; } //update the return id; clientSocket.context.retId = jobj[Protocol.signatureId]; clientSocket.context.message = jobj; const handle = jobj[Protocol.contractObjId] ? this.__eureca_exports__[jobj[Protocol.contractObjId]] : this; this.stub.invokeLocal(clientSocket.context, handle); return; } if (jobj[Protocol.signatureId] !== undefined) //invoke result { //_this.stub.doCallBack(jobj[Protocol.signatureId], jobj[Protocol.resultId], jobj[Protocol.errorId]); Stub.doCallBack(jobj[Protocol.signatureId], jobj[Protocol.resultId], jobj[Protocol.errorId]); return; } this.emit('unhandledMessage', data); }); clientSocket.on('reconnecting', (opts) => this.emit('connectionRetry', opts)); clientSocket.on('close', (e) => { this.emit('disconnect', clientSocket, e); this.emit('connectionLost'); }); clientSocket.on('error', (e) => this.emit('error', e)); clientSocket.on('stateChange', (s) => this.emit('stateChange', s)); } //#region ==[ Deprecated Events bindings ]=================== /** * Bind a callback to 'update' event @see {@link Client#event:update|Client update event} * >**Note :** you can also use Client.on('update', callback) to bind update event * * @function Client#update * */ public update(callback: (any) => void) { console.warn("Deprecated, please use client.on('update', callback) instead"); this.on('update', callback); } /** * Bind a callback to 'connect' event * >**Note :** you can also use Client.on('connect', callback) to bind connect event * * @function Client#onConnect * */ public onConnect(callback: (any) => void) { this.on('connect', callback); } /** * Bind a callback to 'disconnect' event @see {@link Client#event:disconnect|Client disconnect event} * >**Note :** you can also use Client.on('disconnect', callback) to bind disconnect event * * @function Client#donDisconnect * */ public onDisconnect(callback: (any) => void) { /** * triggered when the connection is lost after all retries to reestabilish it. * * @event Client#disconnect */ this.on('disconnect', callback); } /** * Bind a callback to 'message' event @see {@link Client#event:message|Client message event} * >**Note :** you can also use Client.on('message', callback) to bind message event * * @function Client#onMessage * */ public onMessage(callback: (any) => void) { /** * Triggered when the client receive a message from the server. * This event can be used to intercept exchanged messages betweens client and server, if you need to access low level network messages * * @event Client#message * * */ this.on('message', callback); } /** * Bind a callback to 'unhandledMessage' event @see {@link Client#event:unhandledMessage|Client unhandledMessage event} * >**Note :** you can also use Client.on('message', callback) to bind unhandledMessage event * * @function Client#onUnhandledMessage * */ public onUnhandledMessage(callback: (any) => void) { /** * Triggered when the client receive a message from the server and is not able to handle it. * this mean that the message is not an internal eureca.io message.<br /> * if for some reason you need to exchange send/receive raw or custom data, listen to this event which in countrary to {@link Client#event:message|message event} will only trigger for non-eureca messages. * * @event Client#unhandledMessage * * */ this.on('unhandledMessage', callback); } /** * Bind a callback to 'error' event @see {@link Client#event:error|Client error event} * >**Note :** you can also use Client.on('error', callback) to bind error event * * @function Client#onError * */ public onError(callback: (any) => void) { /** * triggered if an error occure. * * @event Client#error * @property {String} error - the error message */ this.on('error', callback); } /** * Bind a callback to 'connectionLost' event * >**Note :** you can also use Client.on('connectionLost', callback) to bind connectionLost event * * @function Client#onConnectionLost * */ public onConnectionLost(callback: (any) => void) { this.on('connectionLost', callback); } /** * Bind a callback to 'connectionRetry' event * >**Note :** you can also use Client.on('connectionRetry', callback) to bind connectionRetry event * * @function Client#onConnectionRetry * */ public onConnectionRetry(callback: (any) => void) { /** * triggered when the connection is lost and the client try to reconnect. * * @event Client#connectionRetry */ this.on('connectionRetry', callback); } /** * Bind a callback to 'authResponse' event @see {@link Client#event:authResponse|Client authResponse event} * >**Note :** you can also use Client.on('authResponse', callback) to bind authResponse event * * @function Client#onAuthResponse * */ public onAuthResponse(callback: (any) => void) { /** * Triggered when the client receive authentication response from the server. * The server should return a null response on authentication success. * * @event Client#authResponse * * */ this.on('authResponse', callback); } //#endregion } export { version } from './version' var is_nodejs = Util.isNodejs; if (is_nodejs) { var _eureca_prefix = 'eureca.io'; }
the_stack
import { join } from 'path'; import type { DeviceDescriptor, ConfigDescriptor, BosDescriptor } from './descriptors'; /* eslint-disable @typescript-eslint/no-var-requires */ const usb = require('node-gyp-build')(join(__dirname, '..', '..')); module.exports = usb; /** * Return a list of `Device` objects for the USB devices attached to the system. */ export declare function getDeviceList(): Device[]; export declare const INIT_ERROR: number; export declare class LibUSBException extends Error { errno: number; } /** * Set the libusb debug level (between 0 and 4) * @param level libusb debug level (between 0 and 4) */ export declare function setDebugLevel(level: number): void; /** * Use USBDK Backend (Windows only) */ export declare function useUsbDkBackend(): void; export declare function _enableHotplugEvents(): void; export declare function _disableHotplugEvents(): void; export declare function _getLibusbCapability(capability: number): number; /** * Restore (re-reference) the hotplug events unreferenced by `unrefHotplugEvents()` */ export declare function refHotplugEvents(): void; /** * Unreference the hotplug events from the event loop, allowing the process to exit even when listening for the `attach` and `detach` events */ export declare function unrefHotplugEvents(): void; /** Represents a USB transfer */ export declare class Transfer { constructor(device: Device, endpointAddr: number, type: number, timeout: number, callback: (error: LibUSBException, buf: Buffer, actual: number) => void); /** * (Re-)submit the transfer. * * @param buffer Buffer where data will be written (for IN transfers) or read from (for OUT transfers). */ submit(buffer: Buffer, callback?: (error: LibUSBException | undefined, buffer: Buffer, actualLength: number) => void): Transfer; /** * Cancel the transfer. * * Returns `true` if the transfer was canceled, `false` if it wasn't in pending state. */ cancel(): boolean; } /** Represents a USB device. */ export declare class Device { /** Integer USB device number */ busNumber: number; /** Integer USB device address */ deviceAddress: number; /** Array containing the USB device port numbers, or `undefined` if not supported on this platform. */ portNumbers: number[]; /** Object with properties for the fields of the device descriptor. */ deviceDescriptor: DeviceDescriptor; _bosDescriptor?: BosDescriptor; __open(): void; __close(): void; __getParent(): Device; __getConfigDescriptor(): ConfigDescriptor; __getAllConfigDescriptors(): ConfigDescriptor[]; __setConfiguration(desired: number, callback: (error?: LibUSBException) => void): void; __clearHalt(addr: number, callback: (error?: LibUSBException) => void): void; __setInterface(addr: number, altSetting: number, callback: (error?: LibUSBException) => void): void; __claimInterface(addr: number): void; __releaseInterface(addr: number, callback: (error?: LibUSBException) => void): void; __detachKernelDriver(addr: number): void; __attachKernelDriver(addr: number): void; __isKernelDriverActive(addr: number): boolean; /** * Performs a reset of the device. Callback is called when complete. * * The device must be open to use this method. * @param callback */ reset(callback: (error?: LibUSBException) => void): void; } /** * In the context of a \ref libusb_device_descriptor "device descriptor", * this bDeviceClass value indicates that each interface specifies its * own class information and all interfaces operate independently. */ export declare const LIBUSB_CLASS_PER_INTERFACE: number; /** Audio class */ export declare const LIBUSB_CLASS_AUDIO: number; /** Communications class */ export declare const LIBUSB_CLASS_COMM: number; /** Human Interface Device class */ export declare const LIBUSB_CLASS_HID: number; /** Printer class */ export declare const LIBUSB_CLASS_PRINTER: number; /** Image class */ export declare const LIBUSB_CLASS_PTP: number; /** Mass storage class */ export declare const LIBUSB_CLASS_MASS_STORAGE: number; /** Hub class */ export declare const LIBUSB_CLASS_HUB: number; /** Data class */ export declare const LIBUSB_CLASS_DATA: number; /** Wireless class */ export declare const LIBUSB_CLASS_WIRELESS: number; /** Application class */ export declare const LIBUSB_CLASS_APPLICATION: number; /** Class is vendor-specific */ export declare const LIBUSB_CLASS_VENDOR_SPEC: number; // libusb_standard_request /** Request status of the specific recipient */ export declare const LIBUSB_REQUEST_GET_STATUS: number; /** Clear or disable a specific feature */ export declare const LIBUSB_REQUEST_CLEAR_FEATURE: number; /** Set or enable a specific feature */ export declare const LIBUSB_REQUEST_SET_FEATURE: number; /** Set device address for all future accesses */ export declare const LIBUSB_REQUEST_SET_ADDRESS: number; /** Get the specified descriptor */ export declare const LIBUSB_REQUEST_GET_DESCRIPTOR: number; /** Used to update existing descriptors or add new descriptors */ export declare const LIBUSB_REQUEST_SET_DESCRIPTOR: number; /** Get the current device configuration value */ export declare const LIBUSB_REQUEST_GET_CONFIGURATION: number; /** Set device configuration */ export declare const LIBUSB_REQUEST_SET_CONFIGURATION: number; /** Return the selected alternate setting for the specified interface */ export declare const LIBUSB_REQUEST_GET_INTERFACE: number; /** Select an alternate interface for the specified interface */ export declare const LIBUSB_REQUEST_SET_INTERFACE: number; /** Set then report an endpoint's synchronization frame */ export declare const LIBUSB_REQUEST_SYNCH_FRAME: number; // libusb_descriptor_type /** Device descriptor. See libusb_device_descriptor. */ export declare const LIBUSB_DT_DEVICE: number; /** Configuration descriptor. See libusb_config_descriptor. */ export declare const LIBUSB_DT_CONFIG: number; /** String descriptor */ export declare const LIBUSB_DT_STRING: number; export declare const LIBUSB_DT_BOS: number; /** Interface descriptor. See libusb_interface_descriptor. */ export declare const LIBUSB_DT_INTERFACE: number; /** Endpoint descriptor. See libusb_endpoint_descriptor. */ export declare const LIBUSB_DT_ENDPOINT: number; /** HID descriptor */ export declare const LIBUSB_DT_HID: number; /** HID report descriptor */ export declare const LIBUSB_DT_REPORT: number; /** Physical descriptor */ export declare const LIBUSB_DT_PHYSICAL: number; /** Hub descriptor */ export declare const LIBUSB_DT_HUB: number; // libusb_endpoint_direction /** In: device-to-host */ export declare const LIBUSB_ENDPOINT_IN: number; /** Out: host-to-device */ export declare const LIBUSB_ENDPOINT_OUT: number; // libusb_transfer_type /** Control endpoint */ export declare const LIBUSB_TRANSFER_TYPE_CONTROL: number; /** Isochronous endpoint */ export declare const LIBUSB_TRANSFER_TYPE_ISOCHRONOUS: number; /** Bulk endpoint */ export declare const LIBUSB_TRANSFER_TYPE_BULK: number; /** Interrupt endpoint */ export declare const LIBUSB_TRANSFER_TYPE_INTERRUPT: number; // libusb_iso_sync_type /** No synchronization */ export declare const LIBUSB_ISO_SYNC_TYPE_NONE: number; /** Asynchronous */ export declare const LIBUSB_ISO_SYNC_TYPE_ASYNC: number; /** Adaptive */ export declare const LIBUSB_ISO_SYNC_TYPE_ADAPTIVE: number; /** Synchronous */ export declare const LIBUSB_ISO_SYNC_TYPE_SYNC: number; // libusb_iso_usage_type /** Data endpoint */ export declare const LIBUSB_ISO_USAGE_TYPE_DATA: number; /** Feedback endpoint */ export declare const LIBUSB_ISO_USAGE_TYPE_FEEDBACK: number; /** Implicit feedback Data endpoint */ export declare const LIBUSB_ISO_USAGE_TYPE_IMPLICIT: number; // libusb_transfer_status /** * Transfer completed without error. Note that this does not indicate * that the entire amount of requested data was transferred. */ export declare const LIBUSB_TRANSFER_COMPLETED: number; /** Transfer failed */ export declare const LIBUSB_TRANSFER_ERROR: number; /** Transfer timed out */ export declare const LIBUSB_TRANSFER_TIMED_OUT: number; /** Transfer was cancelled */ export declare const LIBUSB_TRANSFER_CANCELLED: number; /** * For bulk/interrupt endpoints: halt condition detected (endpoint * stalled). For control endpoints: control request not supported. */ export declare const LIBUSB_TRANSFER_STALL: number; /** Device was disconnected */ export declare const LIBUSB_TRANSFER_NO_DEVICE: number; /** Device sent more data than requested */ export declare const LIBUSB_TRANSFER_OVERFLOW: number; // libusb_transfer_flags /** Report short frames as errors */ export declare const LIBUSB_TRANSFER_SHORT_NOT_OK: number; /** * Automatically free() transfer buffer during libusb_free_transfer(). * Note that buffers allocated with libusb_dev_mem_alloc() should not * be attempted freed in this way, since free() is not an appropriate * way to release such memory. */ export declare const LIBUSB_TRANSFER_FREE_BUFFER: number; /** * Automatically call libusb_free_transfer() after callback returns. * If this flag is set, it is illegal to call libusb_free_transfer() * from your transfer callback, as this will result in a double-free * when this flag is acted upon. */ export declare const LIBUSB_TRANSFER_FREE_TRANSFER: number; // libusb_request_type /** Standard */ export declare const LIBUSB_REQUEST_TYPE_STANDARD: number; /** Class */ export declare const LIBUSB_REQUEST_TYPE_CLASS: number; /** Vendor */ export declare const LIBUSB_REQUEST_TYPE_VENDOR: number; /** Reserved */ export declare const LIBUSB_REQUEST_TYPE_RESERVED: number; // libusb_request_recipient /** Device */ export declare const LIBUSB_RECIPIENT_DEVICE: number; /** Interface */ export declare const LIBUSB_RECIPIENT_INTERFACE: number; /** Endpoint */ export declare const LIBUSB_RECIPIENT_ENDPOINT: number; /** Other */ export declare const LIBUSB_RECIPIENT_OTHER: number; export declare const LIBUSB_CONTROL_SETUP_SIZE: number; export declare const LIBUSB_DT_BOS_SIZE: number; // libusb_capability export declare const LIBUSB_CAP_HAS_CAPABILITY: number; export declare const LIBUSB_CAP_HAS_HOTPLUG: number; export declare const LIBUSB_CAP_HAS_HID_ACCESS: number; export declare const LIBUSB_CAP_SUPPORTS_DETACH_KERNEL_DRIVER: number; // libusb_error /** Input/output error */ export declare const LIBUSB_ERROR_IO: number; /** Invalid parameter */ export declare const LIBUSB_ERROR_INVALID_PARAM: number; /** Access denied (insufficient permissions) */ export declare const LIBUSB_ERROR_ACCESS: number; /** No such device (it may have been disconnected) */ export declare const LIBUSB_ERROR_NO_DEVICE: number; /** Entity not found */ export declare const LIBUSB_ERROR_NOT_FOUND: number; /** Resource busy */ export declare const LIBUSB_ERROR_BUSY: number; /** Operation timed out */ export declare const LIBUSB_ERROR_TIMEOUT: number; /** Overflow */ export declare const LIBUSB_ERROR_OVERFLOW: number; /** Pipe error */ export declare const LIBUSB_ERROR_PIPE: number; /** System call interrupted (perhaps due to signal) */ export declare const LIBUSB_ERROR_INTERRUPTED: number; /** Insufficient memory */ export declare const LIBUSB_ERROR_NO_MEM: number; /** Operation not supported or unimplemented on this platform */ export declare const LIBUSB_ERROR_NOT_SUPPORTED: number; /** Other error */ export declare const LIBUSB_ERROR_OTHER: number;
the_stack
import * as chaiAsPromised from "chai-as-promised"; import * as chai from "chai"; chai.use(chaiAsPromised); const { expect } = chai; import { ReadableStream, Stream, Transform, batcher, mapper, compose, } from "../lib/index"; import "./mocha-init"; import { defer, delay, settle, track, readInto, identity } from "./util"; import { useFakeTimers } from "sinon"; describe("Transform", () => { let s: Stream<number>; let abortError: Error; let boomError: Error; let sinonClock: ReturnType<typeof useFakeTimers>; before(() => { sinonClock = useFakeTimers(); }); beforeEach(() => { s = new Stream<number>(); abortError = new Error("Test stream explicitly aborted"); boomError = new Error("Test error"); }); after(() => { sinonClock.restore(); }); describe("compose()", () => { it("composes stream transformations", async () => { const source = Stream.from([1, 2, 3, 4]); const mapperA = mapper((val: number) => val % 2 === 0); const mapperB = mapper((val: boolean) => (val ? "Even" : "Odd")); const composedTransformA = compose(mapperA, mapperB); // @ts-expect-error const composedTransformB = compose(mapperB, mapperA); const dest = await source.transform(composedTransformA).toArray(); expect(dest).to.deep.equal(["Odd", "Even", "Odd", "Even"]); }); }); describe("batch()", () => { const batchResults: number[][] = []; beforeEach(() => batchResults.splice(0)); /** * Run an async function, advance the sinon mocked clock until the function resolves, * and then return the function's promise. * * This avoids the need to explicitly advance the clock. * * @param fn A test function */ function clockwise(fn: () => Promise<void>) { return async () => { const fnPromise = fn(); await Promise.all([sinonClock.runAllAsync(), fnPromise]); }; } function pipeWithDelay( readableStream: ReadableStream<{ value: number; workTime?: number; wait?: number; abort?: boolean; throwError?: boolean; }> ) { const stream = readableStream.map(async (item) => { const { wait } = item; if (wait !== undefined) { await delay(wait); } return item; }); return stream; } async function resolveBatchToAsyncValues( readableStream: ReadableStream< { value: number; workTime?: number; wait?: number; abort?: boolean; throwError?: boolean; }[] > ) { return readableStream .map(async (batch) => { const isDelay = !!batch.find( ({ workTime }) => workTime !== undefined ); const isError = !!batch.find( ({ throwError }) => !!throwError ); if (isError) { throw boomError; } const isAbort = !!batch.find(({ abort }) => !!abort); if (isAbort) { readableStream.abort(abortError); } if (isDelay) { const totalDelay = batch.reduce( (acc, { workTime }) => acc + (workTime || 0), 0 ); await delay(totalDelay); } return batch.map(({ value }) => value); }) .toArray(); } it("passes the example test from docs", async () => { const batchedStream = Stream.from([1, 2, 3, 4, 5]).transform( batcher(2) ); const result = await batchedStream.toArray(); expect(result).to.deep.equal([[1, 2], [3, 4], [5]]); }); it("batches values", async () => { const batched = s.transform(batcher(2)); const toWrite = [1, 2, 3]; const writes = [ ...toWrite.map((n) => track(s.write(n))), track(s.end()), ]; readInto(batched, batchResults); await s.result(); expect(batchResults).to.deep.equal([[1, 2], [3]]); writes.forEach((write) => expect(write.isFulfilled).to.equal(true)); }); it( "applies backpressure", clockwise(async () => { const batched = s.transform(batcher(2)); const toWrite = [1, 2, 3]; const writes = [ ...toWrite.map((n) => track(s.write(n))), track(s.end()), ]; const resolvers: (() => void)[] = []; batched.forEach(async (value) => { const deferred = defer(); resolvers.push(deferred.resolve); await deferred.promise; batchResults.push(value); }); await delay(1); expect(batchResults).to.deep.equal([]); resolvers[0](); await settle([writes[0].promise, writes[1].promise]); expect(batchResults).to.deep.equal([[1, 2]]); expect(writes[2].isPending).to.equal(true); await delay(1); resolvers[1](); await settle([writes[3].promise]); expect(writes[2].isFulfilled).to.equal(true); expect(writes[3].isFulfilled).to.equal(true); }) ); it("with `minBatchSize`, forms batch if write not pending", async () => { const source = Stream.from([ { value: 1, }, { value: 2, }, { value: 3, }, ]); const batched = source.transform(batcher(3, { minBatchSize: 2 })); const dest = await resolveBatchToAsyncValues(batched); expect(dest).to.deep.equal([[1, 2], [3]]); }); it("with `handleError`, can suppress errors in a flush", async () => { s.write(1); s.write(2); s.write(3); s.end(); let captured: Error | undefined; const failedWrites: number[][] = []; const batched = s.transform( batcher(2, { handleError: (e, batch) => { captured = e; failedWrites.push(batch); }, }) ); await batched.forEach(() => { throw boomError; }); expect(captured).to.equal(boomError); expect(failedWrites).to.deep.equal([[1, 2], [3]]); }); it("with `handleError`, can suppress errors in an early flush", async () => { s.write(1); s.write(2); s.write(3); s.end(); let captured: Error | undefined; const failedWrites: number[][] = []; const batched = s.transform( batcher(2, { minBatchSize: 1, handleError: (e, batch) => { captured = e; failedWrites.push(batch); }, }) ); await batched.forEach(() => { throw boomError; }); expect(captured).to.equal(boomError); expect(failedWrites).to.deep.equal([[1], [2, 3]]); }); it( "with `handleError`, can re-throw errors in any flush", clockwise(async () => { let captured: Error | undefined; const failedWrites: number[][] = []; const confirmedError1 = new Error("Yep, that’s an error"); const confirmedError2 = new Error( "This is for sure an error, too" ); const toThrowFromErrorHandler = [ confirmedError1, confirmedError2, ]; const batched = s.transform( batcher(2, { flushTimeout: 1, handleError: async (e, batch) => { captured = e; failedWrites.push(batch); throw toThrowFromErrorHandler.shift(); }, }) ); async function doWrites() { expect(s.write(1)).to.eventually.equal(undefined); await delay(2); // Trigger early flush expect(s.write(2)).to.eventually.rejectedWith( confirmedError1 ); // Catching the error thrown by the early flush expect(s.write(3)).to.eventually.rejectedWith( confirmedError2 ); // Catching the error of the next, normal flush expect(s.end()).to.eventually.equal(undefined); } const writePromise = doWrites(); const readPromise = batched.forEach(async () => { throw boomError; }); await Promise.all([writePromise, readPromise]); expect(captured).to.equal(boomError); expect(failedWrites).to.deep.equal([[1], [2, 3]]); }) ); it( "applies backpressure to a `maxBatchSize` write from a `minBatchSize` write", clockwise(async () => { const batched = s.transform(batcher(2, { minBatchSize: 1 })); const toWrite = [1, 2, 3]; const writes = [ ...toWrite.map((n) => track(s.write(n))), track(s.end()), ]; const resolvers: (() => void)[] = []; batched.forEach(async (value) => { const deferred = defer(); resolvers.push(deferred.resolve); await deferred.promise; batchResults.push(value); }); await delay(1); expect(batchResults).to.deep.equal([]); expect(writes[0].isFulfilled).to.equal(true); // Commenced silently expect(writes[1].isFulfilled).to.equal(true); // Added to the queue expect(writes[2].isFulfilled).to.equal(false); // Triggers a batch write which can't begin yet expect(resolvers[1]).to.equal(undefined); resolvers[0](); await delay(1); expect(writes[2].isFulfilled).to.equal(false); // Batch write still can't finish, but... expect(resolvers[1]).not.to.equal(undefined); // It's started! resolvers[1](); await delay(1); expect(writes[2].isFulfilled).to.equal(true); // Now the batch write is finished... expect(writes[3].isFulfilled).to.equal(true); // And the stream can end }) ); it( "Can write two `minBatchSize` batches back-to-back without needing to be triggered by write() or end()", clockwise(async () => { async function doWrite() { s.write(1); s.write(2); s.write(3); s.write(4); await delay(10); s.end(); } const batched = s.transform(batcher(5, { minBatchSize: 2 })); const resolvers: (() => void)[] = []; batched.forEach(async (batch) => { const deferred = defer(); resolvers.push(deferred.resolve); await deferred.promise; batchResults.push(batch); }); doWrite(); await delay(1); expect(resolvers.length).to.equal(1); resolvers[0](); await delay(1); expect(batchResults).to.deep.equal([[1, 2]]); expect(resolvers.length).to.equal(2); resolvers[1](); await delay(1); expect(batchResults).to.deep.equal([ [1, 2], [3, 4], ]); expect(batched.isEndingOrEnded()).to.equal(false); await batched.result(); }) ); it( "forms batch not exceeding `maxBatchSize` if a batch write is pending", clockwise(async () => { const source = Stream.from([ { value: 1, }, { value: 2, workTime: 1, }, { value: 3, }, { value: 4, }, { value: 5, workTime: 2, }, { value: 6, }, { value: 7, wait: 3, }, { value: 8, }, ]); const batched = pipeWithDelay(source).transform( batcher(3, { minBatchSize: 2 }) ); const destAsync = resolveBatchToAsyncValues(batched); const dest = await destAsync; expect(dest).to.deep.equal([ [1, 2], // Min batch size (this will take 1ms to write) [3, 4, 5], // Max batch size streams in while first batch is writing (this will take 2ms to write) [6, 7], // Min batch size (7 arrives after a 3ms delay so the previous batch is processed and the new // batch is completed) [8], // Processed alone when stream ends ]); }) ); type FlushErrorTestCase = | "first element" | "second element" | "both elements"; function conditionalThrow(testCase: FlushErrorTestCase) { return async (batch: number[]) => { const [item] = batch; if (testCase === "both elements") { throw boomError; } else if (testCase === "first element" && item === 1) { throw boomError; } else if (testCase === "second element" && item === 2) { throw boomError; } }; } describe("error cases", () => { async function doWrites() { try { await s.write(1); await delay(2); await s.write(2); } finally { // Pass Promise.resolve() to end() to cause the downstream result to depend // on this (resolved) promise, instead of the promise rejection that is expected. await s.end(undefined, Promise.resolve()); } } for (const testCase of [ "first element", "second element", "both elements", ] as FlushErrorTestCase[]) { it( `bounces error - ${testCase}`, clockwise(async () => { let isAborted = false; s.aborted().catch(() => (isAborted = true)); const batched = s.transform(batcher(1)); await Promise.all([ batched.forEach(conditionalThrow(testCase)), expect(doWrites()).rejectedWith(boomError), ]); expect(isAborted).to.equal(false); }) ); it( `bounces error from \`minBatchSize\` batch - ${testCase}`, clockwise(async () => { let isAborted = false; s.aborted().catch(() => (isAborted = true)); const batched = s.transform( batcher(2, { minBatchSize: 1 }) ); await Promise.all([ batched.forEach(conditionalThrow(testCase)), expect(doWrites()).rejectedWith(boomError), ]); expect(isAborted).to.equal(false); }) ); it( `bounces error from \`flushTimeout\` batch - ${testCase}`, clockwise(async () => { let isAborted = false; s.aborted().catch(() => (isAborted = true)); const batched = s.transform( batcher(2, { flushTimeout: 1 }) ); await Promise.all([ batched.forEach(conditionalThrow(testCase)), expect(doWrites()).rejectedWith(boomError), ]); expect(isAborted).to.equal(false); }) ); it( `bounces error from stream end batch - ${testCase}`, clockwise(async () => { let isAborted = false; s.aborted().catch(() => (isAborted = true)); const batched = s.transform(batcher(2)); async function doLongerWrites() { try { await s.write(1); await s.write(1); await s.write(2); } finally { // Pass Promise.resolve() to end() to cause the downstream result to depend // on this (resolved) promise, instead of the promise rejection that is expected. await s.end(undefined, Promise.resolve()); } } await Promise.all([ batched.forEach(conditionalThrow(testCase)), expect(doLongerWrites()).rejectedWith(boomError), ]); expect(isAborted).to.equal(false); }) ); } }); it( "writes any queued items after a duration from the last read if timeout is provided", clockwise(async () => { const source = Stream.from([ { value: 1, }, { wait: 3, value: 2, }, { wait: 1, value: 3, }, { value: 4, }, { value: 5, }, { wait: 3, value: 6, }, { value: 7, }, ]); const batched = pipeWithDelay(source).transform( batcher(3, { flushTimeout: 2 }) ); const dest = await resolveBatchToAsyncValues(batched); expect(dest).to.deep.equal([ [1], // Processed alone because timeout fires before 2 comes in [2, 3, 4], // Processed together because they arrived within the same window // and form a batch (3 arrives after 1ms delay which is within // 2ms timeout) [5], // Processed alone because timeout fires [6, 7], // Processed as short batch because stream ends ]); }) ); it( "on abort, all writes fail with abort, including writes still in the queue", clockwise(async () => { async function doWrites() { await expect(s.write(1)).to.eventually.equal(undefined); await expect(s.write(2)).to.eventually.equal(undefined); await expect(s.write(3)).to.eventually.equal(undefined); await delay(2); await expect(s.end()).to.eventually.rejectedWith( abortError ); } const writePromise = doWrites(); const batched = s.transform(batcher(2)); const listener = batched.map((batch) => batchResults.push(batch) ); const readPromise = expect( listener.toArray() ).to.eventually.rejectedWith(abortError); await delay(1); s.abort(abortError); await Promise.all([writePromise, readPromise]); expect(batchResults).to.deep.equal([[1, 2]]); }) ); it( "waits for source stream to end", clockwise(async () => { const d = defer(); const slowEndingSource = s.transform<number>( (readable, writable) => { readable.forEach( (v) => writable.write(v), (error?: Error) => { writable.end(error, readable.result()); return d.promise; } ); } ); const writes = [ track(s.write(1)), track(s.write(2)), track(s.end()), ]; const batched = slowEndingSource.transform(batcher(1)); const mres = track(batched.result()); readInto(batched, batchResults); await settle([writes[0].promise, writes[1].promise]); expect(batchResults).to.deep.equal([[1], [2]]); expect(writes[0].isFulfilled).to.equal(true); expect(writes[1].isFulfilled).to.equal(true); expect(writes[2].isFulfilled).to.equal(false); expect(mres.isFulfilled).to.equal(false); d.resolve(); await settle([mres.promise]); expect(writes[2].isFulfilled).to.equal(true); }) ); it( "waits for destination stream to end", clockwise(async () => { const d = defer(); const slowEnder: Transform<number[], number[]> = ( readable, writable ) => { readable.forEach( (v) => writable.write(v), (error?: Error) => { writable.end(error, readable.result()); return d.promise; } ); }; const w1 = track(s.write(1)); const w2 = track(s.write(2)); const we = track(s.end()); const batched = s.transform(batcher(1)); const mres = track(batched.result()); const slowed = batched.transform(slowEnder); const sres = track(slowed.result()); await readInto(slowed, batchResults); expect(batchResults).to.deep.equal([[1], [2]]); expect(w1.isFulfilled).to.equal(true); expect(w2.isFulfilled).to.equal(true); expect(we.isFulfilled).to.equal(false); expect(mres.isFulfilled).to.equal(false); expect(sres.isFulfilled).to.equal(false); d.resolve(); await settle([mres.promise, sres.promise]); }) ); it("aborts from source to sink", async () => { const sink = s.transform(batcher(1)).map(identity); const ab = track(sink.aborted()); s.abort(abortError); await settle([ab.promise]); expect(ab.reason).to.equal(abortError); }); it("aborts from sink to source", async () => { const ab = track(s.aborted()); const sink = s.transform(batcher(1)).map(identity); sink.abort(abortError); await settle([ab.promise]); expect(ab.reason).to.equal(abortError); }); }); // batch() });
the_stack
import { DateTime } from "luxon"; import { Collection } from "mongodb"; import { MongoContext } from "coral-server/data/context"; import { CommentNotFoundError } from "coral-server/errors"; import { addCommentTag, Comment, CommentConnectionInput, removeCommentTag, retrieveAllCommentsUserConnection as retrieveAllCommentsUserConnectionModel, retrieveComment as retrieveCommentModel, retrieveCommentConnection as retrieveCommentConnectionModel, retrieveCommentParentsConnection as retrieveCommentParentsConnectionModel, retrieveCommentRepliesConnection as retrieveCommentRepliesConnectionModel, retrieveCommentStoryConnection as retrieveCommentStoryConnectionModel, retrieveCommentUserConnection as retrieveCommentUserConnectionModel, retrieveManyComments as retrieveManyCommentModels, retrieveRejectedCommentUserConnection as retrieveRejectedCommentUserConnectionModel, } from "coral-server/models/comment"; import { getLatestRevision } from "coral-server/models/comment/helpers"; import { Connection } from "coral-server/models/helpers"; import { Tenant } from "coral-server/models/tenant"; import { User } from "coral-server/models/user"; import { GQLTAG } from "coral-server/graph/schema/__generated__/types"; export function getCollection( mongo: MongoContext, isArchived?: boolean ): Collection<Readonly<Comment>> { return isArchived && mongo.archive ? mongo.archivedComments() : mongo.comments(); } /** * getCommentEditableUntilDate will return the date that the given comment is * still editable until. * * @param tenant the tenant that contains settings related editing * @param createdAt the date that is the base, defaulting to the current time */ export function getCommentEditableUntilDate( tenant: Pick<Tenant, "editCommentWindowLength">, createdAt: Date ): Date { return DateTime.fromJSDate(createdAt) .plus({ seconds: tenant.editCommentWindowLength }) .toJSDate(); } /** * addTag will add a tag to the comment. * * @param mongo is the mongo context. * @param tenant is the filtering tenant for this operation. * @param commentID is the comment we are adding a tag to. * @param commentRevisionID is the revision of the comment we are tagging. * @param user is the user adding this tag. * @param tagType is the type of tag we are adding. * @param now is the time this tag was added. * @returns the modified comment with the newly added tag. */ export async function addTag( mongo: MongoContext, tenant: Tenant, commentID: string, commentRevisionID: string, user: User, tagType: GQLTAG, now = new Date() ) { const comment = await retrieveCommentModel( mongo.comments(), tenant.id, commentID ); if (!comment) { throw new CommentNotFoundError(commentID); } // Check to see if the selected comment revision is the latest one. const revision = getLatestRevision(comment); if (revision.id !== commentRevisionID) { throw new Error("revision id does not match latest revision"); } // Check to see if this tag is already on this comment. if (comment.tags.some(({ type }) => type === tagType)) { return comment; } return addCommentTag(mongo, tenant.id, commentID, { type: tagType, createdBy: user.id, createdAt: now, }); } /** * removeTag will remove a specific tag type from a comment. * * @param mongo is the mongo context. * @param tenant is the filtering tenant for this operation. * @param commentID is the comment identifier we are removing the tag from. * @param tagType is the tag type to remove. * @returns the comment with the updated tag attributes. */ export async function removeTag( mongo: MongoContext, tenant: Tenant, commentID: string, tagType: GQLTAG ) { const comment = await retrieveCommentModel( mongo.comments(), tenant.id, commentID ); if (!comment) { throw new CommentNotFoundError(commentID); } // Check to see if this tag is even on this comment. if (comment.tags.every(({ type }) => type !== tagType)) { return comment; } return removeCommentTag(mongo, tenant.id, commentID, tagType); } /** * retrieves a comment from the mongo context. If archiving is enabled and it * cannot find the comment within the live comments, it will try and find it in * the archived comments. * * @param mongo is the mongo context. * @param tenantID is the filtering tenant for this comment. * @param id is the identifier of the comment we want to retrieve. * @param skipArchive if set will not attempt to search the archive for the * comment if it can't find the comment in the live comments. * @returns the requested comment or null if not found. */ export async function retrieveComment( mongo: MongoContext, tenantID: string, id: string, skipArchive?: boolean ) { const liveComment = await retrieveCommentModel( mongo.comments(), tenantID, id ); if (liveComment) { return liveComment; } const archivedComments = mongo.archivedComments(); if (mongo.archive && !skipArchive && archivedComments) { const archivedComment = await retrieveCommentModel( archivedComments, tenantID, id ); return archivedComment; } return null; } /** * retrieves many comments from mongo. This will search both live and archived * comments if the archive database is available. * * @param mongo is the mongo context used to retrieve comments from. * @param tenantID is the filtering tenant for this comment set. * @param ids are the ids of the comments we want to retrieve. * @returns an array of comments. */ export async function retrieveManyComments( mongo: MongoContext, tenantID: string, ids: ReadonlyArray<string> ) { if (ids.length === 0) { return []; } const liveComments = await retrieveManyCommentModels( mongo.comments(), tenantID, ids ); if (liveComments.length > 0 && liveComments.some((c) => c !== null)) { return liveComments; } // Otherwise, try and find it in the archived comments collection if (mongo.archive) { const archived = await retrieveManyCommentModels( mongo.archivedComments(), tenantID, ids ); return archived; } return []; } /** * retrieves a comment connection for the provided input. * * @param mongo is the mongo context used to retrieve the comments. * @param tenantID is the filtering tenant id for this connection. * @param input is the filtered input to determine which comments to * include in the connection. * @param isArchived is whether this connection should retrieve from * the live or the archived comments databases. * @returns a connection of comments. */ export async function retrieveCommentConnection( mongo: MongoContext, tenantID: string, input: CommentConnectionInput, isArchived?: boolean ): Promise<Readonly<Connection<Readonly<Comment>>>> { const collection = getCollection(mongo, isArchived); return retrieveCommentConnectionModel(collection, tenantID, input); } /** * retrieves a comment connection for the provided input specific to a user. * * @param mongo is the mongo context used to retrieve the comments. * @param tenantID is the filtering tenant id for this connection. * @param input is the filtered input to determine which comments to * include in the connection. * @param isArchived is whether this connection should retrieve from * the live or the archived comments databases. * @returns a connection of comments. */ export function retrieveCommentUserConnection( mongo: MongoContext, tenantID: string, userID: string, input: CommentConnectionInput, isArchived?: boolean ) { const collection = getCollection(mongo, isArchived); return retrieveCommentUserConnectionModel( collection, tenantID, userID, input ); } /** * retrieves a comment connection for all comments associated with a user. * * @param mongo is the mongo context used to retrieve the comments. * @param tenantID is the filtering tenant id for this connection. * @param input is the filtered input to determine which comments to * include in the connection. * @param isArchived is whether this connection should retrieve from * the live or the archived comments databases. * @returns a connection of comments. */ export function retrieveAllCommentsUserConnection( mongo: MongoContext, tenantID: string, userID: string, input: CommentConnectionInput, isArchived?: boolean ) { const collection = getCollection(mongo, isArchived); return retrieveAllCommentsUserConnectionModel( collection, tenantID, userID, input ); } /** * retrieves a comment connection for the rejected comments of a user. * * @param mongo is the mongo context used to retrieve the comments. * @param tenantID is the filtering tenant id for this connection. * @param input is the filtered input to determine which comments to * include in the connection. * @param isArchived is whether this connection should retrieve from * the live or the archived comments databases. * @returns a connection of comments. */ export function retrieveRejectedCommentUserConnection( mongo: MongoContext, tenantID: string, userID: string, input: CommentConnectionInput ) { // Rejected comments always come from the live // and never from archived, we don't load mod queues // from the archive const collection = mongo.comments(); return retrieveRejectedCommentUserConnectionModel( collection, tenantID, userID, input ); } /** * retrieves a comment connection for a specific story. * * @param mongo is the mongo context used to retrieve the comments. * @param tenantID is the filtering tenant id for this connection. * @param storyID is the story we are retrieving comments for. * @param input is the filtered input to determine which comments to * include in the connection. * @param isArchived is whether this connection should retrieve from * the live or the archived comments databases. * @returns a connection of comments. */ export function retrieveCommentStoryConnection( mongo: MongoContext, tenantID: string, storyID: string, input: CommentConnectionInput, isArchived?: boolean ) { const collection = getCollection(mongo, isArchived); return retrieveCommentStoryConnectionModel( collection, tenantID, storyID, input ); } /** * retrieves a comment connection for the replies to a certain comment. * * @param mongo is the mongo context used to retrieve the comments. * @param tenantID is the filtering tenant id for this connection. * @param storyID is the story we are retrieving comments for. * @param parentID is the parent comment we are retrieving replies for. * @param input is the filtered input to determine which comments to * include in the connection. * @param isArchived is whether this connection should retrieve from * the live or the archived comments databases. * @returns a connection of comments. */ export function retrieveCommentRepliesConnection( mongo: MongoContext, tenantID: string, storyID: string, parentID: string, input: CommentConnectionInput, isArchived?: boolean ) { const collection = getCollection(mongo, isArchived); return retrieveCommentRepliesConnectionModel( collection, tenantID, storyID, parentID, input ); } /** * retrieves the parent comments for a comment. * * @param mongo is the mongo context we retrieve comments from. * @param tenantID is the filtering tenant for these comments. * @param comment is the comment we want to find parents for. * @param paginationParameters are the pagination sort/select options. * @param isArchived is whether this connection should retrieve from * the live or the archived comments databases. * @returns a connection of comments. */ export function retrieveCommentParentsConnection( mongo: MongoContext, tenantID: string, comment: Comment, paginationParameters: { last: number; before?: number }, isArchived?: boolean ) { const collection = isArchived && mongo.archive ? mongo.archivedComments() : mongo.comments(); return retrieveCommentParentsConnectionModel( collection, tenantID, comment, paginationParameters ); }
the_stack
import { Server } from "@server/index"; import { FileSystem } from "@server/fileSystem"; import { Queue } from "@server/databases/server/entity/Queue"; import { ValidTapback } from "@server/types"; import { sendMessage, startChat, renameGroupChat, addParticipant, removeParticipant, toggleTapback, checkTypingIndicator, exportContacts, restartMessages, openChat, sendMessageFallback } from "@server/fileSystem/scripts"; import { ValidRemoveTapback } from "../types"; import { safeExecuteAppleScript, generateChatNameList, getiMessageNumberFormat, tapbackUIMap, toBoolean, slugifyAddress } from "./utils"; /** * This class handles all actions that require an AppleScript execution. * Pretty much, using command line to execute a script, passing any required * variables */ export class ActionHandler { /** * Sends a message by executing the sendMessage AppleScript * * @param chatGuid The GUID for the chat * @param message The message to send * @param attachmentName The name of the attachment to send (optional) * @param attachment The bytes (buffer) for the attachment * * @returns The command line response */ static sendMessage = async ( tempGuid: string, chatGuid: string, message: string, attachmentGuid?: string, attachmentName?: string, attachment?: Uint8Array ): Promise<void> => { if (!chatGuid) throw new Error("No chat GUID provided"); // Add attachment, if present if (attachment) { FileSystem.saveAttachment(attachmentName, attachment); } try { // Make sure messages is open await FileSystem.startMessages(); // We need offsets here due to iMessage's save times being a bit off for some reason const now = new Date(new Date().getTime() - 10000).getTime(); // With 10 second offset // Try to send the iMessage try { await FileSystem.executeAppleScript( sendMessage( chatGuid, message ?? "", attachment ? `${FileSystem.attachmentsDir}/${attachmentName}` : null ) ); } catch (ex: any) { // Log the actual error Server().log(ex); const errMsg = (ex?.message ?? "") as string; const retry = errMsg.toLowerCase().includes("timed out") || errMsg.includes("1002"); if (retry) { // If it's a plain ole retry case, retry after restarting Messages Server().log("Message send error. Trying to re-send message..."); await FileSystem.executeAppleScript(restartMessages()); await FileSystem.executeAppleScript( sendMessage( chatGuid, message ?? "", attachment ? `${FileSystem.attachmentsDir}/${attachmentName}` : null ) ); } else if (errMsg.includes("-1728") && chatGuid.includes(";-;")) { // If our error has to do with not getting the chat ID, run the fallback script Server().log("Message send error (can't get chat id). Running fallback send script..."); await FileSystem.executeAppleScript( sendMessageFallback( chatGuid, message ?? "", attachment ? `${FileSystem.attachmentsDir}/${attachmentName}` : null ) ); } } // Add queued item if (message && message.length > 0) { const item = new Queue(); item.tempGuid = tempGuid; item.chatGuid = chatGuid; item.dateCreated = now; item.text = message ?? ""; await Server().repo.queue().manager.save(item); } // If there is an attachment, add that to the queue too if (attachment && attachmentName) { const attachmentItem = new Queue(); attachmentItem.tempGuid = attachmentGuid; attachmentItem.chatGuid = chatGuid; attachmentItem.dateCreated = now; attachmentItem.text = `${attachmentGuid}->${attachmentName}`; await Server().repo.queue().manager.save(attachmentItem); } } catch (ex: any) { let msg = ex.message; if (msg instanceof String) { [, msg] = msg.split("execution error: "); [msg] = msg.split(". ("); } Server().log(msg, "warn"); throw new Error(msg); } }; /** * Renames a group chat via an AppleScript * * @param chatGuid The GUID for the chat * @param newName The new name for the group * * @returns The command line response */ static renameGroupChat = async (chatGuid: string, newName: string): Promise<string> => { Server().log(`Executing Action: Rename Group (Chat: ${chatGuid}; Name: ${newName})`, "debug"); const names = await generateChatNameList(chatGuid); /** * Above, we calculate 2 different names. One as-is, returned by the chat query, and one * ordered by the chat_handle_join table insertions. Below, we try to try to find the * corresponding chats, and rename them. If the first name fails to be found, * we are going to try and use the backup (second) name. If both failed, we weren't able to * calculate the correct chat name */ // Make sure messages is restarted to prevent accessibility issues await FileSystem.executeAppleScript(restartMessages()); let err = null; for (const oldName of names) { console.info(`Attempting rename group from [${oldName}] to [${newName}]`); try { // This needs await here, or else it will fail return await safeExecuteAppleScript(renameGroupChat(oldName, newName)); } catch (ex: any) { err = ex; Server().log(`Failed to rename group from [${oldName}] to [${newName}]. Trying again.`, "warn"); continue; } } // If we get here, there was an issue throw err; }; static privateRenameGroupChat = async (chatGuid: string, newName: string): Promise<void> => { const enablePrivateApi = Server().repo.getConfig("enable_private_api") as boolean; if (!enablePrivateApi) { Server().log("Private API disabled! Not executing group rename..."); return; } Server().log(`Executing Action: Changing chat display name (Chat: ${chatGuid}; NewName: ${newName};)`, "debug"); Server().privateApiHelper.setDisplayName(chatGuid, newName); }; /** * Adds a participant using an AppleScript * * @param chatGuid The GUID for the chat * @param participant The paticipant to add * * @returns The command line response */ static addParticipant = async (chatGuid: string, participant: string): Promise<string> => { Server().log(`Executing Action: Add Participant (Chat: ${chatGuid}; Participant: ${participant})`, "debug"); const names = await generateChatNameList(chatGuid); /** * Above, we calculate 2 different names. One as-is, returned by the chat query, and one * ordered by the chat_handle_join table insertions. Below, we try to try to find the * corresponding chats, and rename them. If the first name fails to be found, * we are going to try and use the backup (second) name. If both failed, we weren't able to * calculate the correct chat name */ // Make sure messages is restarted to prevent accessibility issues await FileSystem.executeAppleScript(restartMessages()); let err = null; for (const name of names) { console.info(`Attempting to add participant to group [${name}]`); try { // This needs await here, or else it will fail return await safeExecuteAppleScript(addParticipant(name, participant)); } catch (ex: any) { err = ex; Server().log(`Failed to add participant to group, [${name}]. Trying again.`, "warn"); continue; } } // If we get here, there was an issue throw err; }; /** * Removes a participant using an AppleScript * * @param chatGuid The GUID for the chat * @param participant The paticipant to remove * * @returns The command line response */ static removeParticipant = async (chatGuid: string, participant: string): Promise<string> => { Server().log(`Executing Action: Remove Participant (Chat: ${chatGuid}; Participant: ${participant})`, "debug"); const names = await generateChatNameList(chatGuid); let address = participant; if (!address.includes("@")) { address = getiMessageNumberFormat(address); } /** * Above, we calculate 2 different names. One as-is, returned by the chat query, and one * ordered by the chat_handle_join table insertions. Below, we try to try to find the * corresponding chats, and rename them. If the first name fails to be found, * we are going to try and use the backup (second) name. If both failed, we weren't able to * calculate the correct chat name */ // Make sure messages is restarted to prevent accessibility issues await FileSystem.executeAppleScript(restartMessages()); let err = null; for (const name of names) { console.info(`Attempting to remove participant from group [${name}]`); try { // This needs await here, or else it will fail return await safeExecuteAppleScript(removeParticipant(name, participant)); } catch (ex: any) { err = ex; Server().log(`Failed to remove participant to group, [${name}]. Trying again.`, "warn"); continue; } } // If we get here, there was an issue throw err; }; /** * Opens a chat in iMessage * * @param chatGuid The GUID for the chat * * @returns The command line response */ static openChat = async (chatGuid: string): Promise<string> => { Server().log(`Executing Action: Open Chat (Chat: ${chatGuid})`, "debug"); const chats = await Server().iMessageRepo.getChats({ chatGuid, withParticipants: true, withSMS: true }); if (!chats || chats.length === 0) throw new Error("Chat does not exist"); if (chats[0].participants.length > 1) throw new Error("Chat is a group chat"); const names = await generateChatNameList(chatGuid); /** * Above, we calculate 2 different names. One as-is, returned by the chat query, and one * ordered by the chat_handle_join table insertions. Below, we try to try to find the * corresponding chats, and rename them. If the first name fails to be found, * we are going to try and use the backup (second) name. If both failed, we weren't able to * calculate the correct chat name */ // Make sure messages is restarted to prevent accessibility issues await FileSystem.executeAppleScript(restartMessages()); let err = null; for (const name of names) { console.info(`Attempting to open chat, [${name}]`); try { // This needs await here, or else it will fail return await safeExecuteAppleScript(openChat(name)); } catch (ex: any) { err = ex; Server().log(`Failed to open chat, [${name}]. Trying again.`, "warn"); continue; } } // If we get here, there was an issue throw err; }; static startOrStopTypingInChat = async (chatGuid: string, isTyping: boolean): Promise<void> => { const enablePrivateApi = Server().repo.getConfig("enable_private_api") as boolean; if (!enablePrivateApi) { Server().log("Private API disabled! Not executing typing status change..."); return; } Server().log(`Executing Action: Change Typing Status (Chat: ${chatGuid})`, "debug"); if (isTyping) { Server().privateApiHelper.startTyping(chatGuid); } else { Server().privateApiHelper.stopTyping(chatGuid); } }; static markChatRead = async (chatGuid: string): Promise<void> => { const enablePrivateApi = Server().repo.getConfig("enable_private_api") as boolean; if (!enablePrivateApi) { Server().log("Private API disabled! Not executing mark chat as read..."); return; } Server().log(`Executing Action: Marking chat as read (Chat: ${chatGuid})`, "debug"); Server().privateApiHelper.markChatRead(chatGuid); }; static updateTypingStatus = async (chatGuid: string): Promise<void> => { const enablePrivateApi = Server().repo.getConfig("enable_private_api") as boolean; if (!enablePrivateApi) { Server().log("Private API disabled! Not executing update typing status..."); return; } Server().log(`Executing Action: Update Typing Status (Chat: ${chatGuid})`, "debug"); Server().privateApiHelper.getTypingStatus(chatGuid); }; static togglePrivateTapback = async ( chatGuid: string, actionMessageGuid: string, reactionType: ValidTapback | ValidRemoveTapback ): Promise<void> => { const enablePrivateApi = Server().repo.getConfig("enable_private_api") as boolean; if (!enablePrivateApi) { Server().log("Private API disabled! Not executing tapback..."); return; } Server().log( `Executing Action: Toggle Private Tapback (Chat: ${chatGuid}; Text: ${actionMessageGuid}; Tapback: ${reactionType})`, "debug" ); Server().privateApiHelper.sendReaction(chatGuid, actionMessageGuid, reactionType); }; /** * Toggles a tapback to specific message in a chat * * @param chatGuid The GUID for the chat * @param text The message text * @param tapback The tapback to send (as a strong) * * @returns The command line response */ static toggleTapback = async (chatGuid: string, text: string, tapback: ValidTapback): Promise<string> => { Server().log( `Executing Action: Toggle Tapback (Chat: ${chatGuid}; Text: ${text}; Tapback: ${tapback})`, "debug" ); const names = await generateChatNameList(chatGuid); /** * Above, we calculate 2 different names. One as-is, returned by the chat query, and one * ordered by the chat_handle_join table insertions. Below, we try to try to find the * corresponding chats, and rename them. If the first name fails to be found, * we are going to try and use the backup (second) name. If both failed, we weren't able to * calculate the correct chat name */ const tapbackId = tapbackUIMap[tapback]; const friendlyMsg = text.substring(0, 50); // Make sure messages is restarted to prevent accessibility issues await FileSystem.executeAppleScript(restartMessages()); let err = null; for (const name of names) { console.info(`Attempting to toggle tapback for message [${friendlyMsg}]`); try { // This needs await here, or else it will fail return await safeExecuteAppleScript(toggleTapback(name, text, tapbackId)); } catch (ex: any) { err = ex; Server().log(`Failed to toggle tapback on message, [${friendlyMsg}]. Trying again.`, "warn"); continue; } } // If we get here, there was an issue throw err; }; /** * Checks to see if a typing indicator is present * * @param chatGuid The GUID for the chat * * @returns Boolean on whether a typing indicator was present */ static checkTypingIndicator = async (chatGuid: string): Promise<boolean> => { Server().log(`Executing Action: Check Typing Indicators (Chat: ${chatGuid})`, "debug"); const names = await generateChatNameList(chatGuid); /** * Above, we calculate 2 different names. One as-is, returned by the chat query, and one * ordered by the chat_handle_join table insertions. Below, we try to try to find the * corresponding chats, and rename them. If the first name fails to be found, * we are going to try and use the backup (second) name. If both failed, we weren't able to * calculate the correct chat name */ // Make sure messages is restarted to prevent accessibility issues await FileSystem.executeAppleScript(restartMessages()); let err = null; for (const name of names) { console.info(`Attempting to check for a typing indicator for chat, [${name}]`); try { // This needs await here, or else it will fail const output = await safeExecuteAppleScript(checkTypingIndicator(name)); if (!output) return false; return toBoolean(output.trim()); } catch (ex: any) { err = ex; Server().log(`Failed to check for typing indicators for chat, [${name}]. Trying again.`, "warn"); continue; } } // If we get here, there was an issue throw err; }; /** * Creates a new chat using a list of participants (strings) * * @param participants: The list of participants to include in the chat * * @returns The GUID of the new chat */ static createUniversalChat = async ( participants: string[], service: string, message?: string, tempGuid?: string ): Promise<string> => { Server().log(`Executing Action: Create Chat Universal (Participants: ${participants.join(", ")})`, "debug"); if (participants.length === 0) throw new Error("No participants specified!"); // Add members to the chat const buddies = participants.map(item => slugifyAddress(item)); // Make sure messages is open await FileSystem.startMessages(); // Execute the command let ret = ""; try { try { // First try to send via the AppleScript using the `text chat` qualifier ret = (await FileSystem.executeAppleScript(startChat(buddies, service, true))) as string; } catch (ex: any) { // If the above command fails, try with just the `chat` qualifier ret = (await FileSystem.executeAppleScript(startChat(buddies, service, false))) as string; } } catch (ex: any) { // If we failed to create the chat, we can try to "guess" the // This catch catches the 2nd attempt to start a chat throw new Error(`AppleScript error: ${ex}`); } // Get the chat GUID that was created if (ret.includes("text chat id")) { ret = ret.split("text chat id")[1].trim(); } else if (ret.includes("chat id")) { ret = ret.split("chat id")[1].trim(); } // If no chat ID found, throw an error if (!ret || ret.length === 0) { throw new Error("Failed to get Chat GUID from AppleScript response!"); } // If there is a message attached, try to send it try { if (message && message.length > 0 && tempGuid && tempGuid.length > 0 && ret.startsWith(service)) { await ActionHandler.sendMessage(tempGuid, ret, message); } } catch (ex: any) { throw new Error(`Failed to send message to chat, ${ret}!`); } return ret; }; /** * Creates a new chat using a participant * * @param participant: The participant to include in the chat * * @returns The GUID of the new chat */ static createSingleChat = async ( participant: string, service: string, message: string, tempGuid: string ): Promise<string> => { Server().log(`Executing Action: Create Single Chat (Participant: ${participant})`, "debug"); // Slugify the address const buddy = slugifyAddress(participant); // Make sure messages is open await FileSystem.startMessages(); // Assume the chat GUID const chatGuid = `${service};-;${buddy}`; // Send the message to the chat await ActionHandler.sendMessage(tempGuid, chatGuid, message); // Return the chat GUID return chatGuid; }; /** * Exports contacts from the Contacts app, into a VCF file * * @returns The command line response */ static exportContacts = async (): Promise<void> => { Server().log("Executing Action: Export Contacts", "debug"); try { FileSystem.deleteAddressBook(); await FileSystem.executeAppleScript(exportContacts()); } catch (ex: any) { let msg = ex.message; if (msg instanceof String) [, msg] = msg.split("execution error: "); [msg] = msg.split(". ("); throw new Error(msg); } }; }
the_stack
import 'mocha' import { expect } from 'chai' import * as C from '../../constants' import RpcHandler from './rpc-handler' import * as testHelper from '../../test/helper/test-helper' import { getTestMocks } from '../../test/helper/test-mocks' import { RpcProxy } from './rpc-proxy' const options = testHelper.getDeepstreamOptions() const config = options.config const services = options.services describe('the rpcHandler routes events correctly', () => { let testMocks let rpcHandler let requestor let provider beforeEach(() => { testMocks = getTestMocks() rpcHandler = new RpcHandler(config, services, testMocks.subscriptionRegistry) requestor = testMocks.getSocketWrapper('requestor', {}, { color: 'blue' }) provider = testMocks.getSocketWrapper('provider') }) afterEach(() => { testMocks.subscriptionRegistryMock.verify() requestor.socketWrapperMock.verify() provider.socketWrapperMock.verify() }) it('routes subscription messages', () => { const subscriptionMessage = { topic: C.TOPIC.RPC, action: C.RPC_ACTION.PROVIDE, names: ['someRPC'], correlationId: '123' } testMocks.subscriptionRegistryMock .expects('subscribeBulk') .once() .withExactArgs(subscriptionMessage, provider.socketWrapper) rpcHandler.handle(provider.socketWrapper, subscriptionMessage) }) describe('when receiving a request', () => { const requestMessage = { topic: C.TOPIC.RPC, action: C.RPC_ACTION.REQUEST, name: 'addTwo', correlationId: 1234, data: '{"numA":5, "numB":7}' } const acceptMessage = { topic: C.TOPIC.RPC, action: C.RPC_ACTION.ACCEPT, name: 'addTwo', correlationId: 1234 } const responseMessage = { topic: C.TOPIC.RPC, action: C.RPC_ACTION.RESPONSE, name: 'addTwo', correlationId: 1234, data: '12' } const errorMessage = { topic: C.TOPIC.RPC, action: C.RPC_ACTION.REQUEST_ERROR, isError: true, name: 'addTwo', correlationId: 1234, data: 'ErrorOccured' } beforeEach(() => { testMocks.subscriptionRegistryMock .expects('getLocalSubscribers') .once() .withExactArgs('addTwo') .returns([provider.socketWrapper]) }) it('forwards it to a provider', () => { provider.socketWrapperMock .expects('sendMessage') .once() .withExactArgs(Object.assign({ requestorData: { color: 'blue' }, requestorName: 'requestor' }, requestMessage)) rpcHandler.handle(requestor.socketWrapper, requestMessage) }) it('accepts first accept', () => { requestor.socketWrapperMock .expects('sendMessage') .once() .withExactArgs(acceptMessage) rpcHandler.handle(requestor.socketWrapper, requestMessage) rpcHandler.handle(provider.socketWrapper, acceptMessage) }) it('errors when recieving more than one ack', () => { provider.socketWrapperMock .expects('sendMessage') .once() .withExactArgs({ topic: C.TOPIC.RPC, action: C.RPC_ACTION.MULTIPLE_ACCEPT, name: requestMessage.name, correlationId: requestMessage.correlationId }) provider.socketWrapperMock .expects('sendMessage') .once() .withExactArgs(Object.assign({ requestorData: { color: 'blue' }, requestorName: 'requestor' }, requestMessage)) rpcHandler.handle(requestor.socketWrapper, requestMessage) rpcHandler.handle(provider.socketWrapper, acceptMessage) rpcHandler.handle(provider.socketWrapper, acceptMessage) }) it('gets a response', () => { requestor.socketWrapperMock .expects('sendMessage') .once() .withExactArgs(responseMessage) rpcHandler.handle(requestor.socketWrapper, requestMessage) rpcHandler.handle(provider.socketWrapper, responseMessage) }) it('replies with an error to additonal responses', () => { rpcHandler.handle(requestor.socketWrapper, requestMessage) rpcHandler.handle(provider.socketWrapper, responseMessage) provider.socketWrapperMock .expects('sendMessage') .once() .withExactArgs({ topic: C.TOPIC.RPC, action: C.RPC_ACTION.INVALID_RPC_CORRELATION_ID, originalAction: responseMessage.action, name: responseMessage.name, correlationId: responseMessage.correlationId, isError: true }) rpcHandler.handle(provider.socketWrapper, responseMessage) }) it('gets an error', () => { requestor.socketWrapperMock .expects('sendMessage') .once() .withExactArgs(errorMessage) rpcHandler.handle(requestor.socketWrapper, requestMessage) rpcHandler.handle(provider.socketWrapper, errorMessage) }) it('replies with an error after the first message', () => { rpcHandler.handle(requestor.socketWrapper, requestMessage) rpcHandler.handle(provider.socketWrapper, errorMessage) provider.socketWrapperMock .expects('sendMessage') .once() .withExactArgs({ topic: C.TOPIC.RPC, action: C.RPC_ACTION.INVALID_RPC_CORRELATION_ID, originalAction: errorMessage.action, name: errorMessage.name, correlationId: errorMessage.correlationId, isError: true }) rpcHandler.handle(provider.socketWrapper, errorMessage) }) it('supports multiple RPCs in quick succession', () => { testMocks.subscriptionRegistryMock .expects('getLocalSubscribers') .exactly(49) .withExactArgs('addTwo') .returns([provider.socketWrapper]) expect(() => { for (let i = 0; i < 50; i++) { rpcHandler.handle(requestor.socketWrapper, requestMessage) } }).not.to.throw() }) it('times out if no ack is received', (done) => { rpcHandler.handle(requestor.socketWrapper, requestMessage) requestor.socketWrapperMock .expects('sendMessage') .once() .withExactArgs({ topic: C.TOPIC.RPC, action: C.RPC_ACTION.ACCEPT_TIMEOUT, name: requestMessage.name, correlationId: requestMessage.correlationId }) setTimeout(done, config.rpc.ackTimeout * 2) }) it('times out if response is not received in time', (done) => { rpcHandler.handle(requestor.socketWrapper, requestMessage) rpcHandler.handle(provider.socketWrapper, acceptMessage) requestor.socketWrapperMock .expects('sendMessage') .once() .withExactArgs({ topic: C.TOPIC.RPC, action: C.RPC_ACTION.RESPONSE_TIMEOUT, name: requestMessage.name, correlationId: requestMessage.correlationId }) setTimeout(done, config.rpc.responseTimeout * 2) }) // Should an Ack for a non existant rpc should error? it.skip('ignores ack message if it arrives after response', (done) => { provider.socketWrapperMock .expects('sendMessage') .twice() rpcHandler.handle(requestor.socketWrapper, requestMessage) rpcHandler.handle(provider.socketWrapper, responseMessage) setTimeout(() => { rpcHandler.handle(provider.socketWrapper, acceptMessage) done() }, 30) }) it('doesn\'t throw error on response after timeout', (done) => { rpcHandler.handle(requestor.socketWrapper, requestMessage) rpcHandler.handle(provider.socketWrapper, acceptMessage) requestor.socketWrapperMock .expects('sendMessage') .once() .withExactArgs({ topic: C.TOPIC.RPC, action: C.RPC_ACTION.RESPONSE_TIMEOUT, name: requestMessage.name, correlationId: requestMessage.correlationId }) setTimeout(() => { provider.socketWrapperMock .expects('sendMessage') .once() .withExactArgs({ topic: C.TOPIC.RPC, action: C.RPC_ACTION.INVALID_RPC_CORRELATION_ID, originalAction: responseMessage.action, name: responseMessage.name, correlationId: responseMessage.correlationId, isError: true }) rpcHandler.handle(provider.socketWrapper, responseMessage) done() }, 30) }) }) describe.skip('rpc handler returns alternative providers for the same rpc', () => { let providerForA1 let providerForA2 let providerForA3 let usedProviders before(() => { testMocks = getTestMocks() providerForA1 = testMocks.getSocketWrapper('a1') providerForA2 = testMocks.getSocketWrapper('a2') providerForA3 = testMocks.getSocketWrapper('a3') rpcHandler = new RpcHandler(config, services, testMocks.subscriptionRegistry) testMocks.subscriptionRegistryMock .expects('getLocalSubscribers') .once() .withExactArgs('rpcA') .returns([ providerForA1.socketWrapper ]) rpcHandler.handle(providerForA1.socketWrapper, { topic: C.TOPIC.RPC, action: C.RPC_ACTION.REQUEST, name: 'rpcA', correlationId: '1234', data: 'U' }) usedProviders = [providerForA1.socketWrapper] testMocks.subscriptionRegistryMock .expects('getLocalSubscribers') .exactly(5) .withExactArgs('rpcA') .returns([ providerForA2.socketWrapper, providerForA3.socketWrapper ]) testMocks.subscriptionRegistryMock .expects('getAllRemoteServers') .thrice() .withExactArgs('rpcA') .returns(['random-server-1', 'random-server-2']) }) after(() => { testMocks.subscriptionRegistryMock.verify() }) it('gets alternative rpc providers', () => { let alternativeProvider // first proxy alternativeProvider = rpcHandler.getAlternativeProvider('rpcA', '1234') expect(alternativeProvider).not.to.equal(null) expect(alternativeProvider instanceof RpcProxy).to.equal(false) expect(usedProviders.indexOf(alternativeProvider)).to.equal(-1) // second provider alternativeProvider = rpcHandler.getAlternativeProvider('rpcA', '1234') expect(alternativeProvider).not.to.equal(null) expect(alternativeProvider instanceof RpcProxy).to.equal(false) expect(usedProviders.indexOf(alternativeProvider)).to.equal(-1) // remote provider alternativeProvider = rpcHandler.getAlternativeProvider('rpcA', '1234') expect(alternativeProvider).not.to.equal(null) expect(alternativeProvider instanceof RpcProxy).to.equal(true) expect(usedProviders.indexOf(alternativeProvider)).to.equal(-1) // remote alternative provider alternativeProvider = rpcHandler.getAlternativeProvider('rpcA', '1234') expect(alternativeProvider).not.to.equal(null) expect(alternativeProvider instanceof RpcProxy).to.equal(true) expect(usedProviders.indexOf(alternativeProvider)).to.equal(-1) // null alternativeProvider = rpcHandler.getAlternativeProvider('rpcA', '1234') expect(alternativeProvider).to.equal(null) }) }) describe('the rpcHandler uses requestor fields correctly', () => { beforeEach(() => { testMocks = getTestMocks() requestor = testMocks.getSocketWrapper('requestor', {}, { bestLanguage: 'not BF' }) provider = testMocks.getSocketWrapper('provider') testMocks.subscriptionRegistryMock .expects('getLocalSubscribers') .once() .withExactArgs('addTwo') .returns([provider.socketWrapper]) }) afterEach(() => { testMocks.subscriptionRegistryMock.verify() requestor.socketWrapperMock.verify() provider.socketWrapperMock.verify() }) const requestMessage = { topic: C.TOPIC.RPC, action: C.RPC_ACTION.REQUEST, name: 'addTwo', correlationId: 1234, data: '{"numA":5, "numB":7}' } for (const nameAvailable of [true, false]) { for (const dataAvailable of [true, false]) { const name = `name=${nameAvailable} data=${dataAvailable}` it(name, () => { config.rpc.provideRequestorName = nameAvailable config.rpc.provideRequestorData = dataAvailable const expectedMessage = Object.assign({}, requestMessage) if (nameAvailable) { Object.assign(expectedMessage, { requestorName: 'requestor' }) } if (dataAvailable) { Object.assign(expectedMessage, { requestorData: { bestLanguage: 'not BF' } }) } provider.socketWrapperMock .expects('sendMessage') .once() .withExactArgs(expectedMessage) rpcHandler = new RpcHandler(config, services, testMocks.subscriptionRegistry) rpcHandler.handle(requestor.socketWrapper, requestMessage) }) } } // it ('overwrites fake requestorName and fake requestorData', () => { // config.provideRPCRequestorDetails = true // config.RPCRequestorNameTerm = null // config.RPCRequestorDataTerm = null // // provider.socketWrapperMock // .expects('sendMessage') // .once() // .withExactArgs(Object.assign({ // requestorName: 'requestor', // requestorData: { bestLanguage: 'not BF' } // }, requestMessage)) // // const fakeRequestMessage = Object.assign({ // requestorName: 'evil-requestor', // requestorData: { bestLanguage: 'malbolge' } // }, requestMessage) // rpcHandler = new RpcHandler(config, services, testMocks.subscriptionRegistry) // rpcHandler.handle(requestor.socketWrapper, fakeRequestMessage) // }) }) })
the_stack
import gLong from './gLong'; import ByteStream from './ByteStream'; import * as util from './util'; import {ConstantPoolItemType, MethodHandleReferenceKind} from './enums'; import assert from './assert'; import {ReferenceClassData, ArrayClassData, IJVMConstructor, PrimitiveClassData} from './ClassData'; import {Method, Field} from './methods'; import {ClassLoader} from './ClassLoader'; // For type information. import {JVMThread, BytecodeStackFrame} from './threading'; import * as JVMTypes from '../includes/JVMTypes'; import {setImmediate} from 'browserfs'; /** * Represents a constant pool item. Use the item's type to discriminate among them. */ export interface IConstantPoolItem { getType(): ConstantPoolItemType; /** * Is this constant pool item resolved? Use to discriminate among resolved * and unresolved reference types. */ isResolved(): boolean; /** * Returns the constant associated with the constant pool item. The item *must* * be resolved. * Only defined on constant pool items that return values through LDC. */ getConstant?(thread: JVMThread): any; /** * Resolves an unresolved constant pool item. Can only be called if * isResolved() returns false. */ resolve?(thread: JVMThread, cl: ClassLoader, caller: ReferenceClassData<JVMTypes.java_lang_Object>, cb: (status: boolean) => void, explicit?: boolean): void; } /** * All constant pool items have a static constructor function. */ export interface IConstantPoolType { fromBytes(byteStream: ByteStream, constantPool: ConstantPool): IConstantPoolItem; /** * The resulting size in the constant pool, in machine words. */ size: number; /** * The bytesize on disk of the item's information past the tag byte. */ infoByteSize: number; } /** * Stores all of the constant pool classes, keyed on their enum value. */ var CP_CLASSES: { [n: number]: IConstantPoolType } = {}; // #region Tier 0 /** * Represents a constant UTF-8 string. * ``` * CONSTANT_Utf8_info { * u1 tag; * u2 length; * u1 bytes[length]; * } * ``` */ export class ConstUTF8 implements IConstantPoolItem { public value: string; constructor(rawBytes: Buffer) { this.value = this.bytes2str(rawBytes); } /** * Parse Java's pseudo-UTF-8 strings into valid UTF-16 codepoints (spec 4.4.7) * Note that Java uses UTF-16 internally by default for string representation, * and the pseudo-UTF-8 strings are *only* used for serialization purposes. * Thus, there is no reason for other parts of the code to call this routine! * TODO: To avoid copying, create a character array for this data. * http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4.7 */ private bytes2str(bytes: Buffer): string { var y: number, z: number, v: number, w: number, x: number, charCode: number, idx = 0, rv = ''; while (idx < bytes.length) { x = bytes[idx++] & 0xff; // While the standard specifies that surrogate pairs should be handled, it seems like // they are by default with the three byte format. See parsing code here: // http://hg.openjdk.java.net/jdk8u/jdk8u-dev/jdk/file/3623f1b29b58/src/share/classes/java/io/DataInputStream.java#l618 // One UTF-16 character. if (x <= 0x7f) { // One character, one byte. charCode = x; } else if (x <= 0xdf) { // One character, two bytes. y = bytes[idx++]; charCode = ((x & 0x1f) << 6) + (y & 0x3f); } else { // One character, three bytes. y = bytes[idx++]; z = bytes[idx++]; charCode = ((x & 0xf) << 12) + ((y & 0x3f) << 6) + (z & 0x3f); } rv += String.fromCharCode(charCode); } return rv; } public getType(): ConstantPoolItemType { return ConstantPoolItemType.UTF8; } public getConstant(thread: JVMThread) { return this.value; } public isResolved() { return true; } public static size: number = 1; // Variable-size. public static infoByteSize: number = 0; public static fromBytes(byteStream: ByteStream, constantPool: ConstantPool): IConstantPoolItem { var strlen = byteStream.getUint16(); return new this(byteStream.read(strlen)); } } CP_CLASSES[ConstantPoolItemType.UTF8] = ConstUTF8; /** * Represents a constant 32-bit integer. * ``` * CONSTANT_Integer_info { * u1 tag; * u4 bytes; * } * ``` */ export class ConstInt32 implements IConstantPoolItem { public value: number; constructor(value: number) { this.value = value; } public getType(): ConstantPoolItemType { return ConstantPoolItemType.INTEGER; } public getConstant(thread: JVMThread) { return this.value; } public isResolved() { return true; } public static size: number = 1; public static infoByteSize: number = 4; public static fromBytes(byteStream: ByteStream, constantPool: ConstantPool): IConstantPoolItem { return new this(byteStream.getInt32()); } } CP_CLASSES[ConstantPoolItemType.INTEGER] = ConstInt32; /** * Represents a constant 32-bit floating point number. * ``` * CONSTANT_Float_info { * u1 tag; * u4 bytes; * } * ``` */ export class ConstFloat implements IConstantPoolItem { public value: number; constructor(value: number) { this.value = value; } public getType(): ConstantPoolItemType { return ConstantPoolItemType.FLOAT; } public getConstant(thread: JVMThread) { return this.value; } public isResolved() { return true; } public static size: number = 1; public static infoByteSize: number = 4; public static fromBytes(byteStream: ByteStream, constantPool: ConstantPool): IConstantPoolItem { return new this(byteStream.getFloat()); } } CP_CLASSES[ConstantPoolItemType.FLOAT] = ConstFloat; /** * Represents a constant 64-bit integer. * ``` * CONSTANT_Long_info { * u1 tag; * u4 high_bytes; * u4 low_bytes; * } * ``` */ export class ConstLong implements IConstantPoolItem { public value: gLong; constructor(value: gLong) { this.value = value; } public getType(): ConstantPoolItemType { return ConstantPoolItemType.LONG; } public getConstant(thread: JVMThread) { return this.value; } public isResolved() { return true; } public static size: number = 2; public static infoByteSize: number = 8; public static fromBytes(byteStream: ByteStream, constantPool: ConstantPool): IConstantPoolItem { return new this(byteStream.getInt64()); } } CP_CLASSES[ConstantPoolItemType.LONG] = ConstLong; /** * Represents a constant 64-bit floating point number. * ``` * CONSTANT_Double_info { * u1 tag; * u4 high_bytes; * u4 low_bytes; * } * ``` */ export class ConstDouble implements IConstantPoolItem { public value: number; constructor(value: number) { this.value = value; } public getType(): ConstantPoolItemType { return ConstantPoolItemType.DOUBLE; } public getConstant(thread: JVMThread) { return this.value; } public isResolved() { return true; } public static size: number = 2; public static infoByteSize: number = 8; public static fromBytes(byteStream: ByteStream, constantPool: ConstantPool): IConstantPoolItem { return new this(byteStream.getDouble()); } } CP_CLASSES[ConstantPoolItemType.DOUBLE] = ConstDouble; // #endregion // #region Tier 1 /** * Represents a class or interface. * ``` * CONSTANT_Class_info { * u1 tag; * u2 name_index; * } * ``` * @todo Have a classloader-local cache of class reference objects. */ export class ClassReference implements IConstantPoolItem { /** * The name of the class, in full descriptor form, e.g.: * Lfoo/bar/Baz; */ public name: string; /** * The resolved class reference. */ public cls: ReferenceClassData<JVMTypes.java_lang_Object> | ArrayClassData<any> = null; /** * The JavaScript constructor for the referenced class. */ public clsConstructor: IJVMConstructor<JVMTypes.java_lang_Object> = null; /** * The array class for the resolved class reference. */ public arrayClass: ArrayClassData<any> = null; /** * The JavaScript constructor for the array class. */ public arrayClassConstructor: IJVMConstructor<JVMTypes.JVMArray<any>> = null; constructor(name: string) { this.name = name; } /** * Attempt to synchronously resolve. */ public tryResolve(loader: ClassLoader): boolean { if (this.cls === null) { this.cls = <ReferenceClassData<JVMTypes.java_lang_Object>> loader.getResolvedClass(this.name); } return this.cls !== null; } /** * Resolves the class reference by resolving the class. Does not run * class initialization. */ public resolve(thread: JVMThread, loader: ClassLoader, caller: ReferenceClassData<JVMTypes.java_lang_Object>, cb: (status: boolean) => void, explicit: boolean = true) { // Because of Java 8 anonymous classes, THIS CHECK IS REQUIRED FOR CORRECTNESS. // (ClassLoaders do not know about anonymous classes, hence they are // 'anonymous') // (Anonymous classes are an 'Unsafe' feature, and are not part of the standard, // but they are employed for lambdas and such.) // NOTE: Thread is 'null' during JVM bootstrapping. if (thread !== null) { var currentMethod = thread.currentMethod(); // The stack might be empty during resolution, which occurs during JVM bootup. if (currentMethod !== null && this.name === currentMethod.cls.getInternalName()) { this.setResolved(thread, thread.currentMethod().cls); return cb(true); } } loader.resolveClass(thread, this.name, (cdata: ReferenceClassData<JVMTypes.java_lang_Object>) => { this.setResolved(thread, cdata); cb(cdata !== null); }, explicit); } private setResolved(thread: JVMThread, cls: ReferenceClassData<JVMTypes.java_lang_Object>) { this.cls = cls; if (cls !== null) { this.clsConstructor = cls.getConstructor(thread); } } public getType(): ConstantPoolItemType { return ConstantPoolItemType.CLASS; } public getConstant(thread: JVMThread) { return this.cls.getClassObject(thread); } public isResolved() { return this.cls !== null; } public static size: number = 1; public static infoByteSize: number = 2; public static fromBytes(byteStream: ByteStream, constantPool: ConstantPool): IConstantPoolItem { var nameIndex = byteStream.getUint16(), cpItem = constantPool.get(nameIndex); assert(cpItem.getType() === ConstantPoolItemType.UTF8, 'ConstantPool ClassReference type != UTF8'); // The ConstantPool stores class names without the L...; descriptor stuff return new this(util.typestr2descriptor((<ConstUTF8> cpItem).value)); } } CP_CLASSES[ConstantPoolItemType.CLASS] = ClassReference; /** * Represents a field or method without indicating which class or interface * type it belongs to. * ``` * CONSTANT_NameAndType_info { * u1 tag; * u2 name_index; * u2 descriptor_index; * } * ``` */ export class NameAndTypeInfo implements IConstantPoolItem { public name: string; public descriptor: string; constructor(name: string, descriptor: string) { this.name = name; this.descriptor = descriptor; } public getType(): ConstantPoolItemType { return ConstantPoolItemType.NAME_AND_TYPE; } public isResolved() { return true; } public static size: number = 1; public static infoByteSize: number = 4; public static fromBytes(byteStream: ByteStream, constantPool: ConstantPool): IConstantPoolItem { var nameIndex = byteStream.getUint16(), descriptorIndex = byteStream.getUint16(), nameConst = <ConstUTF8> constantPool.get(nameIndex), descriptorConst = <ConstUTF8> constantPool.get(descriptorIndex); assert(nameConst.getType() === ConstantPoolItemType.UTF8 && descriptorConst.getType() === ConstantPoolItemType.UTF8, 'ConstantPool NameAndTypeInfo types != UTF8'); return new this(nameConst.value, descriptorConst.value); } } CP_CLASSES[ConstantPoolItemType.NAME_AND_TYPE] = NameAndTypeInfo; /** * Represents constant objects of the type java.lang.String. * ``` * CONSTANT_String_info { * u1 tag; * u2 string_index; * } * ``` */ export class ConstString implements IConstantPoolItem { public stringValue: string; public value: JVMTypes.java_lang_String = null; constructor(stringValue: string) { this.stringValue = stringValue; } public getType(): ConstantPoolItemType { return ConstantPoolItemType.STRING; } public resolve(thread: JVMThread, loader: ClassLoader, caller: ReferenceClassData<JVMTypes.java_lang_Object>, cb: (status: boolean) => void) { this.value = thread.getJVM().internString(this.stringValue); setImmediate(() => cb(true)); } public getConstant(thread: JVMThread) { return this.value; } public isResolved() { return this.value !== null; } public static size: number = 1; public static infoByteSize: number = 2; public static fromBytes(byteStream: ByteStream, constantPool: ConstantPool): IConstantPoolItem { var stringIndex = byteStream.getUint16(), utf8Info = <ConstUTF8> constantPool.get(stringIndex); assert(utf8Info.getType() === ConstantPoolItemType.UTF8, 'ConstantPool ConstString type != UTF8'); return new this(utf8Info.value); } } CP_CLASSES[ConstantPoolItemType.STRING] = ConstString; /** * Represents a given method type. * ``` * CONSTANT_MethodType_info { * u1 tag; * u2 descriptor_index; * } * ``` */ export class MethodType implements IConstantPoolItem { private descriptor: string; public methodType: JVMTypes.java_lang_invoke_MethodType = null; constructor(descriptor: string) { this.descriptor = descriptor; } public resolve(thread: JVMThread, cl: ClassLoader, caller: ReferenceClassData<JVMTypes.java_lang_Object>, cb: (status: boolean) => void) { util.createMethodType(thread, cl, this.descriptor, (e: JVMTypes.java_lang_Throwable, type: JVMTypes.java_lang_invoke_MethodType) => { if (e) { thread.throwException(e); cb(false); } else { this.methodType = type; cb(true); } }); } public getConstant(thread: JVMThread) { return this.methodType; } public getType(): ConstantPoolItemType { return ConstantPoolItemType.METHOD_TYPE; } public isResolved() { return this.methodType !== null; } public static size: number = 1; public static infoByteSize: number = 2; public static fromBytes(byteStream: ByteStream, constantPool: ConstantPool): IConstantPoolItem { var descriptorIndex = byteStream.getUint16(), utf8Info = <ConstUTF8> constantPool.get(descriptorIndex); assert(utf8Info.getType() === ConstantPoolItemType.UTF8, 'ConstantPool MethodType type != UTF8'); return new this(utf8Info.value); } } CP_CLASSES[ConstantPoolItemType.METHOD_TYPE] = MethodType; // #endregion // #region Tier 2 /** * Represents a particular method. * ``` * CONSTANT_Methodref_info { * u1 tag; * u2 class_index; * u2 name_and_type_index; * } * ``` */ export class MethodReference implements IConstantPoolItem { public classInfo: ClassReference; public nameAndTypeInfo: NameAndTypeInfo; public method: Method = null; /** * The signature of the method, without the owning class. * e.g. foo(IJ)V */ public signature: string; /** * The signature of the method, including the owning class. * e.g. bar/Baz/foo(IJ)V */ public fullSignature: string = null; public paramWordSize: number = -1; /** * Contains a reference to the MemberName object for the method that invokes * the desired function. */ public memberName: JVMTypes.java_lang_invoke_MemberName = null; /** * Contains an object that needs to be pushed onto the stack before invoking * memberName. */ public appendix: JVMTypes.java_lang_Object = null; /** * The JavaScript constructor for the class that the method belongs to. */ public jsConstructor: any = null; constructor(classInfo: ClassReference, nameAndTypeInfo: NameAndTypeInfo) { this.classInfo = classInfo; this.nameAndTypeInfo = nameAndTypeInfo; this.signature = this.nameAndTypeInfo.name + this.nameAndTypeInfo.descriptor; } public getType(): ConstantPoolItemType { return ConstantPoolItemType.METHODREF; } /** * Checks the method referenced by this constant pool item in the specified * bytecode context. * Returns null if an error occurs. * - Throws a NoSuchFieldError if missing. * - Throws an IllegalAccessError if field is inaccessible. * - Throws an IncompatibleClassChangeError if the field is an incorrect type * for the field access. */ public hasAccess(thread: JVMThread, frame: BytecodeStackFrame, isStatic: boolean): boolean { var method = this.method, accessingCls = frame.method.cls; if (method.accessFlags.isStatic() !== isStatic) { thread.throwNewException('Ljava/lang/IncompatibleClassChangeError;', `Method ${method.name} from class ${method.cls.getExternalName()} is ${isStatic ? 'not ' : ''}static.`); frame.returnToThreadLoop = true; return false; } else if (!util.checkAccess(accessingCls, method.cls, method.accessFlags)) { thread.throwNewException('Ljava/lang/IllegalAccessError;', `${accessingCls.getExternalName()} cannot access ${method.cls.getExternalName()}.${method.name}`); frame.returnToThreadLoop = true; return false; } return true; } private resolveMemberName(method: Method, thread: JVMThread, cl: ClassLoader, caller: ReferenceClassData<JVMTypes.java_lang_Object>, cb: (status: boolean) => void): void { var memberHandleNatives = <typeof JVMTypes.java_lang_invoke_MethodHandleNatives> (<ReferenceClassData<JVMTypes.java_lang_invoke_MethodHandleNatives>> thread.getBsCl().getInitializedClass(thread, 'Ljava/lang/invoke/MethodHandleNatives;')).getConstructor(thread), appendix = new ((<ArrayClassData<JVMTypes.java_lang_Object>> thread.getBsCl().getInitializedClass(thread, '[Ljava/lang/Object;')).getConstructor(thread))(thread, 1); util.createMethodType(thread, cl, this.nameAndTypeInfo.descriptor, (e: JVMTypes.java_lang_Throwable, type: JVMTypes.java_lang_invoke_MethodType) => { if (e) { thread.throwException(e); cb(false); } else { /* MemberName linkMethod( int refKind, Class<?> defc, String name, Object type, Object[] appendixResult) */ memberHandleNatives['java/lang/invoke/MethodHandleNatives/linkMethod(Ljava/lang/Class;ILjava/lang/Class;Ljava/lang/String;Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/invoke/MemberName;']( thread, // Class callerClass [caller.getClassObject(thread), // int refKind MethodHandleReferenceKind.INVOKEVIRTUAL, // Class defc this.classInfo.cls.getClassObject(thread), // String name thread.getJVM().internString(this.nameAndTypeInfo.name), // Object type, Object[] appendixResult type, appendix], (e?: JVMTypes.java_lang_Throwable, rv?: JVMTypes.java_lang_invoke_MemberName) => { if (e !== null) { thread.throwException(e); cb(false); } else { this.appendix = appendix.array[0]; this.memberName = rv; cb(true); } }); } }); } public resolve(thread: JVMThread, loader: ClassLoader, caller: ReferenceClassData<JVMTypes.java_lang_Object>, cb: (status: boolean) => void, explicit: boolean = true) { if (!this.classInfo.isResolved()) { this.classInfo.resolve(thread, loader, caller, (status: boolean) => { if (!status) { cb(false); } else { this.resolve(thread, loader, caller, cb, explicit); } }, explicit); } else { var cls = this.classInfo.cls, method = cls.methodLookup(this.signature); if (method === null) { if (util.is_reference_type(cls.getInternalName())) { // Signature polymorphic lookup. method = (<ReferenceClassData<JVMTypes.java_lang_Object>> cls).signaturePolymorphicAwareMethodLookup(this.signature); if (method !== null && (method.name === 'invoke' || method.name === 'invokeExact')) { // In order to completely resolve the signature polymorphic function, // we need to resolve its MemberName object and Appendix. return this.resolveMemberName(method, thread, loader, caller, (status: boolean) => { if (status === true) { this.setResolved(thread, method); } else { thread.throwNewException('Ljava/lang/NoSuchMethodError;', `Method ${this.signature} does not exist in class ${this.classInfo.cls.getExternalName()}.`); } cb(status); }); } } } if (method !== null) { this.setResolved(thread, method); cb(true); } else { thread.throwNewException('Ljava/lang/NoSuchMethodError;', `Method ${this.signature} does not exist in class ${this.classInfo.cls.getExternalName()}.`); cb(false); } } } public setResolved(thread: JVMThread, method: Method): void { this.method = method; this.paramWordSize = util.getMethodDescriptorWordSize(this.nameAndTypeInfo.descriptor); this.fullSignature = this.method.fullSignature; this.jsConstructor = this.method.cls.getConstructor(thread); } public isResolved() { return this.method !== null; } public getParamWordSize(): number { if (this.paramWordSize === -1) { this.paramWordSize = util.getMethodDescriptorWordSize(this.nameAndTypeInfo.descriptor); } return this.paramWordSize; } public static size: number = 1; public static infoByteSize: number = 4; public static fromBytes(byteStream: ByteStream, constantPool: ConstantPool): IConstantPoolItem { var classIndex = byteStream.getUint16(), nameAndTypeIndex = byteStream.getUint16(), classInfo = <ClassReference> constantPool.get(classIndex), nameAndTypeInfo = <NameAndTypeInfo> constantPool.get(nameAndTypeIndex); assert(classInfo.getType() === ConstantPoolItemType.CLASS && nameAndTypeInfo.getType() === ConstantPoolItemType.NAME_AND_TYPE, 'ConstantPool MethodReference types mismatch'); return new this(classInfo, nameAndTypeInfo); } } CP_CLASSES[ConstantPoolItemType.METHODREF] = MethodReference; /** * Represents a particular interface method. * ``` * CONSTANT_InterfaceMethodref_info { * u1 tag; * u2 class_index; * u2 name_and_type_index; * } * ``` */ export class InterfaceMethodReference implements IConstantPoolItem { public classInfo: ClassReference; public nameAndTypeInfo: NameAndTypeInfo; /** * The signature of the method, without the owning class. * e.g. foo(IJ)V */ public signature: string; /** * The signature of the method, including the owning class. * e.g. bar/Baz/foo(IJ)V */ public fullSignature: string = null; public method: Method = null; public paramWordSize: number = -1; public jsConstructor: any = null; constructor(classInfo: ClassReference, nameAndTypeInfo: NameAndTypeInfo) { this.classInfo = classInfo; this.nameAndTypeInfo = nameAndTypeInfo; this.signature = this.nameAndTypeInfo.name + this.nameAndTypeInfo.descriptor; } public getType(): ConstantPoolItemType { return ConstantPoolItemType.INTERFACE_METHODREF; } /** * Checks the method referenced by this constant pool item in the specified * bytecode context. * Returns null if an error occurs. * - Throws a NoSuchFieldError if missing. * - Throws an IllegalAccessError if field is inaccessible. * - Throws an IncompatibleClassChangeError if the field is an incorrect type * for the field access. */ public hasAccess(thread: JVMThread, frame: BytecodeStackFrame, isStatic: boolean): boolean { var method = this.method, accessingCls = frame.method.cls; if (method.accessFlags.isStatic() !== isStatic) { thread.throwNewException('Ljava/lang/IncompatibleClassChangeError;', `Method ${method.name} from class ${method.cls.getExternalName()} is ${isStatic ? 'not ' : ''}static.`); frame.returnToThreadLoop = true; return false; } else if (!util.checkAccess(accessingCls, method.cls, method.accessFlags)) { thread.throwNewException('Ljava/lang/IllegalAccessError;', `${accessingCls.getExternalName()} cannot access ${method.cls.getExternalName()}.${method.name}`); frame.returnToThreadLoop = true; return false; } return true; } public resolve(thread: JVMThread, loader: ClassLoader, caller: ReferenceClassData<JVMTypes.java_lang_Object>, cb: (status: boolean) => void, explicit: boolean = true) { if (!this.classInfo.isResolved()) { this.classInfo.resolve(thread, loader, caller, (status: boolean) => { if (!status) { cb(false); } else { this.resolve(thread, loader, caller, cb, explicit); } }, explicit); } else { var cls = this.classInfo.cls, method = cls.methodLookup(this.signature); this.paramWordSize = util.getMethodDescriptorWordSize(this.nameAndTypeInfo.descriptor); if (method !== null) { this.setResolved(thread, method); cb(true); } else { thread.throwNewException('Ljava/lang/NoSuchMethodError;', `Method ${this.signature} does not exist in class ${this.classInfo.cls.getExternalName()}.`); cb(false); } } } public setResolved(thread: JVMThread, method: Method): void { this.method = method; this.paramWordSize = util.getMethodDescriptorWordSize(this.nameAndTypeInfo.descriptor); this.fullSignature = this.method.fullSignature; this.jsConstructor = this.method.cls.getConstructor(thread); } public getParamWordSize(): number { if (this.paramWordSize === -1) { this.paramWordSize = util.getMethodDescriptorWordSize(this.nameAndTypeInfo.descriptor); } return this.paramWordSize; } public isResolved() { return this.method !== null; } public static size: number = 1; public static infoByteSize: number = 4; public static fromBytes(byteStream: ByteStream, constantPool: ConstantPool): IConstantPoolItem { var classIndex = byteStream.getUint16(), nameAndTypeIndex = byteStream.getUint16(), classInfo = <ClassReference> constantPool.get(classIndex), nameAndTypeInfo = <NameAndTypeInfo> constantPool.get(nameAndTypeIndex); assert(classInfo.getType() === ConstantPoolItemType.CLASS && nameAndTypeInfo.getType() === ConstantPoolItemType.NAME_AND_TYPE, 'ConstantPool InterfaceMethodReference types mismatch'); return new this(classInfo, nameAndTypeInfo); } } CP_CLASSES[ConstantPoolItemType.INTERFACE_METHODREF] = InterfaceMethodReference; /** * Represents a particular field. * ``` * CONSTANT_Fieldref_info { * u1 tag; * u2 class_index; * u2 name_and_type_index; * } * ``` */ export class FieldReference implements IConstantPoolItem { public classInfo: ClassReference; public nameAndTypeInfo: NameAndTypeInfo; public field: Field = null; /** * The full name of the field, including the owning class. * e.g. java/lang/String/value */ public fullFieldName: string = null; /** * The constructor for the field owner. Used for static fields. */ public fieldOwnerConstructor: any = null; constructor(classInfo: ClassReference, nameAndTypeInfo: NameAndTypeInfo) { this.classInfo = classInfo; this.nameAndTypeInfo = nameAndTypeInfo; } public getType(): ConstantPoolItemType { return ConstantPoolItemType.FIELDREF; } /** * Checks the field referenced by this constant pool item in the specified * bytecode context. * Returns null if an error occurs. * - Throws a NoSuchFieldError if missing. * - Throws an IllegalAccessError if field is inaccessible. * - Throws an IncompatibleClassChangeError if the field is an incorrect type * for the field access. */ public hasAccess(thread: JVMThread, frame: BytecodeStackFrame, isStatic: boolean): boolean { var field = this.field, accessingCls = frame.method.cls; if (field.accessFlags.isStatic() !== isStatic) { thread.throwNewException('Ljava/lang/IncompatibleClassChangeError;', `Field ${name} from class ${field.cls.getExternalName()} is ${isStatic ? 'not ' : ''}static.`); frame.returnToThreadLoop = true; return false; } else if (!util.checkAccess(accessingCls, field.cls, field.accessFlags)) { thread.throwNewException('Ljava/lang/IllegalAccessError;', `${accessingCls.getExternalName()} cannot access ${field.cls.getExternalName()}.${name}`); frame.returnToThreadLoop = true; return false; } return true; } public resolve(thread: JVMThread, loader: ClassLoader, caller: ReferenceClassData<JVMTypes.java_lang_Object>, cb: (status: boolean) => void, explicit: boolean = true) { if (!this.classInfo.isResolved()) { this.classInfo.resolve(thread, loader, caller, (status: boolean) => { if (!status) { cb(false); } else { this.resolve(thread, loader, caller, cb, explicit); } }, explicit); } else { var cls = this.classInfo.cls, field = cls.fieldLookup(this.nameAndTypeInfo.name); if (field !== null) { this.fullFieldName = `${util.descriptor2typestr(field.cls.getInternalName())}/${field.name}`; this.field = field; cb(true); } else { thread.throwNewException('Ljava/lang/NoSuchFieldError;', `Field ${this.nameAndTypeInfo.name} does not exist in class ${this.classInfo.cls.getExternalName()}.`); cb(false); } } } public isResolved() { return this.field !== null; } public static size: number = 1; public static infoByteSize: number = 4; public static fromBytes(byteStream: ByteStream, constantPool: ConstantPool): IConstantPoolItem { var classIndex = byteStream.getUint16(), nameAndTypeIndex = byteStream.getUint16(), classInfo = <ClassReference> constantPool.get(classIndex), nameAndTypeInfo = <NameAndTypeInfo> constantPool.get(nameAndTypeIndex); assert(classInfo.getType() === ConstantPoolItemType.CLASS && nameAndTypeInfo.getType() === ConstantPoolItemType.NAME_AND_TYPE, 'ConstantPool FieldReference types mismatch'); return new this(classInfo, nameAndTypeInfo); } } CP_CLASSES[ConstantPoolItemType.FIELDREF] = FieldReference; /** * Used by an invokedynamic instruction to specify a bootstrap method, * the dynamic invocation name, the argument and return types of the call, * and optionally, a sequence of additional constants called static arguments * to the bootstrap method. * ``` * CONSTANT_InvokeDynamic_info { * u1 tag; * u2 bootstrap_method_attr_index; * u2 name_and_type_index; * } * ``` */ export class InvokeDynamic implements IConstantPoolItem { public bootstrapMethodAttrIndex: number; public nameAndTypeInfo: NameAndTypeInfo; /** * The parameter word size of the nameAndTypeInfo's descriptor. * Does not take appendix into account; this is the static paramWordSize. */ public paramWordSize: number; /** * Once a CallSite is defined for a particular lexical occurrence of * InvokeDynamic, the CallSite will be reused for each future execution * of that particular occurrence. * * We store the CallSite objects here for future retrieval, along with an * optional 'appendix' argument. */ private callSiteObjects: { [pc: number]: [JVMTypes.java_lang_invoke_MemberName, JVMTypes.java_lang_Object] } = {}; /** * A MethodType object corresponding to this InvokeDynamic call's * method descriptor. */ private methodType: JVMTypes.java_lang_invoke_MethodType = null; constructor(bootstrapMethodAttrIndex: number, nameAndTypeInfo: NameAndTypeInfo) { this.bootstrapMethodAttrIndex = bootstrapMethodAttrIndex; this.nameAndTypeInfo = nameAndTypeInfo; this.paramWordSize = util.getMethodDescriptorWordSize(this.nameAndTypeInfo.descriptor); } public getType(): ConstantPoolItemType { return ConstantPoolItemType.INVOKE_DYNAMIC; } public isResolved(): boolean { return this.methodType !== null; } public resolve(thread: JVMThread, loader: ClassLoader, caller: ReferenceClassData<JVMTypes.java_lang_Object>, cb: (status: boolean) => void) { util.createMethodType(thread, loader, this.nameAndTypeInfo.descriptor, (e: JVMTypes.java_lang_Throwable, rv: JVMTypes.java_lang_invoke_MethodType) => { if (e) { thread.throwException(e); cb(false); } else { this.methodType = rv; cb(true); } }); } public getCallSiteObject(pc: number): [JVMTypes.java_lang_invoke_MemberName, JVMTypes.java_lang_Object] { var cso = this.callSiteObjects[pc] if (cso) { return cso; } else { return null; } } public constructCallSiteObject(thread: JVMThread, cl: ClassLoader, clazz: ReferenceClassData<JVMTypes.java_lang_Object>, pc: number, cb: (status: boolean) => void, explicit: boolean = true): void { /** * A call site specifier gives a symbolic reference to a method handle which * is to serve as the bootstrap method for a dynamic call site (§4.7.23). * The method handle is resolved to obtain a reference to an instance of * java.lang.invoke.MethodHandle (§5.4.3.5). */ var bootstrapMethod = clazz.getBootstrapMethod(this.bootstrapMethodAttrIndex), unresolvedItems: IConstantPoolItem[] = bootstrapMethod[1].concat(bootstrapMethod[0], this).filter((item: IConstantPoolItem) => !item.isResolved()); if (unresolvedItems.length > 0) { // Resolve all needed constant pool items (including this one). return util.asyncForEach(unresolvedItems, (cpItem: IConstantPoolItem, nextItem: (err?: any) => void) => { cpItem.resolve(thread, cl, clazz, (status: boolean) => { if (!status) { nextItem("Failed."); } else { nextItem(); } }, explicit); }, (err?: any) => { if (err) { cb(false); } else { // Rerun. This time, all items are resolved. this.constructCallSiteObject(thread, cl, clazz, pc, cb, explicit); } }); } /** * A call site specifier gives zero or more static arguments, which * communicate application-specific metadata to the bootstrap method. Any * static arguments which are symbolic references to classes, method * handles, or method types are resolved, as if by invocation of the ldc * instruction (§ldc), to obtain references to Class objects, * java.lang.invoke.MethodHandle objects, and java.lang.invoke.MethodType * objects respectively. Any static arguments that are string literals are * used to obtain references to String objects. */ function getArguments(): JVMTypes.JVMArray<JVMTypes.java_lang_Object> { var cpItems = bootstrapMethod[1], i: number, cpItem: IConstantPoolItem, rvObj = new ((<ArrayClassData<JVMTypes.java_lang_Object>> thread.getBsCl().getInitializedClass(thread, '[Ljava/lang/Object;')).getConstructor(thread))(thread, cpItems.length), rv = rvObj.array; for (i = 0; i < cpItems.length; i++) { cpItem = cpItems[i]; switch (cpItem.getType()) { case ConstantPoolItemType.CLASS: rv[i] = (<ClassReference> cpItem).cls.getClassObject(thread); break; case ConstantPoolItemType.METHOD_HANDLE: rv[i] = (<MethodHandle> cpItem).methodHandle; break; case ConstantPoolItemType.METHOD_TYPE: rv[i] = (<MethodType> cpItem).methodType; break; case ConstantPoolItemType.STRING: rv[i] = (<ConstString> cpItem).value; break; case ConstantPoolItemType.UTF8: rv[i] = thread.getJVM().internString((<ConstUTF8> cpItem).value); break; case ConstantPoolItemType.INTEGER: rv[i] = (<PrimitiveClassData> cl.getInitializedClass(thread, 'I')).createWrapperObject(thread, (<ConstInt32> cpItem).value); break; case ConstantPoolItemType.LONG: rv[i] = (<PrimitiveClassData> cl.getInitializedClass(thread, 'J')).createWrapperObject(thread, (<ConstLong> cpItem).value); break; case ConstantPoolItemType.FLOAT: rv[i] = (<PrimitiveClassData> cl.getInitializedClass(thread, 'F')).createWrapperObject(thread, (<ConstFloat> cpItem).value); break; case ConstantPoolItemType.DOUBLE: rv[i] = (<PrimitiveClassData> cl.getInitializedClass(thread, 'D')).createWrapperObject(thread, (<ConstDouble> cpItem).value); break; default: assert(false, "Invalid CPItem for static args: " + ConstantPoolItemType[cpItem.getType()]); break; } } assert((() => { var status = true; cpItems.forEach((cpItem: IConstantPoolItem, i: number) => { if (rv[i] === undefined) { console.log("Undefined item at arg " + i + ": " + ConstantPoolItemType[cpItem.getType()]); status = false; } else if (rv[i] === null) { console.log("Null item at arg " + i + ": " + ConstantPoolItemType[cpItem.getType()]); status = false; } }); return status; })(), "Arguments cannot be undefined or null."); return rvObj; } /** * A call site specifier gives a method descriptor, TD. A reference to an * instance of java.lang.invoke.MethodType is obtained as if by resolution * of a symbolic reference to a method type with the same parameter and * return types as TD (§5.4.3.5). * * Do what all OpenJDK-based JVMs do: Call * MethodHandleNatives.linkCallSite with: * - The class w/ the invokedynamic instruction * - The bootstrap method * - The name string from the nameAndTypeInfo * - The methodType object from the nameAndTypeInfo * - The static arguments from the bootstrap method. * - A 1-length appendix box. */ var methodName = thread.getJVM().internString(this.nameAndTypeInfo.name), appendixArr = new ((<ArrayClassData<JVMTypes.java_lang_Object>> cl.getInitializedClass(thread, '[Ljava/lang/Object;')).getConstructor(thread))(thread, 1), staticArgs = getArguments(), mhn = <typeof JVMTypes.java_lang_invoke_MethodHandleNatives> (<ReferenceClassData<JVMTypes.java_lang_invoke_MethodHandleNatives>> cl.getInitializedClass(thread, 'Ljava/lang/invoke/MethodHandleNatives;')).getConstructor(thread); mhn['java/lang/invoke/MethodHandleNatives/linkCallSite(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/invoke/MemberName;'](thread, [clazz.getClassObject(thread), bootstrapMethod[0].methodHandle, methodName, this.methodType, staticArgs, appendixArr], (e?: JVMTypes.java_lang_Throwable, rv?: JVMTypes.java_lang_invoke_MemberName) => { if (e) { thread.throwException(e); cb(false); } else { this.setResolved(pc, [rv, appendixArr.array[0]]); cb(true); } }); } private setResolved(pc: number, cso: [JVMTypes.java_lang_invoke_MemberName, JVMTypes.java_lang_Object]) { // Prevent resolution races. It's OK to create multiple CSOs, but only one // should ever be used! if (this.callSiteObjects[pc] === undefined) { this.callSiteObjects[pc] = cso; } } public static size: number = 1; public static infoByteSize: number = 4; public static fromBytes(byteStream: ByteStream, constantPool: ConstantPool): IConstantPoolItem { var bootstrapMethodAttrIndex = byteStream.getUint16(), nameAndTypeIndex = byteStream.getUint16(), nameAndTypeInfo = <NameAndTypeInfo> constantPool.get(nameAndTypeIndex); assert(nameAndTypeInfo.getType() === ConstantPoolItemType.NAME_AND_TYPE, 'ConstantPool InvokeDynamic types mismatch'); return new this(bootstrapMethodAttrIndex, nameAndTypeInfo); } } CP_CLASSES[ConstantPoolItemType.INVOKE_DYNAMIC] = InvokeDynamic; // #endregion // #region Tier 3 export interface IConstantPoolReference extends IConstantPoolItem { classInfo: ClassReference; nameAndTypeInfo: NameAndTypeInfo; getMethodHandleType(thread: JVMThread, cl: ClassLoader, cb: (e: any, type: JVMTypes.java_lang_Object) => void): void; } /** * Represents a given method handle. * ``` * CONSTANT_MethodHandle_info { * u1 tag; * u1 reference_kind; * u2 reference_index; * } * ``` */ export class MethodHandle implements IConstantPoolItem { private reference: FieldReference | MethodReference | InterfaceMethodReference; private referenceType: MethodHandleReferenceKind; /** * The resolved MethodHandle object. */ public methodHandle: JVMTypes.java_lang_invoke_MethodHandle = null; constructor(reference: FieldReference | MethodReference | InterfaceMethodReference, referenceType: MethodHandleReferenceKind) { this.reference = reference; this.referenceType = referenceType; } public getType(): ConstantPoolItemType { return ConstantPoolItemType.METHOD_HANDLE; } public isResolved(): boolean { return this.methodHandle !== null; } public getConstant(thread: JVMThread) { return this.methodHandle; } /** * Asynchronously constructs a JVM-visible MethodHandle object for this * MethodHandle. * * Requires producing the following, and passing it to a MethodHandle * constructor: * * [java.lang.Class] The defining class. * * [java.lang.String] The name of the field/method/etc. * * [java.lang.invoke.MethodType | java.lang.Class] The type of the field OR, * if a method, the type of the method descriptor. * * If needed, this function will resolve needed classes. */ public resolve(thread: JVMThread, cl: ClassLoader, caller: ReferenceClassData<JVMTypes.java_lang_Object>, cb: (status: boolean) => void, explicit: boolean) { if (!this.reference.isResolved()) { return this.reference.resolve(thread, cl, caller, (status: boolean) => { if (!status) { cb(false); } else { this.resolve(thread, cl, caller, cb, explicit); } }, explicit); } this.constructMethodHandleType(thread, cl, (type: JVMTypes.java_lang_Object) => { if (type === null) { cb(false); } else { var methodHandleNatives = <typeof JVMTypes.java_lang_invoke_MethodHandleNatives> (<ReferenceClassData<JVMTypes.java_lang_invoke_MethodHandleNatives>> cl.getInitializedClass(thread, 'Ljava/lang/invoke/MethodHandleNatives;')).getConstructor(thread); methodHandleNatives['linkMethodHandleConstant(Ljava/lang/Class;ILjava/lang/Class;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/invoke/MethodHandle;']( thread, [caller.getClassObject(thread), this.referenceType, this.getDefiningClassObj(thread), thread.getJVM().internString(this.reference.nameAndTypeInfo.name), type], (e?: JVMTypes.java_lang_Throwable, methodHandle?: JVMTypes.java_lang_invoke_MethodHandle) => { if (e) { thread.throwException(e); cb(false); } else { this.methodHandle = methodHandle; cb(true); } }); } }); } private getDefiningClassObj(thread: JVMThread): JVMTypes.java_lang_Class { if (this.reference.getType() === ConstantPoolItemType.FIELDREF) { return (<FieldReference> this.reference).field.cls.getClassObject(thread); } else { return (<MethodReference> this.reference).method.cls.getClassObject(thread); } } private constructMethodHandleType(thread: JVMThread, cl: ClassLoader, cb: (type: JVMTypes.java_lang_Object) => void): void { if (this.reference.getType() === ConstantPoolItemType.FIELDREF) { var resolveObj: string = this.reference.nameAndTypeInfo.descriptor; cl.resolveClass(thread, resolveObj, (cdata: ReferenceClassData<JVMTypes.java_lang_Object>) => { if (cdata !== null) { cb(cdata.getClassObject(thread)); } else { cb(null); } }); } else { util.createMethodType(thread, cl, this.reference.nameAndTypeInfo.descriptor, (e: JVMTypes.java_lang_Throwable, rv: JVMTypes.java_lang_invoke_MethodType) => { if (e) { thread.throwException(e); cb(null); } else { cb(rv); } }); } } public static size: number = 1; public static infoByteSize: number = 3; public static fromBytes(byteStream: ByteStream, constantPool: ConstantPool): IConstantPoolItem { var referenceKind: MethodHandleReferenceKind = byteStream.getUint8(), referenceIndex = byteStream.getUint16(), reference: FieldReference | MethodReference | InterfaceMethodReference = <any> constantPool.get(referenceIndex); assert(0 < referenceKind && referenceKind < 10, 'ConstantPool MethodHandle invalid referenceKind: ' + referenceKind); // Sanity check. assert((() => { switch (referenceKind) { case MethodHandleReferenceKind.GETFIELD: case MethodHandleReferenceKind.GETSTATIC: case MethodHandleReferenceKind.PUTFIELD: case MethodHandleReferenceKind.PUTSTATIC: return reference.getType() === ConstantPoolItemType.FIELDREF; case MethodHandleReferenceKind.INVOKEINTERFACE: return reference.getType() === ConstantPoolItemType.INTERFACE_METHODREF && (<MethodReference>reference).nameAndTypeInfo.name[0] !== '<'; case MethodHandleReferenceKind.INVOKEVIRTUAL: case MethodHandleReferenceKind.INVOKESTATIC: case MethodHandleReferenceKind.INVOKESPECIAL: // NOTE: Spec says METHODREF, but I've found instances where // INVOKESPECIAL is used on an INTERFACE_METHODREF. return (reference.getType() === ConstantPoolItemType.METHODREF || reference.getType() === ConstantPoolItemType.INTERFACE_METHODREF) && (<MethodReference>reference).nameAndTypeInfo.name[0] !== '<'; case MethodHandleReferenceKind.NEWINVOKESPECIAL: return reference.getType() === ConstantPoolItemType.METHODREF && (<MethodReference>reference).nameAndTypeInfo.name === '<init>'; } return true; })(), "Invalid constant pool reference for method handle reference type: " + MethodHandleReferenceKind[referenceKind]); return new this(reference, referenceKind); } } CP_CLASSES[ConstantPoolItemType.METHOD_HANDLE] = MethodHandle; // #endregion /** * Constant pool type *resolution tiers*. Value is the tier, key is the * constant pool type. * Tier 0 has no references to other constant pool items, and can be resolved * first. * Tier 1 refers to tier 0 items. * Tier n refers to tier n-1 items and below. * Initialized in the given fashion to give the JS engine a tasty type hint. */ var CONSTANT_POOL_TIER: number[] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // Populate CONSTANT_POOL_TIER. Put into a closure to avoid scope pollution. ((tierInfos: ConstantPoolItemType[][]) => { tierInfos.forEach((tierInfo: ConstantPoolItemType[], index: number) => { tierInfo.forEach((type: ConstantPoolItemType) => { CONSTANT_POOL_TIER[type] = index; }); }); })([ // Tier 0 [ ConstantPoolItemType.UTF8, ConstantPoolItemType.INTEGER, ConstantPoolItemType.FLOAT, ConstantPoolItemType.LONG, ConstantPoolItemType.DOUBLE ], // Tier 1 [ ConstantPoolItemType.CLASS, ConstantPoolItemType.STRING, ConstantPoolItemType.NAME_AND_TYPE, ConstantPoolItemType.METHOD_TYPE ], // Tier 2 [ ConstantPoolItemType.FIELDREF, ConstantPoolItemType.METHODREF, ConstantPoolItemType.INTERFACE_METHODREF, ConstantPoolItemType.INVOKE_DYNAMIC ], // Tier 3 [ ConstantPoolItemType.METHOD_HANDLE ] ]); /** * Represents a constant pool for a particular class. */ export class ConstantPool { /** * The core constant pool array. Note that some indices are undefined. */ private constantPool: IConstantPoolItem[]; public parse(byteStream: ByteStream, cpPatches: JVMTypes.JVMArray<JVMTypes.java_lang_Object> = null): ByteStream { var cpCount = byteStream.getUint16(), // First key is the tier. deferredQueue: { offset: number; index: number }[][] = [[], [], []], // The ending offset of the constant pool items. endIdx = 0, idx = 1, // Tag of the currently-being-processed item. tag = 0, // Offset of the currently-being-processed item. itemOffset = 0, // Tier of the currently-being-processed item. itemTier = 0; this.constantPool = new Array<IConstantPoolItem>(cpCount); // Scan for tier info. while (idx < cpCount) { itemOffset = byteStream.pos(); tag = byteStream.getUint8(); assert(CP_CLASSES[tag] !== null && CP_CLASSES[tag] !== undefined, 'Unknown ConstantPool tag: ' + tag); itemTier = CONSTANT_POOL_TIER[tag]; if (itemTier > 0) { deferredQueue[itemTier - 1].push({ offset: itemOffset, index: idx }); byteStream.skip(CP_CLASSES[tag].infoByteSize); } else { this.constantPool[idx] = CP_CLASSES[tag].fromBytes(byteStream, this); } idx += CP_CLASSES[tag].size; } endIdx = byteStream.pos(); // Process tiers. deferredQueue.forEach((deferredItems: { offset: number; index: number; }[]) => { deferredItems.forEach((item: { offset: number; index: number; }) => { byteStream.seek(item.offset); tag = byteStream.getUint8(); this.constantPool[item.index] = CP_CLASSES[tag].fromBytes(byteStream, this); if (cpPatches !== null && cpPatches.array[item.index] !== null && cpPatches.array[item.index] !== undefined) { /* * For each CP entry, the corresponding CP patch must either be null or have * the format that matches its tag: * * * Integer, Long, Float, Double: the corresponding wrapper object type from java.lang * * Utf8: a string (must have suitable syntax if used as signature or name) * * Class: any java.lang.Class object * * String: any object (not just a java.lang.String) * * InterfaceMethodRef: (NYI) a method handle to invoke on that call site's arguments */ var patchObj: JVMTypes.java_lang_Object = cpPatches.array[item.index]; switch (patchObj.getClass().getInternalName()) { case 'Ljava/lang/Integer;': assert(tag === ConstantPoolItemType.INTEGER); (<ConstInt32> this.constantPool[item.index]).value = (<JVMTypes.java_lang_Integer> patchObj)['java/lang/Integer/value']; break; case 'Ljava/lang/Long;': assert(tag === ConstantPoolItemType.LONG); (<ConstLong> this.constantPool[item.index]).value = (<JVMTypes.java_lang_Long> patchObj)['java/lang/Long/value']; break; case 'Ljava/lang/Float;': assert(tag === ConstantPoolItemType.FLOAT); (<ConstFloat> this.constantPool[item.index]).value = (<JVMTypes.java_lang_Float> patchObj)['java/lang/Float/value']; break; case 'Ljava/lang/Double;': assert(tag === ConstantPoolItemType.DOUBLE); (<ConstDouble> this.constantPool[item.index]).value = (<JVMTypes.java_lang_Double> patchObj)['java/lang/Double/value']; break; case 'Ljava/lang/String;': assert(tag === ConstantPoolItemType.UTF8); (<ConstUTF8> this.constantPool[item.index]).value = (<JVMTypes.java_lang_String> patchObj).toString(); break; case 'Ljava/lang/Class;': assert(tag === ConstantPoolItemType.CLASS); (<ClassReference> this.constantPool[item.index]).name = (<JVMTypes.java_lang_Class> patchObj).$cls.getInternalName(); (<ClassReference> this.constantPool[item.index]).cls = <ReferenceClassData<JVMTypes.java_lang_Object>> (<JVMTypes.java_lang_Class> patchObj).$cls; break; default: assert(tag === ConstantPoolItemType.STRING); (<ConstString> this.constantPool[item.index]).stringValue = ""; // XXX: Not actually a string, but the JVM does this. (<ConstString> this.constantPool[item.index]).value = <JVMTypes.java_lang_String> patchObj; break; } } }); }); // Return to the correct offset, at the end of the CP data. byteStream.seek(endIdx); return byteStream; } public get(idx: number): IConstantPoolItem { assert(this.constantPool[idx] !== undefined, "Invalid ConstantPool reference."); return this.constantPool[idx]; } public each(fn: (idx: number, item: IConstantPoolItem) => void): void { this.constantPool.forEach((item: IConstantPoolItem, idx: number) => { if (item !== undefined) { fn(idx, item); } }); } } /// Resolved forms of constant pool items.
the_stack
import React from 'react'; import { JSONSchema7 as JSONSchema } from 'json-schema'; import isEqual from 'lodash/isEqual'; import size from 'lodash/size'; import intersectionBy from 'lodash/intersectionBy'; import { Lenses, CollectionLenses } from './Lenses'; import { Tags } from './Tags'; import { Create } from './Actions/Create'; import { Filters } from './Filters'; import { Update } from './Actions/Update'; import { List } from './List'; import { AutoUIAction, AutoUIContext, AutoUIModel, AutoUIBaseResource, getFieldForFormat, AutoUIRawModel, autoUIJsonSchemaPick, } from '../schemaOps'; import styled from 'styled-components'; import { Flex } from '../../../components/Flex'; import { ResourceTagModelService } from '../../../components/TagManagementModal/tag-management-service'; import { notifications } from '../../../components/Notifications'; import { Spinner } from '../../../components/Spinner'; import { Box } from '../../../components/Box'; import { filter } from '../../../components/Filters/SchemaSieve'; import { Format } from '../../../components/Renderer/types'; import { getFromLocalStorage, setToLocalStorage } from '../../../utils'; import { ResourceTagSubmitInfo, SubmitInfo, } from '../../../components/TagManagementModal/models'; import { autoUIRunTransformers, autoUIGetModelForCollection, autoUIDefaultPermissions, autoUIAddToSchema, } from '../models/helpers'; import { autoUIGetDisabledReason } from '../utils'; import { NoRecordsFoundArrow } from './NoRecordsFoundArrow'; import { Dictionary } from '../../../common-types'; import { useTranslation } from '../../../hooks/useTranslation'; // Assumptions that I think we can easily make: // We only handle a single-level schema. If a schema is nested, it is handled by the `format` component internally. // TODO: // In rendition if there is an existing notification with a certain ID when submitting a new one, replace it with the new one. // Move tableWithCustomColumns to rendition // Make the Table JSON-schema compliant // Implement sort functions per format // 1-to-1 relationships should resolve as an object, not an array with one item (eg is_for__device_type should be an object when expanded). // One to many relationships can be both a number (when using $count) and an array of objects, pine should return counts as part of an object instead (eg. always return an object with __count, and data: []). This can generalize for any field, if we find a `__count` we can render the count instead. Maybe handle this as a format, so it will handle both numbers and arrays? I guess this will be the smallest shape of a collection summary. // Make table handle tags better so we don't have to filter it out from the schema. // Specifically for the table, how should we treat columns that are based on multiple schema fields, shall we have some rule around that? Eg. the release "deployment" column combines "status" and "source" and it does appear more compact than having a separate column just to say it is a cloud build or a balena deploy one. // How shall we handle batch edits (especially when the data differs between entries)? We already do this for HUP but it is all custom code, we need to generalize it. // SDK's CRUD should all have the same function signature (eg. apiKey.create doesnt take a single object, but two separate fields). const HeaderGrid = styled(Flex)` margin-left: -4px; margin-right: -4px; > * { margin-left: 4px; margin-right: 4px; } `; const getSelectedItems = <T extends AutoUIBaseResource<T>>( newItems: T[], selectedItems: T[], ) => { if (!size(selectedItems)) { return selectedItems; } // update the selections selectedItems = intersectionBy(newItems, selectedItems, 'id'); return selectedItems; }; export interface ActionData<T> { action: AutoUIAction<T>; schema: JSONSchema; affectedEntries?: T[]; } export interface AutoUICollectionProps<T> { /** Model is the property that describe the data to display with a JSON structure */ model: AutoUIModel<T>; /** Array of data to display */ data: T[] | undefined; /** Formats are custom widgets to render in the table cell. The type of format to display is described in the model. */ formats?: Format[]; /** Actions is an array of actions applicable on the selected items */ actions?: Array<AutoUIAction<T>>; /** The sdk is used to pass the method to handle tags when added removed or updated */ sdk?: { tags?: ResourceTagModelService; }; /** Dictionary of {[column_property]: customFunction} where the customFunction is the function to sort data on column header click */ customSort?: Dictionary<(a: T, b: T) => void>; /** Pass a component to display each data item in that component instead of a table */ cardRenderer?: AutoUIContext<T>['cardRenderer']; // TODO: Ideally the base URL is autogenerated, but there are some issues with that currently (eg. instead of application we have apps in the URL) /** Redirect on row click */ getBaseUrl?: (entry: T) => string; /** Method to refresh the collection when something is changed */ refresh?: () => void; /** Event emitted on row click */ onRowClick?: ( entry: T, event: React.MouseEvent<HTMLAnchorElement, MouseEvent>, ) => void; } /** Collection component is one of the components that are part of a larger project, namely AutoUI. This component renders a list using an array of data and a template. * * Model example with Description: * <pre><code> * { * resource: 'sshKey' <span style="color:green">// This is the name of the DB resource, </span><br /> * schema: { * type: 'object', <span style="color:green">// Type of each entity inside the resource, </span><br /> * required: ['title', 'public_key'], <span style="color:green">// Required properties for actions like create (NOT WELL DEFINED YET, WIP) </span><br /> * properties: { <span style="color:green">// Entity Properties </span><br /> * id: { * title: 'Id', <span style="color:green">// Column Title </span><br /> * type: 'number', <span style="color:green">// Column type </span><br /> * }, * title: { * title: 'Title', * type: 'string', * }, * fingerprint: { * title: 'Fingerprint', * type: 'string', * }, * public_key: { * title: 'Public key', * type: 'string', * format: 'public-key', <span style="color:green">// Cell format, a custom format can be passed. This will decide how to render the cell </span><br /> * }, * created_at: { * title: 'Date added', * type: 'string', * format: 'date-time', * }, * }, * }, * permissions: { <span style="color:green">// Permissions are necessary to understand which type of user can do a certain action </span><br /> * default: defaultPermissions, * administrator: { * read: ['id', 'title', 'created_at', 'public_key', 'fingerprint'], * create: ['title', 'public_key'], * update: ['title', 'public_key'], * delete: true, * }, * }, * priorities: { <span style="color:green">// Will decide the order of the columns and the visibility </span><br /> * primary: ['title'], <span style="color:green">// Will display these properties in first position </span><br /> * secondary: ['created_at', 'public_key', 'fingerprint'], <span style="color:green">// Will display these properties in a secondary position </span><br /> * tertiary: [], <span style="color:green">// Will initially hide the properties from the list </span><br /> * } * } * </code></pre> * */ export const AutoUICollection = <T extends AutoUIBaseResource<T>>({ model: modelRaw, data, formats, actions, sdk, customSort, refresh, cardRenderer, getBaseUrl, onRowClick, }: AutoUICollectionProps<T>) => { const { t } = useTranslation(); const defaultLens = !!cardRenderer ? CollectionLenses.Grid : CollectionLenses.Table; const modelRef = React.useRef(modelRaw); // This allows the collection to work even if // consumers are passing a new model object every time. const model = React.useMemo(() => { if (isEqual(modelRaw, modelRef.current)) { return modelRef.current; } return modelRaw; }, [modelRaw]); const [lens, setLens] = React.useState( getFromLocalStorage(`${model.resource}__view_lens`) ?? defaultLens, ); const [filters, setFilters] = React.useState<JSONSchema[]>([]); const [selected, setSelected] = React.useState<T[]>([]); const [isBusyMessage, setIsBusyMessage] = React.useState< string | undefined >(); const [actionData, setActionData] = React.useState< ActionData<T> | undefined >(); const showFilters = !!(data?.length && data.length > 5); const showActions = !!data?.length; const autouiContext = React.useMemo( () => ({ resource: model.resource, idField: 'id', nameField: model.priorities?.primary[0] ?? 'id', tagField: getFieldForFormat(model.schema, 'tag'), getBaseUrl, onRowClick, actions, cardRenderer, customSort, sdk, } as AutoUIContext<T>), [model, actions, cardRenderer, sdk, onRowClick], ); const filtered = React.useMemo( () => (data ? filter(filters, data) : []) as T[], [data, filters], ); React.useEffect(() => { setSelected((oldSelected) => getSelectedItems(oldSelected, filtered)); }, [filtered]); const changeTags = React.useCallback( async (tags: SubmitInfo<ResourceTagSubmitInfo, ResourceTagSubmitInfo>) => { if (!sdk?.tags) { return; } setIsBusyMessage(t(`loading.updating_release_tags`)); notifications.addNotification({ id: 'change-tags-loading', content: t(`loading.updating_release_tags`), }); try { await sdk.tags.submit(tags); setSelected([]); notifications.addNotification({ id: 'change-tags', content: 'Tags updated successfully', type: 'success', }); refresh?.(); } catch (err) { notifications.addNotification({ id: 'change-tags', content: err.message, type: 'danger', }); } finally { notifications.removeNotification('change-tags-loading'); setIsBusyMessage(undefined); } }, [sdk?.tags, refresh], ); const onActionTriggered = React.useCallback((actionData: ActionData<T>) => { setActionData(actionData); if (actionData.action.actionFn) { actionData.action.actionFn({ affectedEntries: actionData.affectedEntries || [], }); } }, []); const onActionDone = React.useCallback((isSuccessful: boolean) => { if (isSuccessful) { setSelected([]); } setActionData(undefined); }, []); const handleLensChange = (lens: CollectionLenses) => { setLens(lens); setToLocalStorage(`${model.resource}__view_lens`, lens); }; return ( <Flex flexDirection="column" mt={2}> <Spinner label={ isBusyMessage ?? t('loading.resource', { resource: t(`resource.${model.resource}_plural`).toLowerCase(), }) } show={data == null || !!isBusyMessage} > <Box> <HeaderGrid flexWrap="wrap" justifyContent="space-between"> <Create model={model} autouiContext={autouiContext} hasOngoingAction={false} onActionTriggered={onActionTriggered} /> <Box order={[-1, -1, -1, 0]} flex={['1 0 100%', '1 0 100%', '1 0 100%', 'auto']} > {showFilters && ( <Filters schema={model.schema} filters={filters} autouiContext={autouiContext} changeFilters={setFilters} /> )} </Box> <HeaderGrid> {showActions && !!sdk?.tags && ( <Tags autouiContext={autouiContext} selected={selected} changeTags={changeTags} /> )} {showActions && ( <Update model={model} selected={selected} autouiContext={autouiContext} hasOngoingAction={false} onActionTriggered={onActionTriggered} /> )} <Lenses autouiContext={autouiContext} lens={lens} changeLens={handleLensChange} /> </HeaderGrid> </HeaderGrid> <Filters renderMode={'summary'} schema={model.schema} filters={filters} autouiContext={autouiContext} changeFilters={setFilters} /> </Box> {data && data.length === 0 && ( <NoRecordsFoundArrow> {t(`no_data.no_resource_data`, { resource: t(`resource.item_plural`).toLowerCase(), })} <br /> {t('questions.how_about_adding_one')} </NoRecordsFoundArrow> )} {data && data.length > 0 && ( <List schema={model.schema} priorities={model.priorities} autouiContext={autouiContext} data={data} lens={lens} selected={selected} filtered={filtered} changeSelected={setSelected} formats={formats} /> )} {actionData?.action?.renderer && actionData.action.renderer({ schema: actionData.schema, affectedEntries: actionData.affectedEntries, onDone: onActionDone, })} </Spinner> </Flex> ); }; export { autoUIRunTransformers, autoUIDefaultPermissions, autoUIGetModelForCollection, autoUIAddToSchema, AutoUIAction, AutoUIBaseResource, AutoUIRawModel, AutoUIModel, autoUIJsonSchemaPick, autoUIGetDisabledReason, };
the_stack
import { ITreeNode, ITreeView } from "@abstractions/project-node"; import { ILiteEvent, LiteEvent } from "@core/utils/lite-event"; /** * This class implements a tree node. * @param TNode The type of tree nodes */ export class TreeNode<TNode> implements ITreeNode<TNode> { private _parentNode: ITreeNode<TNode> | undefined; private _parentTree: ITreeView<TNode> | undefined; private _children: Array<ITreeNode<TNode>> = []; private _level = 0; private _depth = 0; private _isExpanded = true; private _isHidden = false; private _viewItemCount = 0; private _parentNodeChanged = new LiteEvent<ITreeNode<TNode> | undefined>(); private _parentTreeChanged = new LiteEvent<ITreeView<TNode> | undefined>(); private _childAdded = new LiteEvent<[ITreeNode<TNode>, number]>(); private _childRemoved = new LiteEvent<ITreeNode<TNode>>(); /** * Instantiated a new node with the specified data. * @param nodeData */ constructor(nodeData: TNode) { this.nodeData = nodeData; this._viewItemCount = 1; } /** * Tree node data */ nodeData: TNode; /** * Retrieves the string representation of the node's data. */ toString(): string { const name = this.nodeData && this.nodeData.toString ? this.nodeData.toString() : ""; return name; } /** * The parent of this node */ get parentNode(): ITreeNode<TNode> | undefined { return this._parentNode; } set parentNode(value: ITreeNode<TNode> | undefined) { if (this._parentNode !== value) { this._parentNode = value; this._parentNodeChanged.fire(value); } } /** * This event is raised when this node's parent has been changed. The event argument * is the new child. */ get parentNodeChanged(): ILiteEvent<ITreeNode<TNode> | undefined> { return this._parentNodeChanged; } /** * The parent tree of this node */ get parentTree(): ITreeView<TNode> | undefined { return this._parentTree; } /** * Sets the parent tree of this node. * @param value The new parent tree value */ setParentTree(value: ITreeView<TNode> | undefined) { if (this._parentTree !== value) { this._parentTree = value; this.forEachDescendant( (child) => ((child as TreeNode<TNode>)._parentTree = value) ); this._parentTreeChanged.fire(value); } } /** * This event is raised when this node's parent tree has been changed. The * event argument is the new tree of this node. */ get parentTreeChanged(): ILiteEvent<ITreeView<TNode> | undefined> { return this._parentTreeChanged; } /** * Gets the number of child nodes nested into this tree node. */ get childCount(): number { return this._children.length; } /** * Gets the set of child nodes. The retrieved value is a clone of the * child node's list. Updating that list does not change the original * list of child nodes. */ getChildren(): Array<ITreeNode<TNode>> { return this._children.slice(0); } /** * Gets the child with the specified index. * @param index Child index */ getChild(index: number): ITreeNode<TNode> { if (index < 0 || index >= this._children.length) { throw new Error( `Children index ${index} is out of range 0..${ this._children.length - 1 }` ); } return this._children[index]; } /** * Appends a new child to this child node. Takes care of * avoiding circular references. * @param child The child to append to this child node. * @returns The number of child nodes after the operation. */ appendChild(child: ITreeNode<TNode>): number { return this._insertChild(this._children.length, child); } /** * Inserts a child into this child node at the specified position. * Takes care of avoiding circular references. * @param index Insertion index. * @param child The child to insert into this child node. * @returns The number of child nodes after the operation. */ insertChildAt(index: number, child: ITreeNode<TNode>): number { return this._insertChild(index, child); } /** * Takes over the specified children * @param children Children to take over */ takeOverChildren(children: Array<ITreeNode<TNode>>): void { this._children = []; for (const child of children) { // --- Insert the child this._children.push(child); // --- Attach parents (child as TreeNode<TNode>).parentNode = this; if (this.parentTree) { (child as TreeNode<TNode>).setParentTree(this.parentTree); } // --- Recalculate level and depth (child as TreeNode<TNode>)._level = this._level + 1; child.forEachDescendant((c) => { (c as TreeNode<TNode>)._level = c.parentNode.level + 1; }); this._depth = this._calcDepth(); child.forEachParent((p) => { (p as TreeNode<TNode>)._depth = (p as TreeNode<TNode>)._calcDepth(); }); // --- The view item count may have changed this.calculateViewItemCount(); } } /** * This event is raised when a new child has been added to this node. The * event argument is a tuple of two values. The first is the new node, the * second is its index in the child list. */ get childAdded(): ILiteEvent<[ITreeNode<TNode>, number]> { return this._childAdded; } /** * Removes the specified child from this node. * @param child The child to append to remove. * @returns The removed child node, if found; otherwise, undefined. */ removeChild(child: ITreeNode<TNode>): ITreeNode<TNode> | undefined { const index = this._children.indexOf(child); if (index < 0) { return undefined; } return this._removeChild(index); } /** * Removes the child at the specified index from this node. * @param index Insertion index. * @returns The removed child node. */ removeChildAt(index: number): ITreeNode<TNode> { return this._removeChild(index); } /** * This event is raised when a child has been removed from this node. The * event argument is the removed child. */ get childRemoved(): ILiteEvent<ITreeNode<TNode>> { return this._childRemoved; } /** * Tests is the specified node is in the tree starting with this node. * This tree node is included in the test. * @param node Child to test * @returns True, if the node is in the tree; otherwise, false. */ isInTree(node: ITreeNode<TNode>): boolean { return node === this || this._children.some((c) => c.isInTree(node)); } /** * Indicates that this tree node is expanded in its view */ get isExpanded(): boolean { return this._isExpanded; } set isExpanded(value: boolean) { if (value !== this._isExpanded) { this._isExpanded = value; this.calculateViewItemCount(); } } /** * Indicates if this node is hidden in its view */ get isHidden(): boolean { return this._isHidden; } set isHidden(value: boolean) { if (value !== this._isHidden) { this._isHidden = value; this.calculateViewItemCount(); } } /** * The depth level of the tree including hidden nodes */ get level(): number { return this._level; } /** * The depth of the tree node. If the node has no children, its depth * is 0, otherwise it is 1 plus the maximum depth of its children. */ get depth(): number { return this._depth; } /** * The number of visible items. * @returns The number of items that would be shown in the * tree view for this node, including this item in its current * state, and its child nodes. */ get viewItemCount(): number { return this._viewItemCount; } /** * Gets the next tree node at using depth-first-search (DFS) traversal. * Hidden and collapsed nodes are skipped. * @returns The next node, if exists; otherwise, `undefined`. */ getNextViewNode(): ITreeNode<TNode> | undefined { // --- Try to retrieve the first visible child if (this.isExpanded && !this.isHidden) { const child = this._getFirstVisibleChild(); if (child) { return child; } } // --- No visible child, let's check the parent hierarchy up to the root let childNode: ITreeNode<TNode> = this; let parentNode = this.parentNode; while (parentNode) { const childIndex = parentNode.getChildren().indexOf(childNode); // --- Check just for the sake of safety if (childIndex < 0) { throw new Error("This node is not on it's parent child list!"); } // --- Get a visible sibling const sibling = (parentNode as TreeNode<TNode>)._getFirstVisibleChild( childIndex + 1 ); if (sibling) { return sibling; } // --- This level completed, step back to an upper level childNode = parentNode; parentNode = childNode.parentNode; } // --- We traversed the entire chain with no next node return undefined; } /** * Traverses from the first parent to the root element and executes * the specified action on each node. * @param action Action to execute. * @param includeThis Should include this node in traversal? */ forEachParent( action: (item: ITreeNode<TNode>) => void, includeThis: boolean = false ): void { let currentNode: ITreeNode<TNode> = includeThis ? this : this._parentNode; while (currentNode) { action(currentNode); currentNode = currentNode.parentNode; } } /** * Traverses all child nodes and then their child nodes recursively. Executes * the specified action on each node. * @param action Action to execute. */ forEachDescendant(action: (item: ITreeNode<TNode>) => void): void { for (const child of this._children) { action(child); child.forEachDescendant(action); } } // ======================================================================== // Helpers /** * Inserts a child node to the children list into the specified position. * @param index Index to insert the child * @param child Child to insert * @returns The number of child nodes after this operation. */ private _insertChild(index: number, child: ITreeNode<TNode>): number { if (child.parentNode) { throw new Error("The child node is attached to another parent."); } if (child.parentTree) { throw new Error("The child node is attached to another tree view."); } if (child.isInTree(this)) { throw new Error("Adding this child would cause a circular reference."); } if (index < 0 || index > this._children.length) { throw new Error( `Children index ${index} is out of range 0..${this._children.length}` ); } // --- Insert the child this._children.splice(index, 0, child); // --- Attach parents (child as TreeNode<TNode>).parentNode = this; if (this.parentTree) { (child as TreeNode<TNode>).setParentTree(this.parentTree); } // --- Recalculate level and depth (child as TreeNode<TNode>)._level = this._level + 1; child.forEachDescendant((c) => { (c as TreeNode<TNode>)._level = c.parentNode.level + 1; }); this._depth = this._calcDepth(); child.forEachParent((p) => { (p as TreeNode<TNode>)._depth = (p as TreeNode<TNode>)._calcDepth(); }); // --- The view item count may have changed this.calculateViewItemCount(); // --- Done this._childAdded.fire([child, index]); return this._children.length; } /** * Removes the specified child from this node. * @param index Index of child to remove. * @returns The removed child node. */ private _removeChild(index: number): ITreeNode<TNode> { if (index < 0 || index >= this._children.length) { throw new Error( `Children index ${index} is out of range 0..${ this._children.length - 1 }` ); } // --- Remove the child const child = this._children.splice(index, 1)[0]; // --- Detach parents (child as TreeNode<TNode>).parentNode = undefined; (child as TreeNode<TNode>).setParentTree(undefined); // --- Recalculate level and depth (child as TreeNode<TNode>)._level = 0; child.forEachDescendant((c) => { (c as TreeNode<TNode>)._level = c.parentNode.level + 1; }); this._depth = this._calcDepth(); child.forEachParent((p) => { (p as TreeNode<TNode>)._depth = (p as TreeNode<TNode>)._calcDepth(); }); // --- The view item count may have changed this.calculateViewItemCount(); // --- Done this._childRemoved.fire(child); return child; } /** * Gets the first visible child of this node * @param index Start index to use */ private _getFirstVisibleChild( index: number = 0 ): ITreeNode<TNode> | undefined { while (index < this.childCount) { const child = this.getChild(index); if (!child.isHidden) { return child; } index++; } return undefined; } /** * Calculates the `viewItemCount` property value */ calculateViewItemCount(): void { const oldViewItemCount = this._viewItemCount; // --- Hidden items if (this._isHidden) { this._viewItemCount = 0; } else { // --- Visible items this._viewItemCount = 1; // --- Expanded visible items if (this._isExpanded) { for (const child of this._children) { this._viewItemCount += (child as TreeNode<TNode>)._viewItemCount; } } } // --- Now, do this for the entire parent chain if (oldViewItemCount !== this._viewItemCount) { this.forEachParent((parent) => (parent as TreeNode<TNode>).calculateViewItemCount() ); } } /** * Calculates the depth of this node */ private _calcDepth(): number { if (this._children.length === 0) { return 0; } let maxDepth = 0; for (const child of this._children) { const childDepth = child.depth; if (childDepth > maxDepth) { maxDepth = childDepth; } } return maxDepth + 1; } }
the_stack
import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { ClientService } from '../services/client.service'; import { SampleBusinessNetworkService } from '../services/samplebusinessnetwork.service'; import { AlertService } from '../basic-modals/alert.service'; import { ConfigService } from '../services/config.service'; import { IdentityCardService } from '../services/identity-card.service'; import { BusinessNetworkDefinition } from 'composer-common'; @Component({ selector: 'deploy-business-network', templateUrl: './deploy.component.html', styleUrls: ['./deploy.component.scss'.toString()], }) export class DeployComponent implements OnInit { @Input() showCredentials: boolean; @Output() finishedSampleImport = new EventEmitter<any>(); private currentBusinessNetwork = null; private deployInProgress: boolean = false; private npmInProgress: boolean = false; private sampleNetworks = []; private chosenNetwork = null; private expandInput: boolean = false; private sampleDropped: boolean = false; private uploadedNetwork = null; private networkDescription: string; private networkName: string; private networkNameValid: boolean = true; private cardNameValid: boolean = true; private userId: string = ''; private userSecret: string = null; private credentials = null; private cardName: string = null; private currentBusinessNetworkPromise: Promise<BusinessNetworkDefinition>; private maxFileSize: number = 5242880; private supportedFileTypes: string[] = ['.bna']; private lastName = 'empty-business-network'; private lastDesc = ''; private NAME = 'empty-business-network'; private DESC = 'Start from scratch with a blank business network'; private EMPTY_BIZNET = {name: this.NAME, description: this.DESC}; constructor(protected clientService: ClientService, protected modalService: NgbModal, protected sampleBusinessNetworkService: SampleBusinessNetworkService, protected alertService: AlertService) { } ngOnInit(): Promise<void> { this.currentBusinessNetwork = null; return this.onShow(); } onShow(): Promise<void> { this.npmInProgress = true; return this.sampleBusinessNetworkService.getSampleList() .then((sampleNetworkList) => { this.initNetworkList(sampleNetworkList); }) .catch((error) => { this.initNetworkList([]); }); } selectNetwork(network): void { this.chosenNetwork = network; this.updateBusinessNetworkNameAndDesc(network); if (this.chosenNetwork.name !== this.NAME) { this.currentBusinessNetworkPromise = this.sampleBusinessNetworkService.getChosenSample(this.chosenNetwork).then((result) => { this.currentBusinessNetwork = result; this.currentBusinessNetwork.participants = result.getModelManager().getParticipantDeclarations(false); this.currentBusinessNetwork.assets = result.getModelManager().getAssetDeclarations(false); this.currentBusinessNetwork.transactions = result.getModelManager().getTransactionDeclarations(false); return this.currentBusinessNetwork; }); } else { this.deployEmptyNetwork(); } } addEmptyNetworkOption(networks: any[]): any[] { let newOrder = []; newOrder.push(this.EMPTY_BIZNET); for (let i = 0; i < networks.length; i++) { newOrder.push(networks[i]); } return newOrder; } updateBusinessNetworkNameAndDesc(network) { let nameEl = this.networkName; let descEl = this.networkDescription; let name = network.name; let desc = (typeof network.description === 'undefined') ? '' : network.description; if ((nameEl === '' || nameEl === this.lastName || typeof nameEl === 'undefined')) { this.networkName = name; this.lastName = name; } if ((descEl === '' || descEl === this.lastDesc || typeof descEl === 'undefined')) { this.networkDescription = desc; this.lastDesc = desc; } } deploy() { let deployed: boolean = true; this.deployInProgress = true; return this.sampleBusinessNetworkService.deployBusinessNetwork(this.currentBusinessNetwork, this.cardName, this.networkName, this.networkDescription, this.userId, this.userSecret, this.credentials) .then(() => { this.cardNameValid = true; this.deployInProgress = false; this.finishedSampleImport.emit({deployed: deployed}); }) .catch((error) => { this.deployInProgress = false; if (error.message.startsWith('Card already exists: ')) { this.cardNameValid = false; } else { this.alertService.errorStatus$.next(error); this.finishedSampleImport.emit({deployed: false, error: error}); } }); } deployEmptyNetwork(): void { let readme = 'This is the readme file for the Business Network Definition created in Playground'; let packageJson = { name: 'unnamed-network', author: 'author', description: 'Empty Business Network', version: '0.0.1', devDependencies: { 'browserfs': '^1.2.0', 'chai': '^3.5.0', 'composer-admin': 'latest', 'composer-cli': 'latest', 'composer-client': 'latest', 'composer-connector-embedded': 'latest', 'eslint': '^3.6.1', 'istanbul': '^0.4.5', 'jsdoc': '^3.4.1', 'mkdirp': '^0.5.1', 'mocha': '^3.2.0', 'moment': '^2.19.3' }, keywords: [], license: 'Apache 2.0', repository: { type: 'e.g. git', url: 'URL' }, scripts: { deploy: './scripts/deploy.sh', doc: 'jsdoc --pedantic --recurse -c jsdoc.conf', lint: 'eslint .', postlicchk: 'npm run doc', postlint: 'npm run licchk', prepublish: 'mkdirp ./dist && composer archive create --sourceType dir --sourceName . -a ./dist/unnamed-network.bna', pretest: 'npm run lint', test: 'mocha --recursive' } }; let permissions = `/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ rule NetworkAdminUser { description: "Grant business network administrators full access to user resources" participant: "org.hyperledger.composer.system.NetworkAdmin" operation: ALL resource: "**" action: ALLOW } rule NetworkAdminSystem { description: "Grant business network administrators full access to system resources" participant: "org.hyperledger.composer.system.NetworkAdmin" operation: ALL resource: "org.hyperledger.composer.system.**" action: ALLOW }`; let emptyModelFile = `/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace org.example.empty `; this.currentBusinessNetworkPromise = Promise.resolve().then(() => { this.currentBusinessNetwork = this.sampleBusinessNetworkService.createNewBusinessDefinition('', '', packageJson, readme); const aclManager = this.currentBusinessNetwork.getAclManager(); const aclFile = aclManager.createAclFile('permissions.acl', permissions); aclManager.setAclFile(aclFile); this.currentBusinessNetwork.getModelManager().addModelFile(emptyModelFile, 'model.cto'); this.currentBusinessNetwork.participants = this.currentBusinessNetwork.getModelManager().getParticipantDeclarations(false); this.currentBusinessNetwork.assets = this.currentBusinessNetwork.getModelManager().getAssetDeclarations(false); this.currentBusinessNetwork.transactions = this.currentBusinessNetwork.getModelManager().getTransactionDeclarations(false); return this.currentBusinessNetwork; }); } updateCredentials($event) { // credentials not valid yet if (!$event || !$event.userId) { this.userId = null; this.userSecret = null; this.credentials = null; return; } if ($event.secret) { this.userSecret = $event.secret; this.credentials = null; } else { this.userSecret = null; this.credentials = { certificate: $event.cert, privateKey: $event.key }; } this.userId = $event.userId; } isInvalidDeploy() { if (!this.networkName || !this.networkNameValid || this.deployInProgress || !this.cardNameValid || (this.showCredentials && !this.userId)) { return true; } return false; } closeSample() { this.sampleDropped = false; this.selectNetwork(this.sampleNetworks[0]); } removeFile() { this.expandInput = false; this.currentBusinessNetwork = null; } private fileDetected() { this.expandInput = true; } private fileLeft() { this.expandInput = false; } private fileAccepted(file: File): void { let fileReader = new FileReader(); fileReader.onload = () => { let dataBuffer = Buffer.from(fileReader.result); this.currentBusinessNetworkPromise = this.clientService.getBusinessNetworkFromArchive(dataBuffer) .then((businessNetwork) => { this.chosenNetwork = businessNetwork.getMetadata().getPackageJson(); this.updateBusinessNetworkNameAndDesc(this.chosenNetwork); this.currentBusinessNetwork = businessNetwork; this.currentBusinessNetwork.participants = businessNetwork.getModelManager().getParticipantDeclarations(false); this.currentBusinessNetwork.assets = businessNetwork.getModelManager().getAssetDeclarations(false); this.currentBusinessNetwork.transactions = businessNetwork.getModelManager().getTransactionDeclarations(false); this.sampleDropped = true; // needed for if browse file this.expandInput = false; this.uploadedNetwork = this.chosenNetwork; return businessNetwork; }) .catch((error) => { let failMessage = 'Cannot import an invalid Business Network Definition. Found ' + error.toString(); this.alertService.errorStatus$.next(failMessage); this.expandInput = false; return null; }); }; fileReader.readAsArrayBuffer(file); } private fileRejected(reason: string): void { this.alertService.errorStatus$.next(reason); this.expandInput = false; } private setNetworkName(name) { this.networkName = name; if (!name) { this.networkNameValid = true; } else { let pattern = /^[a-z0-9-]+$/; this.networkNameValid = pattern.test(this.networkName); } } private setCardName(name) { if (this.cardName !== name) { this.cardName = name; this.cardNameValid = true; } } private initNetworkList(sampleNetworkList): void { this.sampleNetworks = this.addEmptyNetworkOption(sampleNetworkList); if (this.sampleNetworks.length === 1) { this.selectNetwork(this.sampleNetworks[0]); } else { this.selectNetwork(this.sampleNetworks[1]); } this.npmInProgress = false; } }
the_stack
import * as i18n from "i18next"; import * as _ from "lodash"; import { Logger, LogLevel } from "sp-pnp-js"; import ITaxonomyNavigationNode from "../models/ITaxonomyNavigationNode"; import TaxonomyNavigationNode from "../models/TaxonomyNavigationNode"; import LocalizationModule from "./LocalizationModule"; class TaxonomyModule { private workingLanguage: number; constructor() { // Get the current working language from the global i18n object // We ensure a default language by the "fallbackLng" property (see main.ts for initialization) const localization = new LocalizationModule(); // Ensure all resources are loaded before playng with the i18n object. localization.ensureResourcesLoaded(() => { this.workingLanguage = parseInt(i18n.t("LCID"), 10); }); } /** * Ensure all script dependencies are loaded before using the taxonomy SharePoint CSOM functions * @return {Promise<void>} A promise allowing you to execute your code logic. */ public init(): Promise<void> { // Initialize SharePoint script dependencies SP.SOD.registerSod("sp.runtime.js", "/_layouts/15/sp.runtime.js"); SP.SOD.registerSod("sp.js", "/_layouts/15/sp.js"); SP.SOD.registerSod("sp.taxonomy.js", "/_layouts/15/sp.taxonomy.js"); SP.SOD.registerSod("sp.publishing.js", "/_layouts/15/sp.publishing.js"); SP.SOD.registerSodDep("sp.js", "sp.runtime.js"); SP.SOD.registerSodDep("sp.taxonomy.js", "sp.js"); SP.SOD.registerSodDep("sp.publishing.js", "sp.js"); const p = new Promise<void>((resolve) => { SP.SOD.loadMultiple(["sp.runtime.js", "sp.js", "sp.taxonomy.js", "sp.publishing.js"], () => { resolve(); }); }); return p; } /** * Get a taxonomy term set custom property value * @param {SP.Guid} termSetId The taxonomy term set Id * @param {string} customPropertyName The name of the property to retrieve * @return {Promise<string>} A promise containing the value of the property as string */ public getTermSetCustomPropertyValue(termSetId: SP.Guid, customPropertyName: string): Promise<string> { const context: SP.ClientContext = SP.ClientContext.get_current(); const taxSession: SP.Taxonomy.TaxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); const termStore: SP.Taxonomy.TermStore = taxSession.getDefaultSiteCollectionTermStore(); termStore.set_workingLanguage(this.workingLanguage); const termSet: SP.Taxonomy.TermSet = termStore.getTermSet(termSetId); context.load(termSet, "CustomProperties"); const p = new Promise<string>((resolve, reject) => { context.executeQueryAsync(() => { const propertyValue: string = termSet.get_customProperties()[customPropertyName] !== undefined ? termSet.get_customProperties()[customPropertyName] : ""; resolve(propertyValue); }, (sender, args) => { reject("Request failed. " + args.get_message() + "\n" + args.get_stackTrace()); }); }); return p; } /** * Get the taxonomy navigation terms for a specific term set * @param {SP.Guid} termSetId The taxonomy term set Id * @return {Promise<ITaxonomyNavigationNode[]>} A promise containing the array of navigation nodes for the term set */ public getNavigationTaxonomyNodes(termSetId: SP.Guid): Promise<ITaxonomyNavigationNode[]> { const context: SP.ClientContext = SP.ClientContext.get_current(); const currentWeb: SP.Web = SP.ClientContext.get_current().get_web(); const taxSession: SP.Taxonomy.TaxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); const termStore: SP.Taxonomy.TermStore = taxSession.getDefaultSiteCollectionTermStore(); termStore.set_workingLanguage(this.workingLanguage); const termSet: SP.Taxonomy.TermSet = termStore.getTermSet(termSetId); // The method 'getTermSetForWeb' gets the cached read only version of the term set // https://msdn.microsoft.com/EN-US/library/office/microsoft.sharepoint.publishing.navigation.taxonomynavigation.gettermsetforweb.aspx // Ex: var webNavigationTermSet = SP.Publishing.Navigation.TaxonomyNavigation.getTermSetForWeb(context, currentWeb, 'GlobalNavigationTaxonomyProvider', true); // In our case, we use 'getAsResolvedByWeb' method instead to retrieve a taxonomy term set as a navigation term set regardless if it is bound to the current web. // The downside of this approach is that the results are not retrieved from the navigation cache that can cause performance issues during the initial load let webNavigationTermSet = SP.Publishing.Navigation.NavigationTermSet.getAsResolvedByWeb(context, termSet, currentWeb, "GlobalNavigationTaxonomyProvider"); // Get the existing view from the navigation term set const termSetView = webNavigationTermSet.get_view().getCopy(); // Return global and current navigation terms (the subsequent filtering can be done in the Knockout html view) termSetView.set_excludeTermsByProvider(false); // Sets a value that indicates whether NavigationTerm objects are trimmed if the current user does not have permissions to view the target page (the aspx physical page) for the friendly URL // If you don't see anything in the menu, check the node type (term driven page or simple link). In the case of term driven page, the target page must be accessible for the current user termSetView.set_excludeTermsByPermissions(true); // Apply the new view filters webNavigationTermSet = webNavigationTermSet.getWithNewView(termSetView); const firstLevelNavigationTerms = webNavigationTermSet.get_terms(); const allNavigationterms = webNavigationTermSet.getAllTerms(); context.load(allNavigationterms, "Include(Id, Terms, Title, FriendlyUrlSegment, ExcludeFromCurrentNavigation, ExcludeFromGlobalNavigation)"); context.load(firstLevelNavigationTerms, "Include(Id, Terms, Title, FriendlyUrlSegment, ExcludeFromCurrentNavigation, ExcludeFromGlobalNavigation)"); const p = new Promise<ITaxonomyNavigationNode[]>((resolve, reject) => { context.executeQueryAsync(() => { this.getTermNodesAsFlat(context, allNavigationterms).then((nodes: ITaxonomyNavigationNode[]) => { const navigationTree = this.getTermNodesAsTree(context, nodes, firstLevelNavigationTerms, null); resolve(navigationTree); }); }, (sender, args) => { reject("Request failed. " + args.get_message() + "\n" + args.get_stackTrace()); }); }); return p; } /** * Get a single term by its Id using the current taxonomy context. * @param {SP.Guid} termId The taxonomy term Id * @return {Promise<SP.Taxonomy.Term>} A promise containing the term infos. */ public getTermById(termId: SP.Guid): Promise<SP.Taxonomy.Term> { if (termId) { const context: SP.ClientContext = SP.ClientContext.get_current(); const taxSession: SP.Taxonomy.TaxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(context); const termStore: SP.Taxonomy.TermStore = taxSession.getDefaultSiteCollectionTermStore(); termStore.set_workingLanguage(this.workingLanguage); const term: SP.Taxonomy.Term = termStore.getTerm(termId); context.load(term, "Name"); const p = new Promise<SP.Taxonomy.Term>((resolve, reject) => { context.executeQueryAsync(() => { resolve(term); }, (sender, args) => { reject("Request failed. " + args.get_message() + "\n" + args.get_stackTrace()); }); }); return p; } else { Logger.write("[TaxonomyModule.getTermById]: the provided term id is null!", LogLevel.Error); } } // Get the navigation hierarchy as a flat list // This list will be used to easily find a node without dealing too much with asynchronous calls and recursion private getTermNodesAsFlat(context: SP.ClientContext, allTerms: SP.Publishing.Navigation.NavigationTermCollection): Promise<any> { const termNodes: Array<Promise<ITaxonomyNavigationNode>> = []; const termsEnumerator = allTerms.getEnumerator(); while (termsEnumerator.moveNext()) { const p = new Promise<ITaxonomyNavigationNode>((resolve, reject) => { const currentTerm: SP.Publishing.Navigation.NavigationTerm = termsEnumerator.get_current(); const termNode = new TaxonomyNavigationNode(); termNode.Id = currentTerm.get_id().toString(); termNode.Title = currentTerm.get_title().get_value(); termNode.TaxonomyTerm = currentTerm; termNode.FriendlyUrlSegment = currentTerm.get_friendlyUrlSegment().get_value(); termNode.ExcludeFromCurrentNavigation = currentTerm.get_excludeFromCurrentNavigation(); termNode.ExcludeFromGlobalNavigation = currentTerm.get_excludeFromGlobalNavigation(); this.getNavigationTermUrlInfo(context, currentTerm).then((termUrlInfo) => { termNode.Url = termUrlInfo; this.getTermCustomPropertiesForTerm(context, currentTerm.getTaxonomyTerm()).then((properties) => { termNode.Properties = properties; resolve(termNode); termsEnumerator.moveNext(); }); }); }); termNodes.push(p); } return Promise.all(termNodes); } // Get the navigation nodes as tree private getTermNodesAsTree(context: SP.ClientContext, allTerms: ITaxonomyNavigationNode[], currentNodeTerms: SP.Publishing.Navigation.NavigationTermCollection, parentNode: ITaxonomyNavigationNode): ITaxonomyNavigationNode[] { // Special thanks to this blog post // https://social.msd#n.microsoft.com/Forums/office/en-US/ede1aa39-4c47-4308-9aef-3b036ec9b318/get-navigation-taxonomy-term-tree-in-sharepoint-app?forum=appsforsharepoint const termsEnumerator = currentNodeTerms.getEnumerator(); const termNodes: ITaxonomyNavigationNode[] = []; while (termsEnumerator.moveNext()) { // Get the corresponding navigation node in the flat tree const termId = termsEnumerator.get_current().get_id(); const currentNode = _.find(allTerms, (term) => term.Id.toString().localeCompare(termId.toString()) === 0); const subTerms = currentNode.TaxonomyTerm.get_terms(); if (subTerms.get_count() > 0) { currentNode.ChildNodes = this.getTermNodesAsTree(context, allTerms, subTerms, currentNode); } // Clear TaxonomyTerm property to simplify JSON string (property not useful anymore after this step) currentNode.TaxonomyTerm = null; if (parentNode !== null) { // Set the parent infos for the current node (used by the contextual menu and the breadcrumb components) currentNode.ParentUrl = parentNode.Url; currentNode.ParentId = parentNode.Id; } termNodes.push(currentNode); } return termNodes; } // Get the term URL info (simple link or friendly URL) private getNavigationTermUrlInfo(context: SP.ClientContext, navigationTerm: SP.Publishing.Navigation.NavigationTerm): Promise<string> { // This method gets the resolved URL whatever if it is a simple link or a friendly URL const resolvedDisplayUrl = navigationTerm.getResolvedDisplayUrl(""); context.load(navigationTerm); const p = new Promise<string>((resolve, reject) => { context.executeQueryAsync(() => { resolve(resolvedDisplayUrl.get_value()); }, (sender, args) => { reject("Request failed. " + args.get_message() + "\n" + args.get_stackTrace()); }); }); return p; } // Get all custom proeprties for the term private getTermCustomPropertiesForTerm(context: SP.ClientContext, taxonomyTerm: SP.Taxonomy.Term): Promise<{ [key: string]: string }> { context.load(taxonomyTerm, "CustomProperties"); const p = new Promise<{ [key: string]: string }>((resolve, reject) => { context.executeQueryAsync(() => { const properties = taxonomyTerm.get_customProperties(); resolve(properties); }, (sender, args) => { reject("Request failed. " + args.get_message() + "\n" + args.get_stackTrace()); }); }); return p; } } export default TaxonomyModule;
the_stack
* Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { TurnContext } from 'botbuilder-core'; import { QnAMakerResult } from '../qnamaker-interfaces/qnamakerResult'; import { QnAMakerResults } from '../qnamaker-interfaces/qnamakerResults'; import { QnAMakerEndpoint } from '../qnamaker-interfaces/qnamakerEndpoint'; import { QnAMakerOptions } from '../qnamaker-interfaces/qnamakerOptions'; import { QnAMakerTraceInfo } from '../qnamaker-interfaces/qnamakerTraceInfo'; import { HttpRequestUtils } from './httpRequestUtils'; import { QNAMAKER_TRACE_TYPE, QNAMAKER_TRACE_LABEL, QNAMAKER_TRACE_NAME, FeedbackRecords, FeedbackRecord, QnAMakerMetadata, JoinOperator, } from '..'; import { RankerTypes } from '../qnamaker-interfaces/rankerTypes'; import { Filters } from '../qnamaker-interfaces/filters'; import { KnowledgeBaseAnswers } from '../qnamaker-interfaces/knowledgeBaseAnswers'; import { KnowledgeBaseAnswer } from '../qnamaker-interfaces/knowledgeBaseAnswer'; const ApiVersionQueryParam = 'api-version=2021-10-01'; /** * Utilities for using Query Knowledge Base and Add Active Learning feedback APIs of language service. * * @summary * This class is helper class for query-knowledgebases api, used to make queries to a Language service project and returns the knowledgebase answers. */ export class LanguageServiceUtils { httpRequestUtils: HttpRequestUtils; /** * Creates new Language Service utils. * * @param {QnAMakerOptions} _options Settings used to configure the instance. * @param {QnAMakerEndpoint} endpoint The endpoint of the knowledge base to query. */ constructor(public _options: QnAMakerOptions, readonly endpoint: QnAMakerEndpoint) { this.httpRequestUtils = new HttpRequestUtils(); this.validateOptions(this._options); } /** * Adds feedback to the knowledge base. * * @param feedbackRecords A list of Feedback Records for Active Learning. * @returns {Promise<void>} A promise representing the async operation. */ async addFeedback(feedbackRecords: FeedbackRecords): Promise<void> { if (!feedbackRecords) { throw new TypeError('Feedback records can not be null.'); } if (!feedbackRecords.feedbackRecords || feedbackRecords.feedbackRecords.length == 0) { return; } await this.addFeedbackRecordsToKnowledgebase(feedbackRecords.feedbackRecords); } /** * Called to query the Language service. * * @param {string} question Question which need to be queried. * @param {QnAMakerOptions} options (Optional) The options for the QnA Maker knowledge base. If null, constructor option is used for this instance. * @returns {Promise<QnAMakerResult[]>} a promise that resolves to the raw query results */ async queryKnowledgebaseRaw(question: string, options?: QnAMakerOptions): Promise<QnAMakerResults> { const deploymentName = options.isTest ? 'test' : 'production'; const url = `${this.endpoint.host}/language/:query-knowledgebases?projectName=${this.endpoint.knowledgeBaseId}&deploymentName=${deploymentName}&${ApiVersionQueryParam}`; const queryOptions: QnAMakerOptions = { ...this._options, ...options } as QnAMakerOptions; queryOptions.rankerType = !queryOptions.rankerType ? RankerTypes.default : queryOptions.rankerType; this.validateOptions(queryOptions); const payloadBody = JSON.stringify({ question: question, confidenceScoreThreshold: queryOptions.scoreThreshold, top: queryOptions.top, filters: this.getFilters( queryOptions.strictFilters, queryOptions.strictFiltersJoinOperator, queryOptions.filters ), qnaId: queryOptions.qnaId, rankerType: queryOptions.rankerType, context: queryOptions.context, answerSpanRequest: { enable: queryOptions.enablePreciseAnswer }, includeUnstructuredSources: queryOptions.includeUnstructuredSources, }); const qnaResults = await this.httpRequestUtils.executeHttpRequest( url, payloadBody, this.endpoint, queryOptions.timeout ); if (Array.isArray(qnaResults?.answers)) { return this.formatQnaResult(qnaResults as KnowledgeBaseAnswers); } throw new Error(`Failed to query knowledgebase: ${qnaResults}`); } /** * Emits a trace event detailing a Custom Question Answering call and its results. * * @param {TurnContext} turnContext Turn Context for the current turn of conversation with the user. * @param {QnAMakerResult[]} answers Answers returned by Language Service. * @param {QnAMakerOptions} queryOptions (Optional) The options for the Custom Question Answering knowledge base. If null, constructor option is used for this instance. * @returns {Promise<any>} a promise representing the async operation */ async emitTraceInfo( turnContext: TurnContext, answers: QnAMakerResult[], queryOptions?: QnAMakerOptions // eslint-disable-next-line @typescript-eslint/no-explicit-any ): Promise<any> { const requestOptions: QnAMakerOptions = { ...this._options, ...queryOptions }; const { scoreThreshold, top, strictFilters, metadataBoost, context, qnaId } = requestOptions; const traceInfo: QnAMakerTraceInfo = { message: turnContext.activity, queryResults: answers, knowledgeBaseId: this.endpoint.knowledgeBaseId, scoreThreshold, top, strictFilters, metadataBoost, context, qnaId, }; return turnContext.sendActivity({ type: 'trace', valueType: QNAMAKER_TRACE_TYPE, name: QNAMAKER_TRACE_NAME, label: QNAMAKER_TRACE_LABEL, value: traceInfo, }); } /** * Validate qna maker options * * @param {QnAMakerOptions} options The options for the Custom Question Answering knowledge base. If null, constructor option is used for this instance. */ validateOptions(options: QnAMakerOptions): void { const { scoreThreshold, top } = options; if (scoreThreshold) { this.validateScoreThreshold(scoreThreshold); } if (top) { this.validateTop(top); } } private formatQnaResult(kbAnswers: KnowledgeBaseAnswers): QnAMakerResults { const qnaResultsAnswers = kbAnswers.answers?.map((kbAnswer: KnowledgeBaseAnswer) => { const qnaResult: QnAMakerResult = { answer: kbAnswer.answer, score: kbAnswer.confidenceScore, metadata: kbAnswer.metadata ? Array.from(kbAnswer.metadata)?.map((nv) => { return { name: nv[0], value: nv[1] }; }) : null, answerSpan: kbAnswer?.answerSpan ? { text: kbAnswer.answerSpan.text, score: kbAnswer.answerSpan.confidenceScore, startIndex: kbAnswer.answerSpan.offset, endIndex: kbAnswer.answerSpan.offset + kbAnswer.answerSpan.length - 1, } : null, context: kbAnswer?.dialog ? { prompts: kbAnswer.dialog?.prompts?.map((p) => { return { displayOrder: p.displayOrder, displayText: p.displayText, qna: null, qnaId: p.qnaId, }; }), } : null, id: kbAnswer.id, questions: kbAnswer.questions, source: kbAnswer.source, }; return qnaResult; }); const qnaResults = { answers: qnaResultsAnswers, activeLearningEnabled: true }; return qnaResults; } private validateScoreThreshold(scoreThreshold: number): void { if (typeof scoreThreshold !== 'number' || !(scoreThreshold > 0 && scoreThreshold <= 1)) { throw new TypeError( `"${scoreThreshold}" is an invalid scoreThreshold. QnAMakerOptions.scoreThreshold must have a value between 0 and 1.` ); } } private validateTop(qnaOptionTop: number): void { if (!Number.isInteger(qnaOptionTop) || qnaOptionTop < 1) { throw new RangeError( `"${qnaOptionTop}" is an invalid top value. QnAMakerOptions.top must be an integer greater than 0.` ); } } private getFilters( strictFilters: QnAMakerMetadata[], metadataJoinOperator: JoinOperator, filters: Filters ): Filters { if (filters) { return filters; } if (strictFilters) { const metadataKVPairs = []; strictFilters.forEach((filter) => { metadataKVPairs.push({ key: filter.name, value: filter.value }); }); const newFilters = { metadataFilter: { metadata: metadataKVPairs, logicalOperation: metadataJoinOperator ? metadataJoinOperator.toString() : JoinOperator.AND, }, sourceFilter: [], logicalOperation: JoinOperator.AND.toString(), }; return newFilters; } return null; } private async addFeedbackRecordsToKnowledgebase(records: FeedbackRecord[]) { const url = `${this.endpoint.host}/language/query-knowledgebases/projects/${this.endpoint.knowledgeBaseId}/feedback?${ApiVersionQueryParam}`; const payloadBody = JSON.stringify({ records: records, }); await this.httpRequestUtils.executeHttpRequest(url, payloadBody, this.endpoint); } }
the_stack
import {Value} from './value'; import {fuzzyAssertInRange, fuzzyEquals, fuzzyRound} from './utils'; import {hash} from 'immutable'; interface RgbColor { red: number; green: number; blue: number; alpha: number; } interface HslColor { hue: number; saturation: number; lightness: number; alpha: number; } /** A SassScript color. */ export class SassColor extends Value { private redInternal?: number; private greenInternal?: number; private blueInternal?: number; private hueInternal?: number; private saturationInternal?: number; private lightnessInternal?: number; private readonly alphaInternal: number; private constructor(color: RgbColor | HslColor) { super(); if ('red' in color) { this.redInternal = color.red; this.greenInternal = color.green; this.blueInternal = color.blue; } else { this.hueInternal = color.hue; this.saturationInternal = color.saturation; this.lightnessInternal = color.lightness; } this.alphaInternal = color.alpha; } /** * Creates an RGB color. * * Throws an error if `red`, `green`, and `blue` aren't between `0` and `255`, * or if `alpha` isn't between `0` and `1`. */ static rgb( red: number, green: number, blue: number, alpha?: number ): SassColor { return new SassColor({ red: fuzzyAssertInRange(red, 0, 255, 'red'), green: fuzzyAssertInRange(green, 0, 255, 'green'), blue: fuzzyAssertInRange(blue, 0, 255, 'blue'), alpha: alpha === undefined ? 1 : fuzzyAssertInRange(alpha, 0, 1, 'alpha'), }); } /** * Creates an HSL color. * * Throws an error if `saturation` or `lightness` aren't between `0` and * `100`, or if `alpha` isn't between `0` and `1`. */ static hsl( hue: number, saturation: number, lightness: number, alpha?: number ) { return new SassColor({ hue: hue % 360, saturation: fuzzyAssertInRange(saturation, 0, 100, 'saturation'), lightness: fuzzyAssertInRange(lightness, 0, 100, 'lightness'), alpha: alpha === undefined ? 1 : fuzzyAssertInRange(alpha, 0, 1, 'alpha'), }); } /** * Creates an HWB color. * * Throws an error if `whiteness` or `blackness` aren't between `0` and `100`, * or if `alpha` isn't between `0` and `1`. */ static hwb( hue: number, whiteness: number, blackness: number, alpha?: number ) { // From https://www.w3.org/TR/css-color-4/#hwb-to-rgb const scaledHue = (hue % 360) / 360; let scaledWhiteness = fuzzyAssertInRange(whiteness, 0, 100, 'whiteness') / 100; let scaledBlackness = fuzzyAssertInRange(blackness, 0, 100, 'blackness') / 100; const sum = scaledWhiteness + scaledBlackness; if (sum > 1) { scaledWhiteness /= sum; scaledBlackness /= sum; } const factor = 1 - scaledWhiteness - scaledBlackness; function toRgb(hue: number) { const channel = hueToRgb(0, 1, hue) * factor + scaledWhiteness; return fuzzyRound(channel * 255); } // Because HWB is (currently) used much less frequently than HSL or RGB, we // don't cache its values because we expect the memory overhead of doing so // to outweigh the cost of recalculating it on access. Instead, we eagerly // convert it to RGB and then convert back if necessary. return SassColor.rgb( toRgb(scaledHue + 1 / 3), toRgb(scaledHue), toRgb(scaledHue - 1 / 3), alpha ); } /** `this`'s red channel. */ get red(): number { if (this.redInternal === undefined) { this.hslToRgb(); } return this.redInternal!; } /** `this`'s blue channel. */ get blue(): number { if (this.blueInternal === undefined) { this.hslToRgb(); } return this.blueInternal!; } /** `this`'s green channel. */ get green(): number { if (this.greenInternal === undefined) { this.hslToRgb(); } return this.greenInternal!; } /** `this`'s hue value. */ get hue(): number { if (this.hueInternal === undefined) { this.rgbToHsl(); } return this.hueInternal!; } /** `this`'s saturation value. */ get saturation(): number { if (this.saturationInternal === undefined) { this.rgbToHsl(); } return this.saturationInternal!; } /** `this`'s hue value. */ get lightness(): number { if (this.lightnessInternal === undefined) { this.rgbToHsl(); } return this.lightnessInternal!; } /** `this`'s whiteness value. */ get whiteness(): number { // Because HWB is (currently) used much less frequently than HSL or RGB, we // don't cache its values because we expect the memory overhead of doing so // to outweigh the cost of recalculating it on access. return (Math.min(this.red, this.green, this.blue) / 255) * 100; } /** `this`'s blackness value. */ get blackness(): number { // Because HWB is (currently) used much less frequently than HSL or RGB, we // don't cache its values because we expect the memory overhead of doing so // to outweigh the cost of recalculating it on access. return 100 - (Math.max(this.red, this.green, this.blue) / 255) * 100; } /** `this`'s alpha channel. */ get alpha(): number { return this.alphaInternal; } assertColor(): SassColor { return this; } /** * Returns a copy of `this` with its RGB channels changed to `red`, `green`, * `blue`, and/or `alpha`. */ changeRgb(options: { red?: number; green?: number; blue?: number; alpha?: number; }): SassColor { return SassColor.rgb( options.red ?? this.red, options.green ?? this.green, options.blue ?? this.blue, options.alpha ?? this.alpha ); } /** * Returns a copy of `this` with its HSL values changed to `hue`, * `saturation`, `lightness`, and/or `alpha`. */ changeHsl(options: { hue?: number; saturation?: number; lightness?: number; alpha?: number; }): SassColor { return SassColor.hsl( options.hue ?? this.hue, options.saturation ?? this.saturation, options.lightness ?? this.lightness, options.alpha ?? this.alpha ); } /** * Returns a copy of `this` with its HWB values changed to `hue`, `whiteness`, * `blackness`, and/or `alpha`. */ changeHwb(options: { hue?: number; whiteness?: number; blackness?: number; alpha?: number; }): SassColor { return SassColor.hwb( options.hue ?? this.hue, options.whiteness ?? this.whiteness, options.blackness ?? this.blackness, options.alpha ?? this.alpha ); } /** Returns a copy of `this` with its alpha channel changed to `alpha`. */ changeAlpha(alpha: number): SassColor { return new SassColor({ red: this.red, green: this.green, blue: this.blue, alpha: fuzzyAssertInRange(alpha, 0, 1, 'alpha'), }); } equals(other: Value): boolean { return ( other instanceof SassColor && fuzzyEquals(this.red, other.red) && fuzzyEquals(this.green, other.green) && fuzzyEquals(this.blue, other.blue) && fuzzyEquals(this.alpha, other.alpha) ); } hashCode(): number { return hash(this.red ^ this.green ^ this.blue ^ this.alpha); } toString(): string { const isOpaque = fuzzyEquals(this.alpha, 1); let string = isOpaque ? 'rgb(' : 'rgba('; string += `${this.red}, ${this.green}, ${this.blue}`; string += isOpaque ? ')' : `, ${this.alpha})`; return string; } // Computes `this`'s `hue`, `saturation`, and `lightness` values based on // `red`, `green`, and `blue`. // // Algorithm from https://en.wikipedia.org/wiki/HSL_and_HSV#RGB_to_HSL_and_HSV private rgbToHsl(): void { const scaledRed = this.red / 255; const scaledGreen = this.green / 255; const scaledBlue = this.blue / 255; const max = Math.max(scaledRed, scaledGreen, scaledBlue); const min = Math.min(scaledRed, scaledGreen, scaledBlue); const delta = max - min; if (max === min) { this.hueInternal = 0; } else if (max === scaledRed) { this.hueInternal = ((60 * (scaledGreen - scaledBlue)) / delta) % 360; } else if (max === scaledGreen) { this.hueInternal = (120 + (60 * (scaledBlue - scaledRed)) / delta) % 360; } else if (max === scaledBlue) { this.hueInternal = (240 + (60 * (scaledRed - scaledGreen)) / delta) % 360; } this.lightnessInternal = 50 * (max + min); if (max === min) { this.saturationInternal = 0; } else if (this.lightnessInternal < 50) { this.saturationInternal = (100 * delta) / (max + min); } else { this.saturationInternal = (100 * delta) / (2 - max - min); } } // Computes `this`'s red`, `green`, and `blue` channels based on `hue`, // `saturation`, and `value`. // // Algorithm from the CSS3 spec: https://www.w3.org/TR/css3-color/#hsl-color. private hslToRgb(): void { const scaledHue = this.hue / 360; const scaledSaturation = this.saturation / 100; const scaledLightness = this.lightness / 100; const m2 = scaledLightness <= 0.5 ? scaledLightness * (scaledSaturation + 1) : scaledLightness + scaledSaturation - scaledLightness * scaledSaturation; const m1 = scaledLightness * 2 - m2; this.redInternal = fuzzyRound(hueToRgb(m1, m2, scaledHue + 1 / 3) * 255); this.greenInternal = fuzzyRound(hueToRgb(m1, m2, scaledHue) * 255); this.blueInternal = fuzzyRound(hueToRgb(m1, m2, scaledHue - 1 / 3) * 255); } } // An algorithm from the CSS3 spec: http://www.w3.org/TR/css3-color/#hsl-color. function hueToRgb(m1: number, m2: number, hue: number): number { if (hue < 0) hue += 1; if (hue > 1) hue -= 1; if (hue < 1 / 6) { return m1 + (m2 - m1) * hue * 6; } else if (hue < 1 / 2) { return m2; } else if (hue < 2 / 3) { return m1 + (m2 - m1) * (2 / 3 - hue) * 6; } else { return m1; } }
the_stack
import { _, CommandManager, DocumentManager, EditorManager, MainViewManager } from "./brackets-modules"; import * as ErrorHandler from "./ErrorHandler"; import * as Events from "./Events"; import EventEmitter from "./EventEmitter"; import * as Git from "./git/GitCli"; import * as Preferences from "./Preferences"; let gitAvailable = false; const gutterName = "brackets-git-gutter"; const editorsWithGutters = []; let openWidgets = []; function clearWidgets() { const lines = openWidgets.map((mark) => { const w = mark.lineWidget; if (w.visible) { w.visible = false; w.widget.clear(); } return { cm: mark.cm, line: mark.line }; }); openWidgets = []; return lines; } function clearOld(editor) { const cm = editor._codeMirror; if (!cm) { return; } const gutters = cm.getOption("gutters").slice(0); const io = gutters.indexOf(gutterName); if (io !== -1) { gutters.splice(io, 1); cm.clearGutter(gutterName); cm.setOption("gutters", gutters); cm.off("gutterClick", gutterClick); } delete cm.gitGutters; clearWidgets(); } function prepareGutter(editor) { // add our gutter if its not already available const cm = editor._codeMirror; const gutters = cm.getOption("gutters").slice(0); if (gutters.indexOf(gutterName) === -1) { gutters.unshift(gutterName); cm.setOption("gutters", gutters); cm.on("gutterClick", gutterClick); } if (editorsWithGutters.indexOf(editor) === -1) { editorsWithGutters.push(editor); } } function prepareGutters(editors) { editors.forEach((editor) => { prepareGutter(editor); }); // clear the rest let idx = editorsWithGutters.length; while (idx--) { if (editors.indexOf(editorsWithGutters[idx]) === -1) { clearOld(editorsWithGutters[idx]); editorsWithGutters.splice(idx, 1); } } } function showGutters(editor, _results) { prepareGutter(editor); const cm = editor._codeMirror; cm.gitGutters = _.sortBy(_results, "line"); // get line numbers of currently opened widgets const openBefore = clearWidgets(); cm.clearGutter(gutterName); cm.gitGutters.forEach((obj) => { const $marker = $("<div>") .addClass(gutterName + "-" + obj.type + " gitline-" + (obj.line + 1)) .html("&nbsp;"); cm.setGutterMarker(obj.line, gutterName, $marker[0]); }); // reopen widgets that were opened before refresh openBefore.forEach((obj) => { gutterClick(obj.cm, obj.line, gutterName); }); } function gutterClick(cm, lineIndex, gutterId) { if (!cm) { return; } if (gutterId !== gutterName && gutterId !== "CodeMirror-linenumbers") { return; } let mark = _.find(cm.gitGutters, (o) => o.line === lineIndex); if (!mark || mark.type === "added") { return; } // we need to be able to identify cm instance from any mark mark.cm = cm; if (mark.parentMark) { mark = mark.parentMark; } if (!mark.lineWidget) { mark.lineWidget = { visible: false, element: $("<div class='" + gutterName + "-deleted-lines'></div>") }; const $btn = $("<button/>") .addClass("brackets-git-gutter-copy-button") .text("R") .on("click", () => { const doc = DocumentManager.getCurrentDocument(); doc.replaceRange(mark.content + "\n", { line: mark.line, ch: 0 }); CommandManager.execute("file.save"); refresh(); }); $("<pre/>") .attr("style", "tab-size:" + cm.getOption("tabSize")) .text(mark.content || " ") .append($btn) .appendTo(mark.lineWidget.element); } if (mark.lineWidget.visible !== true) { mark.lineWidget.visible = true; mark.lineWidget.widget = cm.addLineWidget(mark.line, mark.lineWidget.element[0], { coverGutter: false, noHScroll: false, above: true, showIfHidden: false }); openWidgets.push(mark); } else { mark.lineWidget.visible = false; mark.lineWidget.widget.clear(); const io = openWidgets.indexOf(mark); if (io !== -1) { openWidgets.splice(io, 1); } } } function getEditorFromPane(paneId) { const currentPath = MainViewManager.getCurrentlyViewedPath(paneId); const doc = currentPath && DocumentManager.getOpenDocumentForPath(currentPath); return doc && doc._masterEditor; } function processDiffResults(editor, diff) { const added = []; const removed = []; const modified = []; const changesets = diff.split(/\n@@/).map((str) => "@@" + str); // remove part before first changesets.shift(); changesets.forEach((str) => { const m = str.match(/^@@ -([,0-9]+) \+([,0-9]+) @@/); const s1 = m[1].split(","); const s2 = m[2].split(","); // removed stuff let lineRemovedFrom; let lineFrom = parseInt(s2[0], 10); let lineCount = parseInt(s1[1], 10); if (isNaN(lineCount)) { lineCount = 1; } if (lineCount > 0) { lineRemovedFrom = lineFrom - 1; removed.push({ type: "removed", line: lineRemovedFrom, content: str.split("\n") .filter((l) => l.indexOf("-") === 0) .map((l) => l.substring(1)) .join("\n") }); } // added stuff lineFrom = parseInt(s2[0], 10); lineCount = parseInt(s2[1], 10); if (isNaN(lineCount)) { lineCount = 1; } let isModifiedMark = false; let firstAddedMark = false; const lineTo = lineFrom + lineCount; for (let i = lineFrom; i < lineTo; i++) { const lineNo = i - 1; if (lineNo === lineRemovedFrom) { // modified const o = removed.pop(); o.type = "modified"; modified.push(o); isModifiedMark = o; } else { const mark = { type: isModifiedMark ? "modified" : "added", line: lineNo, parentMark: isModifiedMark || firstAddedMark || null }; if (!isModifiedMark && !firstAddedMark) { firstAddedMark = mark; } // added new added.push(mark); } } }); // fix displaying of removed lines removed.forEach((o) => { o.line += 1; }); showGutters(editor, [].concat(added, removed, modified)); } function refresh() { if (!gitAvailable) { return; } if (!Preferences.get("useGitGutter")) { return; } const currentGitRoot = Preferences.get("currentGitRoot"); // we get a list of editors, which need to be refreshed const editors = _.compact(_.map(MainViewManager.getPaneIdList(), (paneId) => { return getEditorFromPane(paneId); })); // we create empty gutters in all of these editors, all other editors lose their gutters prepareGutters(editors); // now we launch a diff to fill the gutters in our editors editors.forEach((editor) => { let currentFilePath = null; if (editor.document && editor.document.file) { currentFilePath = editor.document.file.fullPath; } if (currentFilePath.indexOf(currentGitRoot) !== 0) { // file is not in the current project return; } const filename = currentFilePath.substring(currentGitRoot.length); Git.diffFile(filename).then((diff) => { processDiffResults(editor, diff); }).catch((err) => { // if this is launched in a non-git repository, just ignore if (ErrorHandler.contains(err, "Not a git repository")) { return; } // if this file was moved or deleted before this command could be executed, ignore if (ErrorHandler.contains(err, "No such file or directory")) { return; } ErrorHandler.showError(err, "Refreshing gutter failed!"); }); }); } export function goToPrev() { const activeEditor = EditorManager.getActiveEditor(); if (!activeEditor) { return; } const results = activeEditor._codeMirror.gitGutters || []; const searched = _.filter(results, (i) => !i.parentMark); const currentPos = activeEditor.getCursorPos(); let i = searched.length; while (i--) { if (searched[i].line < currentPos.line) { break; } } if (i > -1) { const goToMark = searched[i]; activeEditor.setCursorPos(goToMark.line, currentPos.ch); } } export function goToNext() { const activeEditor = EditorManager.getActiveEditor(); if (!activeEditor) { return; } const results = activeEditor._codeMirror.gitGutters || []; const searched = _.filter(results, (i) => !i.parentMark); const currentPos = activeEditor.getCursorPos(); let i; let l; for (i = 0, l = searched.length; i < l; i++) { if (searched[i].line > currentPos.line) { break; } } if (i < searched.length) { const goToMark = searched[i]; activeEditor.setCursorPos(goToMark.line, currentPos.ch); } } /* // disable because of https://github.com/zaggino/brackets-git/issues/1019 let _timer; let $line = $(), $gitGutterLines = $(); $(document) .on("mouseenter", ".CodeMirror-linenumber", function (evt) { let $target = $(evt.target); // Remove tooltip $line.attr("title", ""); // Remove any misc gutter hover classes $(".CodeMirror-linenumber").removeClass("brackets-git-gutter-hover"); $(".brackets-git-gutter-hover").removeClass("brackets-git-gutter-hover"); // Add new gutter hover classes $gitGutterLines = $(".gitline-" + $target.html()).addClass("brackets-git-gutter-hover"); // Add tooltips if there are any git gutter marks if ($gitGutterLines.hasClass("brackets-git-gutter-modified") || $gitGutterLines.hasClass("brackets-git-gutter-removed")) { $line = $target.attr("title", Strings.GUTTER_CLICK_DETAILS); $target.addClass("brackets-git-gutter-hover"); } }) .on("mouseleave", ".CodeMirror-linenumber", function (evt) { let $target = $(evt.target); if (_timer) { clearTimeout(_timer); } _timer = setTimeout(function () { $(".gitline-" + $target.html()).removeClass("brackets-git-gutter-hover"); $target.removeClass("brackets-git-gutter-hover"); }, 500); }); */ // Event handlers EventEmitter.on(Events.GIT_ENABLED, () => { gitAvailable = true; refresh(); }); EventEmitter.on(Events.GIT_DISABLED, () => { gitAvailable = false; // calling this with an empty array will remove gutters from all editor instances prepareGutters([]); }); EventEmitter.on(Events.BRACKETS_CURRENT_DOCUMENT_CHANGE, (evt, file) => { // file will be null when switching to an empty pane if (!file) { return; } // document change gets launched even when switching panes, // so we check if the file hasn't already got the gutters const alreadyOpened = _.filter(editorsWithGutters, (editor) => { return editor.document.file.fullPath === file.fullPath; }).length > 0; if (!alreadyOpened) { // TODO: here we could sent a particular file to be refreshed only refresh(); } }); EventEmitter.on(Events.GIT_COMMITED, () => { refresh(); }); EventEmitter.on(Events.BRACKETS_FILE_CHANGED, (evt, file) => { const alreadyOpened = _.filter(editorsWithGutters, (editor) => { return editor.document.file.fullPath === file.fullPath; }).length > 0; if (alreadyOpened) { // TODO: here we could sent a particular file to be refreshed only refresh(); } });
the_stack
import * as path from "path"; import * as vscode from "vscode"; import * as sdk from "vscode-iot-device-cube-sdk"; import { OperationCanceledError } from "../common/Error/OperationCanceledError"; import { FileNames, OperationType, ScaffoldType } from "../constants"; import { FileUtility } from "../FileUtility"; import { TelemetryContext } from "../telemetry"; import { askAndOpenInRemote, channelShowAndAppendLine, executeCommand } from "../utils"; import { ContainerDeviceBase } from "./ContainerDeviceBase"; import { DeviceType } from "./Interfaces/Device"; import { TemplateFileInfo } from "./Interfaces/ProjectTemplate"; import { RemoteExtension } from "./RemoteExtension"; import { OperationFailedError } from "../common/Error/OperationFailedErrors/OperationFailedError"; interface DeviceInfo { id: string; mac: string; ip?: string; host?: string; ssid?: string; } class RaspberryPiUploadConfig { static host = "hostname"; static port = 22; static user = "username"; static password = "password"; static projectPath = "IoTProject"; static updated = false; } export class RaspberryPiDevice extends ContainerDeviceBase { private static _boardId = "raspberrypi"; name = "Raspberry Pi"; static get boardId(): string { return RaspberryPiDevice._boardId; } constructor( context: vscode.ExtensionContext, projectPath: string, channel: vscode.OutputChannel, telemetryContext: TelemetryContext, templateFilesInfo: TemplateFileInfo[] = [] ) { super(context, projectPath, channel, telemetryContext, DeviceType.RaspberryPi, templateFilesInfo); } private async getBinaryFileName(): Promise<string | undefined> { // Parse binary name from CMakeLists.txt file const cmakeFilePath = path.join(this.projectFolder, FileNames.cmakeFileName); if (!(await FileUtility.fileExists(ScaffoldType.Workspace, cmakeFilePath))) { return; } const getBinaryFileNameCmd = `cat ${cmakeFilePath} | grep 'add_executable' \ | sed -e 's/^add_executable(//' | awk '{$1=$1};1' | cut -d ' ' -f1 | tr -d '\n'`; const binaryName = await executeCommand(getBinaryFileNameCmd); return binaryName; } private async enableBinaryExecutability(ssh: sdk.SSH, binaryName: string): Promise<void> { if (!binaryName) { return; } const chmodCmd = `cd ${RaspberryPiUploadConfig.projectPath} && [ -f ${binaryName} ] && chmod +x ${binaryName}`; await ssh.exec(chmodCmd); return; } async upload(): Promise<boolean> { const isRemote = RemoteExtension.isRemote(this.extensionContext); if (!isRemote) { await askAndOpenInRemote(OperationType.Upload, this.telemetryContext); return false; } try { const binaryName = await this.getBinaryFileName(); if (!binaryName) { const message = `No executable file specified in ${FileNames.cmakeFileName}. \ Nothing to upload to target machine.`; vscode.window.showWarningMessage(message); channelShowAndAppendLine(this.channel, message); return false; } const binaryFilePath = path.join(this.outputPath, binaryName); if (!(await FileUtility.fileExists(ScaffoldType.Workspace, binaryFilePath))) { const message = `Executable file ${binaryName} does not exist under ${this.outputPath}. \ Please compile device code first.`; vscode.window.showWarningMessage(message); channelShowAndAppendLine(this.channel, message); return false; } if (!RaspberryPiUploadConfig.updated) { await this.configDeviceSettings(); } const ssh = new sdk.SSH(); await ssh.open( RaspberryPiUploadConfig.host, RaspberryPiUploadConfig.port, RaspberryPiUploadConfig.user, RaspberryPiUploadConfig.password ); try { await ssh.uploadFile(binaryFilePath, RaspberryPiUploadConfig.projectPath); } catch (error) { throw new OperationFailedError( "upload file to device", `SSH traffic is too busy. Error: ${error}`, "Please wait a second and retry." ); } try { await this.enableBinaryExecutability(ssh, binaryName); } catch (error) { throw new OperationFailedError("enable binary executability", `${error.message}`, ""); } try { await ssh.close(); } catch (error) { throw new OperationFailedError("close SSH connection", `${error.message}`, ""); } const message = `Successfully deploy compiled files to device board.`; channelShowAndAppendLine(this.channel, message); vscode.window.showInformationMessage(message); } catch (error) { throw new OperationFailedError( `upload binary file to device ${RaspberryPiUploadConfig.user}@${RaspberryPiUploadConfig.host} failed.`, `${error.message}`, "" ); } return true; } private async autoDiscoverDeviceIp(): Promise<vscode.QuickPickItem[]> { const sshDevicePickItems: vscode.QuickPickItem[] = []; const deviceInfos: DeviceInfo[] = await sdk.SSH.discover(); deviceInfos.forEach(deviceInfo => { sshDevicePickItems.push({ label: deviceInfo.ip as string, description: deviceInfo.host || "<Unknown>" }); }); sshDevicePickItems.push( { label: "$(sync) Discover again", detail: "Auto discover SSH enabled device in LAN" }, { label: "$(gear) Manual setup", detail: "Setup device SSH configuration manually" } ); return sshDevicePickItems; } /** * Configure Raspberry PI device SSH */ async configDeviceSettings(): Promise<void> { // Raspberry Pi host const sshDiscoverOrInputItems: vscode.QuickPickItem[] = [ { label: "$(search) Auto discover", detail: "Auto discover SSH enabled device in LAN" }, { label: "$(gear) Manual setup", detail: "Setup device SSH configuration manually" } ]; const sshDiscoverOrInputChoice = await vscode.window.showQuickPick(sshDiscoverOrInputItems, { ignoreFocusOut: true, matchOnDescription: true, matchOnDetail: true, placeHolder: "Select an option" }); if (!sshDiscoverOrInputChoice) { throw new OperationCanceledError("SSH configuration type selection cancelled."); } let raspiHost: string | undefined; if (sshDiscoverOrInputChoice.label === "$(search) Auto discover") { let selectDeviceChoice: vscode.QuickPickItem | undefined; do { const selectDeviceItems = this.autoDiscoverDeviceIp(); selectDeviceChoice = await vscode.window.showQuickPick(selectDeviceItems, { ignoreFocusOut: true, matchOnDescription: true, matchOnDetail: true, placeHolder: "Select a device" }); } while (selectDeviceChoice && selectDeviceChoice.label === "$(sync) Discover again"); if (!selectDeviceChoice) { throw new OperationCanceledError("Device selection cancelled."); } if (selectDeviceChoice.label !== "$(gear) Manual setup") { raspiHost = selectDeviceChoice.label; } } if (!raspiHost) { const raspiHostOption: vscode.InputBoxOptions = { value: RaspberryPiUploadConfig.host, prompt: `Please input device ip or hostname here.`, ignoreFocusOut: true }; raspiHost = await vscode.window.showInputBox(raspiHostOption); if (!raspiHost) { throw new OperationCanceledError("Hostname input cancelled."); } } raspiHost = raspiHost || RaspberryPiUploadConfig.host; // Raspberry Pi SSH port const raspiPortOption: vscode.InputBoxOptions = { value: RaspberryPiUploadConfig.port.toString(), prompt: `Please input SSH port here.`, ignoreFocusOut: true }; const raspiPortString = await vscode.window.showInputBox(raspiPortOption); if (!raspiPortString) { throw new OperationCanceledError("Port input cancelled."); } const raspiPort = raspiPortString && !isNaN(Number(raspiPortString)) ? Number(raspiPortString) : RaspberryPiUploadConfig.port; // Raspberry Pi user name const raspiUserOption: vscode.InputBoxOptions = { value: RaspberryPiUploadConfig.user, prompt: `Please input user name here.`, ignoreFocusOut: true }; let raspiUser = await vscode.window.showInputBox(raspiUserOption); if (!raspiUser) { throw new OperationCanceledError("User name input cancelled."); } raspiUser = raspiUser || RaspberryPiUploadConfig.user; // Raspberry Pi user password const raspiPasswordOption: vscode.InputBoxOptions = { value: RaspberryPiUploadConfig.password, prompt: `Please input password here.`, ignoreFocusOut: true }; let raspiPassword = await vscode.window.showInputBox(raspiPasswordOption); if (raspiPassword === undefined) { throw new OperationCanceledError("Password input cancelled."); } raspiPassword = raspiPassword || RaspberryPiUploadConfig.password; // Raspberry Pi path const raspiPathOption: vscode.InputBoxOptions = { value: RaspberryPiUploadConfig.projectPath, prompt: `Please input project destination path here.`, ignoreFocusOut: true }; let raspiPath = await vscode.window.showInputBox(raspiPathOption); if (!raspiPath) { throw new OperationCanceledError("Project destination path input cancelled."); } raspiPath = raspiPath || RaspberryPiUploadConfig.projectPath; RaspberryPiUploadConfig.host = raspiHost; RaspberryPiUploadConfig.port = raspiPort; RaspberryPiUploadConfig.user = raspiUser; RaspberryPiUploadConfig.password = raspiPassword; RaspberryPiUploadConfig.projectPath = raspiPath; RaspberryPiUploadConfig.updated = true; vscode.window.showInformationMessage("Config SSH successfully."); } }
the_stack
import {canvasPath, CanvasKeyframe} from "./animate"; const genKeyframe = (): CanvasKeyframe => ({ duration: 1000 * Math.random(), delay: 1000 * Math.random(), timingFunction: "linear", callback: () => {}, blobOptions: { extraPoints: Math.floor(10 * Math.random()), randomness: Math.floor(10 * Math.random()), seed: Math.random(), size: 100 + 200 * Math.random(), }, canvasOptions: { offsetX: 100 * Math.random(), offsetY: 100 * Math.random(), }, }); describe("animate", () => { describe("canvasPath", () => { describe("transition", () => { describe("keyframe", () => { it("should accept generated keyframe", () => { const animation = canvasPath(); const keyframe = genKeyframe(); expect(() => animation.transition(keyframe)).not.toThrow(); }); it("should indicate the rejected frame index", () => { const animation = canvasPath(); const keyframes = [genKeyframe(), null as any, genKeyframe()]; expect(() => animation.transition(...keyframes)).toThrow(/keyframe.*1/g); }); interface TestCase { name: string; edit: (keyframe: CanvasKeyframe) => void; error?: RegExp; } const testCases: Array<TestCase> = [ // duration { name: "should accept valid duration", edit: (keyframe) => (keyframe.duration = 100), }, { name: "should accept zero duration", edit: (keyframe) => (keyframe.duration = 0), }, { name: "should reject undefined duration", edit: (keyframe) => delete keyframe.duration, error: /duration.*number.*undefined/g, }, { name: "should reject negative duration", edit: (keyframe) => (keyframe.duration = -10), error: /duration.*invalid/g, }, { name: "should reject broken duration", edit: (keyframe) => (keyframe.duration = NaN), error: /duration.*number.*NaN/g, }, { name: "should reject invalid duration", edit: (keyframe) => (keyframe.duration = "123" as any), error: /duration.*number.*string/g, }, // delay { name: "should accept valid delay", edit: (keyframe) => (keyframe.delay = 200), }, { name: "should accept zero delay", edit: (keyframe) => (keyframe.delay = 0), }, { name: "should accept undefined delay", edit: (keyframe) => delete keyframe.delay, }, { name: "should reject negative delay", edit: (keyframe) => (keyframe.delay = -10), error: /delay.*invalid/g, }, { name: "should reject broken delay", edit: (keyframe) => (keyframe.delay = NaN), error: /delay.*number.*NaN/g, }, { name: "should reject invalid delay", edit: (keyframe) => (keyframe.delay = "123" as any), error: /delay.*number.*string/g, }, // timingFunction { name: "should accept known timingFunction", edit: (keyframe) => (keyframe.timingFunction = "ease"), }, { name: "should accept undefined timingFunction", edit: (keyframe) => delete keyframe.timingFunction, }, { name: "should reject invalid timingFunction", edit: (keyframe) => (keyframe.timingFunction = (() => 0) as any), error: /timingFunction.*string.*function/g, }, { name: "should reject unknown timingFunction", edit: (keyframe) => (keyframe.timingFunction = "unknown" as any), error: /timingFunction.*not recognized.*unknown/g, }, // callback { name: "should accept valid callback", edit: (keyframe) => (keyframe.callback = () => console.log("test")), }, { name: "should accept undefined callback", edit: (keyframe) => delete keyframe.callback, }, { name: "should reject invalid callback", edit: (keyframe) => (keyframe.callback = {} as any), error: /callback.*function.*object/g, }, // blobOptions { name: "should reject undefined blobOptions", edit: (keyframe) => delete keyframe.blobOptions, error: /blobOptions.*object.*undefined/g, }, { name: "should reject invalid blobOptions", edit: (keyframe) => (keyframe.blobOptions = null as any), error: /blobOptions.*object.*null/g, }, // blobOptions.seed { name: "should accept number blobOptions seed", edit: (keyframe) => (keyframe.blobOptions.seed = 123), }, { name: "should accept string blobOptions seed", edit: (keyframe) => (keyframe.blobOptions.seed = "test"), }, { name: "should reject undefined blobOptions seed", edit: (keyframe) => delete keyframe.blobOptions.seed, error: /seed.*string.*number.*undefined/g, }, { name: "should reject broken blobOptions seed", edit: (keyframe) => (keyframe.blobOptions.seed = NaN), error: /seed.*string.*number.*NaN/g, }, // blobOptions.extraPoints { name: "should accept valid blobOptions extraPoints", edit: (keyframe) => (keyframe.blobOptions.extraPoints = 4), }, { name: "should reject undefined blobOptions extraPoints", edit: (keyframe) => delete keyframe.blobOptions.extraPoints, error: /blobOptions.*extraPoints.*number.*undefined/g, }, { name: "should reject broken blobOptions extraPoints", edit: (keyframe) => (keyframe.blobOptions.extraPoints = NaN), error: /blobOptions.*extraPoints.*number.*NaN/g, }, { name: "should reject negative blobOptions extraPoints", edit: (keyframe) => (keyframe.blobOptions.extraPoints = -2), error: /blobOptions.*extraPoints.*invalid/g, }, // blobOptions.randomness { name: "should accept valid blobOptions randomness", edit: (keyframe) => (keyframe.blobOptions.randomness = 3), }, { name: "should reject undefined blobOptions randomness", edit: (keyframe) => delete keyframe.blobOptions.randomness, error: /blobOptions.*randomness.*number.*undefined/g, }, { name: "should reject broken blobOptions randomness", edit: (keyframe) => (keyframe.blobOptions.randomness = NaN), error: /blobOptions.*randomness.*number.*NaN/g, }, { name: "should reject negative blobOptions randomness", edit: (keyframe) => (keyframe.blobOptions.randomness = -10), error: /blobOptions.*randomness.*invalid/g, }, // blobOptions.size { name: "should accept valid blobOptions size", edit: (keyframe) => (keyframe.blobOptions.size = 40), }, { name: "should reject undefined blobOptions size", edit: (keyframe) => delete keyframe.blobOptions.size, error: /blobOptions.*size.*number.*undefined/g, }, { name: "should reject broken blobOptions size", edit: (keyframe) => (keyframe.blobOptions.size = NaN), error: /blobOptions.*size.*number.*NaN/g, }, { name: "should reject negative blobOptions size", edit: (keyframe) => (keyframe.blobOptions.size = -1), error: /blobOptions.*size.*invalid/g, }, // canvasOptions { name: "should accept empty canvasOptions", edit: (keyframe) => (keyframe.canvasOptions = {}), }, { name: "should accept undefined canvasOptions", edit: (keyframe) => delete keyframe.canvasOptions, }, { name: "should reject invalid canvasOptions", edit: (keyframe) => (keyframe.canvasOptions = null as any), error: /canvasOptions.*object.*null/g, }, // canvasOptions.offsetX { name: "should accept valid canvasOptions offsetX", edit: (keyframe) => (keyframe.canvasOptions = {offsetX: 100}), }, { name: "should accept undefined canvasOptions offsetX", edit: (keyframe) => delete keyframe.canvasOptions?.offsetX, }, { name: "should reject broken canvasOptions offsetX", edit: (keyframe) => (keyframe.canvasOptions = {offsetX: NaN}), error: /canvasOptions.*offsetX.*number.*NaN/g, }, // canvasOptions.offsetY { name: "should accept valid canvasOptions offsetY", edit: (keyframe) => (keyframe.canvasOptions = {offsetY: 222}), }, { name: "should accept undefined canvasOptions offsetY", edit: (keyframe) => delete keyframe.canvasOptions?.offsetY, }, { name: "should reject broken canvasOptions offsetY", edit: (keyframe) => (keyframe.canvasOptions = {offsetY: NaN}), error: /canvasOptions.*offsetY.*number.*NaN/g, }, ]; // Run all test cases with a configurable amount of keyframes // and index of the keyframe being edited for the tests. const runSuite = (keyframeCount: number, editIndex: number) => { for (const testCase of testCases) { it(testCase.name, () => { // Create blank animation. const animation = canvasPath(); // Create keyframes to call transition with. const keyframes: CanvasKeyframe[] = []; for (let i = 0; i < keyframeCount; i++) { keyframes.push(genKeyframe()); } // Modify selected keyframe. testCase.edit(keyframes[editIndex]); if (testCase.error) { // Copy regexp because they are stateful. const pattern = new RegExp(testCase.error); expect(() => animation.transition(...keyframes)).toThrow(pattern); } else { expect(() => animation.transition(...keyframes)).not.toThrow(); } }); } }; // Run all cases when given a single test frame and asserting on it. describe("first", () => runSuite(1, 0)); // Run all cases when given more than one frame, asserting on last one. const lastLength = 2 + Math.floor(4 * Math.random()); describe("last", () => runSuite(lastLength, lastLength - 1)); // Run all cases when given more than one frame, asserting on a random one. const nthLength = 2 + Math.floor(16 * Math.random()); const nthIndex = Math.floor(nthLength * Math.random()); describe(`nth (${nthIndex + 1}/${nthLength})`, () => runSuite(nthLength, nthIndex)); }); }); }); });
the_stack
"use strict"; export default function (joint) { var g = joint.g; joint.routers.manhattan = (function (g, asd, joint, util) { var config = { // size of the step to find a route (the grid of the manhattan pathfinder) step: 10, // the number of route finding loops that cause the router to abort // returns fallback route instead maximumLoops: 90000, // the number of decimal places to round floating point coordinates precision: 10, // maximum change of direction maxAllowedDirectionChange: 90, // should the router use perpendicular linkView option? // does not connect anchor of element but rather a point close-by that is orthogonal // this looks much better perpendicular: false, // should the source and/or target not be considered as obstacles? excludeEnds: [], // 'source', 'target' // should certain types of elements not be considered as obstacles? excludeTypes: ["basic.Text"], // possible starting directions from an element startDirections: ["top", "right", "bottom", "left"], // possible ending directions to an element endDirections: ["top", "right", "bottom", "left"], // specify the directions used above and what they mean directionMap: { top: { x: 0, y: -1 }, right: { x: 1, y: 0 }, bottom: { x: 0, y: 1 }, left: { x: -1, y: 0 } }, // cost of an orthogonal step cost: function () { return this.step; }, // an array of directions to find next points on the route // different from start/end directions directions: function () { var step = this.step; var cost = this.cost(); return [ { offsetX: step, offsetY: 0, cost: cost }, { offsetX: 0, offsetY: step, cost: cost }, { offsetX: -step, offsetY: 0, cost: cost }, { offsetX: 0, offsetY: -step, cost: cost } ]; }, // a penalty received for direction change penalties: function () { return { 0: 0, 45: this.step / 2, 90: this.step / 2 }; }, // padding applied on the element bounding boxes paddingBox: function () { var step = this.step; return { x: -step, y: -step, width: 2 * step, height: 2 * step }; }, // a router to use when the manhattan router fails // (one of the partial routes returns null) fallbackRouter: function (vertices, opt, linkView) { if (!util.isFunction(joint.routers.orthogonal)) { throw new Error( "Manhattan requires the orthogonal router as default fallback." ); } return joint.routers.orthogonal( vertices, util.assign({}, config, opt), linkView ); }, /* Deprecated */ // a simple route used in situations when main routing method fails // (exceed max number of loop iterations, inaccessible) fallbackRoute: function (from, to, opt) { return null; // null result will trigger the fallbackRouter // left for reference: /*// Find an orthogonal route ignoring obstacles. var point = ((opt.previousDirAngle || 0) % 180 === 0) ? new g.Point(from.x, to.y) : new g.Point(to.x, from.y); return [point];*/ }, // if a function is provided, it's used to route the link while dragging an end // i.e. function(from, to, opt) { return []; } draggingRoute: null }; // HELPER CLASSES // // Map of obstacles // Helper structure to identify whether a point lies inside an obstacle. function ObstacleMap(opt) { this.map = {}; this.options = opt; // tells how to divide the paper when creating the elements map this.mapGridSize = 100; } ObstacleMap.prototype.build = function (graph, link) { var opt = this.options; // source or target element could be excluded from set of obstacles var excludedEnds = util .toArray(opt.excludeEnds) .reduce(function (res, item) { var end = link.get(item); if (end) { var cell = graph.getCell(end.id); if (cell) { res.push(cell); } } return res; }, []); // Exclude any embedded elements from the source and the target element. var excludedAncestors: any = []; var source = graph.getCell(link.get("source").id); if (source) { excludedAncestors = util.union( excludedAncestors, source.getAncestors().map(function (cell) { return cell.id; }) ); } var target = graph.getCell(link.get("target").id); if (target) { excludedAncestors = util.union( excludedAncestors, target.getAncestors().map(function (cell) { return cell.id; }) ); } // Builds a map of all elements for quicker obstacle queries (i.e. is a point contained // in any obstacle?) (a simplified grid search). // The paper is divided into smaller cells, where each holds information about which // elements belong to it. When we query whether a point lies inside an obstacle we // don't need to go through all obstacles, we check only those in a particular cell. var mapGridSize = this.mapGridSize; graph.getElements().reduce(function (map, element) { var isExcludedType = util .toArray(opt.excludeTypes) .includes(element.get("type")); var isExcludedEnd = excludedEnds.find(function (excluded) { return excluded.id === element.id; }); var isExcludedAncestor: any = excludedAncestors.includes(element.id); var isExcluded = isExcludedType || isExcludedEnd || isExcludedAncestor; if (!isExcluded) { var bbox = element.getBBox().moveAndExpand(opt.paddingBox); var origin = bbox.origin().snapToGrid(mapGridSize); var corner = bbox.corner().snapToGrid(mapGridSize); for (var x = origin.x; x <= corner.x; x += mapGridSize) { for (var y = origin.y; y <= corner.y; y += mapGridSize) { var gridKey = x + "@" + y; map[gridKey] = map[gridKey] || []; map[gridKey].push(bbox); } } } return map; }, this.map); return this; }; ObstacleMap.prototype.isPointAccessible = function (point) { var mapKey = point .clone() .snapToGrid(this.mapGridSize) .toString(); return util.toArray(this.map[mapKey]).every(function (obstacle) { return !obstacle.containsPoint(point); }); }; // Sorted Set // Set of items sorted by given value. function SortedSet() { this.items = []; this.hash = {}; this.values = {}; this.OPEN = 1; this.CLOSE = 2; } SortedSet.prototype.add = function (item, value) { if (this.hash[item]) { // item removal this.items.splice(this.items.indexOf(item), 1); } else { this.hash[item] = this.OPEN; } this.values[item] = value; var index = joint.util.sortedIndex( this.items, item, function (i) { return this.values[i]; }.bind(this) ); this.items.splice(index, 0, item); }; SortedSet.prototype.remove = function (item) { this.hash[item] = this.CLOSE; }; SortedSet.prototype.isOpen = function (item) { return this.hash[item] === this.OPEN; }; SortedSet.prototype.isClose = function (item) { return this.hash[item] === this.CLOSE; }; SortedSet.prototype.isEmpty = function () { return this.items.length === 0; }; SortedSet.prototype.pop = function () { var item = this.items.shift(); this.remove(item); return item; }; // HELPERS // // return source bbox function getSourceBBox(linkView, opt) { // expand by padding box if (opt && opt.paddingBox) return linkView.sourceBBox.clone().moveAndExpand(opt.paddingBox); return linkView.sourceBBox.clone(); } // return target bbox function getTargetBBox(linkView, opt) { // expand by padding box if (opt && opt.paddingBox) return linkView.targetBBox.clone().moveAndExpand(opt.paddingBox); return linkView.targetBBox.clone(); } // return source anchor function getSourceAnchor(linkView, opt) { if (linkView.sourceAnchor) return linkView.sourceAnchor; // fallback: center of bbox var sourceBBox = getSourceBBox(linkView, opt); return sourceBBox.center(); } // return target anchor function getTargetAnchor(linkView, opt) { if (linkView.targetAnchor) return linkView.targetAnchor; // fallback: center of bbox var targetBBox = getTargetBBox(linkView, opt); return targetBBox.center(); // default } // returns a direction index from start point to end point // corrects for grid deformation between start and end function getDirectionAngle(start, end, numDirections, grid, opt) { var quadrant = 360 / numDirections; var angleTheta = start.theta(fixAngleEnd(start, end, grid, opt)); var normalizedAngle = g.normalizeAngle(angleTheta + quadrant / 2); return quadrant * Math.floor(normalizedAngle / quadrant); } // helper function for getDirectionAngle() // corrects for grid deformation // (if a point is one grid steps away from another in both dimensions, // it is considered to be 45 degrees away, even if the real angle is different) // this causes visible angle discrepancies if `opt.step` is much larger than `paper.gridSize` function fixAngleEnd(start, end, grid, opt) { var step = opt.step; var diffX = end.x - start.x; var diffY = end.y - start.y; var gridStepsX = diffX / grid.x; var gridStepsY = diffY / grid.y; var distanceX = gridStepsX * step; var distanceY = gridStepsY * step; return new g.Point(start.x + distanceX, start.y + distanceY); } // return the change in direction between two direction angles function getDirectionChange(angle1, angle2) { var directionChange = Math.abs(angle1 - angle2); return directionChange > 180 ? 360 - directionChange : directionChange; } // fix direction offsets according to current grid function getGridOffsets(directions, grid, opt) { var step = opt.step; util.toArray(opt.directions).forEach(function (direction) { direction.gridOffsetX = (direction.offsetX / step) * grid.x; direction.gridOffsetY = (direction.offsetY / step) * grid.y; }); } // get grid size in x and y dimensions, adapted to source and target positions function getGrid(step, source, target) { return { source: source.clone(), x: getGridDimension(target.x - source.x, step), y: getGridDimension(target.y - source.y, step) }; } // helper function for getGrid() function getGridDimension(diff, step) { // return step if diff = 0 if (!diff) return step; var absDiff = Math.abs(diff); var numSteps = Math.round(absDiff / step); // return absDiff if less than one step apart if (!numSteps) return absDiff; // otherwise, return corrected step var roundedDiff = numSteps * step; var remainder = absDiff - roundedDiff; var stepCorrection = remainder / numSteps; return step + stepCorrection; } // return a clone of point snapped to grid function snapToGrid(point, grid) { var source = grid.source; var snappedX = g.snapToGrid(point.x - source.x, grid.x) + source.x; var snappedY = g.snapToGrid(point.y - source.y, grid.y) + source.y; return new g.Point(snappedX, snappedY); } // round the point to opt.precision function round(point, opt) { if (!point) return point; return point.round(opt.precision); } // return a string representing the point // string is rounded to nearest int in both dimensions function getKey(point) { return point .clone() .round() .toString(); } // return a normalized vector from given point // used to determine the direction of a difference of two points function normalizePoint(point) { return new g.Point( point.x === 0 ? 0 : Math.abs(point.x) / point.x, point.y === 0 ? 0 : Math.abs(point.y) / point.y ); } // PATHFINDING // // reconstructs a route by concatenating points with their parents function reconstructRoute(parents, points, tailPoint, from, to, opt) { var route: any = []; var prevDiff = normalizePoint(to.difference(tailPoint)); var currentKey = getKey(tailPoint); var parent = parents[currentKey]; var point; while (parent) { point = round(points[currentKey], opt); var diff = normalizePoint(point.difference(round(parent.clone(), opt))); if (!diff.equals(prevDiff)) { route.unshift(point); prevDiff = diff; } currentKey = getKey(parent); parent = parents[currentKey]; } var leadPoint = round(points[currentKey], opt); var fromDiff = normalizePoint(leadPoint.difference(from)); if (!fromDiff.equals(prevDiff)) { route.unshift(leadPoint); } return route; } // heuristic method to determine the distance between two points function estimateCost(from, endPoints) { var min = Infinity; for (var i = 0, len = endPoints.length; i < len; i++) { var cost = from.manhattanDistance(endPoints[i]); if (cost < min) min = cost; } return min; } // find points around the bbox taking given directions into account // lines are drawn from anchor in given directions, intersections recorded // if anchor is outside bbox, only those directions that intersect get a rect point // the anchor itself is returned as rect point (representing some directions) // (since those directions are unobstructed by the bbox) function getRectPoints(anchor, bbox, directionList, grid, opt) { var directionMap = opt.directionMap; var snappedAnchor = round(snapToGrid(anchor, grid), opt); var snappedCenter = round(snapToGrid(bbox.center(), grid), opt); var anchorCenterVector = snappedAnchor.difference(snappedCenter); var keys = util.isObject(directionMap) ? Object.keys(directionMap) : []; var dirList = util.toArray(directionList); var rectPoints = keys.reduce(function (res: any, key) { if (dirList.includes(key)) { var direction = directionMap[key]; // create a line that is guaranteed to intersect the bbox if bbox is in the direction // even if anchor lies outside of bbox var endpoint = new g.Point( snappedAnchor.x + direction.x * (Math.abs(anchorCenterVector.x) + bbox.width), snappedAnchor.y + direction.y * (Math.abs(anchorCenterVector.y) + bbox.height) ); var intersectionLine = new g.Line(anchor, endpoint); // get the farther intersection, in case there are two // (that happens if anchor lies next to bbox) var intersections = intersectionLine.intersect(bbox) || []; var numIntersections = intersections.length; var farthestIntersectionDistance; var farthestIntersection = null; for (var i = 0; i < numIntersections; i++) { var currentIntersection = intersections[i]; var distance = snappedAnchor.squaredDistance(currentIntersection); if ( farthestIntersectionDistance === undefined || distance > farthestIntersectionDistance ) { farthestIntersectionDistance = distance; farthestIntersection = snapToGrid(currentIntersection, grid); } } var point = round(farthestIntersection, opt); // if an intersection was found in this direction, it is our rectPoint if (point) { // if the rectPoint lies inside the bbox, offset it by one more step if (bbox.containsPoint(point)) { round( point.offset(direction.x * grid.x, direction.y * grid.y), opt ); } // then add the point to the result array res.push(point); } } return res; }, []); // if anchor lies outside of bbox, add it to the array of points if (!bbox.containsPoint(snappedAnchor)) rectPoints.push(snappedAnchor); return rectPoints; } // finds the route between two points/rectangles (`from`, `to`) implementing A* algorithm // rectangles get rect points assigned by getRectPoints() function findRoute(from, to, map, opt) { // Get grid for this route. var sourceAnchor, targetAnchor; if (from instanceof g.Rect) { // `from` is sourceBBox sourceAnchor = getSourceAnchor(this, opt).clone(); } else { sourceAnchor = from.clone(); } if (to instanceof g.Rect) { // `to` is targetBBox targetAnchor = getTargetAnchor(this, opt).clone(); } else { targetAnchor = to.clone(); } var grid = getGrid(opt.step, sourceAnchor, targetAnchor); // Get pathfinding points. var start, end; var startPoints, endPoints; // set of points we start pathfinding from if (from instanceof g.Rect) { // `from` is sourceBBox start = round(snapToGrid(sourceAnchor, grid), opt); startPoints = getRectPoints( start, from, opt.startDirections, grid, opt ); } else { start = round(snapToGrid(sourceAnchor, grid), opt); startPoints = [start]; } // set of points we want the pathfinding to finish at if (to instanceof g.Rect) { // `to` is targetBBox end = round(snapToGrid(targetAnchor, grid), opt); endPoints = getRectPoints( targetAnchor, to, opt.endDirections, grid, opt ); } else { end = round(snapToGrid(targetAnchor, grid), opt); endPoints = [end]; } // take into account only accessible rect points (those not under obstacles) startPoints = startPoints.filter(map.isPointAccessible, map); endPoints = endPoints.filter(map.isPointAccessible, map); // Check that there is an accessible route point on both sides. // Otherwise, use fallbackRoute(). if (startPoints.length > 0 && endPoints.length > 0) { // The set of tentative points to be evaluated, initially containing the start points. // Rounded to nearest integer for simplicity. var openSet = new SortedSet(); // Keeps reference to actual points for given elements of the open set. var points = {}; // Keeps reference to a point that is immediate predecessor of given element. var parents = {}; // Cost from start to a point along best known path. var costs = {}; for (var i = 0, n = startPoints.length; i < n; i++) { var point = startPoints[i]; var key = getKey(point); openSet.add(key, estimateCost(point, endPoints)); points[key] = point; costs[key] = 0; } var previousRouteDirectionAngle = opt.previousDirectionAngle; // undefined for first route var isPathBeginning = previousRouteDirectionAngle === undefined; // directions var direction, directionChange; var directions = opt.directions; getGridOffsets(directions, grid, opt); var numDirections = directions.length; var endPointsKeys = util .toArray(endPoints) .reduce(function (res, endPoint) { var key = getKey(endPoint); res.push(key); return res; }, []); // main route finding loop var loopsRemaining = opt.maximumLoops; while (!openSet.isEmpty() && loopsRemaining > 0) { // remove current from the open list var currentKey = openSet.pop(); var currentPoint = points[currentKey]; var currentParent = parents[currentKey]; var currentCost = costs[currentKey]; var isRouteBeginning = currentParent === undefined; // undefined for route starts var isStart = currentPoint.equals(start); // (is source anchor or `from` point) = can leave in any direction var previousDirectionAngle; if (!isRouteBeginning) previousDirectionAngle = getDirectionAngle( currentParent, currentPoint, numDirections, grid, opt ); // a vertex on the route else if (!isPathBeginning) previousDirectionAngle = previousRouteDirectionAngle; // beginning of route on the path else if (!isStart) previousDirectionAngle = getDirectionAngle( start, currentPoint, numDirections, grid, opt ); // beginning of path, start rect point else previousDirectionAngle = null; // beginning of path, source anchor or `from` point // check if we reached any endpoint if (endPointsKeys.indexOf(currentKey) >= 0) { opt.previousDirectionAngle = previousDirectionAngle; return reconstructRoute( parents, points, currentPoint, start, end, opt ); } // go over all possible directions and find neighbors for (i = 0; i < numDirections; i++) { direction = directions[i]; var directionAngle = direction.angle; directionChange = getDirectionChange( previousDirectionAngle, directionAngle ); // if the direction changed rapidly, don't use this point // any direction is allowed for starting points if ( !(isPathBeginning && isStart) && directionChange > opt.maxAllowedDirectionChange ) continue; var neighborPoint = currentPoint .clone() .offset(direction.gridOffsetX, direction.gridOffsetY); var neighborKey = getKey(neighborPoint); // Closed points from the openSet were already evaluated. if ( openSet.isClose(neighborKey) || !map.isPointAccessible(neighborPoint) ) continue; // We can only enter end points at an acceptable angle. if (endPointsKeys.indexOf(neighborKey) >= 0) { // neighbor is an end point round(neighborPoint, opt); // remove rounding errors var isNeighborEnd = neighborPoint.equals(end); // (is target anchor or `to` point) = can be entered in any direction if (!isNeighborEnd) { var endDirectionAngle = getDirectionAngle( neighborPoint, end, numDirections, grid, opt ); var endDirectionChange = getDirectionChange( directionAngle, endDirectionAngle ); if (endDirectionChange > opt.maxAllowedDirectionChange) continue; } } // The current direction is ok. var neighborCost = direction.cost; var neighborPenalty = isStart ? 0 : opt.penalties[directionChange]; // no penalties for start point var costFromStart = currentCost + neighborCost + neighborPenalty; if ( !openSet.isOpen(neighborKey) || costFromStart < costs[neighborKey] ) { // neighbor point has not been processed yet // or the cost of the path from start is lower than previously calculated points[neighborKey] = neighborPoint; parents[neighborKey] = currentPoint; costs[neighborKey] = costFromStart; openSet.add( neighborKey, costFromStart + estimateCost(neighborPoint, endPoints) ); } } loopsRemaining--; } } // no route found (`to` point either wasn't accessible or finding route took // way too much calculation) return opt.fallbackRoute.call(this, start, end, opt); } // resolve some of the options function resolveOptions(opt) { opt.directions = util.result(opt, "directions"); opt.penalties = util.result(opt, "penalties"); opt.paddingBox = util.result(opt, "paddingBox"); util.toArray(opt.directions).forEach(function (direction) { var point1 = new g.Point(0, 0); var point2 = new g.Point(direction.offsetX, direction.offsetY); direction.angle = g.normalizeAngle(point1.theta(point2)); }); } // initialization of the route finding function router(vertices, opt, linkView) { resolveOptions(opt); // enable/disable linkView perpendicular option linkView.options.perpendicular = !!opt.perpendicular; var sourceBBox = getSourceBBox(linkView, opt); var targetBBox = getTargetBBox(linkView, opt); var sourceAnchor = getSourceAnchor(linkView, opt); //var targetAnchor = getTargetAnchor(linkView, opt); // pathfinding var map = new ObstacleMap(opt).build( linkView.paper.model, linkView.model ); var oldVertices = util.toArray(vertices).map(g.Point); var newVertices = []; var tailPoint = sourceAnchor; // the origin of first route's grid, does not need snapping // find a route by concatenating all partial routes (routes need to pass through vertices) // source -> vertex[1] -> ... -> vertex[n] -> target for (var i = 0, len = oldVertices.length; i <= len; i++) { var partialRoute: any = null; var from = to || sourceBBox; var to = oldVertices[i]; if (!to) { // this is the last iteration // we ran through all vertices in oldVertices // 'to' is not a vertex. to = targetBBox; // If the target is a point (i.e. it's not an element), we // should use dragging route instead of main routing method if it has been provided. var isEndingAtPoint = !linkView.model.get("source").id || !linkView.model.get("target").id; if (isEndingAtPoint && util.isFunction(opt.draggingRoute)) { // Make sure we are passing points only (not rects). var dragFrom = from === sourceBBox ? sourceAnchor : from; var dragTo = to.origin(); partialRoute = opt.draggingRoute.call( linkView, dragFrom, dragTo, opt ); } } // if partial route has not been calculated yet use the main routing method to find one partialRoute = partialRoute || findRoute.call(linkView, from, to, map, opt); if (partialRoute === null) { // the partial route cannot be found return opt.fallbackRouter(vertices, opt, linkView); } var leadPoint = partialRoute[0]; // remove the first point if the previous partial route had the same point as last if (leadPoint && leadPoint.equals(tailPoint)) partialRoute.shift(); // save tailPoint for next iteration tailPoint = partialRoute[partialRoute.length - 1] || tailPoint; Array.prototype.push.apply(newVertices, partialRoute); } return newVertices; } // public function return function (vertices, opt, linkView) { return router(vertices, util.assign({}, config, opt), linkView); }; })(g, null, joint, joint.util); joint.routers.metro = (function (util) { var config = { maxAllowedDirectionChange: 45, // cost of a diagonal step diagonalCost: function (): any { var step = (this as any).step; return Math.ceil(Math.sqrt((step * step) << 1)); }, // an array of directions to find next points on the route // different from start/end directions directions: function () { var step = (this as any).step; var cost = (this as any).cost(); var diagonalCost = this.diagonalCost(); return [ { offsetX: step, offsetY: 0, cost: cost }, { offsetX: step, offsetY: step, cost: diagonalCost }, { offsetX: 0, offsetY: step, cost: cost }, { offsetX: -step, offsetY: step, cost: diagonalCost }, { offsetX: -step, offsetY: 0, cost: cost }, { offsetX: -step, offsetY: -step, cost: diagonalCost }, { offsetX: 0, offsetY: -step, cost: cost }, { offsetX: step, offsetY: -step, cost: diagonalCost } ]; }, // a simple route used in situations when main routing method fails // (exceed max number of loop iterations, inaccessible) fallbackRoute: function (from: any, to: any, opt: any) { // Find a route which breaks by 45 degrees ignoring all obstacles. var theta = from.theta(to); var route: any[] = []; var a = { x: to.x, y: from.y }; var b = { x: from.x, y: to.y }; if (theta % 180 > 90) { var t = a; a = b; b = t; } var p1 = theta % 90 < 45 ? a : b; var l1 = new g.Line(from, p1); var alpha = 90 * Math.ceil(theta / 90); var p2 = g.Point.fromPolar( l1.squaredLength(), g.toRad(alpha + 135), p1 ); var l2 = new g.Line(to, p2); var intersectionPoint = l1.intersection(l2); var point = intersectionPoint ? intersectionPoint : to; var directionFrom = intersectionPoint ? point : from; var quadrant = 360 / opt.directions.length; var angleTheta = directionFrom.theta(to); var normalizedAngle = g.normalizeAngle(angleTheta + quadrant / 2); var directionAngle = quadrant * Math.floor(normalizedAngle / quadrant); opt.previousDirectionAngle = directionAngle; if (point) route.push(point.round()); route.push(to); return route; } }; // public function return function (vertices: any, opt: any, linkView: any) { if (!util.isFunction(joint.routers.manhattan)) { throw new Error("Metro requires the manhattan router."); } return joint.routers.manhattan( vertices, util.assign({}, config, opt), linkView ); }; })(joint.util); }
the_stack
'use strict'; import { remote } from 'electron'; import { sleep } from 'chord/base/common/time'; import { Logger, LogLevel } from 'chord/platform/log/common/log'; import { filenameToNodeName } from 'chord/platform/utils/common/paths'; const loggerWarning = new Logger(filenameToNodeName(__filename), LogLevel.Warning); import { LoginTimeoutError } from 'chord/music/common/errors'; import { md5 } from 'chord/base/node/crypto'; import { Cookie, makeCookieJar, makeCookies, makeCookie } from 'chord/base/node/cookies'; import { querystringify, getHost } from 'chord/base/node/url'; import { request, IRequestOptions } from 'chord/base/node/_request'; import { IAudio } from 'chord/music/api/audio'; import { ISong } from 'chord/music/api/song'; import { IAlbum } from 'chord/music/api/album'; import { IArtist } from 'chord/music/api/artist'; import { ICollection } from 'chord/music/api/collection'; import { IAccount } from 'chord/music/api/user'; import { makeSong, makeSongs, makeAlbum, makeAlbums, makeArtist, makeArtists, makeCollection, makeCollections, } from "chord/music/xiami/parser"; const DOMAIN = 'xiami.com'; /** * Xiami Web Api */ export class XiamiApi { /** * For json */ static readonly HEADERS1 = { 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh-TW;q=0.7,zh;q=0.6,ja;q=0.5', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36', 'accept': 'application/json, text/plain, */*', 'referer': 'https://www.xiami.com/', 'sec-fetch-mode': 'cors', 'authority': 'www.xiami.com', 'sec-fetch-site': 'same-origin', }; /** * For web page */ static readonly HEADERS2 = { 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,zh-TW;q=0.7', }; static readonly BASICURL = 'https://www.xiami.com/'; static readonly NODE_MAP = { audios: 'song/getSongDetails', song: 'api/song/initialize', // album: 'api/album/getAlbumDetail', album: 'api/album/initialize', collection: 'api/collect/getCollectDetail', collectionSongs: 'api/collect/getCollectSongs', artist: 'api/artist/initialize', // artist: 'api/artist/getArtistDetail', artistAlbums: 'api/album/getArtistAlbums', artistSongs: 'api/album/getArtistSongs', searchSongs: 'api/search/searchSongs', searchAlbums: 'api/search/searchAlbums', searchArtists: 'api/search/searchArtists', searchCollections: 'api/search/searchCollects', }; static readonly REQUEST_METHOD_MAP = { audios: 'GET', song: 'GET', album: 'GET', collection: 'GET', collectionSongs: 'GET', artist: 'GET', artistAlbums: 'GET', artistSongs: 'GET', searchSongs: 'GET', searchAlbums: 'GET', searchArtists: 'GET', searchCollections: 'GET', }; // account private account: IAccount; private token: string; private cookies: { [key: string]: Cookie; } = {}; // For user authority private userId: string; constructor() { } public reset() { this.cookies = {}; this.token = null; } public makeSign(node: string, params: string) { let token = this.token || ''; let s = token + '_xmMain_' + '/' + node + '_' + params; return md5(s); } public async getCookies(): Promise<void> { if (this.token) { return null; } let url = XiamiApi.BASICURL; let options: IRequestOptions = { method: 'GET', url: url, headers: XiamiApi.HEADERS2, gzip: true, resolveWithFullResponse: true, }; let result: any = await request(options); if (result.headers.hasOwnProperty('set-cookie')) { makeCookies(result.headers['set-cookie']).forEach(cookie => { this.cookies[cookie.key] = cookie; if (cookie.key == 'xm_sg_tk') { this.token = cookie.value.split('_')[0]; } }); } else { loggerWarning.warning('[XiamiApi.getCookies] [Error]: (params, response):', options, result); } } async handleVerify(url: string) { let win = new remote.BrowserWindow( { width: 380, height: 320, webPreferences: { enableRemoteModule: false, disableHtmlFullscreenWindowResize: true, }, }); // win.webContents.openDevTools(); win.on('close', () => { win = null; }); win.loadURL(url, { httpReferrer: 'https://www.xiami.com/' }); // clear cache win.webContents.session.clearStorageData(); win.show(); for (let timeout = 0; timeout < 12000000; timeout += 1000) { // waiting to get cookies await sleep(1000); let cookiesStr = await win.webContents.executeJavaScript('Promise.resolve(document.cookie)', true); if (cookiesStr.includes('x5sec')) { let cookies = {}; cookiesStr.split('; ').forEach(chunk => { let index = chunk.indexOf('='); cookies[chunk.slice(0, index)] = chunk.slice(index + 1); }); Object.keys(cookies).forEach(key => { let cookie = makeCookie(key, cookies[key], DOMAIN); this.cookies[key] = cookie; }); // close window win.close(); return; } } // Handle timeout win.close(); throw new LoginTimeoutError('Timeout !!!'); } public async request(method: string, url: string, data?: string): Promise<any> { // init cookies await this.getCookies(); let headers = { ...XiamiApi.HEADERS1 }; let cookieJar = makeCookieJar(); let cookies = { ...this.cookies }; for (let key in cookies) { cookieJar.setCookie(cookies[key], 'http://' + DOMAIN); } let options: IRequestOptions = { method, url: url, jar: cookieJar, headers: headers, body: data, gzip: true, resolveWithFullResponse: false, }; let result: any = await request(options); return result; } public async request_with_sign( method: string, node: string, apiParams: object, referer?: string, basicUrl?: string, excludedCookies: Array<string> = [] ): Promise<any | null> { // init cookies await this.getCookies(); let queryStr = JSON.stringify(apiParams); let sign = this.makeSign(node, queryStr); basicUrl = basicUrl || XiamiApi.BASICURL; let headers = !!referer ? { ...XiamiApi.HEADERS1, referer: referer } : { ...XiamiApi.HEADERS1 }; headers['authority'] = getHost(basicUrl); let xmUA: string = undefined; if (window && (window as any).uabModule) xmUA = (window as any).uabModule.getUA(); headers['xm-ua'] = xmUA; // Make cookie jar let cookieJar = makeCookieJar(); let cookies = { ...this.cookies }; excludedCookies.forEach(key => { delete cookies[key]; }); for (let key in cookies) { cookieJar.setCookie(cookies[key], 'http://' + DOMAIN); } let url = basicUrl + node + '?' + querystringify({ _q: queryStr, _s: sign }); let options: IRequestOptions = { method, url: url, jar: cookieJar, headers: headers, gzip: true, resolveWithFullResponse: false, }; let result: any = await request(options); let json = JSON.parse(result.trim()); // Handle verify if (json['rgv587_flag'] == 'sm') { await this.handleVerify('https:' + json.url); return this.request_with_sign(method, node, apiParams, referer, basicUrl, excludedCookies); } // msg: "令牌过期" if (json.code == 'SG_TOKEN_EXPIRED') { this.reset(); return this.request_with_sign(method, node, apiParams, referer, basicUrl, excludedCookies); } // TODO: Handle each errors if (json.code != 'SUCCESS') { loggerWarning.warning('[XiamiApi.request] [Error]: (params, response):', options, json); } return json; } public async request_without_sign( method: string, node: string, params?: object, data?: any, referer?: string, basicUrl?: string, excludedCookies: Array<string> = [] ): Promise<any | null> { // init cookies await this.getCookies(); basicUrl = basicUrl || XiamiApi.BASICURL; let headers = !!referer ? { ...XiamiApi.HEADERS1, referer: referer } : { ...XiamiApi.HEADERS1 }; headers['authority'] = getHost(basicUrl); let xmUA: string = undefined; if (window && (window as any).uabModule) xmUA = (window as any).uabModule.getUA(); headers['xm-ua'] = xmUA; if (data) headers['content-type'] = 'application/json'; // Make cookie jar let cookieJar = makeCookieJar(); let cookies = { ...this.cookies }; excludedCookies.forEach(key => { delete cookies[key]; }); for (let key in cookies) { cookieJar.setCookie(cookies[key], 'http://' + DOMAIN); } let url = basicUrl + node + (params ? '?' + querystringify(params) : ''); let options: IRequestOptions = { method, url, jar: cookieJar, headers: headers, body: data, gzip: true, resolveWithFullResponse: false, }; let result: any = await request(options); let json = JSON.parse(result.trim()); // TODO: Handle each errors return json; } /** * @param songId is the original song id */ public async audios(songId: string): Promise<Array<IAudio>> { let json = await this.request_with_sign( XiamiApi.REQUEST_METHOD_MAP.audios, XiamiApi.NODE_MAP.audios, { songIds: [songId] }, `https://m.xiami.com/song/${songId}`, 'https://node.xiami.com/', ); let song = makeSong(json.result.data.songDetails[0]); return song.audios || []; } public async song(songId: string): Promise<ISong> { let json = await this.request_with_sign( XiamiApi.REQUEST_METHOD_MAP.song, XiamiApi.NODE_MAP.song, { songId }, `https://www.xiami.com/song/${songId}`, ); let song = makeSong(json.result.data); return song; } /** * Get an album * * @param albumId is the original id */ public async album(albumId: string): Promise<IAlbum> { let json = await this.request_with_sign( XiamiApi.REQUEST_METHOD_MAP.album, XiamiApi.NODE_MAP.album, { albumId }, `https://www.xiami.com/album/${albumId}`, ); let album = makeAlbum(json.result.data.albumDetail); return album; } /** * Get an collection * * @param collectionId is the original id */ public async collection(collectionId: string, page: number = 1, size: number = 100): Promise<ICollection> { let json = await this.request_with_sign( XiamiApi.REQUEST_METHOD_MAP.collection, XiamiApi.NODE_MAP.collection, { listId: collectionId }, `https://www.xiami.com/collect/${collectionId}`, ); let collection = makeCollection(json.result.data.collectDetail); let songs = await this.collectionSongs(collectionId, page, size); collection.songs = songs; return collection; } public async collectionSongs(collectionId: string, page: number = 1, size: number = 100): Promise<Array<ISong>> { let json = await this.request_with_sign( XiamiApi.REQUEST_METHOD_MAP.collectionSongs, XiamiApi.NODE_MAP.collectionSongs, { listId: collectionId, pagingVO: { page, pageSize: size, }, }, `https://www.xiami.com/collect/${collectionId}`, ); let songs = makeSongs(json.result.data.songs); return songs; } /** * Login is needed */ public async artist(artistId: string): Promise<IArtist> { let json = await this.request_with_sign( XiamiApi.REQUEST_METHOD_MAP.artist, XiamiApi.NODE_MAP.artist, { artistId }, `https://www.xiami.com/list/album?artistId=${artistId}`, ); let artist = makeArtist(json.result.data.artistDetail); return artist; } /** * Get albums amount of an artist, the artistId must be number string */ public async artistAlbums(artistId: string, page: number = 1, size: number = 10): Promise<Array<IAlbum>> { let json = await this.request_with_sign( XiamiApi.REQUEST_METHOD_MAP.artistAlbums, XiamiApi.NODE_MAP.artistAlbums, { artistId, pagingVO: { page: page, pageSize: size }, category: 0, }, `https://www.xiami.com/list/album?artistId=${artistId}`, ); let info = json.result.data.albums; let albums = makeAlbums(info); return albums; } /** * Get songs of an artist, the artistId must be number string */ public async artistSongs(artistId: string, page: number = 1, size: number = 10): Promise<Array<ISong>> { let json = await this.request_with_sign( XiamiApi.REQUEST_METHOD_MAP.artistSongs, XiamiApi.NODE_MAP.artistSongs, { artistId, pagingVO: { page: page, pageSize: size }, }, `https://www.xiami.com/list/song?id=${artistId}&type=all`, ); let info = json.result.data.songs; let songs = makeSongs(info); return songs; } public async searchSongs(keyword: string, page: number = 1, size: number = 10): Promise<Array<ISong>> { let json = await this.request_with_sign( XiamiApi.REQUEST_METHOD_MAP.searchSongs, XiamiApi.NODE_MAP.searchSongs, { key: keyword, pagingVO: { page: page, pageSize: size, } }, `https://www.xiami.com/`, ); let info = json.result.data.songs; let songs = makeSongs(info); return songs; } public async searchAlbums(keyword: string, page: number = 1, size: number = 10): Promise<Array<IAlbum>> { let json = await this.request_with_sign( XiamiApi.REQUEST_METHOD_MAP.searchAlbums, XiamiApi.NODE_MAP.searchAlbums, { key: keyword, pagingVO: { page: page, pageSize: size, } }, ); let info = json.result.data.albums; let albums = makeAlbums(info); return albums; } public async searchArtists(keyword: string, page: number = 1, size: number = 10): Promise<Array<IArtist>> { let json = await this.request_with_sign( XiamiApi.REQUEST_METHOD_MAP.searchArtists, XiamiApi.NODE_MAP.searchArtists, { key: keyword.replace(/\s+/g, '+'), pagingVO: { page: page, pageSize: size, } }, ); let info = json.result.data.artists; let artists = makeArtists(info); return artists; } public async searchCollections(keyword: string, page: number = 1, size: number = 10): Promise<Array<ICollection>> { let json = await this.request_with_sign( XiamiApi.REQUEST_METHOD_MAP.searchCollections, XiamiApi.NODE_MAP.searchCollections, { key: keyword.replace(/\s+/g, '+'), pagingVO: { page: page, pageSize: size, } }, ); let info = json.result.data.collects; let collections = makeCollections(info); return collections; } }
the_stack
import {net, hrTime, tls} from "./adapter.node"; import char, * as chars from "./chars"; import {resolveErrorCode} from "./errors/resolve"; import * as errors from "./errors"; import { ReadMessageBuffer, WriteMessageBuffer, ReadBuffer, WriteBuffer, } from "./buffer"; import {versionGreaterThan, versionGreaterThanOrEqual} from "./utils"; import {CodecsRegistry} from "./codecs/registry"; import {ICodec, uuid} from "./codecs/ifaces"; import {Set} from "./datatypes/set"; import LRU from "./lru"; import {EMPTY_TUPLE_CODEC, EmptyTupleCodec, TupleCodec} from "./codecs/tuple"; import {NamedTupleCodec} from "./codecs/namedtuple"; import {ObjectCodec} from "./codecs/object"; import {NULL_CODEC, NullCodec} from "./codecs/codecs"; import { ALLOW_MODIFICATIONS, INNER, OPTIONS, Executor, QueryArgs, Connection, BorrowReason, ParseOptions, PrepareMessageHeaders, ProtocolVersion, } from "./ifaces"; import * as scram from "./scram"; import {Options, RetryOptions, TransactionOptions} from "./options"; import {PartialRetryRule} from "./options"; import { parseConnectArguments, Address, ConnectConfig, NormalizedConnectConfig, } from "./con_utils"; import {Transaction, START_TRANSACTION_IMPL} from "./transaction"; const PROTO_VER: ProtocolVersion = [0, 12]; const PROTO_VER_MIN: ProtocolVersion = [0, 9]; enum AuthenticationStatuses { AUTH_OK = 0, AUTH_SASL = 10, AUTH_SASL_CONTINUE = 11, AUTH_SASL_FINAL = 12, } enum TransactionStatus { TRANS_IDLE = 0, // connection idle TRANS_ACTIVE = 1, // command in progress TRANS_INTRANS = 2, // idle, within transaction block TRANS_INERROR = 3, // idle, within failed transaction TRANS_UNKNOWN = 4, // cannot determine status } const ALLOW_CAPABILITIES = 0xff04; const EXECUTE_CAPABILITIES_BYTES = Buffer.from( // everything except TRANSACTION = 1 << 2 in network byte order [255, 255, 255, 255, 255, 255, 255, 251] ); const OLD_ERROR_CODES = new Map([ [0x05_03_00_01, 0x05_03_01_01], // TransactionSerializationError #2431 [0x05_03_00_02, 0x05_03_01_02], // TransactionDeadlockError #2431 ]); const DEFAULT_MAX_ITERATIONS = 3; function sleep(durationMillis: number): Promise<void> { return new Promise((accept, reject) => { setTimeout(() => accept(), durationMillis); }); } export function borrowError(reason: BorrowReason): errors.EdgeDBError { let text; switch (reason) { case BorrowReason.TRANSACTION: text = "Connection object is borrowed for the transaction. " + "Use the methods on transaction object instead."; break; case BorrowReason.QUERY: text = "Another operation is in progress. Use multiple separate " + "connections to run operations concurrently."; break; case BorrowReason.CLOSE: text = "Connection is being closed. Use multiple separate " + "connections to run operations concurrently."; break; } throw new errors.InterfaceError(text); } export class StandaloneConnection implements Connection { [ALLOW_MODIFICATIONS]: never; [INNER]: InnerConnection; [OPTIONS]: Options; /** @internal */ constructor(config: NormalizedConnectConfig, registry: CodecsRegistry) { this.initInner(config, registry); this[OPTIONS] = Options.defaults(); } protected initInner( config: NormalizedConnectConfig, registry: CodecsRegistry ): void { this[INNER] = new InnerConnection(config, registry); } protected shallowClone(): this { const result = Object.create(this.constructor.prototype); result[INNER] = this[INNER]; result[OPTIONS] = this[OPTIONS]; return result; } withTransactionOptions(opt: TransactionOptions): this { const result = this.shallowClone(); result[OPTIONS] = this[OPTIONS].withTransactionOptions(opt); return result; } withRetryOptions(opt: RetryOptions): this { const result = this.shallowClone(); result[OPTIONS] = this[OPTIONS].withRetryOptions(opt); return result; } async rawTransaction<T>( action: (transaction: Transaction) => Promise<T> ): Promise<T> { let result: T; const transaction = new Transaction(this); await transaction.start(); try { result = await action(transaction); await transaction.commit(); } catch (err) { await transaction.rollback(); throw err; } return result; } async retryingTransaction<T>( action: (transaction: Transaction) => Promise<T> ): Promise<T> { let result: T; for (let iteration = 0; iteration < DEFAULT_MAX_ITERATIONS; ++iteration) { const transaction = new Transaction(this); await transaction[START_TRANSACTION_IMPL](iteration !== 0); try { result = await action(transaction); } catch (err) { try { await transaction.rollback(); } catch (rollback_err) { if (!(rollback_err instanceof errors.EdgeDBError)) { // We ignore EdgeDBError errors on rollback, retrying // if possible. All other errors are propagated. throw rollback_err; } } if ( err instanceof errors.EdgeDBError && err.hasTag(errors.SHOULD_RETRY) ) { const rule = this[OPTIONS].retryOptions.getRuleForException(err); if (iteration + 1 >= rule.attempts) { throw err; } await sleep(rule.backoff(iteration + 1)); continue; } throw err; } // TODO(tailhook) sort out errors on commit, early network errors // and some other errors could be retried // NOTE: we can't retry on all the same errors as we don't know if // commit is succeeded before the database have received it or after // it have been done but network is dropped before we were able // to receive a response await transaction.commit(); return result; } throw Error("unreachable"); } async close(): Promise<void> { const borrowed_for = this[INNER].borrowedFor; if (borrowed_for) { throw borrowError(borrowed_for); } this[INNER].borrowedFor = BorrowReason.CLOSE; try { try { const conn = this[INNER].connection; if (conn) { await conn.close(); } this[INNER].connection = undefined; this[INNER]._isClosed = true; } finally { this.cleanup(); } } finally { this[INNER].borrowedFor = undefined; } } protected cleanup(): void { // empty } isClosed(): boolean { return this[INNER]._isClosed; } async execute(query: string): Promise<void> { const inner = this[INNER]; const borrowed_for = inner.borrowedFor; if (borrowed_for) { throw borrowError(borrowed_for); } inner.borrowedFor = BorrowReason.QUERY; let connection = inner.connection; if (!connection || connection.isClosed()) { connection = await inner.reconnect(); } try { return await connection.execute(query); } finally { inner.borrowedFor = undefined; } } async query<T = unknown>(query: string, args?: QueryArgs): Promise<T[]> { const inner = this[INNER]; const borrowed_for = inner.borrowedFor; if (borrowed_for) { throw borrowError(borrowed_for); } inner.borrowedFor = BorrowReason.QUERY; let connection = inner.connection; if (!connection || connection.isClosed()) { connection = await inner.reconnect(); } try { return await connection.fetch(query, args, false, false); } finally { inner.borrowedFor = undefined; } } async queryJSON(query: string, args?: QueryArgs): Promise<string> { const inner = this[INNER]; const borrowed_for = inner.borrowedFor; if (borrowed_for) { throw borrowError(borrowed_for); } inner.borrowedFor = BorrowReason.QUERY; let connection = inner.connection; if (!connection || connection.isClosed()) { connection = await inner.reconnect(); } try { return await connection.fetch(query, args, true, false); } finally { inner.borrowedFor = undefined; } } async querySingle<T = unknown>(query: string, args?: QueryArgs): Promise<T> { const inner = this[INNER]; const borrowed_for = inner.borrowedFor; if (borrowed_for) { throw borrowError(borrowed_for); } inner.borrowedFor = BorrowReason.QUERY; let connection = inner.connection; if (!connection || connection.isClosed()) { connection = await inner.reconnect(); } try { return await connection.fetch(query, args, false, true); } finally { inner.borrowedFor = undefined; } } async querySingleJSON(query: string, args?: QueryArgs): Promise<string> { const inner = this[INNER]; const borrowed_for = inner.borrowedFor; if (borrowed_for) { throw borrowError(borrowed_for); } inner.borrowedFor = BorrowReason.QUERY; let connection = inner.connection; if (!connection || connection.isClosed()) { connection = await inner.reconnect(); } try { return await connection.fetch(query, args, true, true); } finally { inner.borrowedFor = undefined; } } /** @internal */ static async connect<S extends StandaloneConnection>( this: new (config: NormalizedConnectConfig, registry: CodecsRegistry) => S, config: NormalizedConnectConfig, registry: CodecsRegistry ): Promise<S> { const conn = new this(config, registry); await conn[INNER].reconnect(); return conn; } } export class InnerConnection { borrowedFor?: BorrowReason; config: NormalizedConnectConfig; connection?: ConnectionImpl; registry: CodecsRegistry; _isClosed: boolean; // For compatibility constructor(config: NormalizedConnectConfig, registry: CodecsRegistry) { this.config = config; this.registry = registry; this._isClosed = false; } async getImpl(singleAttempt: boolean = false): Promise<ConnectionImpl> { let connection = this.connection; if (!connection || connection.isClosed()) { connection = await this.reconnect(singleAttempt); } return connection; } isClosed(): boolean { return this._isClosed; } logConnectionError(...args: any): void { if (!this.config.logging) { return; } if ( this.config.inProject && !this.config.fromProject && !this.config.fromEnv ) { args.push( `\n\n\n` + `Hint: it looks like the program is running from a ` + `directory initialized with "edgedb project init". ` + `Consider calling "edgedb.connect()" without arguments.` + `\n` ); } // tslint:disable-next-line: no-console console.warn(...args); } async reconnect(singleAttempt: boolean = false): Promise<ConnectionImpl> { if (this._isClosed) { throw new errors.InterfaceError("Connection is closed"); } let maxTime: number; if (singleAttempt || this.config.waitUntilAvailable === 0) { maxTime = 0; } else { maxTime = hrTime() + (this.config.waitUntilAvailable || 0); } let iteration = 1; let lastLoggingAt = 0; while (true) { for (const addr of this.config.addrs) { try { this.connection = await ConnectionImpl.connectWithTimeout( addr, this.config, this.registry ); return this.connection; } catch (e) { if (e instanceof errors.ClientConnectionError) { if (e.hasTag(errors.SHOULD_RECONNECT)) { const now = hrTime(); if (iteration > 1 && now > maxTime) { // We check here for `iteration > 1` to make sure that all of // `this.configs.addrs` were attempted to be connected. throw e; } if ( iteration > 1 && (!lastLoggingAt || now - lastLoggingAt > 5_000) ) { // We check here for `iteration > 1` to only log // when all addrs of `this.configs.addrs` were attempted to // be connected and we're starting to wait for the DB to // become available. lastLoggingAt = now; this.logConnectionError( `A client connection error occurred; reconnecting because ` + `of "waitUntilAvailable=${this.config.waitUntilAvailable}".`, e ); } continue; } else { throw e; } } else { // tslint:disable-next-line: no-console console.error("Unexpected connection error:", e); throw e; // this shouldn't happen } } } iteration += 1; await sleep(Math.trunc(10 + Math.random() * 200)); } } } export class ConnectionImpl { private sock: net.Socket; private config: NormalizedConnectConfig; private paused: boolean; private connected: boolean = false; private lastStatus: string | null; private codecsRegistry: CodecsRegistry; private queryCodecCache: LRU<string, [number, ICodec, ICodec]>; private serverSecret: Buffer | null; private serverSettings: Map<string, string>; private serverXactStatus: TransactionStatus; private buffer: ReadMessageBuffer; private messageWaiterResolve: ((value: any) => void) | null; private messageWaiterReject: ((error: Error) => void) | null; private connWaiter: Promise<void>; private connWaiterResolve: ((value: any) => void) | null; private connWaiterReject: ((value: any) => void) | null; private opInProgress: boolean = false; protected protocolVersion: ProtocolVersion = PROTO_VER; /** @internal */ protected constructor( sock: net.Socket, config: NormalizedConnectConfig, registry: CodecsRegistry ) { this.buffer = new ReadMessageBuffer(); this.codecsRegistry = registry; this.queryCodecCache = new LRU({capacity: 1000}); this.lastStatus = null; this.serverSecret = null; this.serverSettings = new Map<string, string>(); this.serverXactStatus = TransactionStatus.TRANS_UNKNOWN; this.messageWaiterResolve = null; this.messageWaiterReject = null; this.connWaiterResolve = null; this.connWaiterReject = null; this.connWaiter = new Promise<void>((resolve, reject) => { this.connWaiterResolve = resolve; this.connWaiterReject = reject; }); this.paused = false; this.sock = sock; this.sock.setNoDelay(); this.sock.on("error", this._onError.bind(this)); this.sock.on("data", this._onData.bind(this)); if (this.sock instanceof tls.TLSSocket) { // This is bizarre, but "connect" can be fired before // "secureConnect" for some reason. The documentation // doesn't provide a clue why. We need to be able to validate // that the 'edgedb-binary' ALPN protocol was selected // in connect when we're connecting over TLS. // @ts-ignore this.sock.on("secureConnect", this._onConnect.bind(this)); } else { this.sock.on("connect", this._onConnect.bind(this)); } this.sock.on("close", this._onClose.bind(this)); this.config = config; } private async _waitForMessage(): Promise<void> { if (this.buffer.takeMessage()) { return; } if (this.paused) { this.paused = false; this.sock.resume(); } await new Promise<void>((resolve, reject) => { this.messageWaiterResolve = resolve; this.messageWaiterReject = reject; }); } private _onConnect(): void { if (this.connWaiterResolve) { this.connWaiterResolve(true); this.connWaiterReject = null; this.connWaiterResolve = null; } } private _abortWaiters(err: Error): void { if (this.connWaiterReject) { this.connWaiterReject(err); this.connWaiterReject = null; this.connWaiterResolve = null; } if (this.messageWaiterReject) { this.messageWaiterReject(err); this.messageWaiterResolve = null; this.messageWaiterReject = null; } } private _onClose(): void { if (this.connWaiterReject || this.messageWaiterReject) { /* This can happen, particularly, during the connect phase. If the connection is aborted with a client-side timeout, there can be a situation where the connection has actually been established, and so `conn.sock.destroy` would simply close the socket, without invoking the 'error' event. */ this._abortWaiters(new errors.ClientConnectionClosedError()); } this.close(); } private _onError(err: Error): void { this._abortWaiters(err); } private _onData(data: Buffer): void { let pause = false; try { pause = this.buffer.feed(data); } catch (e: any) { if (this.messageWaiterReject) { this.messageWaiterReject(e); } else { throw e; } } if (pause) { this.paused = true; this.sock.pause(); } if (this.messageWaiterResolve) { if (this.buffer.takeMessage()) { this.messageWaiterResolve(true); this.messageWaiterResolve = null; this.messageWaiterReject = null; } } } private _ignoreHeaders(): void { let numFields = this.buffer.readInt16(); while (numFields) { this.buffer.readInt16(); this.buffer.readLenPrefixedBuffer(); numFields--; } } private _parseHeaders(): Map<number, Buffer> { const ret = new Map<number, Buffer>(); let numFields = this.buffer.readInt16(); while (numFields) { const key = this.buffer.readInt16(); const value = this.buffer.readLenPrefixedBuffer(); ret.set(key, value); numFields--; } return ret; } private _parseDescribeTypeMessage(): [ number, ICodec, ICodec, Buffer, Buffer ] { this._ignoreHeaders(); const cardinality: char = this.buffer.readChar(); const inTypeId = this.buffer.readUUID(); const inTypeData = this.buffer.readLenPrefixedBuffer(); const outTypeId = this.buffer.readUUID(); const outTypeData = this.buffer.readLenPrefixedBuffer(); this.buffer.finishMessage(); let inCodec = this.codecsRegistry.getCodec(inTypeId); if (inCodec == null) { inCodec = this.codecsRegistry.buildCodec( inTypeData, this.protocolVersion ); } let outCodec = this.codecsRegistry.getCodec(outTypeId); if (outCodec == null) { outCodec = this.codecsRegistry.buildCodec( outTypeData, this.protocolVersion ); } return [cardinality, inCodec, outCodec, inTypeData, outTypeData]; } private _parseCommandCompleteMessage(): string { this._ignoreHeaders(); const status = this.buffer.readString(); this.buffer.finishMessage(); return status; } private _parseErrorMessage(): Error { const severity = this.buffer.readChar(); const code = this.buffer.readUInt32(); const message = this.buffer.readString(); const attrs = this._parseHeaders(); const errorType = resolveErrorCode(OLD_ERROR_CODES.get(code) ?? code); this.buffer.finishMessage(); const err = new errorType(message); return err; } private _parseSyncMessage(): void { this._parseHeaders(); // TODO: Reject Headers const status = this.buffer.readChar(); switch (status) { case chars.$I: this.serverXactStatus = TransactionStatus.TRANS_IDLE; break; case chars.$T: this.serverXactStatus = TransactionStatus.TRANS_INTRANS; break; case chars.$E: this.serverXactStatus = TransactionStatus.TRANS_INERROR; break; default: this.serverXactStatus = TransactionStatus.TRANS_UNKNOWN; } this.buffer.finishMessage(); } private _parseDataMessages(codec: ICodec, result: Set | WriteBuffer): void { const frb = ReadBuffer.alloc(); const $D = chars.$D; const buffer = this.buffer; if (Array.isArray(result)) { while (buffer.takeMessageType($D)) { buffer.consumeMessageInto(frb); frb.discard(6); result.push(codec.decode(frb)); frb.finish(); } } else { while (buffer.takeMessageType($D)) { const msg = buffer.consumeMessage(); result.writeChar($D); result.writeInt32(msg.length + 4); result.writeBuffer(msg); } } } private _fallthrough(): void { const mtype = this.buffer.getMessageType(); switch (mtype) { case chars.$S: { const name = this.buffer.readString(); const value = this.buffer.readString(); this.serverSettings.set(name, value); this.buffer.finishMessage(); break; } case chars.$L: { const severity = this.buffer.readChar(); const code = this.buffer.readUInt32(); const message = this.buffer.readString(); this._parseHeaders(); this.buffer.finishMessage(); /* tslint:disable */ console.info("SERVER MESSAGE", severity, code, message); /* tslint:enable */ break; } default: // TODO: terminate connection throw new Error( `unexpected message type ${mtype} ("${chars.chr(mtype)}")` ); } } /** @internal */ static async connectWithTimeout( addr: Address, config: NormalizedConnectConfig, registry: CodecsRegistry ): Promise<ConnectionImpl> { const sock = this.newSock(addr, config.tlsOptions); const conn = new this(sock, {...config, addrs: [addr]}, registry); const connPromise = conn.connect(); let timeoutCb = null; let timeoutHappened = false; // set-up a timeout if (config.connectTimeout) { timeoutCb = setTimeout(() => { if (!conn.connected) { timeoutHappened = true; conn.sock.destroy( new errors.ClientConnectionTimeoutError( `connection timed out (${config.connectTimeout}ms)` ) ); } }, config.connectTimeout); } try { await connPromise; } catch (e: any) { conn._abort(); if (timeoutHappened && e instanceof errors.ClientConnectionClosedError) { /* A race between our timeout `timeoutCb` callback and the client being actually connected. See the `ConnectionImpl._onClose` method. */ throw new errors.ClientConnectionTimeoutError( `connection timed out (${config.connectTimeout}ms)` ); } if (e instanceof errors.EdgeDBError) { throw e; } else { let err: errors.ClientConnectionError; switch (e.code) { case "EPROTO": if (config.tlsOptions != null) { // connecting over tls failed // try to connect using clear text try { return this.connectWithTimeout( addr, { ...config, tlsOptions: undefined, }, registry ); } catch { // pass } } err = new errors.ClientConnectionFailedError(e.message); break; case "ECONNREFUSED": case "ECONNABORTED": case "ECONNRESET": case "ENOTFOUND": // DNS name not found case "ENOENT": // unix socket is not created yet err = new errors.ClientConnectionFailedTemporarilyError(e.message); break; default: err = new errors.ClientConnectionFailedError(e.message); break; } err.source = e; throw err; } } finally { if (timeoutCb != null) { clearTimeout(timeoutCb); } } return conn; } private async connect(): Promise<void> { await this.connWaiter; if (this.sock instanceof tls.TLSSocket) { if (this.sock.alpnProtocol !== "edgedb-binary") { throw new errors.ClientConnectionFailedError( "The server doesn't support the edgedb-binary protocol." ); } } const handshake = new WriteMessageBuffer(); handshake .beginMessage(chars.$V) .writeInt16(this.protocolVersion[0]) .writeInt16(this.protocolVersion[1]); handshake.writeInt16(2); handshake.writeString("user"); handshake.writeString(this.config.user); handshake.writeString("database"); handshake.writeString(this.config.database); // No extensions requested handshake.writeInt16(0); handshake.endMessage(); this.sock.write(handshake.unwrap()); while (true) { if (!this.buffer.takeMessage()) { await this._waitForMessage(); } const mtype = this.buffer.getMessageType(); switch (mtype) { case chars.$v: { const hi = this.buffer.readInt16(); const lo = this.buffer.readInt16(); this._parseHeaders(); this.buffer.finishMessage(); const proposed: ProtocolVersion = [hi, lo]; if ( versionGreaterThan(proposed, PROTO_VER) || versionGreaterThan(PROTO_VER_MIN, proposed) ) { throw new Error( `the server requested an unsupported version of ` + `the protocol ${hi}.${lo}` ); } this.protocolVersion = [hi, lo]; break; } case chars.$R: { const status = this.buffer.readInt32(); if (status === AuthenticationStatuses.AUTH_OK) { this.buffer.finishMessage(); } else if (status === AuthenticationStatuses.AUTH_SASL) { await this._authSasl(); } else { throw new Error( `unsupported authentication method requested by the ` + `server: ${status}` ); } break; } case chars.$K: { this.serverSecret = this.buffer.readBuffer(32); this.buffer.finishMessage(); break; } case chars.$E: { throw this._parseErrorMessage(); } case chars.$Z: { this._parseSyncMessage(); if ( !(this.sock instanceof tls.TLSSocket) && // @ts-ignore typeof Deno === "undefined" && versionGreaterThanOrEqual(this.protocolVersion, [0, 11]) ) { const [major, minor] = this.protocolVersion; throw new Error( `the protocol version requires TLS: ${major}.${minor}` ); } this.connected = true; return; } default: this._fallthrough(); } } } private async _authSasl(): Promise<void> { const numMethods = this.buffer.readInt32(); if (numMethods <= 0) { throw new Error( "the server requested SASL authentication but did not offer any methods" ); } const methods = []; let foundScram256 = false; for (let _ = 0; _ < numMethods; _++) { const method = this.buffer.readLenPrefixedBuffer().toString("utf8"); if (method === "SCRAM-SHA-256") { foundScram256 = true; } methods.push(method); } this.buffer.finishMessage(); if (!foundScram256) { throw new Error( `the server offered the following SASL authentication ` + `methods: ${methods.join(", ")}, neither are supported.` ); } const clientNonce = await scram.generateNonce(); const [clientFirst, clientFirstBare] = scram.buildClientFirstMessage( clientNonce, this.config.user ); const wb = new WriteMessageBuffer(); wb.beginMessage(chars.$p) .writeString("SCRAM-SHA-256") .writeString(clientFirst) .endMessage(); this.sock.write(wb.unwrap()); await this._ensureMessage(chars.$R, "SASLContinue"); let status = this.buffer.readInt32(); if (status !== AuthenticationStatuses.AUTH_SASL_CONTINUE) { throw new Error( `expected SASLContinue from the server, received ${status}` ); } const serverFirst = this.buffer.readString(); this.buffer.finishMessage(); const [serverNonce, salt, itercount] = scram.parseServerFirstMessage(serverFirst); const [clientFinal, expectedServerSig] = scram.buildClientFinalMessage( this.config.password || "", salt, itercount, clientFirstBare, serverFirst, serverNonce ); wb.reset().beginMessage(chars.$r).writeString(clientFinal).endMessage(); this.sock.write(wb.unwrap()); await this._ensureMessage(chars.$R, "SASLFinal"); status = this.buffer.readInt32(); if (status !== AuthenticationStatuses.AUTH_SASL_FINAL) { throw new Error( `expected SASLFinal from the server, received ${status}` ); } const serverFinal = this.buffer.readString(); this.buffer.finishMessage(); const serverSig = scram.parseServerFinalMessage(serverFinal); if (!serverSig.equals(expectedServerSig)) { throw new Error("server SCRAM proof does not match"); } } private async _ensureMessage( expectedMtype: char, err: string ): Promise<void> { if (!this.buffer.takeMessage()) { await this._waitForMessage(); } const mtype = this.buffer.getMessageType(); switch (mtype) { case chars.$E: { throw this._parseErrorMessage(); } case expectedMtype: { return; } default: { throw new Error( `expected ${err} from the server, received ${chars.chr(mtype)}` ); } } } protected async _parse( query: string, asJson: boolean, expectOne: boolean, alwaysDescribe: boolean, options?: ParseOptions ): Promise<[number, ICodec, ICodec, Buffer | null, Buffer | null]> { const wb = new WriteMessageBuffer(); wb.beginMessage(chars.$P) .writeHeaders(options?.headers ?? null) .writeChar(asJson ? chars.$j : chars.$b) .writeChar(expectOne ? chars.$o : chars.$m) .writeString("") // statement name .writeString(query) .endMessage(); wb.writeSync(); this.sock.write(wb.unwrap()); let cardinality: number | void; let inTypeId: uuid | void; let outTypeId: uuid | void; let inCodec: ICodec | null; let outCodec: ICodec | null; let parsing = true; let error: Error | null = null; let inCodecData: Buffer | null = null; let outCodecData: Buffer | null = null; while (parsing) { if (!this.buffer.takeMessage()) { await this._waitForMessage(); } const mtype = this.buffer.getMessageType(); switch (mtype) { case chars.$1: { this._ignoreHeaders(); cardinality = this.buffer.readChar(); inTypeId = this.buffer.readUUID(); outTypeId = this.buffer.readUUID(); this.buffer.finishMessage(); break; } case chars.$E: { error = this._parseErrorMessage(); break; } case chars.$Z: { this._parseSyncMessage(); parsing = false; break; } default: this._fallthrough(); } } if (error != null) { throw error; } if (inTypeId == null || outTypeId == null) { throw new Error("did not receive in/out type ids in Parse response"); } inCodec = this.codecsRegistry.getCodec(inTypeId); outCodec = this.codecsRegistry.getCodec(outTypeId); if (inCodec == null || outCodec == null || alwaysDescribe) { wb.reset(); wb.beginMessage(chars.$D) .writeInt16(0) // no headers .writeChar(chars.$T) .writeString("") // statement name .endMessage() .writeSync(); this.sock.write(wb.unwrap()); parsing = true; while (parsing) { if (!this.buffer.takeMessage()) { await this._waitForMessage(); } const mtype = this.buffer.getMessageType(); switch (mtype) { case chars.$T: { try { [cardinality, inCodec, outCodec, inCodecData, outCodecData] = this._parseDescribeTypeMessage(); } catch (e: any) { error = e; } break; } case chars.$E: { error = this._parseErrorMessage(); break; } case chars.$Z: { this._parseSyncMessage(); parsing = false; break; } default: this._fallthrough(); } } if (error != null) { throw error; } } if (cardinality == null || outCodec == null || inCodec == null) { throw new Error( "failed to receive type information in response to a Parse message" ); } return [cardinality, inCodec, outCodec, inCodecData, outCodecData]; } private _encodeArgs(args: QueryArgs, inCodec: ICodec): Buffer { if (versionGreaterThanOrEqual(this.protocolVersion, [0, 12])) { if (inCodec === NULL_CODEC && !args) { return NullCodec.BUFFER; } if (inCodec instanceof ObjectCodec) { return inCodec.encodeArgs(args); } // Shouldn't ever happen. throw new Error("invalid input codec"); } else { if (inCodec === EMPTY_TUPLE_CODEC && !args) { return EmptyTupleCodec.BUFFER; } if ( inCodec instanceof NamedTupleCodec || inCodec instanceof TupleCodec ) { return inCodec.encodeArgs(args); } // Shouldn't ever happen. throw new Error("invalid input codec"); } } protected async _executeFlow( args: QueryArgs | Buffer, inCodec: ICodec, outCodec: ICodec, result: Set | WriteBuffer ): Promise<void> { const wb = new WriteMessageBuffer(); wb.beginMessage(chars.$E) .writeInt16(0) // no headers .writeString("") // statement name .writeBuffer( args instanceof Buffer ? args : this._encodeArgs(args, inCodec) ) .endMessage() .writeSync(); this.sock.write(wb.unwrap()); let parsing = true; let error: Error | null = null; while (parsing) { if (!this.buffer.takeMessage()) { await this._waitForMessage(); } const mtype = this.buffer.getMessageType(); switch (mtype) { case chars.$D: { if (error == null) { try { this._parseDataMessages(outCodec, result); } catch (e: any) { error = e; this.buffer.finishMessage(); } } else { this.buffer.discardMessage(); } break; } case chars.$C: { this.lastStatus = this._parseCommandCompleteMessage(); break; } case chars.$E: { error = this._parseErrorMessage(); break; } case chars.$Z: { this._parseSyncMessage(); parsing = false; break; } default: this._fallthrough(); } } if (error != null) { throw error; } } private async _optimisticExecuteFlow( args: QueryArgs, asJson: boolean, expectOne: boolean, inCodec: ICodec, outCodec: ICodec, query: string, result: Set ): Promise<void> { const wb = new WriteMessageBuffer(); wb.beginMessage(chars.$O); wb.writeInt16(0); // no headers wb.writeChar(asJson ? chars.$j : chars.$b); wb.writeChar(expectOne ? chars.$o : chars.$m); wb.writeString(query); wb.writeBuffer(inCodec.tidBuffer); wb.writeBuffer(outCodec.tidBuffer); wb.writeBuffer(this._encodeArgs(args, inCodec)); wb.endMessage(); wb.writeSync(); this.sock.write(wb.unwrap()); let reExec = false; let error: Error | null = null; let parsing = true; let newCard: char | null = null; while (parsing) { if (!this.buffer.takeMessage()) { await this._waitForMessage(); } const mtype = this.buffer.getMessageType(); switch (mtype) { case chars.$D: { if (error == null) { try { this._parseDataMessages(outCodec, result); } catch (e: any) { error = e; this.buffer.finishMessage(); } } else { this.buffer.discardMessage(); } break; } case chars.$C: { this.lastStatus = this._parseCommandCompleteMessage(); break; } case chars.$Z: { this._parseSyncMessage(); parsing = false; break; } case chars.$T: { try { [newCard, inCodec, outCodec] = this._parseDescribeTypeMessage(); const key = this._getQueryCacheKey(query, asJson, expectOne); this.queryCodecCache.set(key, [newCard, inCodec, outCodec]); reExec = true; } catch (e: any) { error = e; } break; } case chars.$E: { error = this._parseErrorMessage(); break; } default: this._fallthrough(); } } if (error != null) { throw error; } if (reExec) { this._validateFetchCardinality(newCard!, asJson, expectOne); return await this._executeFlow(args, inCodec, outCodec, result); } } private _getQueryCacheKey( query: string, asJson: boolean, expectOne: boolean ): string { return [asJson, expectOne, query.length, query].join(";"); } private _validateFetchCardinality( card: char, asJson: boolean, expectOne: boolean ): void { if (expectOne && card === chars.$n) { const methname = asJson ? "querySingleJSON" : "querySingle"; throw new Error(`query executed via ${methname}() returned no data`); } } async fetch( query: string, args: QueryArgs = null, asJson: boolean, expectOne: boolean ): Promise<any> { const key = this._getQueryCacheKey(query, asJson, expectOne); const ret = new Set(); if (this.queryCodecCache.has(key)) { const [card, inCodec, outCodec] = this.queryCodecCache.get(key)!; this._validateFetchCardinality(card, asJson, expectOne); await this._optimisticExecuteFlow( args, asJson, expectOne, inCodec, outCodec, query, ret ); } else { const [card, inCodec, outCodec] = await this._parse( query, asJson, expectOne, false ); this._validateFetchCardinality(card, asJson, expectOne); this.queryCodecCache.set(key, [card, inCodec, outCodec]); await this._executeFlow(args, inCodec, outCodec, ret); } if (expectOne) { if (ret && ret.length) { return ret[0]; } else { throw new Error("query returned no data"); } } else { if (ret && ret.length) { if (asJson) { return ret[0]; } else { return ret; } } else { if (asJson) { return "[]"; } else { return ret; } } } } async execute(query: string): Promise<void> { const wb = new WriteMessageBuffer(); wb.beginMessage(chars.$Q) .writeInt16(1) // headers .writeUInt16(ALLOW_CAPABILITIES) .writeBytes(EXECUTE_CAPABILITIES_BYTES) .writeString(query) // statement name .endMessage(); this.sock.write(wb.unwrap()); let error: Error | null = null; let parsing = true; while (parsing) { if (!this.buffer.takeMessage()) { await this._waitForMessage(); } const mtype = this.buffer.getMessageType(); switch (mtype) { case chars.$C: { this.lastStatus = this._parseCommandCompleteMessage(); break; } case chars.$Z: { this._parseSyncMessage(); parsing = false; break; } case chars.$E: { error = this._parseErrorMessage(); break; } default: this._fallthrough(); } } if (error != null) { throw error; } } private _abort(): void { if (this.sock && this.connected) { this.sock.destroy(); } this.connected = false; } isClosed(): boolean { return !this.connected; } async close(): Promise<void> { if (this.sock && this.connected) { this.sock.write( new WriteMessageBuffer().beginMessage(chars.$X).endMessage().unwrap() ); } this._abort(); } /** @internal */ private static newSock( addr: string | [string, number], options?: tls.ConnectionOptions ): net.Socket { if (typeof addr === "string") { // unix socket return net.createConnection(addr); } const [host, port] = addr; if (options == null) { return net.createConnection(port, host); } const opts = {...options, host, port}; return tls.connect(opts); } } export class RawConnection extends ConnectionImpl { // Note that this class, while exported, is not documented. // Its API is subject to change. static async connectWithTimeout( addr: Address, config: NormalizedConnectConfig ): Promise<RawConnection> { const registry = new CodecsRegistry(); return ConnectionImpl.connectWithTimeout.call( RawConnection, addr, config, registry ) as unknown as RawConnection; } public async rawParse( query: string, headers?: PrepareMessageHeaders ): Promise<[Buffer, Buffer, ProtocolVersion]> { const result = await this._parse(query, false, false, true, {headers}); return [result[3]!, result[4]!, this.protocolVersion]; } public async rawExecute(encodedArgs: Buffer | null = null): Promise<Buffer> { const result = new WriteBuffer(); let inCodec = EMPTY_TUPLE_CODEC; if (versionGreaterThanOrEqual(this.protocolVersion, [0, 12])) { inCodec = NULL_CODEC; } await this._executeFlow( encodedArgs, // arguments inCodec, // inCodec -- to encode lack of arguments. EMPTY_TUPLE_CODEC, // outCodec -- does not matter, it will not be used. result ); return result.unwrap(); } // Mask the actual connection API; only the raw* methods should // be used with this class. async execute(query: string): Promise<void> { throw new Error("not implemented"); } async query<T = unknown>( query: string, args: QueryArgs = null ): Promise<T[]> { throw new Error("not implemented"); } async querySingle<T = unknown>( query: string, args: QueryArgs = null ): Promise<T> { throw new Error("not implemented"); } async queryJSON(query: string, args: QueryArgs = null): Promise<string> { throw new Error("not implemented"); } async querySingleJSON( query: string, args: QueryArgs = null ): Promise<string> { throw new Error("not implemented"); } }
the_stack
import { AuthInfo, Connection } from '@salesforce/core'; import { MockTestOrgData, testSetup } from '@salesforce/core/lib/testSetup'; import { expect } from 'chai'; import * as fs from 'fs'; import * as path from 'path'; import { createSandbox, SinonStub, stub } from 'sinon'; import { isNullOrUndefined } from 'util'; import { workspaceContext } from '../../../src/context'; import { ComponentUtils } from '../../../src/orgBrowser'; import { getRootWorkspacePath, OrgAuthInfo } from '../../../src/util'; const sb = createSandbox(); const $$ = testSetup(); const mockFieldData = { result: { fields: [ { type: 'string', relationshipName: undefined, name: 'Name__c', length: 50 }, { type: 'email', relationshipName: undefined, name: 'Email__c', length: 100 }, { type: 'textarea', relationshipName: undefined, name: 'Notes__c', length: 500 }, { type: 'number', relationshipName: undefined, name: 'Age__c', length: undefined } ] } }; const expectedfetchAndSaveSObjectFieldsPropertiesResult = { status: 0, result: [mockFieldData.result.fields] }; const sObjectDescribeResult = { fields: [mockFieldData.result.fields] }; const expectedFieldList = [ 'Name__c (string(50))', 'Email__c (email(100))', 'Notes__c (textarea(500))', 'Age__c (number)' ]; // tslint:disable:no-unused-expression describe('get metadata components path', () => { let getUsernameStub: SinonStub; const rootWorkspacePath = getRootWorkspacePath(); const cmpUtil = new ComponentUtils(); const alias = 'test user 1'; const username = 'test-username1@example.com'; beforeEach(() => { getUsernameStub = stub(OrgAuthInfo, 'getUsername').returns( 'test-username1@example.com' ); }); afterEach(() => { getUsernameStub.restore(); }); function expectedPath(fileName: string) { return path.join( rootWorkspacePath, '.sfdx', 'orgs', username, 'metadata', fileName + '.json' ); } it('should return the path for a given username and metadata type', async () => { const metadataType = 'ApexClass'; expect(await cmpUtil.getComponentsPath(metadataType, alias)).to.equal( expectedPath(metadataType) ); }); it('should return the path for a given folder', async () => { const metadataType = 'Report'; const folder = 'TestFolder'; expect( await cmpUtil.getComponentsPath(metadataType, alias, folder) ).to.equal(expectedPath(metadataType + '_' + folder)); }); }); describe('build metadata components list', () => { let readFileStub: SinonStub; const cmpUtil = new ComponentUtils(); beforeEach(() => { readFileStub = stub(fs, 'readFileSync'); }); afterEach(() => { readFileStub.restore(); }); it('should return a sorted list of fullNames when given a list of metadata components', async () => { const metadataType = 'ApexClass'; const fileData = JSON.stringify({ status: 0, result: [ { fullName: 'fakeName2', type: 'ApexClass', manageableState: 'unmanaged' }, { fullName: 'fakeName1', type: 'ApexClass', manageableState: 'unmanaged' } ] }); const fullNames = cmpUtil.buildComponentsList( metadataType, fileData, undefined ); if (!isNullOrUndefined(fullNames)) { expect(fullNames[0]).to.equal('fakeName1'); expect(fullNames[1]).to.equal('fakeName2'); expect(readFileStub.called).to.equal(false); } }); it('should return a sorted list of fullNames when given the metadata components result file path', async () => { const filePath = '/test/metadata/ApexClass.json'; const metadataType = 'ApexClass'; const fileData = JSON.stringify({ status: 0, result: [ { fullName: 'fakeName2', type: 'ApexClass', manageableState: 'unmanaged' }, { fullName: 'fakeName1', type: 'ApexClass', manageableState: 'unmanaged' } ] }); readFileStub.returns(fileData); const fullNames = cmpUtil.buildComponentsList( metadataType, undefined, filePath ); if (!isNullOrUndefined(fullNames)) { expect(fullNames[0]).to.equal('fakeName1'); expect(fullNames[1]).to.equal('fakeName2'); expect(readFileStub.called).to.equal(true); } }); it('should not return components if they are uneditable', async () => { const type = 'ApexClass'; const states = ['installed', 'released', 'deleted', 'deprecated', 'beta']; const fileData = { status: 0, result: states.map((s, i) => ({ fullName: `fakeName${i}`, type, manageableState: s })) }; const fullNames = cmpUtil.buildComponentsList( type, JSON.stringify(fileData), undefined ); expect(fullNames.length).to.equal(0); }); it('should return components that are editable', () => { const type = 'CustomObject'; const validStates = [ 'unmanaged', 'deprecatedEditable', 'installedEditable', undefined // unpackaged component ]; const fileData = { status: 0, result: validStates.map((s, i) => ({ fullName: `fakeName${i}`, type, manageableState: s })) }; const fullNames = cmpUtil.buildComponentsList( type, JSON.stringify(fileData), undefined ); expect(fullNames).to.deep.equal([ 'fakeName0', 'fakeName1', 'fakeName2', 'fakeName3' ]); }); }); describe('load metadata components and custom objects fields list', () => { let mockConnection: Connection; let connectionStub: SinonStub; let getComponentsPathStub: SinonStub; let getUsernameStub: SinonStub; let fileExistsStub: SinonStub; let buildComponentsListStub: SinonStub; let buildCustomObjectFieldsListStub: SinonStub; let fetchAndSaveMetadataComponentPropertiesStub: SinonStub; let fetchAndSaveSObjectFieldsPropertiesStub: SinonStub; const cmpUtil = new ComponentUtils(); const defaultOrg = 'defaultOrg@test.com'; const metadataType = 'ApexClass'; const metadataTypeCustomObject = 'CustomObject'; const sObjectName = 'DemoCustomObject'; const folderName = 'DemoDashboard'; const metadataTypeDashboard = 'Dashboard'; const filePath = '/test/metadata/ApexClass.json'; const fileData = JSON.stringify({ status: 0, result: [ { fullName: 'fakeName2', type: 'ApexClass' }, { fullName: 'fakeName1', type: 'ApexClass' } ] }); beforeEach(async () => { const testData = new MockTestOrgData(); $$.setConfigStubContents('AuthInfoConfig', { contents: await testData.getConfig() }); mockConnection = await Connection.create({ authInfo: await AuthInfo.create({ username: testData.username }) }); getComponentsPathStub = sb.stub(ComponentUtils.prototype, 'getComponentsPath').returns(filePath); connectionStub = sb.stub(workspaceContext, 'getConnection').resolves(mockConnection); getUsernameStub = sb.stub(OrgAuthInfo, 'getUsername').returns('test-username1@example.com'); fileExistsStub = sb.stub(fs, 'existsSync'); buildComponentsListStub = sb.stub(ComponentUtils.prototype, 'buildComponentsList'); buildCustomObjectFieldsListStub = sb.stub(ComponentUtils.prototype, 'buildCustomObjectFieldsList'); fetchAndSaveMetadataComponentPropertiesStub = sb.stub(cmpUtil, 'fetchAndSaveMetadataComponentProperties').resolves(fileData); fetchAndSaveSObjectFieldsPropertiesStub = sb.stub(cmpUtil, 'fetchAndSaveSObjectFieldsProperties').resolves(mockFieldData); }); afterEach(() => { sb.restore(); }); it('should load metadata components through sfdx-core library if file does not exist', async () => { fileExistsStub.returns(false); const components = await cmpUtil.loadComponents(defaultOrg, metadataType); expect(fetchAndSaveMetadataComponentPropertiesStub.calledOnce).to.equal(true); expect(fetchAndSaveMetadataComponentPropertiesStub.calledWith(metadataType, mockConnection, filePath)).to.be.true; expect(buildComponentsListStub.calledOnce).to.be.true; expect(buildComponentsListStub.calledWith(metadataType, fileData, undefined)).to .be.true; }); it('should load metadata components from json file if the file exists', async () => { fileExistsStub.returns(true); const components = await cmpUtil.loadComponents(defaultOrg, metadataType); expect(fetchAndSaveMetadataComponentPropertiesStub.called).to.equal(false); expect(buildComponentsListStub.calledWith(metadataType, undefined, filePath)).to.be.true; }); it('should load metadata components through sfdx-core library if forceRefresh is set to true and file exists', async () => { fileExistsStub.returns(true); await cmpUtil.loadComponents(defaultOrg, metadataType, undefined, true); expect(fetchAndSaveMetadataComponentPropertiesStub.calledOnce).to.be.true; expect(fetchAndSaveMetadataComponentPropertiesStub.calledWith(metadataType, mockConnection, filePath)).to.be.true; expect(buildComponentsListStub.calledOnce).to.be.true; expect(buildComponentsListStub.calledWith(metadataType, fileData, undefined)).to.be.true; }); it('should load metadata components listed under folders of Dashboards through sfdx-core library if file does not exist', async () => { fileExistsStub.returns(false); const components = await cmpUtil.loadComponents(defaultOrg, metadataTypeDashboard, folderName, undefined); expect(fetchAndSaveMetadataComponentPropertiesStub.calledOnce).to.equal(true); expect(fetchAndSaveMetadataComponentPropertiesStub.calledWith(metadataTypeDashboard, mockConnection, filePath, folderName)).to.be.true; expect(buildComponentsListStub.calledOnce).to.be.true; expect(buildComponentsListStub.calledWith(metadataTypeDashboard, fileData, undefined)).to .be.true; }); it('should load metadata components listed under folders of Dashboards from json file if the file exists', async () => { fileExistsStub.returns(true); const components = await cmpUtil.loadComponents(defaultOrg, metadataTypeDashboard, folderName, undefined); expect(fetchAndSaveMetadataComponentPropertiesStub.called).to.equal(false); expect(buildComponentsListStub.calledWith(metadataTypeDashboard, undefined, filePath)).to.be.true; }); it('should load sobject fields list through sfdx-core if file does not exist', async () => { fileExistsStub.returns(false); buildCustomObjectFieldsListStub.returns(''); const components = await cmpUtil.loadComponents(defaultOrg, metadataTypeCustomObject, sObjectName, undefined); expect(fetchAndSaveSObjectFieldsPropertiesStub.called).to.equal(true); expect(fetchAndSaveSObjectFieldsPropertiesStub.calledWith(mockConnection, filePath, sObjectName)).to.be.true; expect(buildCustomObjectFieldsListStub.called).to.equal(true); expect(buildCustomObjectFieldsListStub.calledWith(mockFieldData, filePath)).to.be.true; }); it('should load sobject fields list from json file if the file exists', async () => { fileExistsStub.returns(true); buildCustomObjectFieldsListStub.returns(''); const components = await cmpUtil.loadComponents(defaultOrg, metadataTypeCustomObject, sObjectName, undefined); expect(fetchAndSaveSObjectFieldsPropertiesStub.called).to.equal(false); expect(buildCustomObjectFieldsListStub.called).to.equal(true); expect(buildCustomObjectFieldsListStub.calledWith(undefined, filePath)).to.be.true; }); it('should load sobject fields list through sfdx-core if forceRefresh is set to true and file exists', async () => { fileExistsStub.returns(true); buildCustomObjectFieldsListStub.returns(''); const components = await cmpUtil.loadComponents(defaultOrg, metadataTypeCustomObject, sObjectName, true); expect(fetchAndSaveSObjectFieldsPropertiesStub.called).to.equal(true); expect(fetchAndSaveSObjectFieldsPropertiesStub.calledWith(mockConnection, filePath, sObjectName)).to.be.true; expect(buildCustomObjectFieldsListStub.called).to.equal(true); expect(buildCustomObjectFieldsListStub.calledWith(mockFieldData, filePath)).to.be.true; }); it('should validate that buildCustomObjectFieldsList() returns correctly formatted fields', async () => { // const fieldData = JSON.stringify(mockFieldData); const formattedFields = expectedFieldList; buildCustomObjectFieldsListStub.returns(formattedFields); const components = await cmpUtil.loadComponents(defaultOrg, metadataTypeCustomObject, sObjectName); expect(JSON.stringify(components)).to.equal(JSON.stringify(formattedFields)); }); }); describe('fetch metadata components and custom objects fields list', () => { let mockConnection: Connection; let connectionStub: SinonStub; let fileExistsStub: SinonStub; let fetchCustomObjectsFieldsStub: SinonStub; let fetchExistingCustomObjectsFieldsStub: SinonStub; let fetchMetadataComponentsStub: SinonStub; let fetchExistingMetadataComponentsStub: SinonStub; let getComponentsPathStub: SinonStub; const cmpUtil = new ComponentUtils(); const defaultOrg = 'defaultOrg@test.com'; const customObjectMetadataType = 'CustomObject'; const metadataType = 'ApexClass'; const sObject = 'DemoCustomObject'; const filePath = '/test/metadata/CustomObject_DemoCustomObject.json'; const fieldsList = expectedFieldList; beforeEach(async () => { const testData = new MockTestOrgData(); $$.setConfigStubContents('AuthInfoConfig', { contents: await testData.getConfig() }); mockConnection = await Connection.create({ authInfo: await AuthInfo.create({ username: testData.username }) }); fileExistsStub = sb.stub(fs, 'existsSync'); connectionStub = sb.stub(workspaceContext, 'getConnection').resolves(mockConnection); getComponentsPathStub = sb.stub(ComponentUtils.prototype, 'getComponentsPath').returns(filePath); fetchCustomObjectsFieldsStub = sb.stub(ComponentUtils.prototype, 'fetchCustomObjectsFields').resolves(fieldsList); fetchExistingCustomObjectsFieldsStub = sb.stub(ComponentUtils.prototype, 'fetchExistingCustomObjectsFields').resolves(fieldsList); fetchMetadataComponentsStub = sb.stub(ComponentUtils.prototype, 'fetchMetadataComponents').resolves(''); fetchExistingMetadataComponentsStub = sb.stub(ComponentUtils.prototype, 'fetchExistingMetadataComponents').resolves(''); }); afterEach(() => { sb.restore(); }); it('should call fetchCustomObjectsFields() to fetch fields of a sobject if json file does not exist', async () => { fileExistsStub.returns(false); const components = await cmpUtil.loadComponents(defaultOrg, customObjectMetadataType, sObject); expect(fetchCustomObjectsFieldsStub.called).to.equal(true); expect(fetchCustomObjectsFieldsStub.calledWith(mockConnection, filePath, sObject)).to.be.true; }); it('should call fetchExistingCustomObjectsFields() to fetch fields of a sobject if json file exists', async () => { fileExistsStub.returns(true); const components = await cmpUtil.loadComponents(defaultOrg, customObjectMetadataType, sObject); expect(fetchExistingCustomObjectsFieldsStub.called).to.equal(true); expect(fetchExistingCustomObjectsFieldsStub.calledWith(filePath)).to.be.true; }); it('should call fetchCustomObjectsFields() to fetch fields of a sobject if json file exists and force is set to true', async () => { fileExistsStub.returns(true); const components = await cmpUtil.loadComponents(defaultOrg, customObjectMetadataType, sObject, true); expect(fetchCustomObjectsFieldsStub.called).to.be.true; expect(fetchCustomObjectsFieldsStub.calledWith(mockConnection, filePath, sObject)).to.be.true; }); it('should call fetchMetadataComponents() to fetch metadata components if json file does not exist', async () => { fileExistsStub.returns(false); const components = await cmpUtil.loadComponents(defaultOrg, metadataType); expect(fetchMetadataComponentsStub.called).to.equal(true); expect(fetchMetadataComponentsStub.calledWith(metadataType, mockConnection, filePath, undefined)).to.be.true; }); it('should call fetchExistingMetadataComponents() to fetch metadata components if json file exists', async () => { fileExistsStub.returns(true); const components = await cmpUtil.loadComponents(defaultOrg, metadataType); expect(fetchExistingMetadataComponentsStub.called).to.equal(true); expect(fetchExistingMetadataComponentsStub.calledWith(metadataType, filePath)).to.be.true; }); it('should call fetchMetadataComponents() to fetch metadata components if json file exists and force is set to true', async () => { fileExistsStub.returns(true); const components = await cmpUtil.loadComponents(defaultOrg, metadataType, undefined, true); expect(fetchMetadataComponentsStub.called).to.be.true; expect(fetchMetadataComponentsStub.calledWith(metadataType, mockConnection, filePath, undefined)).to.be.true; }); }); describe('fetch fields of a standard or custom object', () => { let mockConnection: Connection; let connectionStub: SinonStub; let fetchAndSaveSObjectFieldsPropertiesStub: SinonStub; let buildCustomObjectFieldsListStub: SinonStub; const cmpUtil = new ComponentUtils(); const metadataType = 'CustomObject'; const sObject = 'DemoCustomObject'; const filePath = '/test/metadata/CustomObject_DemoCustomObject.json'; const fieldData = JSON.stringify(mockFieldData); const fieldsList = expectedFieldList; beforeEach(async () => { const testData = new MockTestOrgData(); $$.setConfigStubContents('AuthInfoConfig', { contents: await testData.getConfig() }); mockConnection = await Connection.create({ authInfo: await AuthInfo.create({ username: testData.username }) }); fetchAndSaveSObjectFieldsPropertiesStub = sb.stub(cmpUtil, 'fetchAndSaveSObjectFieldsProperties').resolves(fieldData); buildCustomObjectFieldsListStub = sb.stub(ComponentUtils.prototype, 'buildCustomObjectFieldsList').returns(fieldsList); connectionStub = sb.stub(workspaceContext, 'getConnection').resolves(mockConnection); }); afterEach(() => { sb.restore(); }); it('should call fetchAndSaveSObjectFieldsProperties() and buildCustomObjectFields() while fetching custom object fields if file does not exist or forceRefresh is set to true', async () => { const fieldList = await cmpUtil.fetchCustomObjectsFields(mockConnection, filePath, sObject); expect(fetchAndSaveSObjectFieldsPropertiesStub.called).to.equal(true); expect(fetchAndSaveSObjectFieldsPropertiesStub.calledWith(mockConnection, filePath, sObject)).to.be.true; expect(buildCustomObjectFieldsListStub.called).to.equal(true); expect(buildCustomObjectFieldsListStub.calledWith(fieldData, filePath)).to.be.true; }); it('should validate that buildCustomObjectFields() is called while fetching custom object fields if file exists', async () => { const fieldList = await cmpUtil.fetchExistingCustomObjectsFields(filePath); expect(buildCustomObjectFieldsListStub.called).to.equal(true); expect(buildCustomObjectFieldsListStub.calledWith(undefined, filePath)).to.be.true; }); it('should validate that fetchAndSaveSObjectFieldsProperties() is not called while fetching custom object fields if file exists', async () => { const fieldList = await cmpUtil.fetchExistingCustomObjectsFields(filePath); expect(fetchAndSaveSObjectFieldsPropertiesStub.called).to.equal(false); }); }); describe('retrieve fields data of a sobject to write in a json file designated for the sobject', () => { let mockConnection: Connection; let connectionStub: SinonStub; let describeSObjectFieldsStub: SinonStub; let writeFileStub: SinonStub; const cmpUtil = new ComponentUtils(); const sObjectName = 'DemoAccount'; const filePath = '/test/metadata/CustomObject_DemoAccount.json'; beforeEach(async () => { const testData = new MockTestOrgData(); $$.setConfigStubContents('AuthInfoConfig', { contents: await testData.getConfig() }); mockConnection = await Connection.create({ authInfo: await AuthInfo.create({ username: testData.username }) }); connectionStub = sb.stub(workspaceContext, 'getConnection').resolves(mockConnection); describeSObjectFieldsStub = sb.stub(mockConnection, 'describe').resolves(sObjectDescribeResult); writeFileStub = sb.stub(fs, 'writeFileSync').returns({}); }); afterEach(() => { sb.restore(); }); it('should validate that fetchAndSaveSObjectFieldsProperties() writes a json file at sobject components path', async () => { const sObjectFields = await cmpUtil.fetchAndSaveSObjectFieldsProperties(mockConnection, filePath, sObjectName); expect(writeFileStub.called).to.equal(true); expect(writeFileStub.calledWith(filePath)).to.be.true; }); it('should validate that fetchAndSaveSObjectFieldsProperties() returns the correctly formatted result file', async () => { const sObjectFields = await cmpUtil.fetchAndSaveSObjectFieldsProperties(mockConnection, filePath, sObjectName); expect(sObjectFields).to.equal(JSON.stringify(expectedfetchAndSaveSObjectFieldsPropertiesResult, null, 2)); expect(JSON.parse(sObjectFields).result.length).to.equal(expectedfetchAndSaveSObjectFieldsPropertiesResult.result.length); }); });
the_stack
import { BlockRegData, BlockPortRegData } from "../Define/BlockDef"; import { Block } from "../Define/Block"; import CommonUtils from "../../utils/CommonUtils"; import AllEditors from "../TypeEditors/AllEditors"; import StringUtils from "../../utils/StringUtils"; import { BlockPort, BlockPortDirection } from "../Define/Port"; import { CustomStorageObject } from "../Define/CommonDefine"; import { BlockEditor } from "../Editor/BlockEditor"; export default { register() { return registerCalcBase().concat( registerCalcScalar()).concat( registerOperatorBase()); }, packageName: 'Operator', version: 1, } function registerCalcBase() { let blockAddition = new BlockRegData("31CCFD61-0164-015A-04B1-732F0A7D6661", "加", '相加单元,相加两个或多个参数', 'imengyu', '运算'); let blockSubstract = new BlockRegData("1B0A8EDC-D8FE-C6D1-0DD6-803BC08562EB", "减", '相减单元,相减两个或多个参数', 'imengyu', '运算'); let blockMultiply = new BlockRegData("49984155-77D8-3C54-AEB1-24F4695C0609", "乘", '相乘单元,相乘两个或多个参数', 'imengyu', '运算'); let blockDivide = new BlockRegData("FFCA28BB-B182-0D05-5ECE-AF2F7B549B6B", "除", '相除单元,相除两个或多个参数', 'imengyu', '运算'); let CalcBase_onCreate = (block : Block) => { if(typeof block.options['opType'] == 'undefined') { block.options['opType'] = 'any'; }else { //更换数据类型 block.allPorts.forEach((port) => { if(!port.paramType.isExecute()) block.changePortParamType(port, block.options['opType']); }); } }; let CalcBase_onUserAddPort = (block : Block, dirction : BlockPortDirection, type : 'execute'|'param') => { block.data['portCount'] = typeof block.data['portCount'] == 'number' ? block.data['portCount'] + 1 : block.inputPortCount; return { guid: 'PI' + block.data['portCount'], paramType: type == 'execute' ? 'execute' : block.options['opType'], direction: dirction, portAnyFlexable: { flexable: true } }; }; let CalcBase_portAnyFlexables = { flexable: { setResultToOptions: 'opType' } }; let CalcBase_cm_ports : Array<BlockPortRegData> = [ { direction: 'input', guid: 'PI0', paramType: 'any', portAnyFlexable: { flexable: true }, }, { description: '', direction: 'input', guid: 'PI1', paramType: 'any', portAnyFlexable: { flexable: true }, }, { description: '', direction: 'output', guid: 'PO1', paramType: 'any', portAnyFlexable: { flexable: true }, }, ]; //#region 加 blockAddition.baseInfo.version = '2.0'; blockAddition.baseInfo.logo = require('../../assets/images/BlockIcon/add.svg'); blockAddition.ports = CalcBase_cm_ports; blockAddition.settings.parametersChangeSettings.userCanAddInputParameter = true; blockAddition.portAnyFlexables = CalcBase_portAnyFlexables; blockAddition.callbacks.onCreate = CalcBase_onCreate; blockAddition.callbacks.onPortParamRequest = (block, port, context) => { let rs : number = null; Object.keys(block.inputPorts).forEach(guid => { let v = block.getInputParamValue(guid, context); if(typeof v != 'undefined') if(rs == null) rs = v else rs += v; }); return rs; }; blockAddition.callbacks.onUserAddPort = CalcBase_onUserAddPort; blockAddition.blockStyle.logoBackground = blockAddition.baseInfo.logo; blockAddition.blockStyle.noTitle = true; //#endregion //#region 减 blockSubstract.baseInfo.version = '2.0'; blockSubstract.baseInfo.logo = require('../../assets/images/BlockIcon/sub.svg'); blockSubstract.ports = CalcBase_cm_ports; blockSubstract.settings.parametersChangeSettings.userCanAddInputParameter = true; blockSubstract.portAnyFlexables = CalcBase_portAnyFlexables; blockSubstract.callbacks.onCreate = CalcBase_onCreate; blockSubstract.callbacks.onPortParamRequest = (block, port, context) => { let rs : number = null; Object.keys(block.inputPorts).forEach(guid => { let v = block.getInputParamValue(guid, context); if(typeof v != 'undefined') if(rs == null) rs = v; else rs -= v; }); return rs; }; blockSubstract.callbacks.onUserAddPort = CalcBase_onUserAddPort; blockSubstract.blockStyle.logoBackground = blockSubstract.baseInfo.logo; blockSubstract.blockStyle.noTitle = true; //#endregion //#region 乘 blockMultiply.baseInfo.version = '2.0'; blockMultiply.baseInfo.logo = require('../../assets/images/BlockIcon/multiply.svg'); blockMultiply.ports = CalcBase_cm_ports; blockMultiply.settings.parametersChangeSettings.userCanAddInputParameter = true; blockDivide.portAnyFlexables = CalcBase_portAnyFlexables; blockMultiply.callbacks.onCreate = CalcBase_onCreate; blockMultiply.callbacks.onPortParamRequest = (block, port, context) => { let rs : number = null; Object.keys(block.inputPorts).forEach(guid => { let v = block.getInputParamValue(guid, context); if(typeof v != 'undefined') if(rs == null) rs = v; else rs *= v; }); return rs; }; blockMultiply.callbacks.onUserAddPort = CalcBase_onUserAddPort; blockMultiply.blockStyle.logoBackground = blockMultiply.baseInfo.logo; blockMultiply.blockStyle.noTitle = true; //#endregion //#region 除 blockDivide.baseInfo.version = '2.0'; blockDivide.baseInfo.logo = require('../../assets/images/BlockIcon/divide.svg'); blockDivide.ports = CalcBase_cm_ports; blockDivide.settings.parametersChangeSettings.userCanAddInputParameter = true; blockDivide.portAnyFlexables = CalcBase_portAnyFlexables; blockDivide.callbacks.onCreate = CalcBase_onCreate; blockDivide.callbacks.onPortParamRequest = (block, port, context) => { let rs : number = null; Object.keys(block.inputPorts).forEach(guid => { let v = block.getInputParamValue(guid, context); if(typeof v != 'undefined') if(rs == null) rs = v; else rs /= v; }); return rs; }; blockDivide.callbacks.onUserAddPort = CalcBase_onUserAddPort; blockDivide.blockStyle.noTitle = true; blockDivide.blockStyle.logoBackground = blockDivide.baseInfo.logo; //#endregion return [ blockAddition, blockSubstract, blockMultiply, blockDivide, ] } function registerCalcScalar() { let CalcScalar_onUserAddPort = (block : BlockEditor, dirction : BlockPortDirection, type : 'execute'|'param') : BlockPortRegData => { block.data['portCount'] = typeof block.data['portCount'] == 'number' ? block.data['portCount'] + 1 : block.inputPortCount; return { guid: 'PI' + block.data['portCount'], paramType: type == 'execute' ? 'execute' : 'number', direction: dirction, }; }; let CalcScalar_cm_ports : Array<BlockPortRegData> = [ { direction: 'input', guid: 'BI', paramType: 'execute' }, { direction: 'output', guid: 'BO', paramType: 'execute' } ]; let CalcScalar_cm_param_ports : Array<BlockPortRegData> = [ { direction: 'input', guid: 'PI1', paramType: 'number' }, { direction: 'input', guid: 'PI2', paramType: 'number' }, { direction: 'output', guid: 'PO1', paramType: 'number' }, ]; let blockAbsolute = new BlockRegData("24CC6573-C39B-915C-5356-AAEB8EEF9CAF", '绝对值', '求一个数的绝对值', '基础', '运算'); let blockExponentiate = new BlockRegData("3279E42C-0A2D-38B2-9B46-5E1BD444A817", '指数', '求一个数的n次方', '基础', '运算'); let blockRoot = new BlockRegData("83AB5460-07E1-6F55-CE3E-841DD117D891", '开方', '开一个数的n次方', '基础', '运算'); let blockRound = new BlockRegData("ACE2AF65-C644-9B68-C3E0-92484F60301A", '取整', '将一个数取整', '基础', '运算'); let blockAverage = new BlockRegData("C71EB51A-A0D8-9C12-A5F2-0D3CAE3111FC", '平均值', '求一些数的平均值', '基础', '运算'); let blockMaximum = new BlockRegData("62FCF10F-1891-9DD7-1C53-129F5F580E18", '最大值', '获取一些数中的最大值', '基础', '运算'); let blockMinimum = new BlockRegData("FA97A675-A872-0967-715D-57F0E0FFB75B", '最小值', '获取一些数中的最小值', '基础', '运算'); let blockModulo = new BlockRegData("ECD228AA-D88D-E02D-51FB-DAEE67ABA31C", "求余", '求余单元,对两个参数求余', '基础', '运算'); let blockRandom = new BlockRegData("2076EDF9-91D4-5C77-28A1-D6390ECD5BFC", "随机数", '生成指定范围的随机数', '基础', '运算'); //#region 最小值 blockMinimum.baseInfo.category = '运算'; blockMinimum.baseInfo.version = '2.0'; blockMinimum.baseInfo.logo = require('../../assets/images/BlockIcon/min.svg'); blockMinimum.ports = CalcScalar_cm_ports.concat(CalcScalar_cm_param_ports); blockMinimum.settings.parametersChangeSettings.userCanAddInputParameter = true; blockMinimum.callbacks.onPortExecuteIn = (block, port) => { let rs : number = null; Object.keys(block.inputPorts).forEach(guid => { let v = block.getInputParamValue(guid); if(typeof v != 'undefined') if(rs == null) rs = v; else { let vn : number = v; if(vn < rs) rs = v; } }); block.setOutputParamValue('PO1', rs); block.activeOutputPort('BO'); }; blockMinimum.callbacks.onUserAddPort = CalcScalar_onUserAddPort; //#endregion //#region 最大值 blockMaximum.baseInfo.version = '2.0'; blockMaximum.baseInfo.logo = require('../../assets/images/BlockIcon/max.svg'); blockMaximum.ports = CalcScalar_cm_ports.concat(CalcScalar_cm_param_ports); blockMaximum.settings.parametersChangeSettings.userCanAddInputParameter = true; blockMaximum.callbacks.onPortExecuteIn = (block, port) => { let rs : number = null; Object.keys(block.inputPorts).forEach(guid => { let v = block.getInputParamValue(guid); if(typeof v != 'undefined') if(rs == null) rs = v; else { let vn : number = v; if(vn > rs) rs = v; } }); block.setOutputParamValue('PO1', rs); block.activeOutputPort('BO'); }; blockMaximum.callbacks.onUserAddPort = CalcScalar_onUserAddPort; //#endregion //#region 平均值 blockAverage.baseInfo.version = '2.0'; blockAverage.baseInfo.logo = require('../../assets/images/BlockIcon/avg.svg'); blockAverage.ports = CalcScalar_cm_ports.concat(CalcScalar_cm_param_ports); blockAverage.settings.parametersChangeSettings.userCanAddInputParameter = true; blockAverage.callbacks.onPortExecuteIn = (block, port) => { let rs : number = null; let paramCount = 0; Object.keys(block.inputPorts).forEach(guid => { let v = block.getInputParamValue(guid); if(v != null && typeof v == 'number') { if(rs == null) rs = v; else rs += v; paramCount++; } }); block.setOutputParamValue('PO1', rs / paramCount); block.activeOutputPort('BO'); }; blockAverage.callbacks.onUserAddPort = CalcScalar_onUserAddPort; //#endregion //#region 取整 blockRound.baseInfo.version = '2.0'; blockRound.baseInfo.logo = require('../../assets/images/BlockIcon/round.svg'); blockRound.ports = CalcScalar_cm_ports.concat([ { direction: 'input', guid: 'PI1', paramType: 'number' }, { name: "结果", direction: 'output', guid: 'PO1', paramType: 'number' }, ]); blockRound.callbacks.onCreate = (block) => { if(typeof block.options['opType'] == 'undefined') block.options['opType'] = 'floor'; }; blockRound.callbacks.onPortExecuteIn = (block, port) => { let rs = block.getInputParamValue('PI1'); switch(block.options['opType']) { case 'floor': rs = Math.floor(rs); break; case 'ceil': rs = Math.ceil(rs); break; case 'round': rs = Math.round(rs); break; } block.setOutputParamValue('PO1', rs); block.activeOutputPort('BO'); }; blockRound.callbacks.onCreateCustomEditor = (parentEle, block : Block, regData) => { let el = document.createElement('div'); let typeSelector = document.createElement('select'); typeSelector.innerHTML = '<option value="floor">向上取整</option><option value="ceil">向下取整</option><option value="round">四舍五入</option>'; typeSelector.value = block.options['opType']; typeSelector.onchange = () => block.options['opType'] = typeSelector.value; el.appendChild(typeSelector); parentEle.appendChild(el); }; //#endregion //#region 开方 blockRoot.baseInfo.version = '2.0'; blockRoot.baseInfo.logo = require('../../assets/images/BlockIcon/sqrt.svg'); blockRoot.ports = CalcScalar_cm_ports.concat([ { name: "x", description: '被开方数', direction: 'input', paramDefaultValue: 9, guid: 'PI1', paramType: 'number' }, { name: "n", description: '开方次数', direction: 'input', paramDefaultValue: 2, guid: 'PI2', paramType: 'number' }, { name: "ⁿ√x", description: 'x的n次根', direction: 'output', guid: 'PO1', paramType: 'number' }, ]); blockRoot.callbacks.onPortExecuteIn = (block, port) => { let x = block.getInputParamValue('PI1'); let n = block.getInputParamValue('PI2'); block.setOutputParamValue('PO1', Math.pow(x, 1 / n)); block.activeOutputPort('BO'); }; //#endregion //#region 指数 blockExponentiate.baseInfo.version = '2.0'; blockExponentiate.baseInfo.logo = require('../../assets/images/BlockIcon/exp.svg'); blockExponentiate.ports = CalcScalar_cm_ports.concat([ { name: "x", description: '底数', direction: 'input', paramDefaultValue: 2, guid: 'PI1', paramType: 'number' }, { name: "n", description: '指数', direction: 'input', paramDefaultValue: 3, guid: 'PI2', paramType: 'number' }, { name: "xⁿ", description: 'x的n次方', direction: 'output', guid: 'PO1', paramType: 'number' }, ]); blockExponentiate.callbacks.onPortExecuteIn = (block, port) => { let x = block.getInputParamValue('PI1'); let n = block.getInputParamValue('PI2'); block.setOutputParamValue('PO1', Math.pow(x, n)); block.activeOutputPort('BO'); }; //#endregion //#region 绝对值 blockAbsolute.baseInfo.version = '2.0'; blockAbsolute.baseInfo.logo = require('../../assets/images/BlockIcon/abs.svg'); blockAbsolute.ports = CalcScalar_cm_ports.concat([ { description: '需要取绝对值的数', direction: 'input', paramDefaultValue: 0, guid: 'PI1', paramType: 'number' }, { description: '绝对值', direction: 'output', guid: 'PO1', paramType: 'number' }, ]); blockAbsolute.callbacks.onPortExecuteIn = (block, port) => { let x = block.getInputParamValue('PI1'); block.setOutputParamValue('PO1', Math.abs(x)); block.activeOutputPort('BO'); }; //#endregion //#region 求余 blockModulo.baseInfo.version = '2.0'; blockModulo.baseInfo.logo = require('../../assets/images/BlockIcon/modulo.svg'); blockModulo.ports = CalcScalar_cm_ports.concat(CalcScalar_cm_param_ports); blockModulo.callbacks.onPortExecuteIn = (block, port) => { let v1 = block.getInputParamValue('PI1') , v2 = block.getInputParamValue('PI2'); if(CommonUtils.isDefinedAndNotNull(v1) && CommonUtils.isDefinedAndNotNull(v2)) block.setOutputParamValue('PO1', v1 % v2); block.activeOutputPort('BO'); }; //#endregion //#region 随机数 blockRandom.baseInfo.version = '2.0'; blockRandom.ports = [ { direction: 'input', guid: 'IN', paramType: 'execute' }, { direction: 'output', guid: 'OUT', paramType: 'execute' }, { direction: 'input', guid: 'MIN', name: '最小值', paramType: 'number', paramDefaultValue: 0, }, { direction: 'input', guid: 'MAX', name: '最大值', paramType: 'number', paramDefaultValue: 10, }, { direction: 'output', guid: 'VALUE', paramType: 'number' }, ]; blockRandom.callbacks.onPortExecuteIn = (block, port) => { let min = block.getInputParamValue('MIN') , max = block.getInputParamValue('MAX'); if(CommonUtils.isDefinedAndNotNull(min) && CommonUtils.isDefinedAndNotNull(max)) block.setOutputParamValue('VALUE', CommonUtils.genRandom(min, max)); block.activeOutputPort('OUT'); }; //#endregion return [ blockModulo, blockMaximum, blockMinimum, blockExponentiate, blockAbsolute, blockRoot, blockRound, blockAverage, blockRandom, ]; } function registerOperatorBase() { let blockAccessObject = new BlockRegData("CDC97AAC-1E4F-3C65-94D8-1566A246D0A2", "访问对象属性", '通过键值访问对象的属性', '', '基础/对象'); let blockCreateObject = new BlockRegData("B46A7D4E-3A89-D190-4D15-57A1D176FA8B", "创建对象", '创建一个复合对象', '', '基础/对象'); let blockSetObject = new BlockRegData("42CCD2DC-8BA4-C6BC-82B6-A783C58F6804", "设置对象属性", '通过键值设置对象的属性', '', '基础/对象'); let blockObjectKeys = new BlockRegData("41A68F58-F8F6-DA97-65C4-0C5D89A6FA46", "获取对象所有键值", '', '', '基础/对象'); //#region 通过键值访问对象的属性 blockAccessObject.baseInfo.version = '2.0'; blockAccessObject.ports = [ { guid: 'IN', direction: 'input', paramType: 'execute' }, { guid: 'OBJECT', direction: 'input', paramType: 'object', description: '要访问的对象', }, { guid: 'KEY0', direction: 'input', paramType: 'string', description: '要访问的字段键值0', }, { guid: 'OUT', direction: 'output', paramType: 'execute' }, { guid: 'VALUE0', direction: 'output', description: '键值0的字段', paramType: 'any' }, ] blockAccessObject.settings.parametersChangeSettings.userCanAddInputParameter = true; blockAccessObject.blockStyle.noTitle = true; blockAccessObject.blockStyle.logoBackground = 'title:通过键值访问对象的属性'; blockAccessObject.blockStyle.minWidth = '170px'; blockAccessObject.callbacks.onPortExecuteIn = (block, port) => { Object.keys(block.inputPorts).forEach((key) => { let port = block.inputPorts[key]; let id = port.guid.substr(3); if(port.guid.startsWith('KEY')) block.setOutputParamValue('VALUE' + id, block.getInputParamValue('OBJECT')[block.getInputParamValue('KEY' + id)]) }); block.activeOutputPort('OUT'); }; blockAccessObject.callbacks.onUserAddPort = (block, direction, type) => { block.data['portCount'] = typeof block.data['portCount'] == 'number' ? block.data['portCount'] + 2 : 1; return [ { guid: 'KEY' + block.data['portCount'], direction: 'input', paramType: 'string', description: '要访问的字段键值' + block.data['portCount'], }, { guid: 'VALUE' + block.data['portCount'], direction: 'output', paramType: 'any', name: '键值' + block.data['portCount'] + '的字段', }, ]; }; blockAccessObject.callbacks.onPortRemove = (block, port) => { if(port.guid.startsWith('KEY')) { let id = port.guid.substr(3); let port2 = block.getPortByGUID('VALUE' + id); if(port2) block.deletePort(port2); }else if(port.guid.startsWith('VALUE')) { let id = port.guid.substr(5); let port2 = block.getPortByGUID('KEY' + id); if(port2) block.deletePort(port2); } }; //#endregion //#region 通过键值设置对象的属性 blockSetObject.baseInfo.version = '2.0'; blockSetObject.blockStyle.noTitle = true; blockSetObject.blockStyle.logoBackground = 'title:通过键值设置对象的属性'; blockSetObject.blockStyle.minWidth = '170px'; blockSetObject.ports = [ { guid: 'IN', direction: 'input', paramType: 'execute' }, { guid: 'OBJECT', direction: 'input', paramType: 'object', description: '要设置的对象', }, { guid: 'KEY', direction: 'input', paramType: 'string', description: '要设置的字段键值', }, { guid: 'INVAL', direction: 'input', paramType: 'any', description: '要设置的值', }, { guid: 'OUT', direction: 'output', paramType: 'execute' }, { guid: 'OUTVAL', direction: 'output', description: '键值的字段', paramType: 'any' }, ] blockSetObject.callbacks.onPortExecuteIn = (block, port) => { let val = block.getInputParamValue('INVAL'); block.getInputParamValue('OBJECT')[block.getInputParamValue('KEY')] = val; block.setOutputParamValue('OUTVAL', val); block.activeOutputPort('OUT'); }; //#endregion //#region 创建对象 blockCreateObject.baseInfo.version = '2.0'; blockCreateObject.ports = [ { guid: 'IN', direction: 'input', paramType: 'execute' }, { guid: 'OUT', direction: 'output', paramType: 'execute' }, { guid: 'OUTOBJ', direction: 'output', paramType: 'object' }, ]; blockCreateObject.settings.parametersChangeSettings.userCanAddInputParameter = true; blockCreateObject.blockStyle.noTitle = true; blockCreateObject.blockStyle.logoBackground = 'title:创建对象'; blockCreateObject.blockStyle.minWidth = '160px'; blockCreateObject.callbacks.onUserAddPort = (block, direction, type) => { block.data['portCount'] = typeof block.data['portCount'] == 'number' ? block.data['portCount'] + 2 : 1; return [ { guid: 'KEY' + block.data['portCount'], direction: 'input', paramType: 'any', description: '键' + block.data['portCount'], }, ]; }; blockCreateObject.callbacks.onCreatePortCustomEditor = (parentEle, block, port) => { let el = document.createElement('div'); let input = AllEditors.getBaseEditors('string').editorCreate(block, port, parentEle, (newV) => { port.options['key'] = newV; port.description = '键为 ' + StringUtils.valueToStr(newV) + ' 的值'; port.regData.description = port.description; block.updatePort(port); return newV; }, port.options['key'], null, null); el.style.display = 'inline-block'; el.innerText = '键 = '; el.appendChild(input); return el; }; blockCreateObject.callbacks.onPortExecuteIn = (block, port) => { let object : CustomStorageObject = new Object(); Object.keys(block.inputPorts).forEach((key) => { let port = <BlockPort>block.inputPorts[key]; if(!CommonUtils.isNullOrEmpty(port.options['key'])) object[port.options['key']] = port.rquestInputValue(block.currentRunningContext); }); block.setOutputParamValue('VALUE', object); block.activeOutputPort('OUTOBJ'); }; //#endregion //#region 获取对象所有键值 blockObjectKeys.blockStyle.noTitle = true; blockObjectKeys.blockStyle.logoBackground = 'title:获取对象所有键值'; blockObjectKeys.blockStyle.minWidth = '170px'; blockObjectKeys.ports = [ { guid: 'IN', direction: 'input', paramType: 'execute' }, { guid: 'OUT', direction: 'output', paramType: 'execute' }, { guid: 'OBJECT', direction: 'input', paramType: 'object', description: '要获取键值的对象' }, { guid: 'KEYS', direction: 'output', paramType: 'string', paramSetType: 'array', description: '对象的所有键值' }, ]; blockObjectKeys.callbacks.onPortExecuteIn = (block, port) => { block.setOutputParamValue('KEYS', Object.keys(block.getInputParamValue('OBJECT'))); block.activeOutputPort('OUT'); }; //#endregion return [ blockAccessObject, blockSetObject, blockCreateObject, ]; }
the_stack
import { GameDriver } from "../gameDriver"; import { Dir } from "fs-extra"; import { Language } from "../../state"; import { KaiDiscipline, MgnDiscipline, GndDiscipline } from "../../model/disciplinesDefinitions"; import { BookSeriesId, BookSeries } from "../../model/bookSeries"; import { Disciplines } from "../../model/disciplines"; import { CombatMechanics, Book, SetupDisciplines, Item } from "../.."; import { Driver } from "selenium-webdriver/chrome"; import { projectAon } from "../../model/projectAon"; import { WebElement, Alert } from "selenium-webdriver"; // Selenium web driver const driver: GameDriver = new GameDriver(); GameDriver.globalSetup(); jest.setTimeout(2000000); // Initial setup beforeAll( async () => { await driver.setupBrowser(); }); // Final shutdown afterAll( async () => { await driver.close(); }); describe("combat", () => { test("noMindblast", async () => { await driver.setupBookState(1, Language.ENGLISH); await driver.setDisciplines( [ KaiDiscipline.Mindblast] ); await driver.goToSection("sect133"); expect( await driver.getCombatRatio() ).toBe(-5); }); test("noPsiSurge", async () => { await driver.setupBookState(6, Language.ENGLISH); await driver.setDisciplines( [ MgnDiscipline.PsiSurge ] ); await driver.goToSection("sect156"); // No mindblast bonus: expect( await driver.getCombatRatio() ).toBe(-2); // No Psi-surge check available: expect( await (await driver.getSurgeCheckbox()).isDisplayed() ).toBe(false); }); test("noKaiSurge", async () => { await driver.setupBookState(13, Language.ENGLISH); await driver.setDisciplines( [ GndDiscipline.KaiSurge ] ); await driver.goToSection("sect56"); // No mindblast bonus: expect( await driver.getCombatRatio() ).toBe(-6); // No Kai-surge check available: expect( await (await driver.getSurgeCheckbox()).isDisplayed() ).toBe(false); }); test("maxEludeTurn", async () => { await driver.setupBookState(6, Language.ENGLISH); await driver.goToSection("sect116"); // Expect to elude to be clickable in first turn const eludeBtn = await driver.getEludeCombatButton(); expect(await GameDriver.isClickable(eludeBtn)).toBe(true); // Play turn await driver.setNextRandomValue(0); await driver.clickPlayCombatTurn(); // Expect to elude to be not visible expect(await eludeBtn.isDisplayed()).toBe(false); }); test("mindblastBonus", async () => { await driver.setupBookState(5, Language.ENGLISH); await driver.setDisciplines( [ KaiDiscipline.Mindblast ] ); await driver.goToSection("sect110"); expect( await driver.getCombatRatio() ).toBe(-4); }); test("psiSurgeBonus", async () => { await driver.setupBookState(10, Language.ENGLISH); await driver.setDisciplines( [ MgnDiscipline.PsiSurge ] ); await driver.goToSection("sect81"); // Check use Kai Surge. Expect CS increase await driver.cleanClickAndWait( await driver.getSurgeCheckbox() ); expect( await driver.getCombatRatio() ).toBe(-9); }); test("kaiSurgeBonus", async () => { await driver.setupBookState(13, Language.ENGLISH); await driver.setDisciplines( [ GndDiscipline.KaiSurge ] ); await driver.goToSection("sect301"); // Check use Kai Surge. Expect CS increase await driver.cleanClickAndWait( await driver.getSurgeCheckbox() ); expect( await driver.getCombatRatio() ).toBe(0); }); test("eludeEnemyEP", async () => { await driver.setupBookState(13, Language.ENGLISH); await driver.pick("sommerswerd"); await driver.goToSection("sect38"); await driver.setNextRandomValue(0); await driver.clickPlayCombatTurn(); for (let i = 0; i < 4 ; i++) { await driver.setNextRandomValue(0); await driver.clickPlayCombatTurn(); } // Enemy EP here = 40 await driver.setNextRandomValue(5); await driver.clickPlayCombatTurn(); // EP = 37. Expect no elude allowed const eludeBtn = await driver.getEludeCombatButton(); expect( await eludeBtn.isDisplayed() ).toBe(false); await driver.setNextRandomValue(3); await driver.clickPlayCombatTurn(); // EP = 36. Expect elude allowed expect( await GameDriver.isClickable(eludeBtn) ).toBe(true); }); test("combatSkillModifier", async () => { await driver.setupBookState(13, Language.ENGLISH); await driver.setDisciplines([]); await driver.goToSection("sect86"); expect( await driver.getCombatRatio() ).toBe(-10); }); }); // setDisciplines -> See setDisciplines.tests.ts describe("test", () => { test("hasDiscipline", async () => { await driver.setupBookState(13, Language.ENGLISH); await driver.setDisciplines([]); await driver.goToSection("sect84"); expect( await driver.choiceIsEnabled("sect7") ).toBe(false); expect( await driver.choiceIsEnabled("sect171") ).toBe(true); await driver.setDisciplines([GndDiscipline.AnimalMastery]); await driver.goToSection("sect84"); expect( await driver.choiceIsEnabled("sect7") ).toBe(true); expect( await driver.choiceIsEnabled("sect171") ).toBe(false); }); test("hasObject", async () => { await driver.setupBookState(13, Language.ENGLISH); await driver.pick("sommerswerd"); await driver.goToSection("sect290"); expect( await driver.choiceIsEnabled("sect199") ).toBe(true); expect( await driver.choiceIsEnabled("sect316") ).toBe(false); await driver.drop("sommerswerd", true); await driver.goToSection("sect290"); expect( await driver.choiceIsEnabled("sect199") ).toBe(false); expect( await driver.choiceIsEnabled("sect316") ).toBe(true); // Pick object from section, expect allow to go to section right now await driver.pick("sommerswerd", true); expect( await driver.choiceIsEnabled("sect199") ).toBe(true); expect( await driver.choiceIsEnabled("sect316") ).toBe(false); }); test("canUseBow", async () => { await driver.setupBookState(13, Language.ENGLISH); await driver.goToSection("sect96"); expect( await driver.choiceIsEnabled("sect225") ).toBe(false); // Only bow, you cannot shot await driver.pick(Item.BOW); await driver.goToSection("sect96"); expect( await driver.choiceIsEnabled("sect225") ).toBe(false); // Bow and quiver, but no arrows, you cannot shot await driver.pick(Item.QUIVER); await driver.goToSection("sect96"); expect( await driver.choiceIsEnabled("sect225") ).toBe(false); await driver.increaseArrows(1); await driver.goToSection("sect96"); expect( await driver.choiceIsEnabled("sect225") ).toBe(true); // If you pick the bow from the section, expect to shot inmediatelly await driver.drop(Item.BOW, true); await driver.goToSection("sect96"); expect( await driver.choiceIsEnabled("sect225") ).toBe(false); await driver.pick(Item.BOW, true); expect( await driver.choiceIsEnabled("sect225") ).toBe(true); }); }); describe("expressions", () => { test("ENDURANCE", async () => { await driver.setupBookState(13, Language.ENGLISH); async function setup(endurance: number, randomValue: number) { await driver.loadCleanSection(Book.INITIAL_SECTION); await driver.setDisciplines([]); await driver.setEndurance(endurance); await driver.goToSection("sect91"); await driver.setNextRandomValue(randomValue); await driver.clickRandomLink(); } await setup(20, 6); // Expect to get +2 and go to sect184 expect( await driver.choiceIsEnabled("sect184") ).toBe(true); await setup(19, 7); expect( await driver.choiceIsEnabled("sect184") ).toBe(false); }); test("COMBATSDURATION", async () => { await driver.setupBookState(13, Language.ENGLISH); async function playCombat(randomValues: number[]) { await driver.loadCleanSection("sect100"); for (const r of randomValues) { await driver.setNextRandomValue(r); await driver.clickPlayCombatTurn(); } } await driver.setDisciplines([]); await playCombat([5, 5, 5, 5, 0]); expect( await driver.choiceIsEnabled("sect254") ).toBe(true); await driver.setDisciplines([]); await playCombat([4, 4, 4, 4, 0, 0]); expect( await driver.choiceIsEnabled("sect37") ).toBe(true); }); test("BOWBONUS", async () => { async function shot(expectedRandom: number) { await driver.goToSection("sect99"); await driver.setNextRandomValue(0); await driver.clickRandomLink(); expect( await driver.getRandomFinalValue() ).toBe(expectedRandom); } async function setInventory(silverBow: boolean) { await driver.pick(silverBow ? "silverbowduadon" : Item.BOW); await driver.pick(Item.QUIVER); await driver.increaseArrows(6); } await driver.setupBookState(12, Language.ENGLISH); // Expect -4 if no bow: await driver.setDisciplines([]); await shot(-4); // Expect no bonus if no Weaponskill with bow await driver.loadCleanSection(Book.INITIAL_SECTION); await driver.setDisciplines([MgnDiscipline.Weaponmastery]); await driver.setWeaponskill([]); await setInventory(false); await shot(0); // Expect bow bonus await driver.loadCleanSection(Book.INITIAL_SECTION); await driver.setDisciplines([MgnDiscipline.Weaponmastery]); await driver.setWeaponskill([Item.BOW]); await setInventory(false); await shot(3); // Expect bow bonus + Silver Bow of Duadon bonus await driver.loadCleanSection(Book.INITIAL_SECTION); await driver.setDisciplines([MgnDiscipline.Weaponmastery]); await driver.setWeaponskill([Item.BOW]); await setInventory(true); await shot(6); // TODO: Test Grand Master bonus when book 14 is ready (book 13 has erratas with this and is not reliable) // TODO: Test loyalty bonus in Grand Master }); }); test("endurance", async () => { await driver.setupBookState(13, Language.ENGLISH); await driver.setDisciplines([]); await driver.setEndurance(10); await driver.goToSection("sect92"); expect( (await driver.getActionChart()).currentEndurance ).toBe(5); }); test("death", async () => { await driver.setupBookState(13, Language.ENGLISH); await driver.pick("healingpotion"); await driver.setDisciplines([GndDiscipline.Deliverance]); await driver.goToSection("sect99"); expect( (await driver.getActionChart()).currentEndurance ).toBe(0); expect( await (await driver.getElementById("mechanics-death")).isDisplayed() ).toBe(true); // TODO: Create a mechanics.tests.ts for this, and test everything else is disabled (choices, etc), test "mechanics-death" options // Expect do not use objects or curing button await driver.goToActionChart(); expect( await GameDriver.isClickable( await driver.getElementById("achart-restore20Ep") ) ).toBe(false); expect( await driver.getUseObjectLink("healingpotion") ).toBe(null); });
the_stack
export const isEmail = (s: string) => /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s) // 手机号码 export const isMobile = (s: string) => /^1[0-9]{10}$/.test(s) // 电话号码 export const isPhone = (s: string) => /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s) // 是否URL地址 export const isURL = (s: string) => /^http[s]?:\/\/.*/.test(s) // 是否字符串 export const isString = (o: any) => Object.prototype.toString.call(o).slice(8, -1) === 'String' // 是否数字 export const isNumber = (o: any) => Object.prototype.toString.call(o).slice(8, -1) === 'Number' // 是否boolean export const isBoolean = (o: any) => Object.prototype.toString.call(o).slice(8, -1) === 'Boolean' // 是否函数 export const isFunction = (o: any) => Object.prototype.toString.call(o).slice(8, -1) === 'Function' // 是否为null export const isNull = (o: any) => Object.prototype.toString.call(o).slice(8, -1) === 'Null' // 是否undefined export const isUndefined = (o: any) => Object.prototype.toString.call(o).slice(8, -1) === 'Undefined' // 是否对象 export const isObj = (o: any) => Object.prototype.toString.call(o).slice(8, -1) === 'Object' // 是否数组 export const isArray = (o: any) => Object.prototype.toString.call(o).slice(8, -1) === 'Array' // 是否时间 export const isDate = (o: any) => Object.prototype.toString.call(o).slice(8, -1) === 'Date' // 是否正则 export const isRegExp = (o: any) => Object.prototype.toString.call(o).slice(8, -1) === 'RegExp' // 是否错误对象 export const isError = (o: any) => Object.prototype.toString.call(o).slice(8, -1) === 'Error' // 是否Symbol函数 export const isSymbol = (o: any) => Object.prototype.toString.call(o).slice(8, -1) === 'Symbol' // 是否Promise对象 export const isPromise = (o: any) => Object.prototype.toString.call(o).slice(8, -1) === 'Promise' // 是否Set对象 export const isSet = (o) => { return Object.prototype.toString.call(o).slice(8, -1) === 'Set' } // 是否是微信浏览器 export const ua = navigator.userAgent.toLowerCase(); // export const isWeiXin = () => { // return ua.match(/microMessenger/i) == 'micromessenger' // } // 是否是移动端 export const isDeviceMobile = () => { return /android|webos|iphone|ipod|balckberry/i.test(ua) } // 是否是QQ浏览器 export const isQQBrowser = () => { return !!ua.match(/mqqbrowser|qzone|qqbrowser|qbwebviewtype/i) } // 是否是爬虫 export const isSpider = () => { return /adsbot|googlebot|bingbot|msnbot|yandexbot|baidubot|robot|careerbot|seznambot|bot|baiduspider|jikespider|symantecspider|scannerlwebcrawler|crawler|360spider|sosospider|sogou web sprider|sogou orion spider/.test(ua) } // 是否ios export const isIos = () => { var u = navigator.userAgent; if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) { //安卓手机 return false } else if (u.indexOf('iPhone') > -1) {//苹果手机 return true } else if (u.indexOf('iPad') > -1) {//iPad return false } else if (u.indexOf('Windows Phone') > -1) {//winphone手机 return false } else { return false } } // 是否为PC端 export const isPC = () => { var userAgentInfo = navigator.userAgent; var Agents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"]; var flag = true; for (var v = 0; v < Agents.length; v++) { if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; } } return flag; } // 去除html标签 export const removeHtmltag = (str: string) => { return str.replace(/<[^>]+>/g, '') } //获取url参数 export const getQueryString = (name: string) => { const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'); const search = window.location.search.split('?')[1] || ''; const r = search.match(reg) || []; return r[2]; } // 动态引入js export const injectScript = (src: string) => { const s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = src; const t = document.getElementsByTagName('script')[0]; t.parentNode!.insertBefore(s, t); } // 根据url地址下载 export const download = (url: string) => { var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1; if (isChrome || isSafari) { var link = document.createElement('a'); link.href = url; if (link.download !== undefined) { var fileName = url.substring(url.lastIndexOf('/') + 1, url.length); link.download = fileName; } if (document.createEvent) { var e = document.createEvent('MouseEvents'); e.initEvent('click', true, true); link.dispatchEvent(e); return true; } } if (url.indexOf('?') === -1) { url += '?download'; } window.open(url, '_self'); return true; } // el是否包含某个class export const hasClass = (el: HTMLElement, className: string) => { let reg = new RegExp('(^|\\s)' + className + '(\\s|$)') return reg.test(el.className) } // el添加某个class export const addClass = (el: HTMLElement, className: string) => { if (hasClass(el, className)) { return } let newClass = el.className.split(' ') newClass.push(className) el.className = newClass.join(' ') } // el去除某个class export const removeClass = (el: HTMLElement, className: string) => { if (!hasClass(el, className)) { return } let reg = new RegExp('(^|\\s)' + className + '(\\s|$)', 'g') el.className = el.className.replace(reg, ' ') } // 获取滚动的坐标 export const getScrollPosition = (el = window) => ({ x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop }); // 滚动到顶部 export const scrollToTop = () => { const c = document.documentElement.scrollTop || document.body.scrollTop; if (c > 0) { window.requestAnimationFrame(scrollToTop); window.scrollTo(0, c - c / 8); } } // el是否在视口范围内 export const elementIsVisibleInViewport = (el: HTMLElement, partiallyVisible = false) => { const { top, left, bottom, right } = el.getBoundingClientRect(); const { innerHeight, innerWidth } = window; return partiallyVisible ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; } // 洗牌算法随机 export const shuffle = (arr: any[]) => { var result = [], random; while (arr.length > 0) { random = Math.floor(Math.random() * arr.length); result.push(arr[random]) arr.splice(random, 1) } return result; } // 劫持粘贴板 export const copyTextToClipboard = (value: any) => { var textArea = document.createElement("textarea"); textArea.style.background = 'transparent'; textArea.value = value; document.body.appendChild(textArea); textArea.select(); try { var successful = document.execCommand('copy'); } catch (err) { console.log('Oops, unable to copy'); } document.body.removeChild(textArea); } // 判断类型集合 export const checkStr = (str: string, type: string) => { switch (type) { case 'phone': //手机号码 return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str); case 'tel': //座机 return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str); case 'card': //身份证 return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str); case 'pwd': //密码以字母开头,长度在6~18之间,只能包含字母、数字和下划线 return /^[a-zA-Z]\w{5,17}$/.test(str) case 'postal': //邮政编码 return /[1-9]\d{5}(?!\d)/.test(str); case 'QQ': //QQ号 return /^[1-9][0-9]{4,9}$/.test(str); case 'email': //邮箱 return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str); case 'money': //金额(小数点2位) return /^\d*(?:\.\d{0,2})?$/.test(str); case 'URL': //网址 return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str) case 'IP': //IP return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str); case 'date': //日期时间 return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str) case 'number': //数字 return /^[0-9]$/.test(str); case 'english': //英文 return /^[a-zA-Z]+$/.test(str); case 'chinese': //中文 return /^[\\u4E00-\\u9FA5]+$/.test(str); case 'lower': //小写 return /^[a-z]+$/.test(str); case 'upper': //大写 return /^[A-Z]+$/.test(str); case 'HTML': //HTML标记 return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str); default: return true; } } // 严格的身份证校验 export const isCardID = (sId: string) => { if (!/(^\d{15}$)|(^\d{17}(\d|X|x)$)/.test(sId)) { console.log('你输入的身份证长度或格式错误') return false } //身份证城市 var aCity = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外" }; if (!aCity[parseInt(sId.substr(0, 2))]) { console.log('你的身份证地区非法') return false } // 出生日期验证 var sBirthday = (sId.substr(6, 4) + "-" + Number(sId.substr(10, 2)) + "-" + Number(sId.substr(12, 2))).replace(/-/g, "/"), d = new Date(sBirthday) if (sBirthday != (d.getFullYear() + "/" + (d.getMonth() + 1) + "/" + d.getDate())) { console.log('身份证上的出生日期非法') return false } // 身份证号码校验 var sum = 0, weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2], codes = "10X98765432" for (var i = 0; i < sId.length - 1; i++) { sum += sId[i] * weights[i]; } var last = codes[sum % 11]; //计算出来的最后一位身份证号码 if (sId[sId.length - 1] != last) { console.log('你输入的身份证号非法') return false } return true } // 随机数范围 export const random = (min: number, max: number) => { if (arguments.length === 2) { return Math.floor(min + Math.random() * ((max + 1) - min)) } else { return null; } } // 将阿拉伯数字翻译成中文的大写数字 export const numberToChinese = (num: number) => { var AA = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十"); var BB = new Array("", "十", "百", "仟", "萬", "億", "点", ""); var a = ("" + num).replace(/(^0*)/g, "").split("."), k = 0, re = ""; for (var i = a[0].length - 1; i >= 0; i--) { switch (k) { case 0: re = BB[7] + re; break; case 4: if (!new RegExp("0{4}//d{" + (a[0].length - i - 1) + "}$") .test(a[0])) re = BB[4] + re; break; case 8: re = BB[5] + re; BB[7] = BB[5]; k = 0; break; } if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0) re = AA[0] + re; if (a[0].charAt(i) != 0) re = AA[a[0].charAt(i)] + BB[k % 4] + re; k++; } if (a.length > 1) // 加上小数部分(如果有小数部分) { re += BB[6]; for (var i = 0; i < a[1].length; i++) re += AA[a[1].charAt(i)]; } if (re == '一十') re = "十"; if (re.match(/^一/) && re.length == 3) re = re.replace("一", ""); return re; } // 将数字转换为大写金额 export const changeToChinese = Num => { // 判断如果传递进来的不是字符的话转换为字符 if (typeof Num == "number") { Num = new String(Num); }; Num = Num.replace(/,/g, "") //替换tomoney()中的“,” Num = Num.replace(/ /g, "") //替换tomoney()中的空格 Num = Num.replace(/¥/g, "") //替换掉可能出现的¥字符 if (isNaN(Num)) { //验证输入的字符是否为数字 //alert("请检查小写金额是否正确"); return ""; }; //字符处理完毕后开始转换,采用前后两部分分别转换 var part = String(Num).split("."); var newchar = ""; //小数点前进行转化 for (var i = part[0].length - 1; i >= 0; i--) { if (part[0].length > 10) { return ""; //若数量超过拾亿单位,提示 } var tmpnewchar = "" var perchar = part[0].charAt(i); switch (perchar) { case "0": tmpnewchar = "零" + tmpnewchar; break; case "1": tmpnewchar = "壹" + tmpnewchar; break; case "2": tmpnewchar = "贰" + tmpnewchar; break; case "3": tmpnewchar = "叁" + tmpnewchar; break; case "4": tmpnewchar = "肆" + tmpnewchar; break; case "5": tmpnewchar = "伍" + tmpnewchar; break; case "6": tmpnewchar = "陆" + tmpnewchar; break; case "7": tmpnewchar = "柒" + tmpnewchar; break; case "8": tmpnewchar = "捌" + tmpnewchar; break; case "9": tmpnewchar = "玖" + tmpnewchar; break; } switch (part[0].length - i - 1) { case 0: tmpnewchar = tmpnewchar + "元"; break; case 1: if (perchar != 0) tmpnewchar = tmpnewchar + "拾"; break; case 2: if (perchar != 0) tmpnewchar = tmpnewchar + "佰"; break; case 3: if (perchar != 0) tmpnewchar = tmpnewchar + "仟"; break; case 4: tmpnewchar = tmpnewchar + "万"; break; case 5: if (perchar != 0) tmpnewchar = tmpnewchar + "拾"; break; case 6: if (perchar != 0) tmpnewchar = tmpnewchar + "佰"; break; case 7: if (perchar != 0) tmpnewchar = tmpnewchar + "仟"; break; case 8: tmpnewchar = tmpnewchar + "亿"; break; case 9: tmpnewchar = tmpnewchar + "拾"; break; } var newchar = tmpnewchar + newchar; } //小数点之后进行转化 if (Num.indexOf(".") != -1) { if (part[1].length > 2) { // alert("小数点之后只能保留两位,系统将自动截断"); part[1] = part[1].substr(0, 2) } for (i = 0; i < part[1].length; i++) { tmpnewchar = "" perchar = part[1].charAt(i) switch (perchar) { case "0": tmpnewchar = "零" + tmpnewchar; break; case "1": tmpnewchar = "壹" + tmpnewchar; break; case "2": tmpnewchar = "贰" + tmpnewchar; break; case "3": tmpnewchar = "叁" + tmpnewchar; break; case "4": tmpnewchar = "肆" + tmpnewchar; break; case "5": tmpnewchar = "伍" + tmpnewchar; break; case "6": tmpnewchar = "陆" + tmpnewchar; break; case "7": tmpnewchar = "柒" + tmpnewchar; break; case "8": tmpnewchar = "捌" + tmpnewchar; break; case "9": tmpnewchar = "玖" + tmpnewchar; break; } if (i == 0) tmpnewchar = tmpnewchar + "角"; if (i == 1) tmpnewchar = tmpnewchar + "分"; newchar = newchar + tmpnewchar; } } //替换所有无用汉字 while (newchar.search("零零") != -1) newchar = newchar.replace("零零", "零"); newchar = newchar.replace("零亿", "亿"); newchar = newchar.replace("亿万", "亿"); newchar = newchar.replace("零万", "万"); newchar = newchar.replace("零元", "元"); newchar = newchar.replace("零角", ""); newchar = newchar.replace("零分", ""); if (newchar.charAt(newchar.length - 1) == "元") { newchar = newchar + "整" } return newchar; } // 判断一个元素是否在数组中 export const contains = (arr, val) => { return arr.indexOf(val) != -1 ? true : false; } // 数组排序,{ type } 1:从小到大 2:从大到小 3:随机 export const sort = (arr, type = 1) => { return arr.sort((a, b) => { switch (type) { case 1: return a - b; case 2: return b - a; case 3: return Math.random() - 0.5; default: return arr; } }) } //去重 export const unique = (arr) => { if (Array.hasOwnProperty('from')) { return Array.from(new Set(arr)); } else { var n = {}, r = []; for (var i = 0; i < arr.length; i++) { if (!n[arr[i]]) { n[arr[i]] = true; r.push(arr[i]); } } return r; } } // 求两个集合的并集 export const union = (a, b) => { var newArr = a.concat(b); return this.unique(newArr); } // 求两个集合的交集 export const intersect = (a, b) => { var _this = this; a = this.unique(a); return this.map(a, function (o) { return _this.contains(b, o) ? o : null; }); } // 删除其中一个元素 export const remove = (arr, ele) => { var index = arr.indexOf(ele); if (index > -1) { arr.splice(index, 1); } return arr; } // 将类数组转换为数组 export const formArray = (ary) => { var arr = []; if (Array.isArray(ary)) { arr = ary; } else { arr = Array.prototype.slice.call(ary); }; return arr; } // 最大值 export const max = (arr) => { return Math.max.apply(null, arr); } // 最小值 export const min = (arr) => { return Math.min.apply(null, arr); } // 求和 export const sum = (arr) => { return arr.reduce((pre, cur) => { return pre + cur }) } // 平均值 export const average = (arr) => { return this.sum(arr) / arr.length } // 去除空格, type: 1 - 所有空格 2 - 前后空格 3 - 前空格 4 - 后空格 export const trim = (str, type) => { type = type || 1 switch (type) { case 1: return str.replace(/\s+/g, ""); case 2: return str.replace(/(^\s*)|(\s*$)/g, ""); case 3: return str.replace(/(^\s*)/g, ""); case 4: return str.replace(/(\s*$)/g, ""); default: return str; } } // 字符转换,type: 1: 首字母大写 2:首字母小写 3:大小写转换 4:全部大写 5:全部小写 export const changeCase = (str, type) => { type = type || 4 switch (type) { case 1: return str.replace(/\b\w+\b/g, function (word) { return word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase(); }); case 2: return str.replace(/\b\w+\b/g, function (word) { return word.substring(0, 1).toLowerCase() + word.substring(1).toUpperCase(); }); case 3: return str.split('').map(function (word) { if (/[a-z]/.test(word)) { return word.toUpperCase(); } else { return word.toLowerCase() } }).join('') case 4: return str.toUpperCase(); case 5: return str.toLowerCase(); default: return str; } } // 检测密码强度 export const checkPwd = (str) => { var Lv = 0; if (str.length < 6) { return Lv } if (/[0-9]/.test(str)) { Lv++ } if (/[a-z]/.test(str)) { Lv++ } if (/[A-Z]/.test(str)) { Lv++ } if (/[\.|-|_]/.test(str)) { Lv++ } return Lv; } // 函数节流器 export const debouncer = (fn, time, interval = 200) => { if (time - (window.debounceTimestamp || 0) > interval) { fn && fn(); window.debounceTimestamp = time; } } // 在字符串中插入新字符串 export const insertStr = (soure, index, newStr) => { var str = soure.slice(0, index) + newStr + soure.slice(index); return str; } // 判断两个对象是否键值相同 export const isObjectEqual = (a, b) => { var aProps = Object.getOwnPropertyNames(a); var bProps = Object.getOwnPropertyNames(b); if (aProps.length !== bProps.length) { return false; } for (var i = 0; i < aProps.length; i++) { var propName = aProps[i]; if (a[propName] !== b[propName]) { return false; } } return true; } // 16进制颜色转RGBRGBA字符串 export const colorToRGB = (val, opa) => { var pattern = /^(#?)[a-fA-F0-9]{6}$/; //16进制颜色值校验规则 var isOpa = typeof opa == 'number'; //判断是否有设置不透明度 if (!pattern.test(val)) { //如果值不符合规则返回空字符 return ''; } var v = val.replace(/#/, ''); //如果有#号先去除#号 var rgbArr = []; var rgbStr = ''; for (var i = 0; i < 3; i++) { var item = v.substring(i * 2, i * 2 + 2); var num = parseInt(item, 16); rgbArr.push(num); } rgbStr = rgbArr.join(); rgbStr = 'rgb' + (isOpa ? 'a' : '') + '(' + rgbStr + (isOpa ? ',' + opa : '') + ')'; return rgbStr; } // 追加url参数 export const appendQuery = (url, key, value) => { var options = key; if (typeof options == 'string') { options = {}; options[key] = value; } options = $.param(options); if (url.includes('?')) { url += '&' + options } else { url += '?' + options } return url; }
the_stack
import { html, render } from "lit-html"; import { eventmit } from "eventmit"; export type TextCheckerPopupElementAttributes = { target?: HTMLElement; }; export type TextCheckerCard = { id: string; message: string; messageRuleId: string; fixable: boolean; }; export type TextCheckerCardRect = { left: number; top: number; width: number; height?: number; }; export type TextCheerHandlers = { onFixText?: () => void; onFixAll?: () => void; onFixRule?: () => void; onIgnore?: () => void; onSeeDocument?: () => void; }; export type TextCheckerPopupState = { card?: TextCheckerCard; targetRect?: TextCheckerCardRect; handlers?: TextCheerHandlers; }; const createTextCheckerPopupState = (state?: Partial<TextCheckerPopupState>) => { let currentState: TextCheckerPopupState = { ...state }; const changeEvent = eventmit<void>(); return { get(): TextCheckerPopupState { return currentState; }, onChange(handler: () => void) { changeEvent.on(handler); }, dispose() { changeEvent.offAll(); }, update(state: Partial<TextCheckerPopupState>) { currentState = { ...currentState, ...state }; changeEvent.emit(); }, removeCardById(cardId: TextCheckerCard["id"]) { if (currentState?.card?.id !== cardId) { return; } currentState = { ...currentState, card: undefined }; changeEvent.emit(); }, removeAllCard() { currentState = { ...currentState, card: undefined }; changeEvent.emit(); } }; }; export type TextCheckerPopupElementArgs = { onEnter?: () => void; onLeave?: () => void; }; export class TextCheckerPopupElement extends HTMLElement { private overlay!: HTMLDivElement; private store: ReturnType<typeof createTextCheckerPopupState>; public isHovering = false; private onEnter?: () => void; private onLeave?: () => void; constructor(args: TextCheckerPopupElementArgs) { super(); this.onEnter = args.onEnter; this.onLeave = args.onLeave; this.store = createTextCheckerPopupState(); } private onMouseEnter = () => { this.isHovering = true; this.onEnter?.(); }; private onMouseLeave = () => { this.isHovering = false; this.onLeave?.(); }; connectedCallback(): void { const shadow = this.attachShadow({ mode: "closed" }); const overlay = document.createElement("div"); overlay.className = "popup"; const style = document.createElement("style"); const highlightColor = "#F35373"; const highlightTextColor = "#9095AA"; style.textContent = ` :root { --highlight-color: ${highlightColor}; --highlight-textColor: ${highlightTextColor}; } .popup { color: #000; background-color: #fff; box-shadow: 0 2px 10px rgba(0,0,0,.2); padding: 0; } .popoup-list { margin: 0; padding: 0 0 var(--padding) 0; list-style: none; } .popup-listItem { padding: var(--padding); cursor: pointer; } .popup-listItem--icon, .popup-listItem--iconImage { padding-right: 12px; fill: ${highlightTextColor}; width: 24px; height: 24px; min-height: 24px; min-width: 24px; } .popup-listItem:first-child { padding-top: var(--padding); padding-bottom: var(--padding); } .popup-listItem-message { font-size: 12px; margin: 0; padding: 0 0 6px 0; } .popup-listItem--ruleName { font-size: 12px; margin: 0 0.5em; } .popup-listItem-content { font-size: 16px; /* align icon + text */ display: flex; align-items: center; margin: 0; padding: 0; } .popup-listItem:hover { color: #fff; background-color: ${highlightColor}; } .popup-listItem:hover .popup-listItem--icon { fill: #ffffff !important; stroke: #ffffff !important; } `; this.overlay = overlay; this.overlay.addEventListener("mouseenter", this.onMouseEnter); this.overlay.addEventListener("mouseleave", this.onMouseLeave); shadow.append(style); shadow.append(overlay); this.store.onChange(() => { this.renderAnnotationMarkers(this.store.get()); }); } public disconnectedCallback() { this.overlay.removeEventListener("mouseenter", this.onMouseEnter); this.overlay.removeEventListener("mouseleave", this.onMouseLeave); } public updateCard({ card, rect, handlers }: { card: TextCheckerCard; rect: TextCheckerCardRect; handlers: TextCheerHandlers; }) { this.store.update({ card, targetRect: rect, handlers }); } public dismissCard(card: TextCheckerCard) { this.store.removeCardById(card.id); } public dismissCards() { this.store.removeAllCard(); } private renderAnnotationMarkers = (state: TextCheckerPopupState) => { const rect = state.targetRect; if (!rect) { return; } if (!state.card) { render("", this.overlay); return; } const itemPadding = 16; // TODO: more correct handle const firstLine = state.card.message.split(/\n/)[0]; const fixIcon = html` <svg class="popup-listItem--icon" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M7.5 5.6L5 7L6.4 4.5L5 2L7.5 3.4L10 2L8.6 4.5L10 7L7.5 5.6ZM19.5 15.4L22 14L20.6 16.5L22 19L19.5 17.6L17 19L18.4 16.5L17 14L19.5 15.4ZM22 2L20.6 4.5L22 7L19.5 5.6L17 7L18.4 4.5L17 2L19.5 3.4L22 2ZM13.34 12.78L15.78 10.34L13.66 8.22L11.22 10.66L13.34 12.78ZM14.37 7.29L16.71 9.63C17.1 10 17.1 10.65 16.71 11.04L5.04 22.71C4.65 23.1 4 23.1 3.63 22.71L1.29 20.37C0.899998 20 0.899998 19.35 1.29 18.96L12.96 7.29C13.35 6.9 14 6.9 14.37 7.29Z" /> </svg>`; const items = [ state.card.fixable ? { message: firstLine, label: html`Fix it!`, onClick: state.handlers?.onFixText, icon: fixIcon } : { message: state.card.message }, ...(state.card.fixable ? [ { label: html`Fix <span class="popup-listItem--ruleName">${state.card.messageRuleId}</span> problems`, onClick: state.handlers?.onFixRule, icon: fixIcon } ] : []), ...(state.card.fixable ? [ { label: html`Fix all problems`, onClick: state.handlers?.onFixAll, icon: fixIcon } ] : []), { label: html`Ignore`, onClick: () => { state.handlers?.onIgnore?.(); }, icon: html` <svg class="popup-listItem--icon" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M5.00299 20C5.00299 21.103 5.89999 22 7.00299 22H17.003C18.106 22 19.003 21.103 19.003 20V8H21.003V6H17.003V4C17.003 2.897 16.106 2 15.003 2H9.00299C7.89999 2 7.00299 2.897 7.00299 4V6H3.00299V8H5.00299V20ZM9.00299 4H15.003V6H9.00299V4ZM8.00299 8H17.003L17.004 20H7.00299V8H8.00299Z" fill="#9095AA" /> <path d="M9.00299 10H11.003V18H9.00299V10ZM13.003 10H15.003V18H13.003V10Z" /> </svg> ` }, { label: html`Rule <span class="popup-listItem--ruleName">${state.card.messageRuleId}</span>`, onClick: state.handlers?.onSeeDocument, icon: html` <svg class="popup-listItem--iconImage" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" > <path fill-rule="evenodd" clip-rule="evenodd" d="M12 24C18.6274 24 24 18.6274 24 12C24 5.37258 18.6274 0 12 0C5.37258 0 0 5.37258 0 12C0 18.6274 5.37258 24 12 24Z" fill="#F4F4F4" /> <path fill-rule="evenodd" clip-rule="evenodd" d="M8.33502 8.33504H5.39325V18.6067H18.6067V8.33504L18.6067 15.665H8.33502V8.33504Z" fill="#878787" /> <path fill-rule="evenodd" clip-rule="evenodd" d="M5.39325 5.39326H18.6067V8.33504H13.4831V18.6067L18.6067 18.6067H5.39325L10.5168 18.6067V8.33504H5.39325V5.39326Z" fill="black" /> </svg>` } ]; // Require tabIndex for blur event's relatedElement // https://stackoverflow.com/questions/42764494/blur-event-relatedtarget-returns-null const cardContent = html` <ul class="popoup-list" style="--padding: ${itemPadding}px"> ${items.map((item) => { const clickHandler = { handleEvent: item.onClick }; if (item.message) { if (item.onClick) { return html` <li @click=${clickHandler} class="popup-listItem" style="--padding: ${itemPadding}px;" tabindex="0" > <p class="popup-listItem-message">${item.message}</p> <p class="popup-listItem-content">${item.icon}${item.label}</p> </li>`; } else { return html` <li class="popup-listItem" style="--padding: ${itemPadding}px; padding-bottom: 0;" tabindex="0" > <p class="popup-listItem-message">${item.message}</p> <p class="popup-listItem-content">${item.icon}${item.label}</p> </li>`; } } return html` <li @click=${clickHandler} class="popup-listItem" style="--padding: ${itemPadding}px;" tabindex="0" > <p class="popup-listItem-content">${item.icon}${item.label}</p> </li>`; })} </ul>`; // https://www.figma.com/file/9kRm0Cr869zbdACytRE74R/textlint-editor?node-id=4%3A2 const style = `position: fixed; z-index: 2147483644; min-width: 300px; max-width: 800px; top: ${ rect.top }px; left: ${rect.left - itemPadding}px;`; this.overlay.setAttribute("style", style); render(cardContent, this.overlay); }; } if (!window.customElements.get("textchecker-popoup-element")) { window.customElements.define("textchecker-popoup-element", TextCheckerPopupElement); }
the_stack
import xml = require("../xml/index"); import utils = require("../utils"); import file = require("../FileUtil"); import CodeUtil = require("./code_util"); import exml_config = require("./exml_config"); var compiler: EXMLCompiler; export function compile(exmlPath: string, srcPath: string): egret.TaskResult { var result: egret.TaskResult = { exitCode: 0, messages: [] }; exmlPath = exmlPath.split("\\").join("/"); srcPath = srcPath.split("\\").join("/"); var tsPath: string = exmlPath.substring(0, exmlPath.length - 5) + ".g.ts"; if (srcPath.charAt(srcPath.length - 1) != "/") { srcPath += "/"; } if (!compiler) { compiler = new EXMLCompiler(); } var exitCode = 0, message = ""; if (!file.exists(exmlPath)) { result.messages.push(utils.tr(2001, exmlPath)); result.exitCode = 2001; return result; } while (true) { var className: string = exmlPath.substring(srcPath.length, exmlPath.length - 5); className = className.split("/").join("."); var xmlString = file.read(exmlPath, true); try { var xmlData = xml.parse(xmlString); } catch (e) { message = utils.tr(2002, exmlPath, e.message); exitCode = 2002; break; } if (!xmlData) { message = utils.tr(2002, exmlPath, ""); exitCode = 2002; break } try { var tsText = compiler.compile(xmlData, className, srcPath, exmlPath); file.save(tsPath, tsText); } catch (e) { message = compiler.errorMessage; exitCode = compiler.errorCode || 2002; } break; } if (exitCode) { file.save(tsPath, ""); } result.exitCode = exitCode; result.messages.push(message); return result; }; class EXMLCompiler { /** * Egret命名空间 */ public static E: string = "http://ns.egret-labs.org/egret"; /** * Wing命名空间 */ public static W: string = "http://ns.egret-labs.org/wing"; private static DECLARATIONS: string = "Declarations"; public errorCode: number; public errorMessage: string; /** * 构造函数 */ public constructor() { } /** * 配置管理器实例 */ private exmlConfig: exml_config; /** * 获取重复的ID名 */ public getRepeatedIds(xml: any): Array<any> { var result: Array<any> = []; this.getIds(xml, result); this.repeatedIdDic = {}; return result; } private exit(code: number, ...params: string[]) { this.errorCode = code; this.errorMessage = utils.tr.apply(utils, [<any>code].concat(params)); throw this.errorMessage; } private repeatedIdDic: any = {}; private getIds(xml: any, result: Array<any>): void { if (xml.namespace != EXMLCompiler.W && xml["$id"]) { var id: string = xml.$id; if (this.repeatedIdDic[id]) { result.push(this.toXMLString(xml)); } else { this.repeatedIdDic[id] = true; } } var children: Array<any> = xml.children; if (children) { var length: number = children.length; for (var i: number = 0; i < length; i++) { var node: any = children[i]; this.getIds(node, result); } } } /** * 当前类 */ private currentClass: CpClass; /** * 当前编译的类名 */ private currentClassName: string; /** * 当前要编译的EXML文件 */ private currentXML: any; /** * id缓存字典 */ private idDic: any; /** * 状态代码列表 */ private stateCode: Array<CpState>; private stateNames: Array<string>; /** * 需要单独创建的实例id列表 */ private stateIds: Array<any>; private exmlPath: string = ""; private idToNode: any; private skinParts: Array<string>; private toXMLString(node: any): string { if (!node) { return ""; } var str: string = " at <" + node.name; for (var key in node) { if (key.charAt(0) == "$") { var value: string = node[key]; key = key.substring(1); if (key == "id" && value.substring(0, 2) == "__") { continue; } str += " " + key + "=\"" + value + "\""; } } if (node.isSelfClosing) { str += "/>"; } else { str += ">"; } return str; } /** * 编译指定的XML对象为TypeScript类。 * 注意:编译前要先注入egret-manifest.xml清单文件给manifestData属性。 * @param xmlData 要编译的EXML文件内容 * @param className 要编译成的完整类名,包括命名空间。 */ public compile(xmlData: any, className: string, srcPath: string, exmlPath: string): string { if (!this.exmlConfig) { this.exmlConfig = exml_config.getInstance(); } this.exmlPath = exmlPath; this.currentXML = xmlData; this.currentClassName = className; this.exmlConfig.srcPath = srcPath; this.delayAssignmentDic = {}; this.idDic = {}; this.idToNode = {}; this.stateCode = []; this.stateNames = []; this.skinParts = []; this.declarations = null; this.currentClass = new CpClass(); this.stateIds = []; var index: number = className.lastIndexOf("."); if (index != -1) { this.currentClass.moduleName = className.substring(0, index); this.currentClass.className = className.substring(index + 1); this.currentClass.classPath = className.split(".").join("/") + ".ts"; } else { this.currentClass.className = className; } this.startCompile(); var resutlCode: string = this.currentClass.toCode(); this.currentClass = null; return resutlCode; } private declarations: any; /** * 开始编译 */ private startCompile(): void { var result: Array<any> = this.getRepeatedIds(this.currentXML); if (result.length > 0) { this.exit(2004, this.exmlPath, result.join("\n")); } this.currentClass.superClass = this.getPackageByNode(this.currentXML); this.getStateNames(); var children: Array<any> = this.currentXML.children; if (children) { var length: number = children.length; for (var i: number = 0; i < length; i++) { var node: any = children[i]; if (node.namespace == EXMLCompiler.W && node.localName == EXMLCompiler.DECLARATIONS) { this.declarations = node; break; } } } var list: Array<string> = []; this.checkDeclarations(this.declarations, list); if (list.length > 0) { this.exit(2020, this.exmlPath, list.join("\n")); } if (!this.currentXML.namespace) { this.exit(2017, this.exmlPath, this.toXMLString(this.currentXML)); } this.addIds(this.currentXML.children); this.currentClass.addVariable(new CpVariable("__s", Modifiers.M_PRIVATE, "Function", "egret.gui.setProperties")); this.createConstructFunc(); } /** * 清理声明节点里的状态标志 */ private checkDeclarations(declarations: any, list: Array<string>): void { if (!declarations) { return; } var children: Array<any> = declarations.children; if (children) { var length: number = children.length; for (var i: number = 0; i < length; i++) { var node: any = children[i]; if (node["$includeIn"]) { list.push(this.toXMLString(node)) delete node.$includeIn; } if (node["$excludeFrom"]) { list.push(this.toXMLString(node)) delete node.$excludeFrom; } this.checkDeclarations(node, list); } } } /** * 添加必须的id */ private addIds(items: Array<any>): void { if (!items) { return; } var length: number = items.length; for (var i: number = 0; i < length; i++) { var node: any = items[i]; if (!node.namespace) { this.exit(2017, this.exmlPath, this.toXMLString(node)); } this.addIds(node.children); if (node.namespace == EXMLCompiler.W) { } else if (node["$id"]) { this.idToNode[node.$id] = node; if (this.skinParts.indexOf(node.$id) == -1) { this.skinParts.push(node.$id); } this.createVarForNode(node); if (this.isStateNode(node))//检查节点是否只存在于一个状态里,需要单独实例化 this.stateIds.push(node.$id); } else if (node.localName) { if (this.isProperty(node)) { var prop: string = node.localName; var index: number = prop.indexOf("."); var children: Array<any> = node.children; if (index == -1 || !children || children.length == 0) { continue; } var firstChild: any = children[0]; this.stateIds.push(firstChild.$id); } else { this.createIdForNode(node); this.idToNode[node.$id] = node; if (this.isStateNode(node)) this.stateIds.push(node.$id); } } } } /** * 检测指定节点的属性是否含有视图状态 */ private containsState(node: any): boolean { if (node["$includeIn"] || node["$excludeFrom"]) { return true; } for (var name in node) { if (name.charAt(0) == "$") { if (name.indexOf(".") != -1) { return true; } } } return false; } /** * 为指定节点创建id属性 */ private createIdForNode(node: any): void { var idName: string = this.getNodeId(node); if (this.idDic[idName] == null) this.idDic[idName] = 1; else this.idDic[idName]++; idName += this.idDic[idName]; node.$id = idName; } /** * 获取节点ID */ private getNodeId(node: any): string { if (node["$id"]) return node.$id; return "__"; } /** * 为指定节点创建变量 */ private createVarForNode(node: any): void { var moduleName: string = this.getPackageByNode(node); if (moduleName == "") return; if (!this.currentClass.containsVar(node.$id)) this.currentClass.addVariable(new CpVariable(node.$id, Modifiers.M_PUBLIC, moduleName)); } /** * 为指定节点创建初始化函数,返回函数名引用 */ private createFuncForNode(node: any): string { var className: string = node.localName; if (this.isProperty(node)) return ""; var isBasicType: boolean = this.isBasicTypeData(className); if (isBasicType) return this.createBasicTypeForNode(node); var moduleName: string = this.getPackageByNode(node); var func: CpFunction = new CpFunction; var tailName: string = "_i"; var id: string = node.$id; func.name = id + tailName; func.returnType = moduleName; var cb: CpCodeBlock = new CpCodeBlock; var varName: string = "t"; if (className == "Object") { cb.addVar(varName, "any", "{}"); } else { cb.addVar(varName, moduleName, "new " + moduleName + "()"); } var containsId: boolean = this.currentClass.containsVar(node.$id); if (containsId) { cb.addAssignment("this." + node.$id, varName); } this.addAttributesToCodeBlock(cb, varName, node); this.initlizeChildNode(node, cb, varName); if (this.delayAssignmentDic[id]) { var length = this.delayAssignmentDic[id].length; for (var i: number = 0; i < length; i++) { var delaycb: any = this.delayAssignmentDic[id][i]; cb.concat(delaycb); } } cb.addReturn(varName); func.codeBlock = cb; this.currentClass.addFunction(func); return "this." + func.name + "()"; } private basicTypes: Array<string> = ["Array", "boolean", "string", "number"]; /** * 检查目标类名是否是基本数据类型 */ private isBasicTypeData(className: string): boolean { return this.basicTypes.indexOf(className) != -1; } /** * 为指定基本数据类型节点实例化,返回实例化后的值。 */ private createBasicTypeForNode(node: any): string { var className: string = node.localName; var returnValue: string = ""; var child: any; var varItem: CpVariable = this.currentClass.getVariableByName(node.$id); switch (className) { case "Array": var values: Array<any> = []; var children: Array<any> = node.children; if (children) { var length: number = children.length; for (var i: number = 0; i < length; i++) { var child: any = children[i]; values.push(this.createFuncForNode(child)); } } returnValue = "[" + values.join(",") + "]"; break; case "boolean": returnValue = node.text.trim(); returnValue = (returnValue == "false" || !returnValue) ? "false" : "true"; break; case "number": returnValue = node.text.trim(); if (returnValue.indexOf("%") != -1) returnValue = returnValue.substring(0, returnValue.length - 1); break; case "string": returnValue = this.formatString(node.toString()); break; } if (varItem) varItem.defaultValue = returnValue; return returnValue; } /** * 延迟赋值字典 */ private delayAssignmentDic: any = {}; /** * 将节点属性赋值语句添加到代码块 */ private addAttributesToCodeBlock(cb: CpCodeBlock, varName: string, node: any): void { var keyList: Array<any> = []; var key: string; var value: string; for (key in node) { if (key.charAt(0) != "$" || !this.isNormalKey(key)) { continue; } keyList.push(key); } keyList.sort();//排序一下防止出现随机顺序 var className: string = this.exmlConfig.getClassNameById(node.localName, node.namespace); var length: number = keyList.length; var values: Array<any> = []; var keys: Array<any> = []; for (var i: number = 0; i < length; i++) { key = keyList[i]; value = node[key]; key = this.formatKey(key.substring(1), value); value = this.formatValue(key, value, node); if (!value) { continue; } if (this.currentClass.containsVar(value)) {//赋的值对象是一个id var id: string = node.$id; var codeLine: string = "this." + id + " = t;"; if (!this.currentClass.containsVar(id)) this.createVarForNode(node); if (!cb.containsCodeLine(codeLine)) { cb.addCodeLineAt(codeLine, 1); } var delayCb: CpCodeBlock = new CpCodeBlock(); if (varName == KeyWords.KW_THIS) { delayCb.addAssignment(varName, "this." + value, key); } else { delayCb.startIf("this." + id); delayCb.addAssignment("this." + id, "this." + value, key); delayCb.endBlock(); } if (!this.delayAssignmentDic[value]) { this.delayAssignmentDic[value] = []; } this.delayAssignmentDic[value].push(delayCb); value = "this." + value; } if (this.exmlConfig.isStyleProperty(key, className)) { cb.addCodeLine(varName + ".setStyle(\"" + key + "\"," + value + ")"); } else { keys.push(key); values.push(value); } } var length: number = keys.length; if (length > 1) { var allKey: string = "[\"" + keys.join("\",\"") + "\"]"; var allValue: string = "[" + values.join(",") + "]" cb.addCodeLine("this.__s(" + varName + "," + allKey + "," + allValue + ")"); } else if (length == 1) { cb.addAssignment(varName, values[0], keys[0]); } } /** * 初始化子项 */ private initlizeChildNode(node: any, cb: CpCodeBlock, varName: string): void { var children: Array<any> = node.children; if (!children || children.length == 0) return; var className: string = this.exmlConfig.getClassNameById(node.localName, node.namespace); var directChild: Array<any> = []; var length: number = children.length; var propList: Array<string> = []; var isContainer: boolean = this.exmlConfig.isInstanceOf(className, "egret.gui.IContainer"); for (var i: number = 0; i < length; i++) { var child: any = children[i]; var prop: string = child.localName; if (child.namespace == EXMLCompiler.W) { continue; } if (this.isProperty(child)) { if (!this.isNormalKey(prop)) { continue; } var type: string = this.exmlConfig.getPropertyType(child.localName, className); if (!type) { globals.warn(2005, this.exmlPath, child.localName, this.getPropertyStr(child)); } if (!child.children || child.children.length == 0) { globals.warn(2102, this.exmlPath, this.getPropertyStr(child)); continue; } var errorInfo: string = this.getPropertyStr(child); this.addChildrenToProp(child.children, type, prop, cb, varName, errorInfo, propList, className, isContainer); } else { directChild.push(child); } } if (directChild.length == 0) return; var defaultProp: string = this.exmlConfig.getDefaultPropById(node.localName, node.namespace); var defaultType: string = this.exmlConfig.getPropertyType(defaultProp, className); var errorInfo: string = this.getPropertyStr(directChild[0]); if (!defaultProp || !defaultType) { this.exit(2012, this.exmlPath, errorInfo); } this.addChildrenToProp(directChild, defaultType, defaultProp, cb, varName, errorInfo, propList, className, isContainer); } /** * 添加多个子节点到指定的属性 */ private addChildrenToProp(children: Array<any>, type: string, prop: string, cb: CpCodeBlock, varName: string, errorInfo: string, propList: Array<string>, className: string, isContainer: boolean): void { var childFunc: string = ""; var childLength: number = children.length; if (childLength > 1) { if (type != "Array") { this.exit(2011, this.exmlPath, prop, errorInfo) } var values: Array<any> = []; for (var j: number = 0; j < childLength; j++) { var item: any = children[j]; childFunc = this.createFuncForNode(item); var childClassName: string = this.exmlConfig.getClassNameById(item.localName, item.namespace); if (!this.isStateNode(item)) values.push(childFunc); } childFunc = "[" + values.join(",") + "]"; } else { var firstChild: any = children[0]; if (type == "Array") { if (firstChild.localName == "Array") { values = []; if (firstChild.children) { var len: number = firstChild.children.length; for (var k: number = 0; k < len; k++) { item = firstChild.children[k]; childFunc = this.createFuncForNode(item); childClassName = this.exmlConfig.getClassNameById(item.localName, item.namespace); if (!this.isStateNode(item)) values.push(childFunc); } } childFunc = "[" + values.join(",") + "]"; } else { childFunc = this.createFuncForNode(firstChild); var childClassName: string = this.exmlConfig.getClassNameById(firstChild.localName, firstChild.namespace); if (!this.isStateNode(firstChild)) childFunc = "[" + childFunc + "]"; else childFunc = "[]"; } } else { var targetClass: string = this.exmlConfig.getClassNameById(firstChild.localName, firstChild.namespace); if (!this.exmlConfig.isInstanceOf(targetClass, type)) { this.exit(2008, this.exmlPath, targetClass, prop, errorInfo); } childFunc = this.createFuncForNode(firstChild); } } if (childFunc != "") { if (childFunc.indexOf("()") == -1) prop = this.formatKey(prop, childFunc); if (propList.indexOf(prop) == -1) { propList.push(prop); } else { globals.warn(2103, this.exmlPath, prop, errorInfo); } if (this.exmlConfig.isStyleProperty(prop, className)) { cb.addCodeLine(varName + ".setStyle(\"" + prop + "\"," + childFunc + ")"); } else { cb.addAssignment(varName, childFunc, prop); } } } private getPropertyStr(child: any): string { var parentStr: string = this.toXMLString(child.parent); var childStr: string = this.toXMLString(child).substring(5); return parentStr + "\n \t" + childStr; } /** * 指定节点是否是属性节点 */ private isProperty(node: any): boolean { var name: string = node.localName; if (name == null) return true; if (this.isBasicTypeData(name)) return false; var firstChar: string = name.charAt(0); return firstChar < "A" || firstChar > "Z"; } /** * 命名空间为fs的属性名列表 */ public static wingKeys: Array<string> = ["$id", "$locked", "$includeIn", "$excludeFrom", "id", "locked", "includeIn", "excludeFrom"]; /** * 是否是普通赋值的key */ private isNormalKey(key: string): boolean { if (!key || key.indexOf(".") != -1 || EXMLCompiler.wingKeys.indexOf(key) != -1) return false; return true; } /** * 格式化key */ private formatKey(key: string, value: string): string { if (value.indexOf("%") != -1) { if (key == "height") key = "percentHeight"; else if (key == "width") key = "percentWidth"; } return key; } /** * 格式化值 */ private formatValue(key: string, value: string, node: any): string { if (!value) { value = ""; } var stringValue: string = value;//除了字符串,其他类型都去除两端多余空格。 value = value.trim(); var className: string = this.exmlConfig.getClassNameById(node.localName, node.namespace); var type: string = this.exmlConfig.getPropertyType(key, className); if (!type) { globals.warn(2005, this.exmlPath, key, this.toXMLString(node)); } if (type != "string" && value.charAt(0) == "{" && value.charAt(value.length - 1) == "}") { value = value.substr(1, value.length - 2); value = value.trim(); if (value.indexOf("this.") == 0) { if (CodeUtil.isVariableWord(value.substring(5))) { value = value.substring(5); } } if (CodeUtil.isVariableWord(value)) { var targetNode: any = this.idToNode[value]; if (!targetNode) { this.exit(2010, this.exmlPath, key, value, this.toXMLString(node)); } var targetClass: string = this.exmlConfig.getClassNameById(targetNode.localName, targetNode.namespace); if (!this.exmlConfig.isInstanceOf(targetClass, type)) { this.exit(2008, this.exmlPath, targetClass, key, this.toXMLString(node)); } } else { this.exit(2009, this.exmlPath, this.toXMLString(node)); } } else if (type == "Class" && value.indexOf("@ButtonSkin(") == 0 && value.charAt(value.length - 1) == ")") { value = value.substring(12, value.length - 1); var skinNames: Array<string> = value.split(","); if (skinNames.length > 3) { this.exit(2018, this.exmlPath, this.toXMLString(node)); } for (var i: number = skinNames.length - 1; i >= 0; i--) { var skinName: string = skinNames[i]; skinName = skinName.trim(); var firstChar: string = skinName.charAt(0); var lastChar: string = skinName.charAt(skinName.length - 1); if (firstChar != lastChar || (firstChar != "'" && firstChar != "\"")) { this.exit(2018, this.exmlPath, this.toXMLString(node)); break; } skinNames[i] = this.formatString(skinName.substring(1, skinName.length - 1)); } value = "new egret.gui.ButtonSkin(" + skinNames.join(",") + ")"; } else if (key == "scale9Grid" && type == "egret.Rectangle") { var rect: Array<any> = value.split(","); if (rect.length != 4 || isNaN(parseInt(rect[0])) || isNaN(parseInt(rect[1])) || isNaN(parseInt(rect[2])) || isNaN(parseInt(rect[3]))) { this.exit(2016, this.exmlPath, this.toXMLString(node)); } value = "egret.gui.getScale9Grid(\"" + value + "\")"; } else { var orgValue: string = value; switch (type) { case "egret.gui.IFactory": value = "new egret.gui.ClassFactory(" + orgValue + ")"; case "Class": if (!this.exmlConfig.checkClassName(orgValue)) { this.exit(2015, this.exmlPath, orgValue, this.toXMLString(node)); } if (value == this.currentClassName) {//防止无限循环。 this.exit(2014, this.exmlPath, this.toXMLString(node)); } break; case "number": if (value.indexOf("#") == 0) value = "0x" + value.substring(1); else if (value.indexOf("%") != -1) value = (parseFloat(value.substr(0, value.length - 1))).toString(); break; case "boolean": value = (value == "false" || !value) ? "false" : "true"; break; case "string": case "any": value = this.formatString(stringValue); break; default: this.exit(2008, this.exmlPath, "string", key + ":" + type, this.toXMLString(node)); break; } } return value; } /** * 格式化字符串 */ private formatString(value: string): string { value = this.unescapeHTMLEntity(value); value = value.split("\n").join("\\n"); value = value.split("\r").join("\\n"); value = value.split("\"").join("\\\""); value = "\"" + value + "\""; return value; } private htmlEntities: Array<any> = [["<", "&lt;"], [">", "&gt;"], ["&", "&amp;"], ["\"", "&quot;"], ["'", "&apos;"]]; /** /** * 转换HTML实体字符为普通字符 */ private unescapeHTMLEntity(str: string): string { if (!str) return ""; var list: Array<any> = this.htmlEntities; var length: number = list.length; for (var i: number = 0; i < length; i++) { var arr: Array<any> = list[i]; var key: string = arr[0]; var value: string = arr[1]; str = str.split(value).join(key); } return str; } /** * 创建构造函数 */ private createConstructFunc(): void { var cb: CpCodeBlock = new CpCodeBlock; cb.addEmptyLine(); var varName: string = KeyWords.KW_THIS; this.addAttributesToCodeBlock(cb, varName, this.currentXML); if (this.declarations) { var children: Array<any> = this.declarations.children; if (children && children.length > 0) { var length: number = children.length; for (var i: number = 0; i < length; i++) { var decl: any = children[i]; var funcName: string = this.createFuncForNode(decl); if (funcName != "") { cb.addCodeLine(funcName + ";"); } } } } this.initlizeChildNode(this.currentXML, cb, varName); var id: string; if (this.stateIds.length > 0) { length = this.stateIds.length; for (var i: number = 0; i < length; i++) { id = this.stateIds[i]; cb.addCodeLine("this." + id + "_i();"); } cb.addEmptyLine(); } length = this.skinParts.length; if (length > 0) { for (i = 0; i < length; i++) { this.skinParts[i] = "\"" + this.skinParts[i] + "\""; } var skinPartStr: string = "[" + this.skinParts.join(",") + "]"; var skinPartVar: CpVariable = new CpVariable("_skinParts", Modifiers.M_PRIVATE, "Array<string>", skinPartStr, true); this.currentClass.addVariable(skinPartVar); var skinPartFunc: CpFunction = new CpFunction(); skinPartFunc.name = "skinParts"; skinPartFunc.modifierName = Modifiers.M_PUBLIC; skinPartFunc.isGet = true; skinPartFunc.returnType = "Array<string>"; var skinPartCB: CpCodeBlock = new CpCodeBlock(); skinPartCB.addReturn(this.currentClass.className + "._skinParts"); skinPartFunc.codeBlock = skinPartCB; this.currentClass.addFunction(skinPartFunc); } this.currentXML.$id = ""; //生成视图状态代码 this.createStates(this.currentXML); var states: Array<CpState>; var node: any = this.currentXML; var nodeClassName: string = this.exmlConfig.getClassNameById(node.localName, node.namespace); for (var itemName in node) { var value: string = node[itemName]; if (itemName.charAt(0) != "$") { continue; } itemName = itemName.substring(1); var index: number = itemName.indexOf("."); if (index != -1) { var key: string = itemName.substring(0, index); key = this.formatKey(key, value); var itemValue: string = this.formatValue(key, value, node); if (!itemValue) { continue; } var stateName: string = itemName.substr(index + 1); states = this.getStateByName(stateName, node); var stateLength: number = states.length; if (stateLength > 0) { for (var i: number = 0; i < stateLength; i++) { var state: CpState = states[i]; if (this.exmlConfig.isStyleProperty(key, nodeClassName)) { state.addOverride(new CpSetStyle("", key, itemValue)); } else { state.addOverride(new CpSetProperty("", key, itemValue)); } } } } } //打印视图状态初始化代码 if (this.stateCode.length > 0) { cb.addCodeLine("this.states = ["); var first: boolean = true; var indentStr: string = " "; var length: number = this.stateCode.length; for (var i: number = 0; i < length; i++) { state = this.stateCode[i]; if (first) first = false; else cb.addCodeLine(indentStr + ","); var codes: Array<any> = state.toCode().split("\n"); var codeIndex: number = 0; while (codeIndex < codes.length) { var code: string = codes[codeIndex]; if (code) cb.addCodeLine(indentStr + code); codeIndex++; } } cb.addCodeLine("];"); } this.currentClass.constructCode = cb; } /** * 是否含有includeIn和excludeFrom属性 */ private isStateNode(node: any): boolean { return node.hasOwnProperty("$includeIn") || node.hasOwnProperty("$excludeFrom"); } /** * 获取视图状态名称列表 */ private getStateNames(): void { var stateNames: Array<string> = this.stateNames; var states: Array<any>; var children = this.currentXML.children; if (children) { var length: number = children.length; for (var i: number = 0; i < length; i++) { var item: any = children[i]; if (item.localName == "states") { item.namespace = EXMLCompiler.W; states = item.children; break; } } } if (states == null) return; if (states.length == 0) { globals.warn(2102, this.exmlPath, this.getPropertyStr(item)); return; } length = states.length; for (i = 0; i < length; i++) { var state: any = states[i]; var stateGroups: Array<any> = []; if (state["$stateGroups"]) { var groups: Array<any> = state.$stateGroups.split(","); var len: number = groups.length; for (var j: number = 0; j < len; j++) { var group: string = groups[j].trim(); if (group) { if (stateNames.indexOf(group) == -1) { stateNames.push(group); } stateGroups.push(group); } } } var stateName: string = state.$name; if (stateNames.indexOf(stateName) == -1) { stateNames.push(stateName); } this.stateCode.push(new CpState(stateName, stateGroups)); } } /** * 解析视图状态代码 */ private createStates(parentNode: any): void { var items: Array<any> = parentNode.children; if (!items) { return; } var className: string = this.exmlConfig.getClassNameById(parentNode.localName, parentNode.namespace); var length: number = items.length; for (var i: number = 0; i < length; i++) { var node: any = items[i]; this.createStates(node); if (node.namespace == EXMLCompiler.W || !node.localName) { continue; } if (this.isProperty(node)) { var prop: string = node.localName; var index: number = prop.indexOf("."); var children: Array<any> = node.children; if (index == -1 || !children || children.length == 0) { continue; } var stateName: string = prop.substring(index + 1); prop = prop.substring(0, index); var type: string = this.exmlConfig.getPropertyType(prop, className); if (type == "Array") { this.exit(2013, this.exmlPath, this.getPropertyStr(node)); } if (children.length > 1) { this.exit(2011, this.exmlPath, prop, this.getPropertyStr(node)); } var firstChild: any = children[0]; this.createFuncForNode(firstChild); this.checkIdForState(firstChild); var value: string = "this." + firstChild.$id; states = this.getStateByName(stateName, node); var l: number = states.length; if (l > 0) { for (var j: number = 0; j < l; j++) { state = states[j]; if (this.exmlConfig.isStyleProperty(prop, className)) { state.addOverride(new CpSetStyle(parentNode.$id, prop, value)); } else { state.addOverride(new CpSetProperty(parentNode.$id, prop, value)); } } } } else if (this.containsState(node)) { var id: string = node.$id; var nodeClassName: string = this.exmlConfig.getClassNameById(node.localName, node.namespace); this.checkIdForState(node); var stateName: string; var states: Array<CpState>; var state: CpState; if (this.isStateNode(node)) { if (!this.isIVisualElement(node)) { this.exit(2007, this.exmlPath, this.toXMLString(node)); } var propertyName: string = ""; var parent: any = (node.parent); if (parent.localName == "Array") parent = parent.parent; if (this.isProperty(parent)) parent = parent.parent; if (parent && parent != this.currentXML) { propertyName = parent.$id; this.checkIdForState(parent); } var positionObj: any = this.findNearNodeId(node); var stateNames: Array<any> = []; if (node.hasOwnProperty("$includeIn")) { stateNames = node.$includeIn.split(","); } else { var excludeNames: Array<any> = node.$excludeFrom.split(","); var stateLength: number = excludeNames.length; for (var j: number = 0; j < stateLength; j++) { var name: string = excludeNames[j]; this.getStateByName(name, node);//检查exlcudeFrom是否含有未定义的视图状态名 } stateLength = this.stateCode.length; for (j = 0; j < stateLength; j++) { state = this.stateCode[j]; if (excludeNames.indexOf(state.name) == -1) stateNames.push(state.name); } } var len: number = stateNames.length; for (var k: number = 0; k < len; k++) { stateName = stateNames[k]; states = this.getStateByName(stateName, node); if (states.length > 0) { var l: number = states.length; for (var j: number = 0; j < l; j++) { state = states[j]; state.addOverride(new CpAddItems(id, propertyName, positionObj.position, positionObj.relativeTo)); } } } } var name: string; for (name in node) { var value: string = node[name]; if (name.charAt(0) != "$") { continue; } name = name.substring(1); var index: number = name.indexOf("."); if (index != -1) { var key: string = name.substring(0, index); key = this.formatKey(key, value); var value: string = this.formatValue(key, value, node); if (!value) { continue; } stateName = name.substr(index + 1); states = this.getStateByName(stateName, node); var l: number = states.length; if (l > 0) { for (var j: number = 0; j < l; j++) { state = states[j]; if (this.exmlConfig.isStyleProperty(key, nodeClassName)) { state.addOverride(new CpSetStyle(id, key, value)); } else { state.addOverride(new CpSetProperty(id, key, value)); } } } } } } } } /** * 检查指定的节点是否是显示对象 */ private isIVisualElement(node: any): boolean { var className: string = this.exmlConfig.getClassNameById(node.localName, node.namespace); var result: boolean = this.exmlConfig.isInstanceOf(className, "egret.gui.IVisualElement"); if (!result) { return false; } var parent: any = node.parent; if (!parent) { return false; } if (parent.localName == "Array") { parent = parent.parent; } if (!parent) { return false; } if (this.isProperty(parent)) { return (parent.localName == "elementsContent") } var prop: string = this.exmlConfig.getDefaultPropById(parent.localName, parent.namespace); return prop == "elementsContent"; } /** * 检查指定的ID是否创建了类成员变量,若没创建则为其创建。 */ private checkIdForState(node: any): void { if (!node || this.currentClass.containsVar(node.$id)) { return; } this.createVarForNode(node); var id: string = node.$id; var funcName: string = id + "_i"; var func: CpFunction = this.currentClass.getFuncByName(funcName); if (!func) return; var codeLine: string = "this." + id + " = t;"; var cb: CpCodeBlock = func.codeBlock; if (!cb) return; if (!cb.containsCodeLine(codeLine)) { cb.addCodeLineAt(codeLine, 1); } } /** * 通过视图状态名称获取对应的视图状态 */ private getStateByName(name: string, node: any): Array<CpState> { var states: Array<CpState> = []; var length: number = this.stateCode.length; for (var i: number = 0; i < length; i++) { var state: CpState = this.stateCode[i]; if (state.name == name) { if (states.indexOf(state) == -1) states.push(state); } else if (state.stateGroups.length > 0) { var found: boolean = false; var len: number = state.stateGroups.length; for (var j: number = 0; j < len; j++) { var g: string = state.stateGroups[j]; if (g == name) { found = true; break; } } if (found) { if (states.indexOf(state) == -1) states.push(state); } } } if (states.length == 0) { this.exit(2006, this.exmlPath, name, this.toXMLString(node)); } return states; } /** * 寻找节点的临近节点ID和位置 */ private findNearNodeId(node: any): any { var parentNode: any = node.parent; var targetId: string = ""; var postion: string; var index: number = -1; var totalCount: number = 0; var preItem: any; var afterItem: any; var found: boolean = false; var children: Array<any> = parentNode.children; var length: number = children.length; for (var i: number = 0; i < length; i++) { var item: any = children[i]; if (this.isProperty(item)) continue; if (item == node) { found = true; index = i; } else { if (found && !afterItem && !this.isStateNode(item)) { afterItem = item; } } if (!found && !this.isStateNode(item)) preItem = item; } if (index == 0) { postion = "first"; return { position: postion, relativeTo: targetId }; } if (index == length - 1) { postion = "last"; return { position: postion, relativeTo: targetId }; } if (afterItem) { postion = "before"; targetId = afterItem.$id; if (targetId) { this.checkIdForState(afterItem); return { position: postion, relativeTo: targetId }; } } return { position: "last", relativeTo: targetId }; } /** * 根据类名获取对应的包,并自动导入相应的包 */ private getPackageByNode(node: any): string { var moduleName: string = this.exmlConfig.getClassNameById(node.localName, node.namespace); if (!moduleName) { this.exit(2003, this.exmlPath, this.toXMLString(node)); } return moduleName; } /** * 检查变量是否是包名 */ private isPackageName(name: string): boolean { return name.indexOf(".") != -1; } } //=================代码生成工具类=================== class CodeBase { public constructor() { } public toCode(): string { return ""; } public indent: number = 0; /** * 获取缩进字符串 */ public getIndent(indent: number = -1): string { if (indent == -1) indent = this.indent; var str: string = ""; for (var i: number = 0; i < indent; i++) { str += " "; } return str; } } class CpArguments extends CodeBase { public constructor(name: string = "", type: string = "") { super(); this.name = name; this.type = type; } public name: string = ""; public type: string = ""; public toCode(): string { return this.name + ":" + this.type; } } class CpClass extends CodeBase { public constructor() { super(); this.indent = 1; } /** * 构造函数的参数列表 */ private argumentBlock: Array<any> = []; /** * 添加构造函数的参数 */ public addArgument(argumentItem: CodeBase): void { if (this.argumentBlock.indexOf(argumentItem) == -1) { this.argumentBlock.push(argumentItem); } } /** * 构造函数代码块 */ public constructCode: CpCodeBlock; /** * 类名 */ public className: string = "CpClass"; /** * 类所在的路径,用于计算reference的相对路径 */ public classPath: string = ""; /** * 包名 */ public moduleName: string = ""; /** * 父类类名 */ public superClass: string = ""; /** * 接口列表 */ private interfaceBlock: Array<any> = []; /** * 添加接口 */ public addInterface(interfaceName: string): void { if (interfaceName == null || interfaceName == "") return; if (this.interfaceBlock.indexOf(interfaceName) == -1) { this.interfaceBlock.push(interfaceName); } } /** * 引用文件区块 */ private referenceBlock: Array<any> = []; /** * 引用一个文件 */ public addReference(referenceItem: string): void { if (referenceItem == null || referenceItem == "") return; if (this.referenceBlock.indexOf(referenceItem) == -1) { this.referenceBlock.push(referenceItem); } } /** * 变量定义区块 */ private variableBlock: Array<any> = []; /** * 添加变量 */ public addVariable(variableItem: CodeBase): void { if (this.variableBlock.indexOf(variableItem) == -1) { this.variableBlock.push(variableItem); } } /** * 根据变量名获取变量定义 */ public getVariableByName(name: string): CpVariable { var list: Array<any> = this.variableBlock; var length: number = list.length; for (var i: number; i < length; i++) { var item: CpVariable = list[i]; if (item.name == name) { return item; } } return null; } /** * 是否包含指定名称的变量 */ public containsVar(name: string): boolean { var list: Array<any> = this.variableBlock; var length: number = list.length; for (var i: number = 0; i < length; i++) { var item: CpVariable = list[i]; if (item.name == name) { return true; } } return false; } private sortOn(list: Array<any>, key: string, reverse: boolean = false): void { var length: number = list.length; for (var i: number = 0; i < length; i++) { var min: number = i; for (var j: number = i + 1; j < length; j++) { if (reverse) { if (list[j][key] > list[min][key]) min = j; } else { if (list[j][key] < list[min][key]) min = j; } } if (min != i) { var temp: any = list[min]; list[min] = list[i]; list[i] = temp; } } } /** * 函数定义区块 */ private functionBlock: Array<any> = []; /** * 添加函数 */ public addFunction(functionItem: CodeBase): void { if (this.functionBlock.indexOf(functionItem) == -1) { this.functionBlock.push(functionItem); } } /** * 是否包含指定名称的函数 */ public containsFunc(name: string): boolean { var list: Array<any> = this.functionBlock; var length: number = list.length; for (var i: number = 0; i < length; i++) { var item: CpFunction = list[i]; if (item.name == name) { return true; } } return false; } /** * 根据函数名返回函数定义块 */ public getFuncByName(name: string): CpFunction { var list: Array<any> = this.functionBlock; var length: number = list.length; for (var i: number = 0; i < length; i++) { var item: CpFunction = list[i]; if (item.name == name) { return item; } } return null; } /** * 类注释 */ public notation: CpNotation; private getRelativePath(path: string): string { var curs: Array<any> = this.classPath.split("/"); var targets: Array<any> = path.split("/"); var length: number = Math.min(curs.length, targets.length - 1); var index: number = 0; for (var i: number = 0; i < length; i++) { var cur: String = curs[i]; var tar: String = targets[i]; if (cur != tar) { break; } index++; } var paths: Array<any> = []; length = curs.length; for (i = index; i < length - 1; i++) { paths.push(".."); } length = targets.length; for (i = index; i < length; i++) { paths.push(targets[i]); } return paths.join("/"); } public toCode(): string { //字符串排序 this.referenceBlock.sort(); this.sortOn(this.variableBlock, "name"); this.sortOn(this.variableBlock, "isStatic", true); this.sortOn(this.functionBlock, "name"); this.sortOn(this.functionBlock, "isGet", true); var isFirst: boolean = true; if (this.moduleName) { this.indent = 1; } else { this.indent = 0; } var indentStr: string = this.getIndent(); var returnStr: string = ""; //打印文件引用区域 var index: number = 0; while (index < this.referenceBlock.length) { var importItem: string = this.referenceBlock[index]; var path: string = this.getRelativePath(importItem); returnStr += "/// <reference path=\"" + path + "\"/>\n"; index++; } if (returnStr) returnStr += "\n"; var exportStr: string = ""; //打印包名 if (this.moduleName) { returnStr += KeyWords.KW_MODULE + " " + this.moduleName + "{\n"; exportStr = KeyWords.KW_EXPORT + " "; } //打印注释 if (this.notation != null) { this.notation.indent = this.indent; returnStr += this.notation.toCode() + "\n"; } returnStr += indentStr + exportStr + KeyWords.KW_CLASS + " " + this.className; //打印父类 if (this.superClass != null && this.superClass != "") { returnStr += " " + KeyWords.KW_EXTENDS + " " + this.superClass; } //打印接口列表 if (this.interfaceBlock.length > 0) { returnStr += " " + KeyWords.KW_IMPLEMENTS + " "; index = 0; while (this.interfaceBlock.length > index) { isFirst = true; var interfaceItem: string = this.interfaceBlock[index]; if (isFirst) { returnStr += interfaceItem; isFirst = false; } else { returnStr += "," + interfaceItem; } index++; } } returnStr += "{\n"; //打印变量列表 index = 0; while (this.variableBlock.length > index) { var variableItem: CodeBase = this.variableBlock[index]; variableItem.indent = this.indent + 1; returnStr += variableItem.toCode() + "\n"; index++; } returnStr += "\n"; //打印构造函数 returnStr += this.getIndent(this.indent + 1) + Modifiers.M_PUBLIC + " constructor("; isFirst = true; index = 0; while (this.argumentBlock.length > index) { var arg: CodeBase = this.argumentBlock[index]; if (isFirst) { returnStr += arg.toCode(); isFirst = false; } else { returnStr += "," + arg.toCode(); } index++; } returnStr += "){\n"; var indent2Str: string = this.getIndent(this.indent + 2); if (this.superClass != null && this.superClass != "") { returnStr += indent2Str + "super();\n"; } if (this.constructCode != null) { var codes: Array<any> = this.constructCode.toCode().split("\n"); index = 0; while (codes.length > index) { var code: string = codes[index]; returnStr += indent2Str + code + "\n"; index++; } } returnStr += this.getIndent(this.indent + 1) + "}\n\n"; //打印函数列表 index = 0; while (this.functionBlock.length > index) { var functionItem: CodeBase = this.functionBlock[index]; functionItem.indent = this.indent + 1; returnStr += functionItem.toCode() + "\n"; index++; } returnStr += indentStr + "}"; if (this.moduleName) { returnStr += "\n}"; } return returnStr; } } class CpCodeBlock extends CodeBase { public constructor() { super(); this.indent = 0; } /** * 添加变量声明语句 * @param name 变量名 * @param type 变量类型 * @param value 变量初始值 */ public addVar(name: string, type: string, value: string = ""): void { var valueStr: string = ""; if (value != null && value != "") { valueStr = " = " + value; } this.addCodeLine(KeyWords.KW_VAR + " " + name + ":" + type + valueStr + ";"); } /** * 添加赋值语句 * @param target 要赋值的目标 * @param value 值 * @param prop 目标的属性(用“.”访问),不填则是对目标赋值 */ public addAssignment(target: string, value: string, prop: string = ""): void { var propStr: string = ""; if (prop != null && prop != "") { propStr = "." + prop; } this.addCodeLine(target + propStr + " = " + value + ";"); } /** * 添加返回值语句 */ public addReturn(data: string): void { this.addCodeLine(KeyWords.KW_RETURN + " " + data + ";"); } /** * 添加一条空行 */ public addEmptyLine(): void { this.addCodeLine(""); } /** * 开始添加if语句块,自动调用startBlock(); */ public startIf(expression: string): void { this.addCodeLine("if(" + expression + ")"); this.startBlock(); } /** * 开始else语句块,自动调用startBlock(); */ public startElse(): void { this.addCodeLine("else"); this.startBlock(); } /** * 开始else if语句块,自动调用startBlock(); */ public startElseIf(expression: string): void { this.addCodeLine("else if(" + expression + ")"); this.startBlock(); } /** * 添加一个左大括号,开始新的语句块 */ public startBlock(): void { this.addCodeLine("{"); this.indent++; } /** * 添加一个右大括号,结束当前的语句块 */ public endBlock(): void { this.indent--; this.addCodeLine("}"); } /** * 添加执行函数语句块 * @param functionName * @param args */ public doFunction(functionName: string, args: Array<any>): void { var argsStr: string = ""; var isFirst: boolean = true; while (args.length > 0) { var arg: string = args.shift(); if (isFirst) { argsStr += arg; } else { argsStr += "," + arg; } } this.addCodeLine(functionName + "(" + argsStr + ")"); } private lines: Array<any> = []; /** * 添加一行代码 */ public addCodeLine(code: string): void { this.lines.push(this.getIndent() + code); } /** * 添加一行代码到指定行 */ public addCodeLineAt(code: string, index: number): void { this.lines.splice(index, 0, this.getIndent() + code); } /** * 是否存在某行代码内容 */ public containsCodeLine(code: string): boolean { return this.lines.indexOf(code) != -1; } /** * 在结尾追加另一个代码块的内容 */ public concat(cb: CpCodeBlock): void { this.lines = this.lines.concat(cb.lines); } public toCode(): string { return this.lines.join("\n"); } } class CpFunction extends CodeBase { public constructor() { super(); this.indent = 2 } /** * 修饰符 ,默认Modifiers.M_PRIVATE */ public modifierName: string = Modifiers.M_PRIVATE; /** * 代码块 */ public codeBlock: CpCodeBlock; /** * 是否是静态 ,默认false */ public isStatic: boolean = false; public isSet: boolean = false; public isGet: boolean = false; /** *参数列表 */ private argumentBlock: Array<any> = []; /** * 添加参数 */ public addArgument(argumentItem: CodeBase): void { if (this.argumentBlock.indexOf(argumentItem) == -1) { this.argumentBlock.push(argumentItem); } } /** * 函数注释 */ public notation: CpNotation; /** * 函数名 */ public name: string = ""; public returnType: string = DataType.DT_VOID; public toCode(): string { var index: number = 0; var indentStr: string = this.getIndent(); var staticStr: string = this.isStatic ? Modifiers.M_STATIC + " " : ""; var noteStr: string = ""; if (this.notation != null) { this.notation.indent = this.indent; noteStr = this.notation.toCode() + "\n"; } var getSetStr: string = ""; if (this.isGet) { getSetStr = "get "; } else if (this.isSet) { getSetStr = "set "; } var returnStr: string = noteStr + indentStr + this.modifierName + " " + staticStr + getSetStr + this.name + "("; var isFirst: boolean = true; index = 0; while (this.argumentBlock.length > index) { var arg: CodeBase = this.argumentBlock[index]; if (isFirst) { returnStr += arg.toCode(); isFirst = false; } else { returnStr += "," + arg.toCode(); } index++; } returnStr += ")"; if (this.returnType != "") returnStr += ":" + this.returnType; returnStr += "{\n"; if (this.codeBlock != null) { var lines: Array<any> = this.codeBlock.toCode().split("\n"); var codeIndent: string = this.getIndent(this.indent + 1); index = 0; while (lines.length > index) { var line: string = lines[index]; returnStr += codeIndent + line + "\n"; index++; } } returnStr += indentStr + "}"; return returnStr; } } class CpNotation extends CodeBase { public constructor(notation: string = "") { super(); this.notation = notation; } public notation: string = ""; public toCode(): string { var lines: Array<any> = this.notation.split("\n"); var firstIndent: string = this.getIndent(); var secondIndent: string = firstIndent + " "; var returnStr: string = firstIndent + "/**\n"; var line: string; while (lines.length > 0) { line = lines.shift(); returnStr += secondIndent + "* " + line + "\n"; } returnStr += secondIndent + "*/"; return returnStr; } } //=================常量定义=================== class CpVariable extends CodeBase { public constructor(name: string = "varName", modifierName: string = "public", type: string = "any", defaultValue: string = "", isStatic: boolean = false) { super(); this.indent = 2; this.name = name; this.modifierName = modifierName; this.type = type; this.isStatic = isStatic; this.defaultValue = defaultValue; } /** * 修饰符 */ public modifierName: string = Modifiers.M_PUBLIC; /** * 是否是静态 */ public isStatic: boolean = false; /** * 常量名 */ public name: string = "varName"; /** * 默认值 */ public defaultValue: string = ""; /** * 数据类型 */ public type: string; /** * 变量注释 */ public notation: CpNotation; public toCode(): string { var noteStr: string = ""; if (this.notation != null) { this.notation.indent = this.indent; noteStr = this.notation.toCode() + "\n"; } var staticStr: string = this.isStatic ? Modifiers.M_STATIC + " " : ""; var valueStr: string = ""; if (this.defaultValue != "" && this.defaultValue != null) { valueStr = " = " + this.defaultValue; } return noteStr + this.getIndent() + this.modifierName + " " + staticStr + this.name + ":" + this.type + valueStr + ";"; } } class CpState extends CodeBase { public constructor(name: string, stateGroups: Array<any> = null) { super(); this.name = name; if (stateGroups) this.stateGroups = stateGroups; } /** * 视图状态名称 */ public name: string = ""; public stateGroups: Array<any> = []; public addItems: Array<any> = []; public setProperty: Array<any> = []; /** * 添加一个覆盖 */ public addOverride(item: CodeBase): void { if (item instanceof CpAddItems) this.addItems.push(item); else this.setProperty.push(item); } public toCode(): string { var indentStr: string = this.getIndent(1); var returnStr: string = "new egret.gui.State (\"" + this.name + "\",\n" + indentStr + "[\n"; var index: number = 0; var isFirst: boolean = true; var overrides: Array<any> = this.addItems.concat(this.setProperty); while (index < overrides.length) { if (isFirst) isFirst = false; else returnStr += ",\n"; var item: CodeBase = overrides[index]; var codes: Array<any> = item.toCode().split("\n"); var length: number = codes.length; for (var i: number = 0; i < length; i++) { var code: string = codes[i]; codes[i] = indentStr + indentStr + code; } returnStr += codes.join("\n"); index++; } returnStr += "\n" + indentStr + "])"; return returnStr; } } class CpAddItems extends CodeBase { public constructor(target: string, propertyName: string, position: string, relativeTo: string) { super(); this.target = target; this.propertyName = propertyName; this.position = position; this.relativeTo = relativeTo; } /** * 创建项目的工厂类实例 */ public target: string; /** * 要添加到的属性 */ public propertyName: string; /** * 添加的位置 */ public position: string; /** * 相对的显示元素 */ public relativeTo: string; public toCode(): string { var indentStr: string = this.getIndent(1); var returnStr: string = "new egret.gui.AddItems(\"" + this.target + "\",\"" + this.propertyName + "\",\"" + this.position + "\",\"" + this.relativeTo + "\")"; return returnStr; } } class CpSetProperty extends CodeBase { public constructor(target: string, name: string, value: string) { super(); this.target = target; this.name = name; this.value = value; } /** * 要修改的属性名 */ public name: string; /** * 目标实例名 */ public target: string; /** * 属性值 */ public value: string; public toCode(): string { var indentStr: string = this.getIndent(1); return "new egret.gui.SetProperty(\"" + this.target + "\",\"" + this.name + "\"," + this.value + ")"; } } class CpSetStyle extends CodeBase { public constructor(target: string, name: string, value: string) { super(); this.target = target; this.name = name; this.value = value; } /** * 要修改的属性名 */ public name: string; /** * 目标实例名 */ public target: string; /** * 属性值 */ public value: string; public toCode(): string { var indentStr: string = this.getIndent(1); return "new egret.gui.SetStyle(\"" + this.target + "\",\"" + this.name + "\"," + this.value + ")"; } } class DataType { public static DT_VOID: string = "void"; public static DT_NUMBER: string = "number"; public static DT_BOOLEAN: string = "boolean"; public static DT_ARRAY: string = "Array"; public static DT_STRING: string = "string"; public static DT_OBJECT: string = "Object"; public static DT_FUNCTION: string = "Function"; } class KeyWords { public static KW_CLASS: string = "class"; public static KW_FUNCTION: string = "function"; public static KW_VAR: string = "var"; public static KW_INTERFACE: string = "interface"; public static KW_EXTENDS: string = "extends"; public static KW_IMPLEMENTS: string = "implements"; public static KW_MODULE: string = "module"; public static KW_SUPER: string = "super"; public static KW_THIS: string = "this"; public static KW_OVERRIDE: string = "override"; public static KW_RETURN: string = "return"; public static KW_EXPORT: string = "export"; } class Modifiers { public static M_PUBLIC: string = "public"; public static M_PRIVATE: string = "private"; public static M_STATIC: string = "static"; }
the_stack
import { $log } from '@tsed/logger'; import { BigNumber } from 'bignumber.js'; import moment from 'moment'; import { bootstrap, TestTz } from '../bootstrap-sandbox'; import { Contract, bytes, address } from '../../src/type-aliases'; import { MintNftParam, originateFtFaucet, originateNftFaucet, originateEnglishAuctionFA2, MintFtParam, } from '../../src/nft-contracts'; import { MichelsonMap } from '@taquito/taquito'; import { addOperator } from '../../src/fa2-interface'; import { Fa2_token, Tokens, sleep } from '../../src/auction-interface'; import { queryBalancesWithLambdaView, getBalances, QueryBalances, hasTokens } from '../../test/fa2-balance-inspector'; jest.setTimeout(360000); // 6 minutes describe('test NFT auction', () => { let tezos: TestTz; let nftAuction: Contract; let nftAuctionBob : Contract; let nftAuctionAlice : Contract; let nftAuctionEve : Contract; let nftContract : Contract; let ftContract : Contract; let bobAddress : address; let aliceAddress : address; let eveAddress : address; let startTime : Date; let endTime : Date; let tokenIdNft : BigNumber; let tokenIdBidToken : BigNumber; let empty_metadata_map : MichelsonMap<string, bytes>; let nft : MintNftParam; let bid_tokens_eve : MintFtParam; let bid_tokens_alice : MintFtParam; let queryBalances : QueryBalances; beforeAll(async () => { tezos = await bootstrap(); empty_metadata_map = new MichelsonMap(); tokenIdNft = new BigNumber(1); tokenIdBidToken = new BigNumber(0); eveAddress = await tezos.eve.signer.publicKeyHash(); aliceAddress = await tezos.alice.signer.publicKeyHash(); bobAddress = await tezos.bob.signer.publicKeyHash(); nft = { token_metadata: { token_id: tokenIdNft, token_info: empty_metadata_map, }, owner: bobAddress, }; bid_tokens_eve = { token_id: tokenIdBidToken, owner: eveAddress, amount : new BigNumber(300), }; bid_tokens_alice = { token_id: tokenIdBidToken, owner: aliceAddress, amount : new BigNumber(300), }; queryBalances = queryBalancesWithLambdaView(tezos.lambdaView); }); beforeEach(async() =>{ $log.info('originating nft faucet...'); nftContract = await originateNftFaucet(tezos.bob); $log.info('originating ft faucet...'); ftContract = await originateFtFaucet(tezos.bob); $log.info('minting nft'); const opMintNft = await nftContract.methods.mint([nft]).send(); await opMintNft.confirmation(); $log.info(`Minted nft. Consumed gas: ${opMintNft.consumedGas}`); $log.info('creating fa2 for bids'); const opCreateFA2 = await ftContract.methods.create_token(tokenIdBidToken, empty_metadata_map).send(); await opCreateFA2.confirmation(); $log.info(`Created FA2 Consumed gas: ${opCreateFA2.consumedGas}`); $log.info('minting fa2 for bids'); const opMintFA2 = await ftContract.methods.mint_tokens([bid_tokens_alice, bid_tokens_eve]).send(); await opMintFA2.confirmation(); $log.info(`Minted FA2. Consumed gas: ${opMintFA2.consumedGas}`); $log.info('originating nft auction with payment in FA2...'); nftAuction = await originateEnglishAuctionFA2(tezos.bob, ftContract.address, tokenIdBidToken); nftAuctionBob = await tezos.bob.contract.at(nftAuction.address); nftAuctionAlice = await tezos.alice.contract.at(nftAuction.address); nftAuctionEve = await tezos.eve.contract.at(nftAuction.address); $log.info('adding auction contract as operator for nft'); await addOperator(nftContract.address, tezos.bob, nftAuction.address, tokenIdNft); $log.info('Auction contract added as operator for nft'); $log.info('adding auction contract as operator for bid token for alice'); await addOperator(ftContract.address, tezos.alice, nftAuction.address, tokenIdBidToken); $log.info('Auction contract added as operator for bid token'); $log.info('adding auction contract as operator for bid token for eve'); await addOperator(ftContract.address, tezos.eve, nftAuction.address, tokenIdBidToken); $log.info('Auction contract added as operator for bid token for eve'); const fa2_token : Fa2_token = { token_id : tokenIdNft, amount : new BigNumber(1), }; const tokens : Tokens = { fa2_address : nftContract.address, fa2_batch : [fa2_token], }; startTime = moment.utc().add(7, 'seconds').toDate(); endTime = moment(startTime).add(1, 'minute').toDate(); $log.info(`Configuring auction`); const opAuction = await nftAuctionBob.methods.configure( //opening price = 1 new BigNumber(10), //percent raise =10 new BigNumber(10), //min_raise = 10 new BigNumber(10), //round_time = 1 hr new BigNumber(3600), //extend_time = 0 seconds new BigNumber(0), //asset [tokens], //start_time = now + 7seconds startTime, //end_time = start_time + 1minute, endTime, ).send({ amount : 0 }); await opAuction.confirmation(); $log.info(`Auction configured. Consumed gas: ${opAuction.consumedGas}`); await sleep(7000); //7 seconds }); test('NFT is held by the auction contract after configuration', async() => { const [auctionHasNft] = await hasTokens([ { owner: nftAuction.address, token_id: tokenIdNft }, ], queryBalances, nftContract); expect(auctionHasNft).toBe(true); }); test('bid of less than asking price should fail', async() => { $log.info(`Alice bids 9 tokens expecting it to fail`); const failedOpeningBid = nftAuctionAlice.methods.bid(0, 9).send({ amount : 0 }); //TODO: test contents of error message return expect(failedOpeningBid).rejects.toHaveProperty('errors'); }); test('place bid meeting opening price and then raise it by valid amount by min_raise_percent', async () => { $log.info(`Alice bids 10 token`); const opBid = await nftAuctionAlice.methods.bid(0, 10).send({ amount : 0 }); await opBid.confirmation(); $log.info(`Bid placed`); $log.info(`Eve bids 11 tokens`); const opBid2 = await nftAuctionEve.methods.bid(0, 11).send({ amount : 0 }); await opBid2.confirmation(); $log.info(`Bid placed`); }); test('place bid meeting opening price and then raise it by valid amount by min_raise', async () => { $log.info(`Alice bids 200 tokens`); const opBid = await nftAuctionAlice.methods.bid(0, 200).send({ amount : 0 }); await opBid.confirmation(); $log.info(`Bid placed`); $log.info(`Eve bids 210 tokens, a 10 token increase but less than a 10% raise of previous bid `); const opBid2 = await nftAuctionEve.methods.bid(0, 210).send({ amount : 0 }); await opBid2.confirmation(); $log.info(`Bid placed.`); }); test('bid too small should fail', async () => { $log.info(`Alice bids 20 tokens`); const opBid = await nftAuctionAlice.methods.bid(0, 20).send({ amount : 0 }); await opBid.confirmation(); $log.info(`Bid placed`); $log.info(`Eve bids 21 tokens and we expect it to fail`); const smallBidPromise = nftAuctionEve.methods.bid(0, 21).send({ amount : 0 }); return expect(smallBidPromise).rejects.toHaveProperty('errors' ); }); test('auction without bids that is cancelled should only return asset', async () => { const [aliceBalanceBefore, bobBalanceBefore] = await getBalances([ { owner: aliceAddress, token_id: tokenIdBidToken }, { owner: bobAddress, token_id: tokenIdBidToken }, ], queryBalances, ftContract); $log.info(`Alices's balance is ${aliceBalanceBefore.toNumber()} and Bob's is ${bobBalanceBefore.toNumber()} `); $log.info("Cancelling auction"); const opCancel = await nftAuctionBob.methods.cancel(0).send({ amount : 0, mutez : true }); await opCancel.confirmation(); $log.info("Auction cancelled"); const [aliceBalanceAfter, bobBalanceAfter] = await getBalances([ { owner: aliceAddress, token_id: tokenIdBidToken }, { owner: bobAddress, token_id: tokenIdBidToken }, ], queryBalances, ftContract); $log.info(`Bob's balance is ${bobBalanceAfter.toNumber()} and Alice's is ${aliceBalanceAfter.toNumber()}`); expect(aliceBalanceBefore.eq(aliceBalanceAfter)).toBe(true); expect(bobBalanceBefore.eq(bobBalanceAfter)).toBe(true); $log.info("Bids returned as expected"); const [sellerHasNft, auctionHasNft] = await hasTokens([ { owner: bobAddress, token_id: tokenIdNft }, { owner: nftAuction.address, token_id: tokenIdNft }, ], queryBalances, nftContract); expect(sellerHasNft).toBe(true); expect(auctionHasNft).toBe(false); $log.info(`NFT returned as expected`); }); test('auction with bid that is cancelled should return asset and bid', async () => { const [aliceBalanceBefore, bobBalanceBefore] = await getBalances([ { owner: aliceAddress, token_id: tokenIdBidToken }, { owner: bobAddress, token_id: tokenIdBidToken }, ], queryBalances, ftContract); $log.info(`Bob's balance is ${bobBalanceBefore.toNumber()} and Alice's is ${aliceBalanceBefore.toNumber()}`); $log.info(`Alice bids 200 tokens`); const alicesBid = new BigNumber(200); const opBid = await nftAuctionAlice.methods.bid(0, alicesBid.toNumber()).send({ amount : 0 }); await opBid.confirmation(); $log.info(`Bid placed`); $log.info("Cancelling auction should return asset and highest bid"); const opCancel = await nftAuctionBob.methods.cancel(0).send({ amount : 0, mutez : true }); await opCancel.confirmation(); $log.info("Auction cancelled"); const [aliceBalanceAfter, bobBalanceAfter] = await getBalances([ { owner: aliceAddress, token_id: tokenIdBidToken }, { owner: bobAddress, token_id: tokenIdBidToken }, ], queryBalances, ftContract); $log.info(`Bob's balance is ${bobBalanceAfter.toNumber()} and Alice's is ${aliceBalanceAfter.toNumber()}`); expect(aliceBalanceBefore.eq(aliceBalanceAfter)).toBe(true); expect(bobBalanceBefore.eq(bobBalanceAfter)).toBe(true); $log.info("Bids returned as expected"); const [sellerHasNft, auctionHasNft] = await hasTokens([ { owner: bobAddress, token_id: tokenIdNft }, { owner: nftAuction.address, token_id: tokenIdNft }, ], queryBalances, nftContract); expect(sellerHasNft).toBe(true); expect(auctionHasNft).toBe(false); $log.info(`NFT returned as expected`); }); test('auction resolved before end time should fail', async () => { $log.info(`Alice bids 200 tokens`); const alicesBid = new BigNumber(200); const opBid = await nftAuctionAlice.methods.bid(0, alicesBid.toNumber()).send({ amount : 0 }); await opBid.confirmation(); $log.info(`Bid placed`); $log.info("Resolving auction"); const opResolve = nftAuctionBob.methods.resolve(0).send({ amount : 0 }); expect(opResolve).rejects.toHaveProperty('message', 'AUCTION_NOT_ENDED'); }); test('auction without bids that is resolved after end time should only return asset to seller', async () => { const [aliceBalanceBefore, bobBalanceBefore] = await getBalances([ { owner: aliceAddress, token_id: tokenIdBidToken }, { owner: bobAddress, token_id: tokenIdBidToken }, ], queryBalances, ftContract); await sleep(70000); //70 seconds $log.info("Resolving auction"); const opResolve = await nftAuctionBob.methods.resolve(0).send({ amount : 0 }); await opResolve.confirmation(); const [sellerHasNft] = await hasTokens([ { owner: bobAddress, token_id: tokenIdNft }, ], queryBalances, nftContract); expect(sellerHasNft).toBe(true); $log.info(`NFT returned as expected`); const [aliceBalanceAfter, bobBalanceAfter] = await getBalances([ { owner: aliceAddress, token_id: tokenIdBidToken }, { owner: bobAddress, token_id: tokenIdBidToken }, ], queryBalances, ftContract); $log.info(`Bob's balance is ${bobBalanceAfter.toNumber()} and Alice's is ${aliceBalanceAfter.toNumber()}`); expect(aliceBalanceBefore.eq(aliceBalanceAfter)).toBe(true); expect(bobBalanceBefore.eq(bobBalanceAfter)).toBe(true); $log.info("Balances are the same before and after auction as expected"); }); test('auction cancelled after end time should fail', async () => { const alicesBid = new BigNumber(200); const opBid = await nftAuctionAlice.methods.bid(0, alicesBid.toNumber()).send({ amount : 0 }); await opBid.confirmation(); $log.info(`Bid placed`); await sleep(70000); //70 seconds const opCancel = nftAuctionBob.methods.cancel(0).send({ amount : 0, mutez : true }); expect(opCancel).rejects.toHaveProperty('message', 'AUCTION_ENDED'); }); test('resolved auction should send asset to buyer and highest bid to seller', async () => { const [aliceBalanceBefore, bobBalanceBefore] = await getBalances([ { owner: aliceAddress, token_id: tokenIdBidToken }, { owner: bobAddress, token_id: tokenIdBidToken }, ], queryBalances, ftContract); $log.info(`Bob's balance is ${bobBalanceBefore.toNumber()} and Alice's is ${aliceBalanceBefore.toNumber()}`); $log.info(`Alice bids 200 tokens`); const alicesBid = new BigNumber(200); const opBid = await nftAuctionAlice.methods.bid(0, alicesBid.toNumber()).send({ amount : 0 }); await opBid.confirmation(); $log.info(`Bid placed`); await sleep(70000); //70 seconds $log.info("Resolving auction"); const opResolve = await nftAuctionBob.methods.resolve(0).send({ amount : 0 }); await opResolve.confirmation(); $log.info("Auction Resolve"); const [aliceBalanceAfter, bobBalanceAfter] = await getBalances([ { owner: aliceAddress, token_id: tokenIdBidToken }, { owner: bobAddress, token_id: tokenIdBidToken }, ], queryBalances, ftContract); $log.info(`Bob's balance is ${bobBalanceAfter.toNumber()} and Alice's is ${aliceBalanceAfter.toNumber()}`); expect(aliceBalanceBefore.eq(aliceBalanceAfter.plus(alicesBid))).toBe(true); expect(bobBalanceBefore.eq(bobBalanceAfter.minus(alicesBid))).toBe(true); $log.info("Bids returned as expected"); const [sellerHasNft, auctionHasNft, buyerHasNft] = await hasTokens([ { owner: bobAddress, token_id: tokenIdNft }, { owner: nftAuction.address, token_id: tokenIdNft }, { owner: aliceAddress, token_id: tokenIdNft }, ], queryBalances, nftContract); expect(sellerHasNft).toBe(false); expect(auctionHasNft).toBe(false); expect(buyerHasNft).toBe(true); $log.info(`NFT returned as expected`); }); });
the_stack
//Set to false to test remotely even when running it locally const TEST_LOCAL_DEFAULT = true; const TEST_LOCAL: boolean = hasSetting('remote') || !!process.env.TRAVIS ? false : TEST_LOCAL_DEFAULT; const TIME_MODIFIER = 1.2; const LOCAL_URL = 'http://localhost:9515'; function hasSetting(setting: string) { return process.argv.indexOf(`--${setting}`) > -1; } import * as firefoxExtensionData from './UI/drivers/firefox-extension'; import * as chromeExtensionData from './UI/drivers/chrome-extension'; import * as operaExtensionData from './UI/drivers/opera-extension'; import * as edgeExtensionData from './UI/drivers/edge-extension'; import * as webdriver from 'selenium-webdriver'; import * as chai from 'chai'; import { TypedWebdriver, BrowserstackCapabilities, wait, findElement, inlineFn, tryReadManifest, getGitHash, setTimeModifier, setDriver } from './imports'; require('mocha-steps'); const request = require('request'); const _promise = global.Promise; global.Promise = webdriver.promise.Promise; const assert = chai.assert; let driver: TypedWebdriver; function arrContains<T>(arr: ArrayLike<T>, fn: (item: T) => boolean): T { for (const item of Array.prototype.slice.apply(arr)) { if (fn(item)) { return item; } } return null; } function getCapabilities(): BrowserstackCapabilities { let secrets: { user: string; key: string; }; if (!TEST_LOCAL) { secrets = require('./UI/secrets'); } else { secrets = { user: '', key: '' } } if (process.argv.indexOf('--chrome-latest') > -1) { return { 'browserName' : 'Chrome', 'os' : 'Windows', 'os_version' : '10', 'resolution' : '1920x1080', 'browserstack.user' : secrets.user, 'browserstack.key' : secrets.key, 'browserstack.local': true, 'browserstack.debug': process.env.BROWSERSTACK_LOCAL_IDENTIFIER ? false : true, 'browserstack.localIdentifier': process.env.BROWSERSTACK_LOCAL_IDENTIFIER } } if (arrContains<string>(process.argv, str => str.indexOf('--chrome-') > -1)) { const chromeStr = arrContains<string>(process.argv, str => str.indexOf('--chrome-') > -1); const chromeVersion = chromeStr.split('--chrome-')[1]; return { 'browserName' : 'Chrome', 'browser_version': `${chromeVersion}.0`, 'os' : 'Windows', 'os_version' : '8.1', 'resolution' : '1920x1080', 'browserstack.user' : secrets.user, 'browserstack.key' : secrets.key, 'browserstack.local': true, 'browserstack.debug': process.env.BROWSERSTACK_LOCAL_IDENTIFIER ? false : true, 'browserstack.localIdentifier': process.env.BROWSERSTACK_LOCAL_IDENTIFIER } } if (process.argv.indexOf('--firefox-quantum') > -1) { return { 'browserName' : 'Firefox', 'browser_version': '57.0', 'os' : 'Windows', 'os_version' : '10', 'resolution' : '1920x1080', 'browserstack.user' : secrets.user, 'browserstack.key' : secrets.key, 'browserstack.local': true, 'browserstack.debug': process.env.BROWSERSTACK_LOCAL_IDENTIFIER ? false : true, 'browserstack.localIdentifier': process.env.BROWSERSTACK_LOCAL_IDENTIFIER } } if (process.argv.indexOf('--firefox-latest') > -1) { return { 'browserName' : 'Firefox', 'os' : 'Windows', 'os_version' : '10', 'resolution' : '1920x1080', 'browserstack.user' : secrets.user, 'browserstack.key' : secrets.key, 'browserstack.local': true, 'browserstack.debug': process.env.BROWSERSTACK_LOCAL_IDENTIFIER ? false : true, 'browserstack.localIdentifier': process.env.BROWSERSTACK_LOCAL_IDENTIFIER } } if (arrContains<string>(process.argv, str => str.indexOf('--firefox-') > -1)) { const firefoxStr = arrContains<string>(process.argv, str => str.indexOf('--firefox-') > -1); const firefoxVersion = firefoxStr.split('--firefox-')[1]; return { 'browserName' : 'Firefox', 'browser_version': `${firefoxVersion}.0`, 'os' : 'Windows', 'os_version' : '10', 'resolution' : '1920x1080', 'browserstack.user' : secrets.user, 'browserstack.key' : secrets.key, 'browserstack.local': true, 'browserstack.debug': process.env.BROWSERSTACK_LOCAL_IDENTIFIER ? false : true, 'browserstack.localIdentifier': process.env.BROWSERSTACK_LOCAL_IDENTIFIER } } if (process.argv.indexOf('--edge-latest') > -1) { return { 'browserName' : 'Edge', 'os' : 'Windows', 'os_version' : '10', 'resolution' : '1920x1080', 'browserstack.user' : secrets.user, 'browserstack.key' : secrets.key, 'browserstack.local': true, 'browserstack.debug': process.env.BROWSERSTACK_LOCAL_IDENTIFIER ? false : true, 'browserstack.localIdentifier': process.env.BROWSERSTACK_LOCAL_IDENTIFIER } } if (arrContains<string>(process.argv, str => str.indexOf('--edge-') > -1)) { const edgeStr = arrContains<string>(process.argv, str => str.indexOf('--edge-') > -1); const edgeVersion = edgeStr.split('--edge-')[1]; return { 'browserName' : 'Edge', 'browser_version': `${edgeVersion}.0`, 'os' : 'Windows', 'os_version' : '10', 'resolution' : '1920x1080', 'browserstack.user' : secrets.user, 'browserstack.key' : secrets.key, 'browserstack.local': true, 'browserstack.debug': process.env.BROWSERSTACK_LOCAL_IDENTIFIER ? false : true, 'browserstack.localIdentifier': process.env.BROWSERSTACK_LOCAL_IDENTIFIER } } if (process.argv.indexOf('--opera-latest') > -1) { return { 'browserName' : 'Opera', 'os' : 'Windows', 'os_version' : '10', 'resolution' : '1920x1080', 'browserstack.user' : secrets.user, 'browserstack.key' : secrets.key, 'browserstack.local': true, 'browserstack.debug': process.env.BROWSERSTACK_LOCAL_IDENTIFIER ? false : true, 'browserstack.localIdentifier': process.env.BROWSERSTACK_LOCAL_IDENTIFIER } } if (arrContains<string>(process.argv, str => str.indexOf('--opera-') > -1)) { const operaStr = arrContains<string>(process.argv, str => str.indexOf('--opera-') > -1); const operaVersion = operaStr.split('--opera-')[1]; return { 'browserName' : 'Opera', 'browser_version': `${operaVersion}.0`, 'os' : 'Windows', 'os_version' : '10', 'resolution' : '1920x1080', 'browserstack.user' : secrets.user, 'browserstack.key' : secrets.key, 'browserstack.local': true, 'browserstack.debug': process.env.BROWSERSTACK_LOCAL_IDENTIFIER ? false : true, 'browserstack.localIdentifier': process.env.BROWSERSTACK_LOCAL_IDENTIFIER } } if (TEST_LOCAL) { return {} as any; } console.error('Please specify a browser version to test'); console.error('Choose from:'); console.error('\n--chrome-latest\n--chrome-{version}\n--firefox-quantum') console.error('--firefox-latest\n--edge-16\n--edge-latest\n--opera-51\n--opera-latest') process.exit(1); return {} as any; } type InstallTest = 'greasyfork'|'openuserjs'|'userscripts.org'|'userstyles.org'|'openusercss'; function getTest(): InstallTest { const index = process.argv.indexOf('--test'); if (index === -1 || (!process.argv[index + 1])) { console.error('Please specify a test to run through --test'); console.error('Choose from:'); console.error('Greasyfork, openuserjs, userscripts.org, userstyles.org or openusercss'); process.exit(1); return null; } const test = process.argv[index + 1]; switch (test) { case 'greasyfork': case 'openuserjs': case 'userscripts.org': case 'userstyles.org': case 'openusercss': return test; default: console.error('Unsupported test passed, please choose one of:'); console.error('Greasyfork, openuserjs, userscripts.org, userstyles.org or openusercss'); process.exit(1); return null; } } const browserCapabilities = getCapabilities(); function getBrowser(): 'Chrome'|'Firefox'|'Edge'|'Opera' { return browserCapabilities.browserName || 'Chrome' as any } function getExtensionData() { const browser = getBrowser(); switch (browser) { case 'Chrome': return chromeExtensionData; case 'Firefox': return firefoxExtensionData; case 'Edge': return edgeExtensionData; case 'Opera': return operaExtensionData; } } function beforeUserscriptInstall(url: string) { it('should be possible to navigate to the page', async function() { this.timeout(600000 * TIME_MODIFIER); this.slow(600000 * TIME_MODIFIER); await driver.get(url); }); } function installScriptFromInstallPage(getConfig: () => { prefix: string|void; url: string; href: string; title: string; }) { it('should be possible to open the install page', async function() { this.timeout(20000); this.slow(20000); const { prefix, url, href } = getConfig(); await driver.get(`${prefix}/html/install.html?i=${ encodeURIComponent(href) }&s=${url}`); await wait(5000); }); it('should be possible to click the "allow and install" button', async function() { this.timeout(20000); this.slow(15000); await wait(3000); await findElement(webdriver.By.tagName('install-page')) .findElement(webdriver.By.tagName('install-confirm')) .findElement(webdriver.By.id('acceptAndInstallbutton')) .click(); await wait(5000); }); it('should have been installed into the CRM', async function() { this.timeout(600000 * TIME_MODIFIER); this.slow(600000 * TIME_MODIFIER); const { prefix, href, title } = getConfig(); await driver.get(`${prefix}/html/options.html`); await wait(5000); const code = await new webdriver.promise.Promise<string>((resolve) => { request(href, (err: Error|void, res: XMLHttpRequest & { statusCode: number; }, body: string) => { assert.ifError(err, 'Should not fail the GET request'); if (res.statusCode === 200) { resolve(body); } else { assert.ifError(new Error('err'), 'Should get 200 statuscode' + ' when doing GET request'); } }).end(); }); const crm = JSON.parse(await driver.executeScript(inlineFn(() => { return JSON.stringify(window.app.settings.crm); }))); const node = crm[1] as CRM.ScriptNode; assert.strictEqual(node.type, 'script', 'node is of type script'); assert.strictEqual(node.name, title, 'names match'); assert.strictEqual(node.value.script, code, 'scripts match'); }); } function beforeUserstyleInstall(url: string) { it('should be possible to navigate to the page', async function() { this.timeout(600000 * TIME_MODIFIER); this.slow(600000 * TIME_MODIFIER); await driver.get(url); }); } function installStylesheetFromInstallPage(getConfig: () => { prefix: string|void; href: string; }) { it('should have been installed into the CRM', async function() { this.timeout(600000 * TIME_MODIFIER); this.slow(600000 * TIME_MODIFIER); const { prefix, href } = getConfig(); await driver.get(`${prefix}/html/options.html`); await wait(15000); let testName: boolean = true; let parsed: { md5Url :string; name: string; originalMd5: string; updateUrl: string; url: string; sections: { domains: string[]; regexps: string[]; urlPrefixes: string[]; urls: string[]; code: string; }[]; }; try { const descriptor = await new webdriver.promise.Promise<string>((resolve) => { request(href, (err: Error|void, res: XMLHttpRequest & { statusCode: number; }, body: string) => { assert.ifError(err, 'Should not fail the GET request'); if (res.statusCode === 200) { resolve(body); } else { assert.ifError(new Error('err'), 'Should get 200 statuscode' + ' when doing GET request'); } }).end(); }); parsed = JSON.parse(descriptor) as { md5Url :string; name: string; originalMd5: string; updateUrl: string; url: string; sections: { domains: string[]; regexps: string[]; urlPrefixes: string[]; urls: string[]; code: string; }[]; }; } catch(e) { testName = false; } const crm = JSON.parse(await driver.executeScript(inlineFn(() => { return JSON.stringify(window.app.settings.crm); }))); const node = crm[1] as CRM.StylesheetNode; assert.exists(node, 'node exists in CRM'); if (testName) { assert.strictEqual(node.type, 'stylesheet', 'node is of type stylesheet'); assert.strictEqual(node.name, parsed.name, 'names match'); assert.strictEqual(node.value.stylesheet, parsed.sections[0].code, 'stylesheets match'); } }); } function doGreasyForkTest(prefix: () => string|void) { describe('Installing from greasyfork', () => { const URL = 'https://greasyfork.org/en/scripts/35252-google-night-mode'; let href: string; let title: string; beforeUserscriptInstall(URL); it('should be possible to click the install link', async function() { this.timeout(20000); this.slow(15000); const button = await findElement(webdriver.By.className('install-link')); title = await findElement(webdriver.By.id('script-info')) .findElement(webdriver.By.tagName('header')) .findElement(webdriver.By.tagName('h2')) .getText(); assert.exists(button, 'Install link exists'); href = await button.getProperty('href') as string; const isUserScript = href.indexOf('.user.js') > -1; assert.isTrue(isUserScript, 'button leads to userscript'); }); //Generic logic installScriptFromInstallPage(() => { return { href, title, url: URL, prefix: prefix() } }); it('should be applied', async function() { this.timeout(600000 * TIME_MODIFIER); this.slow(600000 * TIME_MODIFIER); await driver.get('http://www.google.com'); await wait(5000); assert.strictEqual(await driver.executeScript(inlineFn(() => { return window.getComputedStyle(document.getElementById('viewport'))['backgroundColor']; })), 'rgb(51, 51, 51)', 'background color changed (script is applied)'); }); }); } function doOpenUserJsTest(prefix: () => string|void) { describe('Installing from OpenUserJS', () => { const URL = 'https://openuserjs.org/scripts/Ede_123/GitHub_Latest'; let href: string; let title: string; beforeUserscriptInstall(URL); it('should be possible to click the install link', async function() { this.timeout(20000); this.slow(15000); const button = await findElement(webdriver.By.tagName('h2')) .findElement(webdriver.By.tagName('a')); title = await findElement(webdriver.By.className('script-name')) .getText(); assert.exists(button, 'Install link exists'); href = await button.getProperty('href') as string; const isUserScript = href.indexOf('.user.js') > -1; assert.isTrue(isUserScript, 'button leads to userscript'); }); //Generic logic installScriptFromInstallPage(() => { return { href, title, url: URL, prefix: prefix() } }); it('should be applied', async function() { this.timeout(600000 * TIME_MODIFIER); this.slow(600000 * TIME_MODIFIER); await driver.get('https://github.com/SanderRonde/CustomRightClickMenu'); await wait(5000); assert.exists(await driver.executeScript(inlineFn(() => { return document.getElementById('latest-button'); })), 'element was created (script was applied)'); }); }); } function doUserScriptsOrgTest(prefix: () => string|void) { describe('installing from userscripts.org', () => { const URL = 'http://userscripts-mirror.org/scripts/show/175391'; let href: string; let title: string; beforeUserscriptInstall(URL); it('should be possible to click the install link', async function() { this.timeout(20000); this.slow(15000); const button = await findElement(webdriver.By.id('install_script')) .findElement(webdriver.By.tagName('a')); title = await findElement(webdriver.By.className('title')) .getText(); assert.exists(button, 'Install link exists'); href = await button.getProperty('href') as string; const isUserScript = href.indexOf('.user.js') > -1; assert.isTrue(isUserScript, 'button leads to userscript'); }); //Generic logic installScriptFromInstallPage(() => { return { href, title, url: URL, prefix: prefix() } }); it('should be applied', async function() { this.timeout(600000 * TIME_MODIFIER); this.slow(600000 * TIME_MODIFIER); await driver.get('https://www.youtube.com'); await wait(5000); assert.strictEqual(await driver.executeScript(inlineFn(() => { return window.getComputedStyle(document.body)['backgroundColor']; })), 'rgb(0, 0, 0)', 'background color changed (script is applied)'); }); }); } function doUserStylesOrgTest(prefix: () => string|void) { describe('Userstyles.org', () => { const URL = 'https://userstyles.org/styles/144028/google-clean-dark'; let href: string; beforeUserstyleInstall(URL); it('should be possible to click the install link', async function() { this.timeout(20000); this.slow(15000); await wait(500); const button = await findElement(webdriver.By.id('install_style_button')); assert.exists(button, 'Install link exists'); href = await driver.executeScript(inlineFn(() => { var e = document.querySelector("link[rel='stylish-code-chrome']"); return e ? e.getAttribute("href") : null; })); await button.click(); await wait(5000); const isUserStyle = href.indexOf('.json') > -1; assert.isTrue(isUserStyle, 'button leads to userstyle'); }); //Generic logic installStylesheetFromInstallPage(() => { return { href, prefix: prefix() } }); it('should be applied', async function() { this.timeout(600000 * TIME_MODIFIER); this.slow(600000 * TIME_MODIFIER); await driver.get('http://www.google.com'); await wait(5000); assert.strictEqual(await driver.executeScript(inlineFn(() => { return window.getComputedStyle(document.body)['backgroundColor']; })), 'rgb(27, 27, 27)', 'background color changed (stylesheet is applied)'); }); }); } function doOpenUserCssTest(prefix: () => string|void) { describe('Userstyles.org', () => { const URL = 'https://openusercss.org/theme/5b314c73ae380a0b00767cfa'; let href: string; beforeUserstyleInstall(URL); it('should be possible to click the install link', async function() { this.timeout(80000); this.slow(80000); await wait(10000); for (let i = 0 ; i < 4; i++) { const exists = await driver.executeScript(inlineFn(() => { const els: HTMLDivElement[] = Array.prototype.slice.apply(document.querySelectorAll('div')); const all = els.filter((d) => { return d.innerText.indexOf('Custom Right-Click Menu') > -1; }); return !!all.slice(-1)[0]; })); if (exists) { assert.isTrue(exists, 'Install link exists'); break; } await driver.get(URL); await wait(8000); } href = await driver.executeScript(inlineFn(() => { var e = document.querySelector('a[href^="https://api.open"]'); return e ? e.getAttribute("href") : null; })); await driver.executeScript(inlineFn(() => { const els: HTMLDivElement[] = Array.prototype.slice.apply(document.querySelectorAll('div')); const containerEl = els.filter((d) => { return d.innerText.indexOf('Custom Right-Click Menu') > -1; }).slice(-1)[0]; const button = containerEl.querySelector('button'); button.click(); })); await wait(5000); const isUserCss = href.indexOf('user.css') > -1; assert.isTrue(isUserCss, 'button leads to userstyle'); }); //Generic logic installStylesheetFromInstallPage(() => { return { href, prefix: prefix() } }); it('should be applied', async function() { this.timeout(600000 * TIME_MODIFIER); this.slow(600000 * TIME_MODIFIER); await driver.get('https://gitlab.com/explore/'); await wait(5000); assert.strictEqual(await driver.executeScript(inlineFn(() => { return window.getComputedStyle(document.body)['backgroundColor']; })), 'rgb(56, 60, 74)', 'background color changed (stylesheet is applied)'); }); }); } (() => { before('Driver connect', async function() { const url = TEST_LOCAL ? LOCAL_URL : 'http://hub-cloud.browserstack.com/wd/hub'; console.log('Testing extensions is no longer supported :('); process.exit(1); // global.Promise = _promise; // this.timeout(600000 * TIME_MODIFIER); // const additionalCapabilities = getExtensionData().getCapabilities(); // const unBuilt = new webdriver.Builder() // .usingServer(url) // .withCapabilities(new webdriver.Capabilities({...browserCapabilities, ...{ // project: 'Custom Right-Click Menu', // build: `${( // await tryReadManifest('app/manifest.json') || // await tryReadManifest('app/manifest.chrome.json') // ).version} - ${await getGitHash()}`, // name: (() => { // if (process.env.TRAVIS) { // // Travis // return `${process.env.TEST} attempt ${process.env.ATTEMPTS}`; // } // // Local // return `local:${ // browserCapabilities.browserName // } ${ // browserCapabilities.browser_version || 'latest' // }` // })(), // 'browserstack.local': false // }}).merge(additionalCapabilities)); // if (TEST_LOCAL) { // driver = unBuilt.forBrowser('Chrome').build(); // } else { // driver = unBuilt.build(); // } // setTimeModifier(TIME_MODIFIER); // setDriver(driver); // global.Promise = webdriver.promise.Promise; }); let prefix: string|void; describe('Extension prefix', () => { it('should be extractable from the options page', async function() { this.timeout(60000); this.slow(20000); prefix = await getExtensionData() .getExtensionURLPrefix(driver, browserCapabilities); }); }); switch (getTest()) { case 'greasyfork': doGreasyForkTest(() => prefix); break; case 'openuserjs': doOpenUserJsTest(() => prefix); break; case 'userscripts.org': doUserScriptsOrgTest(() => prefix); break; case 'userstyles.org': doUserStylesOrgTest(() => prefix); break; case 'openusercss': doOpenUserCssTest(() => prefix); break; } after('quit driver', function() { this.timeout(210000); return new webdriver.promise.Promise<void>((resolve) => { resolve(null); setTimeout(() => { driver && driver.quit(); }, 600000); }); }); })();
the_stack
import React from 'react'; import PropTypes from 'prop-types'; import { Editor, EditorState, ContentState, CompositeDecorator, Modifier, getDefaultKeyBinding, KeyBindingUtil, DefaultDraftBlockRenderMap, DraftBlockRenderConfig, DraftInlineStyle, } from 'draft-js'; import { List, Map } from 'immutable'; import 'setimmediate'; import classnames from 'classnames'; import { createToolbar } from '../Toolbar'; import ConfigStore from './ConfigStore'; import GetHTML from './export/getHTML'; import exportText, { decodeContent } from './export/exportText'; import handlePastedText from './handlePastedText'; import customHTML2Content from './customHTML2Content'; const { hasCommandModifier } = KeyBindingUtil; function noop(): void {}; export type DraftHandleValue = 'handled' | 'not-handled'; export interface Plugin { name: string; decorators?: any[]; component?: Function; onChange: (editorState: EditorState) => EditorState; customStyleFn?: Function; blockRendererFn?: Function; callbacks: { onUpArrow?: Function; onDownArrow?: Function; handleReturn?: Function; handleKeyBinding?: Function; setEditorState: (editorState: EditorState) => void; getEditorState: () => EditorState; }; config?: Object; } export interface EditorProps { multiLines: boolean; plugins: Plugin[]; pluginConfig?: Object; prefixCls: string; onChange?: (editorState: EditorState) => EditorState; toolbars: any[]; splitLine: String; onKeyDown?: (ev: any) => boolean; defaultValue?: EditorState; placeholder?: string; onFocus?: () => void; onBlur?: () => void; style?: Object; value?: EditorState | any; readOnly?: boolean; } export interface EditorCoreState { editorState?: EditorState; inlineStyleOverride?: DraftInlineStyle; customStyleMap?: Object; customBlockStyleMap?: Object; blockRenderMap?: Map<String, DraftBlockRenderConfig>; toolbarPlugins?: List<Plugin>; plugins?: Plugin[]; compositeDecorator?: CompositeDecorator; } const defaultPluginConfig = { }; const focusDummyStyle = { width: 0, opacity: 0, border: 0, position: 'absolute', left: 0, top: 0, }; const toolbar = createToolbar(); const configStore = new ConfigStore(); class EditorCore extends React.Component<EditorProps, EditorCoreState> { static ToEditorState(text: string): EditorState { const createEmptyContentState = ContentState.createFromText(decodeContent(text) || ''); const editorState = EditorState.createWithContent(createEmptyContentState); return EditorState.forceSelection(editorState, createEmptyContentState.getSelectionAfter()); } public static GetText = exportText; public static GetHTML = GetHTML(configStore); public getDefaultValue(): EditorState { const { defaultValue, value } = this.props; return value || defaultValue; } public Reset(): void { const defaultValue = this.getDefaultValue(); const contentState = defaultValue ? defaultValue.getCurrentContent() : ContentState.createFromText(''); const updatedEditorState = EditorState.push(this.state.editorState, contentState, 'remove-range'); this.setEditorState( EditorState.forceSelection(updatedEditorState, contentState.getSelectionBefore()), ); } public SetText(text: string): void { const createTextContentState = ContentState.createFromText(text || ''); const editorState = EditorState.push(this.state.editorState, createTextContentState, 'change-block-data'); this.setEditorState( EditorState.moveFocusToEnd(editorState) , true); } public state: EditorCoreState; private plugins: any; private controlledMode: boolean; private _editorWrapper: Element; private forceUpdateImmediate: number; private _focusDummy: Element; constructor(props: EditorProps) { super(props); this.plugins = List(List(props.plugins).flatten(true)); let editorState; if (props.value !== undefined) { if (props.value instanceof EditorState) { editorState = props.value || EditorState.createEmpty(); } else { editorState = EditorState.createEmpty(); } } else { editorState = EditorState.createEmpty(); } editorState = this.generatorDefaultValue(editorState); this.state = { plugins: this.reloadPlugins(), editorState, customStyleMap: {}, customBlockStyleMap: {}, compositeDecorator: null, }; if (props.value !== undefined) { this.controlledMode = true; } } refs: { [str: string]: any; editor?: any; }; public static defaultProps = { multiLines: true, plugins: [], prefixCls: 'rc-editor-core', pluginConfig: {}, toolbars: [], spilitLine: 'enter', }; public static childContextTypes = { getEditorState: PropTypes.func, setEditorState: PropTypes.func, }; public getChildContext() { return { getEditorState: this.getEditorState, setEditorState: this.setEditorState, }; } public reloadPlugins(): Plugin[] { return this.plugins && this.plugins.size ? this.plugins.map((plugin: Plugin) => { // 如果插件有 callbacks 方法,则认为插件已经加载。 if (plugin.callbacks) { return plugin; } // 如果插件有 constructor 方法,则构造插件 if (plugin.hasOwnProperty('constructor')) { const pluginConfig = Object.assign(this.props.pluginConfig, plugin.config || {}, defaultPluginConfig); return plugin.constructor(pluginConfig); } // else 无效插件 console.warn('>> 插件: [', plugin.name , '] 无效。插件或许已经过期。'); return false; }).filter(plugin => plugin).toArray() : []; } public componentWillMount(): void { const plugins = this.initPlugins().concat([toolbar]); const customStyleMap = {}; const customBlockStyleMap = {}; let customBlockRenderMap: Map<String, DraftBlockRenderConfig> = Map(DefaultDraftBlockRenderMap); let toHTMLList: List<Function> = List([]); // initialize compositeDecorator const compositeDecorator = new CompositeDecorator( plugins.filter(plugin => plugin.decorators !== undefined) .map(plugin => plugin.decorators) .reduce((prev, curr) => prev.concat(curr), []), ); // initialize Toolbar const toolbarPlugins = List(plugins.filter(plugin => !!plugin.component && plugin.name !== 'toolbar')); // load inline styles... plugins.forEach( plugin => { const { styleMap, blockStyleMap, blockRenderMap, toHtml } = plugin; if (styleMap) { for (const key in styleMap) { if (styleMap.hasOwnProperty(key)) { customStyleMap[key] = styleMap[key]; } } } if (blockStyleMap) { for (const key in blockStyleMap) { if (blockStyleMap.hasOwnProperty(key)) { customBlockStyleMap[key] = blockStyleMap[key]; customBlockRenderMap = customBlockRenderMap.set(key, { element: null, }); } } } if (toHtml) { toHTMLList = toHTMLList.push(toHtml); } if (blockRenderMap) { for (const key in blockRenderMap) { if (blockRenderMap.hasOwnProperty(key)) { customBlockRenderMap = customBlockRenderMap.set(key, blockRenderMap[key]); } } } }); configStore.set('customStyleMap', customStyleMap); configStore.set('customBlockStyleMap', customBlockStyleMap); configStore.set('blockRenderMap', customBlockRenderMap); configStore.set('customStyleFn', this.customStyleFn.bind(this)); configStore.set('toHTMLList', toHTMLList); this.setState({ toolbarPlugins, compositeDecorator, }); this.setEditorState(EditorState.set(this.state.editorState, { decorator: compositeDecorator }, ), false, false); } public componentWillReceiveProps(nextProps) { if (this.forceUpdateImmediate) { this.cancelForceUpdateImmediate(); } if (this.controlledMode) { const decorators = nextProps.value.getDecorator(); const editorState = decorators ? nextProps.value : EditorState.set(nextProps.value, { decorator: this.state.compositeDecorator }, ); this.setState({ editorState, }); } } public componentWillUnmount() { this.cancelForceUpdateImmediate(); } private cancelForceUpdateImmediate = () => { clearImmediate(this.forceUpdateImmediate); this.forceUpdateImmediate = null; } // 处理 value generatorDefaultValue(editorState: EditorState): EditorState { const defaultValue = this.getDefaultValue(); if (defaultValue) { return defaultValue; } return editorState; } public getStyleMap(): Object { return configStore.get('customStyleMap'); } public setStyleMap(customStyleMap): void { configStore.set('customStyleMap', customStyleMap); this.render(); } public initPlugins(): any[] { const enableCallbacks = ['focus', 'getEditorState', 'setEditorState', 'getStyleMap', 'setStyleMap']; return this.getPlugins().map(plugin => { enableCallbacks.forEach( callbackName => { if (plugin.callbacks.hasOwnProperty(callbackName)) { plugin.callbacks[callbackName] = this[callbackName].bind(this); } }); return plugin; }); } private focusEditor(ev) { this.refs.editor.focus(ev); if (this.props.readOnly) { this._focusDummy.focus(); } if (this.props.onFocus) { this.props.onFocus(ev); } } private _focus(ev): void { if (!ev || !ev.nativeEvent || !ev.nativeEvent.target) { return; } if (document.activeElement && document.activeElement.getAttribute('contenteditable') === 'true' ) { return; } return this.focus(ev); } public focus(ev): void { const event = ev && ev.nativeEvent; if (event && event.target === this._editorWrapper) { const { editorState } = this.state; const selection = editorState.getSelection(); if (!selection.getHasFocus()) { if (selection.isCollapsed()) { return this.setState({ editorState: EditorState.moveSelectionToEnd(editorState), }, () => { this.focusEditor(ev); }); } } } this.focusEditor(ev); } public getPlugins(): Plugin[] { return this.state.plugins.slice(); } public getEventHandler(): Object { const enabledEvents = [ 'onUpArrow', 'onDownArrow', 'handleReturn', 'onFocus', 'onBlur', 'onTab', 'handlePastedText', ]; const eventHandler = {}; enabledEvents.forEach(event => { eventHandler[event] = this.generatorEventHandler(event); }); return eventHandler; } getEditorState(needFocus = false): EditorState { if (needFocus) { this.refs.editor.focus(); } return this.state.editorState; } setEditorState(editorState: EditorState, focusEditor: boolean = false, triggerChange: boolean = true): void { let newEditorState = editorState; this.getPlugins().forEach(plugin => { if (plugin.onChange) { const updatedEditorState = plugin.onChange(newEditorState); if (updatedEditorState) { newEditorState = updatedEditorState; } } }); if (this.props.onChange && triggerChange) { this.props.onChange(newEditorState); // close this issue https://github.com/ant-design/ant-design/issues/5788 // when onChange not take any effect // `<Editor />` won't rerender cause no props is changed. // add an timeout here, // if props.onChange not trigger componentWillReceiveProps, // we will force render Editor with previous editorState, if (this.controlledMode) { this.forceUpdateImmediate = setImmediate(() => this.setState({ editorState: new EditorState(this.state.editorState.getImmutable()), })); } } if (!this.controlledMode) { this.setState( { editorState: newEditorState }, focusEditor ? () => setImmediate(() => this.refs.editor.focus()) : noop, ); } } public handleKeyBinding(ev): any { if (this.props.onKeyDown) { ev.ctrlKey = hasCommandModifier(ev); const keyDownResult = this.props.onKeyDown(ev); if (keyDownResult) { return keyDownResult; } return getDefaultKeyBinding(ev); } return getDefaultKeyBinding(ev); } public handleKeyCommand(command: String): DraftHandleValue { if (this.props.multiLines) { return this.eventHandle('handleKeyBinding', command); } return command === 'split-block' ? 'handled' : 'not-handled'; } public getBlockStyle(contentBlock): String { const customBlockStyleMap = configStore.get('customBlockStyleMap'); const type = contentBlock.getType(); if (customBlockStyleMap.hasOwnProperty(type)) { return customBlockStyleMap[type]; } return ''; } public blockRendererFn(contentBlock) { let blockRenderResult = null; this.getPlugins().forEach(plugin => { if (plugin.blockRendererFn) { const result = plugin.blockRendererFn(contentBlock); if (result) { blockRenderResult = result; } } }); return blockRenderResult; } eventHandle(eventName, ...args): DraftHandleValue { const plugins = this.getPlugins(); for (let i = 0; i < plugins.length; i++) { const plugin = plugins[i]; if (plugin.callbacks[eventName] && typeof plugin.callbacks[eventName] === 'function') { const result = plugin.callbacks[eventName](...args); if (result === true) { return 'handled'; } } } return this.props.hasOwnProperty(eventName) && this.props[eventName](...args) === true ? 'handled' : 'not-handled'; } generatorEventHandler(eventName): Function { return (...args) => { return this.eventHandle(eventName, ...args); }; } customStyleFn(styleSet): Object { if (styleSet.size === 0) { return {}; } const plugins = this.getPlugins(); const resultStyle = {}; for (let i = 0; i < plugins.length; i++) { if (plugins[i].customStyleFn) { const styled = plugins[i].customStyleFn(styleSet); if (styled) { Object.assign(resultStyle, styled); } } } return resultStyle; } handlePastedText = (text: string, html: string): DraftHandleValue => { const { editorState } = this.state; if (html) { const contentState = editorState.getCurrentContent(); const selection = editorState.getSelection(); const fragment = customHTML2Content(html, contentState); const pastedContent = Modifier.replaceWithFragment( contentState, selection, fragment, ); const newContent = pastedContent.merge({ selectionBefore: selection, selectionAfter: pastedContent.getSelectionAfter().set('hasFocus', true), }); this.setEditorState( EditorState.push(editorState, newContent as ContentState, 'insert-fragment'), true, ); return 'handled'; } return 'not-handled'; } render() { const { prefixCls, toolbars, style, readOnly, multiLines } = this.props; const { editorState, toolbarPlugins } = this.state; const customStyleMap = configStore.get('customStyleMap'); const blockRenderMap = configStore.get('blockRenderMap'); const eventHandler = this.getEventHandler(); const Toolbar = toolbar.component; const cls = classnames({ [`${prefixCls}-editor`]: true, readonly: readOnly, oneline: !multiLines, }); return (<div style={style} className={cls} onClick={this._focus.bind(this)} > <Toolbar editorState={editorState} prefixCls={prefixCls} className={`${prefixCls}-toolbar`} plugins={toolbarPlugins} toolbars={toolbars} /> <div className={`${prefixCls}-editor-wrapper`} ref={(ele) => this._editorWrapper = ele} style={style} onClick={(ev) => ev.preventDefault()} > <Editor {...this.props} {...eventHandler} ref="editor" customStyleMap={customStyleMap} customStyleFn={this.customStyleFn.bind(this)} editorState={editorState} handleKeyCommand={this.handleKeyCommand.bind(this)} keyBindingFn={this.handleKeyBinding.bind(this)} onChange={this.setEditorState.bind(this)} blockStyleFn={this.getBlockStyle.bind(this)} blockRenderMap={blockRenderMap} handlePastedText={this.handlePastedText} blockRendererFn={this.blockRendererFn.bind(this)} /> {readOnly ? <input style={focusDummyStyle} ref={ele => this._focusDummy = ele } onBlur={eventHandler.onBlur}/> : null } {this.props.children} </div> </div>); } } export default EditorCore;
the_stack
import * as nodeunit from 'nodeunit'; import * as fs from 'fs'; import * as path from 'path'; import * as or from '../tasks/modules/optionsResolver'; import * as tsconfig from '../tasks/modules/tsconfig'; import * as utils from '../tasks/modules/utils'; import * as _ from 'lodash'; import { testExpectedFile } from './testHelpers'; let grunt: IGrunt = require('grunt'); // inline strings for newline configs import { crlf_newline_tsconfig_json } from './tsconfig_artifact/newlineConfigs/crlf_newline_tsconfig.json'; import { crlf_newline_tsconfig_expected_json } from './tsconfig_artifact/newlineConfigs/crlf_newline_tsconfig.expected.json'; import { lf_newline_tsconfig_json } from './tsconfig_artifact/newlineConfigs/lf_newline_tsconfig.json'; import { lf_newline_tsconfig_expected_json } from './tsconfig_artifact/newlineConfigs/lf_newline_tsconfig.expected.json'; import { mixed_newline_tsconfig_json } from './tsconfig_artifact/newlineConfigs/mixed_newline_tsconfig.json'; import { mixed_newline_tsconfig_expected_json } from './tsconfig_artifact/newlineConfigs/mixed_newline_tsconfig.expected.json'; const config : {[name: string]: IGruntTargetOptions} = { "minimalist": <any>{ src: ["**/*.ts", "!node_modules/**/*.ts"] }, "has ES3 and sourceMap": <any>{ options: { target: 'es3', sourceMap: true } }, "bad sourceMap capitalization": <any>{ options: { target: 'es3', sourcemap: true } }, "sourceMap in wrong place": <any>{ options: { target: 'es3' }, sourceMap: true }, "tsconfig in wrong place": <any>{ options: { tsconfig: true } }, "tsconfig in wrong place and wrong case": <any>{ options: { TSConfig: true } }, "bad sourceMap capitalization in wrong place": <any>{ options: { target: 'es3' }, sourcemap: true }, "has ES6 and no sourceMap": <any>{ options: { target: 'es6', sourceMap: false } }, "has outDir set to ./built": <any>{ outDir: './built', options: { target: 'es6', sourceMap: false } }, "has outDir set to ./myOutDir": <any>{ outDir: './myOutDir' }, "has outDir set to null": <any>{ outDir: null }, "has outDir set to undefined": <any>{ outDir: undefined }, "out has spaces": <any>{ out: "my folder/out has spaces.js" }, "outDir has spaces": <any>{ outDir: "./my folder" }, "reference set to ref1.ts": <any>{ reference: "ref1.ts" }, "reference set to ref2.ts": <any>{ reference: "ref2.ts" }, "reference set to null": <any>{ reference: null }, "reference set to undefined": <any>{ reference: undefined }, "files minimalist": <any>{ files: [{ src: "source/**/*.ts", dest: "build" }] }, "vs minimalist": <any>{ vs: "test/vsproj/testproject.csproj" }, "vs ignoreSettings Release": <any>{ vs: { project: "test/vsproj/testproject.csproj", config: "Release", ignoreSettings: true } }, "vs Release": <any>{ vs: { project: "test/vsproj/testproject.csproj", config: "Release", } }, "vs TestOutFile": <any>{ vs: { project: "test/vsproj/testproject.csproj", config: "TestOutFile", } }, "has tsCacheDir set": <any>{ options: { tsCacheDir: 'some/other/path' } }, "tsconfig has true": <any>{ tsconfig: true }, "tsconfig has specific file": <any>{ tsconfig: 'test/tsconfig/test_simple_tsconfig.json' }, "tsconfig test exclude": <any>{ tsconfig: 'test/tsconfig/test_exclude_tsconfig.json' }, "zoo": <any>{ src: ["test/simple/ts/**/*.ts"] }, "use html templates": <any>{ options: { htmlVarTemplate: 'markup', htmlModuleTemplate: 'html', htmlOutputTemplate: '/* tslint:disable:max-line-length */ \n\ export module <%= modulename %> {\n\ export var <%= varname %> = \'<%= content %>\';\n\ }\n', htmlOutDir: 'html/generated', htmlOutDirFlatten: true } } }; function getConfig(name: string) : IGruntTargetOptions { return _.cloneDeep(config[name]); } export var tests : nodeunit.ITestGroup = { "Warnings and Errors Tests": { "Bad capitalization detected and fixed": (test: nodeunit.Test) => { test.expect(2); const result = or.resolveAsync(null, getConfig("bad sourceMap capitalization")).then((result) => { let allWarnings = result.warnings.join('\n'); test.ok(allWarnings.indexOf('Property "sourcemap" in target "" options is incorrectly cased; it should be "sourceMap"') > -1); test.strictEqual((<any>result).sourcemap, undefined); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "Option in wrong place detected": (test: nodeunit.Test) => { test.expect(1); const result = or.resolveAsync(null, getConfig("sourceMap in wrong place")).then((result) => { let allWarnings = result.warnings.join('\n'); test.ok(allWarnings.indexOf('Property "sourceMap" in target "" is possibly in the wrong place and will be ignored. It is expected on the options object.') > -1); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "tsconfig in wrong place detected and warns": (test: nodeunit.Test) => { test.expect(2); const result = or.resolveAsync(null, getConfig("tsconfig in wrong place")).then((result) => { let allWarnings = result.warnings.join('\n'); test.ok(allWarnings.indexOf('Property "tsconfig" in target "" is possibly in the wrong place and will be ignored. It is expected on the task or target, not under options.') > -1); test.strictEqual(allWarnings.indexOf('It is also the wrong case and should be tsconfig'),-1, 'expect to not find warning about case.'); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "tsconfig in wrong place and wrong case detected and warns": (test: nodeunit.Test) => { test.expect(2); const result = or.resolveAsync(null, getConfig("tsconfig in wrong place and wrong case")).then((result) => { let allWarnings = result.warnings.join('\n'); test.ok(allWarnings.indexOf('Property "TSConfig" in target "" is possibly in the wrong place and will be ignored. It is expected on the task or target, not under options.') > -1); test.ok(allWarnings.indexOf('It is also the wrong case and should be tsconfig') > -1); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "Option in wrong place and wrong case detected": (test: nodeunit.Test) => { test.expect(2); const result = or.resolveAsync(null, getConfig("bad sourceMap capitalization in wrong place")).then((result) => { let allWarnings = result.warnings.join('\n'); test.ok(allWarnings.indexOf('Property "sourcemap" in target "" is possibly in the wrong place and will be ignored. It is expected on the options object.') > -1); test.ok(allWarnings.indexOf('It is also the wrong case and should be sourceMap') > -1); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "compile as target name should not be a warning (issue #364)": (test: nodeunit.Test) => { test.expect(2); const result = or.resolveAsync(null, <any>{compile: { tsconfig:true } }).then((result) => { test.equal(result.warnings.length, 0, "expected no warnings"); test.equal(result.errors.length, 0, "expected no errors"); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "COMPILE as target name should not be a warning (issue #364)": (test: nodeunit.Test) => { test.expect(2); const result = or.resolveAsync(null, <any>{COMPILE: { tsconfig:true } }).then((result) => { test.equal(result.warnings.length, 0, "expected no warnings"); test.equal(result.errors.length, 0, "expected no errors"); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "No warning on target named src that uses files": (test: nodeunit.Test) => { test.expect(1); const cfg = getConfig("files minimalist"); const fakeTask: any = {src: {}}; const result = or.resolveAsync(fakeTask, cfg, "src").then((result) => { let allWarnings = result.warnings.join('\n'); test.strictEqual(allWarnings.length, 0, "expected no warnings."); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "Warning when using grunt-ts keyword as target name": (test: nodeunit.Test) => { test.expect(2); const cfg = getConfig("minimalist"); const result = or.resolveAsync(null, cfg, "watch").then((result) => { test.strictEqual(result.warnings.length, 1, "expected one warning."); let allWarnings = result.warnings.join('\n'); test.ok(allWarnings.indexOf(`keyword "watch"`) > -1, "expected warning about keyword watch"); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "Works OK when using grunt keyword (src) as target name": (test: nodeunit.Test) => { test.expect(3); const cfg = getConfig("minimalist"); const tsTaskCfg: any = { "src": cfg }; const files: IGruntTSCompilationInfo[] = [{src: ['test/gruntkeyword.ts']}]; const result = or.resolveAsync(tsTaskCfg, cfg, "src", files).then((result) => { test.strictEqual(result.warnings.length, 0, "expected zero warnings."); test.strictEqual(result.errors.length, 0, "expected zero errors."); test.strictEqual(result.CompilationTasks[0].src.join(""), "test/gruntkeyword.ts", "expected just the test file"); test.done(); }).catch((err) => {test.ifError(err); test.done();}); } }, "Special processing Tests": { "path with spaces gets enclosed in double-quotes": (test: nodeunit.Test) => { test.expect(1); const result = utils.enclosePathInQuotesIfRequired("this is a path/path.txt"); test.strictEqual(result, "\"this is a path/path.txt\""); test.done(); }, "path that is already enclosed in double-quotes is unchanged": (test: nodeunit.Test) => { test.expect(1); const result = utils.enclosePathInQuotesIfRequired("\"this is a path/path.txt\""); test.strictEqual(result, "\"this is a path/path.txt\""); test.done(); }, "path without spaces is unchanged": (test: nodeunit.Test) => { test.expect(1); const result = utils.enclosePathInQuotesIfRequired("thisIsAPath/path.txt"); test.strictEqual(result, "thisIsAPath/path.txt"); test.done(); }, "out with spaces gets escaped with double-quotes": (test: nodeunit.Test) => { test.expect(1); const files = [getConfig("out has spaces")]; const result = or.resolveAsync(null, getConfig("out has spaces"), null, files).then((result) => { test.strictEqual(result.CompilationTasks[0].out, "\"my folder/out has spaces.js\""); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "outDir with spaces gets escaped with double-quotes": (test: nodeunit.Test) => { test.expect(1); const files = [getConfig("outDir has spaces")]; const result = or.resolveAsync(null, getConfig("outDir has spaces"), null, files).then((result) => { test.strictEqual(result.CompilationTasks[0].outDir, "\"./my folder\""); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "html features are resolved correctly": (test: nodeunit.Test) => { test.expect(5); const cfg = getConfig("use html templates"); const result = or.resolveAsync(null, cfg, null).then((result) => { test.strictEqual(result.htmlModuleTemplate, "html"); test.strictEqual(result.htmlVarTemplate, "markup"); test.ok(result.htmlOutputTemplate.indexOf('export module <%= modulename %> {\n') > -1); test.strictEqual(result.htmlOutDir, "html/generated"); test.strictEqual(result.htmlOutDirFlatten, true); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "On Windows, CRLF is redundant": (test: nodeunit.Test) => { test.expect(1); const result = utils.newLineIsRedundantForTsc("CRLF", {EOL: "\r\n"}); test.strictEqual(result, true); test.done(); }, "On Windows, LF is NOT redundant": (test: nodeunit.Test) => { test.expect(1); const result = utils.newLineIsRedundantForTsc("LF", {EOL: "\r\n"}); test.strictEqual(result, false); test.done(); }, "On UNIX, CRLF is NOT redundant": (test: nodeunit.Test) => { test.expect(1); const result = utils.newLineIsRedundantForTsc("CRLF", {EOL: "\n"}); test.strictEqual(result, false); test.done(); }, "On UNIX, LF is redundant": (test: nodeunit.Test) => { test.expect(1); const result = utils.newLineIsRedundantForTsc("LF", {EOL: "\n"}); test.strictEqual(result, true); test.done(); } }, "Precedence and defaults override Tests": { "The grunt-ts defaults come through when not specified": (test: nodeunit.Test) => { test.expect(2); const result = or.resolveAsync(null, getConfig("minimalist")).then((result) => { test.strictEqual(result.target, "es5"); test.strictEqual(result.fast, "watch"); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "Task properties should override grunt-ts defaults if not specified on the target": (test: nodeunit.Test) => { test.expect(2); const result = or.resolveAsync(getConfig("reference set to ref1.ts"), getConfig("minimalist")).then((result) => { test.strictEqual(getConfig("minimalist").outDir, undefined); test.strictEqual(result.reference, 'ref1.ts'); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "Target name is set if specified": (test: nodeunit.Test) => { test.expect(1); const result = or.resolveAsync(null, getConfig("minimalist"), "MyTarget").then((result) => { test.strictEqual(result.targetName, "MyTarget"); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "Target name is default if not specified": (test: nodeunit.Test) => { test.expect(1); const result = or.resolveAsync(null, getConfig("minimalist")).then((result) => { test.strictEqual(result.targetName, ''); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "The `baseDir` option is picked-up if passed": (test: nodeunit.Test) => { test.expect(1); const config = getConfig("minimalist"); config.outDir = 'dist'; config.baseDir = 'src'; const result = or.resolveAsync(null, config).then((result) => { test.strictEqual(result.baseDir, 'src'); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "Task options should override grunt-ts defaults if not specified in the target options": (test: nodeunit.Test) => { test.expect(2); const result = or.resolveAsync(getConfig("has ES6 and no sourceMap"), getConfig("minimalist")).then((result) => { test.strictEqual(result.target, "es6"); test.strictEqual(result.sourceMap, false); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "Properties specified on the target should override anything specified in the task and the grunt-ts defaults": (test: nodeunit.Test) => { test.expect(1); const result = or.resolveAsync(getConfig("reference set to ref1.ts"), getConfig("reference set to ref2.ts")).then((result) => { test.strictEqual(result.reference, "ref2.ts"); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "Explicit null specified on the target should override anything specified in the task and the grunt-ts defaults": (test: nodeunit.Test) => { test.expect(1); const result = or.resolveAsync(getConfig("reference set to ref1.ts"), getConfig("reference set to null")).then((result) => { test.strictEqual(result.reference, null); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "Explicit undefined specified on the target should override anything specified in the task and the grunt-ts defaults": (test: nodeunit.Test) => { test.expect(1); const files = [getConfig("has outDir set to undefined")]; const result = or.resolveAsync(getConfig("reference set to ref1.ts"), getConfig("reference set to undefined")).then((result) => { test.strictEqual(result.reference, undefined); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "Properties on target `options` should override the task options `options` object and the grunt-ts defaults": (test: nodeunit.Test) => { test.expect(2); const result = or.resolveAsync(getConfig("has ES6 and no sourceMap"), getConfig("has ES3 and sourceMap")).then((result) => { test.strictEqual(result.target, "es3"); test.strictEqual(result.sourceMap, true); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "outDir works in combination with tsconfig": (test: nodeunit.Test) => { // as reported by @gilamran in https://github.com/TypeStrong/grunt-ts/issues/312 const config = <any>{ options: { target: 'es5' }, build: { outDir: '.tmp', tsconfig: { tsconfig: 'test/tsconfig/blank_tsconfig.json', ignoreFiles: true, ignoreSettings: false, overwriteFilesGlob: false, updateFiles: true, passThrough: false } } }; const result = or.resolveAsync(config, config.build, "build").then((result) => { test.strictEqual(result.target, "es5"); test.strictEqual(result.CompilationTasks[0].outDir, ".tmp"); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "out overrides out in tsconfig": (test: nodeunit.Test) => { // as reported by @jkanchelov in https://github.com/TypeStrong/grunt-ts/issues/409 const config = <any>{ options: { target: 'es5' }, build: { out: 'myfile.js', tsconfig: 'test/tsconfig/test_simple_with_out.json', } }; const result = or.resolveAsync(config, config.build, "build").then(result => { test.strictEqual(result.target, "es5"); test.strictEqual(result.CompilationTasks[0].out, "myfile.js"); test.done(); }).catch(err => {test.ifError(err); test.done();}); }, "out overrides outFile in tsconfig": (test: nodeunit.Test) => { // as reported by @jkanchelov in https://github.com/TypeStrong/grunt-ts/issues/409 const config = <any>{ options: { target: 'es5' }, build: { out: 'myfile2.js', tsconfig: 'test/tsconfig/test_simple_with_outfile.json', } }; const result = or.resolveAsync(config, config.build, "build").then(result => { test.strictEqual(result.target, "es5"); test.strictEqual(result.CompilationTasks[0].out, "myfile2.js"); test.done(); }).catch(err => {test.ifError(err); test.done();}); }, "tsCacheDir default `.tscache` directory is overriden if passed in the grunt-ts task options": (test: nodeunit.Test) => { test.expect(1); const result = or.resolveAsync(null, getConfig("has tsCacheDir set")).then((result) => { test.strictEqual(result.tsCacheDir, 'some/other/path'); test.done(); }).catch((err) => {test.ifError(err); test.done();}); } }, "Visual Studio `vs` Integration Tests": { "Visual Studio properties come across as expected": (test: nodeunit.Test) => { test.expect(3); const cfg = getConfig("vs minimalist"); cfg.options = <any>{sourceMap : false}; const result = or.resolveAsync(null, cfg).then((result) => { test.strictEqual(result.allowSyntheticDefaultImports, true) test.strictEqual(result.noStrictGenericChecks, true) test.strictEqual(result.esModuleInterop, true) test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "Visual Studio properties should override the grunt-ts defaults ONLY": (test: nodeunit.Test) => { test.expect(3); const cfg = getConfig("vs minimalist"); cfg.options = <any>{sourceMap : false}; const result = or.resolveAsync(null, cfg).then((result) => { test.strictEqual(result.removeComments, false); test.strictEqual(result.sourceMap, false); test.strictEqual(result.module, 'commonjs'); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "If a particular grunt-ts setting is not specified in the gruntfile, and `ignoreSettings` is true, the grunt-ts defaults should be used for that setting": (test: nodeunit.Test) => { test.expect(1); const result = or.resolveAsync(null, getConfig("vs ignoreSettings Release")).then((result) => { test.strictEqual(result.sourceMap, true, 'Since this csproj file\'s Release config sets sourceMap as false, if the setting is ignored, the grunt-ts default of true should come through.'); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "Any options specified on the target should override the Visual Studio settings": (test: nodeunit.Test) => { test.expect(1); const cfg = getConfig("vs Release"); cfg.outDir = "this is the test outDir"; const result = or.resolveAsync(null, cfg).then((result) => { test.strictEqual(result.CompilationTasks[0].outDir, "this is the test outDir"); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "Any 'options' options specified on the target should override the Visual Studio settings": (test: nodeunit.Test) => { test.expect(1); const cfg = getConfig("vs Release"); cfg.options = <any>{removeComments: false}; const result = or.resolveAsync(null, cfg).then((result) => { test.strictEqual(result.removeComments, false); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "out in Visual Studio settings is converted from relative to project to relative to gruntfile.": (test: nodeunit.Test) => { test.expect(1); const result = or.resolveAsync(null, getConfig("vs TestOutFile")).then((result) => { test.strictEqual(result.CompilationTasks[0].out, "test/vsproj/test_out.js"); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "outDir in Visual Studio settings is converted from relative to project to relative to gruntfile.": (test: nodeunit.Test) => { test.expect(1); const result = or.resolveAsync(null, getConfig("vs minimalist")).then((result) => { test.strictEqual(result.CompilationTasks[0].outDir, 'test/vsproj/vsproj_test'); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "paths to TypeScript files in Visual Studio project are converted from relative to project to relative to gruntfile.": (test: nodeunit.Test) => { test.expect(1); const result = or.resolveAsync(null, getConfig("vs minimalist")).then((result) => { test.strictEqual(result.CompilationTasks[0].src[0], 'test/vsproj/vsprojtest1.ts'); test.done(); }).catch((err) => {test.ifError(err); test.done();}); } }, "tsconfig.json Integration Tests": { setUp: (callback) => { const processFiles = (err, files: string[]) => { let count = 0; files.forEach(file => { if (utils.endsWith(file, '.json')) { utils.copyFile( path.join('./test/tsconfig_artifact',file), path.join('./test/tsconfig',file), (err?: Error) => { if (err) { console.log(err); throw err; } count += 1; if (count === files.length) { callback(); } } ); } else { count += 1; if (count === files.length) { callback(); } }; }) } try { // write inline string configs to test config files fs.writeFileSync('./test/tsconfig/crlf_newline_tsconfig.json', crlf_newline_tsconfig_json); fs.writeFileSync('./test/tsconfig/crlf_newline_tsconfig.expected.json', crlf_newline_tsconfig_expected_json); fs.writeFileSync('./test/tsconfig/lf_newline_tsconfig.json', lf_newline_tsconfig_json); fs.writeFileSync('./test/tsconfig/lf_newline_tsconfig.expected.json', lf_newline_tsconfig_expected_json); fs.writeFileSync('./test/tsconfig/mixed_newline_tsconfig.json', mixed_newline_tsconfig_json); fs.writeFileSync('./test/tsconfig/mixed_newline_tsconfig.expected.json', mixed_newline_tsconfig_expected_json); fs.readdir('test/tsconfig_artifact', processFiles); } catch(ex) { console.log(ex); callback(ex); } }, "include will record an error in presence of overwriteFilesGlob or updateFiles": (test: nodeunit.Test) => { test.expect(4); const config = <any>{ options: { target: 'es5' }, build: { tsconfig: { tsconfig: './test/tsconfig/test_include_tsconfig.json', overwriteFilesGlob: true, updateFiles: true } } }; const result = or.resolveAsync(config, config.build, "build").then((result) => { test.strictEqual(result.errors.length, 3); const errorText = JSON.stringify(result.errors); test.ok(errorText.indexOf("the `overwriteFilesGlob` feature") > -1); test.ok(errorText.indexOf("the `updateFiles` feature") > -1); test.ok(errorText.indexOf("no glob was passed-in") > -1); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "include will bring in files when specified": (test: nodeunit.Test) => { test.expect(7) const config = <any>{ options: { target: 'es5' }, build: { tsconfig: { tsconfig: './test/tsconfig/test_include_tsconfig.json', ignoreFiles: false, ignoreSettings: false, overwriteFilesGlob: false, updateFiles: false, passThrough: false } } }; const result = or.resolveAsync(config, config.build, "build", [], null, grunt.file.expand).then((result) => { test.strictEqual(result.CompilationTasks.length, 1, "expected a compilation task"); test.strictEqual(result.CompilationTasks[0].src.length, 5); test.ok(result.CompilationTasks[0].src.indexOf("test/customcompiler/ts/foo.ts") > -1); test.ok(result.CompilationTasks[0].src.indexOf("test/abtest/a.ts") > -1); test.ok(result.CompilationTasks[0].src.indexOf("test/abtest/b.ts") > -1); test.ok(result.CompilationTasks[0].src.indexOf("test/abtest/c.ts") > -1); test.ok(result.CompilationTasks[0].src.indexOf("test/abtest/reference.ts") > -1); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "include with wildcard is limited to valid TypeScript extensions when allowJs is not specified.": (test: nodeunit.Test) => { test.expect(5) const config = <any>{ options: { target: 'es5' }, build: { tsconfig: { tsconfig: './test/tsconfig/test_include_wildcard.json' } } }; const result = or.resolveAsync(config, config.build, "build", [], null, grunt.file.expand).then((result) => { test.strictEqual(result.CompilationTasks.length, 1, "expected a compilation task"); test.ok(result.CompilationTasks[0].src.length === 2, "expected to find ts.ts and scratch.ts"); test.ok(result.CompilationTasks[0].src.indexOf("tasks/ts.js.map") === -1, "expected non-TypeScript files to be filtered out."); test.ok(result.CompilationTasks[0].src.indexOf("tasks/ts.js") === -1, "expected non-TypeScript files to be filtered out."); test.ok(result.CompilationTasks[0].src.indexOf("tasks/ts.ts") > -1, "expected TypeScript files to be included."); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "include with wildcard is limited to valid TypeScript and JavaScript extensions when allowJs is specified.": (test: nodeunit.Test) => { test.expect(5) const config = <any>{ options: { target: 'es5', allowJs: true }, build: { tsconfig: { tsconfig: './test/tsconfig/test_include_wildcard.json' } } }; if (!fs.existsSync('tasks/scratch.js')) { fs.writeFileSync('tasks/scratch.js', ''); // ensure there is a scratch file there just in case it hasn't been compiled. } const result = or.resolveAsync(config, config.build, "build", [], null, grunt.file.expand).then((result) => { test.strictEqual(result.CompilationTasks.length, 1, "expected a compilation task"); test.strictEqual(result.CompilationTasks[0].src.length, 4, "expected to find ts.ts, scratch.ts, ts.js, and scratch.js only."); test.ok(result.CompilationTasks[0].src.indexOf("tasks/ts.js.map") === -1, "expected non-TypeScript files to be filtered out."); test.ok(result.CompilationTasks[0].src.indexOf("tasks/ts.js") > -1, "expected JS file to be included."); test.ok(result.CompilationTasks[0].src.indexOf("tasks/ts.ts") > -1, "expected TypeScript files to be included."); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "Can get config from a valid file": (test: nodeunit.Test) => { test.expect(1); const cfg = getConfig("minimalist"); cfg.tsconfig = './test/tsconfig/full_valid_tsconfig.json'; const result = or.resolveAsync(null, cfg).then((result) => { test.ok(true); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "ignoreSettings works": (test: nodeunit.Test) => { test.expect(2); const cfg = getConfig("minimalist"); cfg.tsconfig = { tsconfig: './test/tsconfig/test_simple_tsconfig.json', ignoreSettings: true }; const result = or.resolveAsync(null, cfg).then((result) => { test.strictEqual(result.target, 'es5'); test.strictEqual(result.module, undefined); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "Error from invalid file": (test: nodeunit.Test) => { test.expect(2); const cfg = getConfig("minimalist"); cfg.tsconfig = './test/tsconfig/invalid_tsconfig.json'; const result = or.resolveAsync(null, cfg).then((result) => { test.strictEqual(result.errors.length, 1); test.ok(result.errors[0].indexOf("Error parsing") >= 0, "Expected error parsing"); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "No exception from blank file": (test: nodeunit.Test) => { test.expect(1); const expectedMemo = 'expected blank file to NOT throw an exception (should be treated as contents = {}).'; const cfg = getConfig("minimalist"); cfg.tsconfig = './test/tsconfig/blank_tsconfig.json'; const result = or.resolveAsync(null, cfg).then((result) => { test.ok(true, expectedMemo); test.done(); }).catch((err) => { test.ok(false, expectedMemo); test.done(); }); }, "No exception from file with contents {}": (test: nodeunit.Test) => { test.expect(1); const cfg = getConfig("minimalist"); cfg.tsconfig = './test/tsconfig/empty_object_literal_tsconfig.json'; const result = or.resolveAsync(null, cfg, "", null, null, grunt.file.expand).then((result) => { test.ok(true); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "Exception from missing file": (test: nodeunit.Test) => { test.expect(3); const cfg = getConfig("minimalist"); cfg.tsconfig = './test/tsconfig/does_not_exist_tsconfig.json'; const result = or.resolveAsync(null, cfg).then((result) => { test.strictEqual(result.errors.length, 1); test.ok(result.errors[0].indexOf('ENOENT') > -1); test.ok(result.errors[0].indexOf('does_not_exist_tsconfig.json') > -1); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "config entries come through appropriately": (test: nodeunit.Test) => { test.expect(24); const cfg = getConfig("minimalist"); cfg.tsconfig = './test/tsconfig/full_valid_tsconfig.json'; const result = or.resolveAsync(null, cfg).then((result) => { test.strictEqual(result.target, 'es5'); test.strictEqual(result.module, 'commonjs'); test.strictEqual(result.declaration, false); test.strictEqual(result.noImplicitAny, false); test.strictEqual(result.removeComments, false); test.strictEqual(result.preserveConstEnums, false); test.strictEqual(result.suppressImplicitAnyIndexErrors, true); test.strictEqual(result.sourceMap, true); test.strictEqual(result.emitDecoratorMetadata, undefined, 'emitDecoratorMetadata is not specified in this tsconfig.json'); test.strictEqual(result.CompilationTasks.length, 1); test.strictEqual(result.allowSyntheticDefaultImports, true); test.strictEqual(result.charset, 'utf8'); test.strictEqual(result.strictNullChecks, false); test.strictEqual(result.listFiles, true); test.strictEqual(result.checkJs, true); test.strictEqual(result.allowJs, true); test.strictEqual(result.preserveSymlinks, true); test.strictEqual(result.esModuleInterop, true); test.strictEqual(result.types.length, 3); test.ok(result.types.indexOf('issue') > -1); test.strictEqual(result.typeRoots.length, 2); test.ok(result.typeRoots.indexOf('test/node_modules/@types') > -1); test.strictEqual(result.CompilationTasks[0].outDir, 'test/tsconfig/files'); test.strictEqual(result.CompilationTasks[0].out, undefined); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "out comes through with a warning and is NOT remapped relative to Gruntfile.js": (test: nodeunit.Test) => { test.expect(5); const cfg = getConfig("minimalist"); cfg.tsconfig = './test/tsconfig/test_simple_with_out.json'; const result = or.resolveAsync(null, cfg).then((result) => { test.strictEqual(result.CompilationTasks.length, 1); test.strictEqual(result.CompilationTasks[0].out, 'files/this_is_the_out_file.js'); test.strictEqual(result.CompilationTasks[0].outDir, undefined); test.strictEqual(result.warnings.length, 2); test.ok(result.warnings[0].indexOf('Using `out` in tsconfig.json can be unreliable') > -1); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "outFile comes through appropriately and is remapped relative to Gruntfile.js": (test: nodeunit.Test) => { test.expect(3); const cfg = getConfig("minimalist"); cfg.tsconfig = './test/tsconfig/test_simple_with_outFile.json'; const result = or.resolveAsync(null, cfg).then((result) => { test.strictEqual(result.CompilationTasks.length, 1); test.strictEqual(result.CompilationTasks[0].out, 'test/tsconfig/files/this_is_the_outFile_file.js'); test.strictEqual(result.CompilationTasks[0].outDir, undefined); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "most basic tsconfig with true works": (test: nodeunit.Test) => { test.expect(12); const result = or.resolveAsync(null, getConfig("tsconfig has true")).then((result) => { // NOTE: With tsconfig: true, this depends on the actual grunt-ts tsconfig so technically it could be wrong in the future. test.strictEqual((<ITSConfigSupport>result.tsconfig).tsconfig, path.join(path.resolve('.'), 'tsconfig.json')); test.strictEqual(result.target, 'es5'); test.strictEqual(result.module, 'commonjs'); test.strictEqual(result.declaration, false); test.strictEqual(result.noImplicitAny, false); test.strictEqual(result.removeComments, false); test.strictEqual(result.preserveConstEnums, false); test.strictEqual(result.suppressImplicitAnyIndexErrors, true); test.strictEqual(result.sourceMap, true); test.strictEqual(result.emitDecoratorMetadata, undefined, 'emitDecoratorMetadata is not specified in this tsconfig.json'); test.ok(result.CompilationTasks[0].src.indexOf('tasks/ts.ts') > -1); test.ok(result.CompilationTasks[0].src.indexOf('tasks/modules/compile.ts') > -1); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "simple tsconfig with file path works": (test: nodeunit.Test) => { test.expect(13); const result = or.resolveAsync(null, getConfig("tsconfig has specific file")).then((result) => { test.strictEqual((<ITSConfigSupport>result.tsconfig).tsconfig, 'test/tsconfig/test_simple_tsconfig.json'); test.strictEqual(result.target, 'es6'); test.strictEqual(result.module, 'amd'); test.strictEqual(result.declaration, true); test.strictEqual(result.noImplicitAny, true); test.strictEqual(result.removeComments, false); test.strictEqual(result.preserveConstEnums, false); test.strictEqual(result.suppressImplicitAnyIndexErrors, true); test.strictEqual(result.sourceMap, false); test.strictEqual(result.emitDecoratorMetadata, true); test.strictEqual(result.experimentalDecorators, true); test.strictEqual(result.CompilationTasks[0].src.length, 1); test.ok(result.CompilationTasks[0].src.indexOf('test/tsconfig/files/validtsconfig.ts') === 0); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "src appends to files from tsconfig": (test: nodeunit.Test) => { test.expect(3); const cfg = getConfig("tsconfig has specific file"); const files: IGruntTSCompilationInfo[] = [{src: ['test/simple/ts/zoo.ts']}]; const result = or.resolveAsync(null, getConfig("tsconfig has specific file"), null, files, null, grunt.file.expand).then((result) => { test.strictEqual(result.CompilationTasks[0].src.length, 2); test.ok(result.CompilationTasks[0].src.indexOf('test/tsconfig/files/validtsconfig.ts') > -1); test.ok(result.CompilationTasks[0].src.indexOf('test/simple/ts/zoo.ts') > -1); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "target settings override tsconfig": (test: nodeunit.Test) => { test.expect(2); let cfg = getConfig("tsconfig has specific file"); cfg.options = <ITaskOptions>{ target: 'es3' }; const result = or.resolveAsync(null, cfg).then((result) => { test.strictEqual(result.target, 'es3', 'this setting on the grunt-ts target options overrides the tsconfig'); test.strictEqual(result.removeComments, false, 'this setting is not specified in the options so tsconfig wins over grunt-ts defaults'); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "If files and exclude, files will be used and exclude will be ignored.": (test: nodeunit.Test) => { test.expect(1); const result = or.resolveAsync(null, getConfig("tsconfig has specific file")).then((result) => { test.ok(result.CompilationTasks[0].src.indexOf('test/tsconfig/otherFiles/other.ts') === -1); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "if no files, but exclude, *.ts and *.tsx will be included except for the excluded files and folders": (test: nodeunit.Test) => { test.expect(5); const cfg = getConfig("tsconfig test exclude"); const result = or.resolveAsync(null, cfg, "", null, null, grunt.file.expand).then((result) => { test.ok(result.CompilationTasks[0].src.indexOf('test/tsconfig/otherFiles/other.ts') > -1); test.ok(result.CompilationTasks[0].src.indexOf('test/tsconfig/otherFiles/this.ts') === -1); test.ok(result.CompilationTasks[0].src.indexOf('test/tsconfig/otherFiles/that.ts') > -1); test.ok(result.CompilationTasks[0].src.indexOf('test/tsconfig/files/validconfig.ts') === -1); const resultingTSConfig = utils.readAndParseJSONFromFileSync(<string>cfg.tsconfig); test.ok(!('files' in resultingTSConfig), 'expected that grunt-ts would not add a files element.'); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "outDir from gruntfile affects tsconfig.json resolved files": (test: nodeunit.Test) => { test.expect(3); let cfg: any = {}; cfg.src = ["./test/issue_392_2/**","!./test/issue_392_2/node_modules/**"]; cfg.outDir = "./test/issue_392_2/compiled"; cfg.tsconfig = "./test/issue_392_2/tsconfig.json" const result = or.resolveAsync(null, cfg, "", null, null, grunt.file.expand).then((result) => { test.ok(result.CompilationTasks[0].src.indexOf('test/issue_392_2/app/subfolder/test1.ts') > -1); test.ok(result.CompilationTasks[0].src.indexOf('test/issue_392_2/app/subfolder/test1.spec.ts') > -1); test.ok(result.CompilationTasks[0].src.indexOf('test/issue_392_2/compiled/shouldnotbefound.ts') === -1); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "typeRoots files are resolved relative to Gruntfile (See GitHub issue 397)": (test: nodeunit.Test) => { test.expect(3); let cfg = getConfig("minimalist"); cfg.tsconfig = "./test/issue_397/src/issue_397-tsconfig.json" const result = or.resolveAsync(null, cfg).then((result) => { test.strictEqual(result.typeRoots.length, 2); test.ok(result.typeRoots.indexOf('test/issue_397/src/typings') > -1); test.ok(result.typeRoots.indexOf('test/issue_397/src/other_typings') > -1); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "paths written to filesGlob are resolved first": (test: nodeunit.Test) => { test.expect(4); let cfg: any = getConfig("minimalist"); // this assumes the test gruntfile which uses the {% and %} delimiters. cfg.src = [`./test/{%= grunt.pathsFilesGlobProperty %}/a*.ts`]; cfg.tsconfig = { tsconfig: 'test/tsconfig/simple_filesGlob_tsconfig.json', ignoreFiles: false, updateFiles: true, overwriteFilesGlob: true }; (<any>grunt).pathsFilesGlobProperty = "abtest"; const result = or.resolveAsync(null, cfg, "myTarget", null, grunt.template.process, grunt.file.expand).then((result) => { const resultingTSConfig = utils.readAndParseJSONFromFileSync((<ITSConfigSupport>cfg.tsconfig).tsconfig); test.strictEqual(resultingTSConfig.filesGlob.length, 1, "expected one element."); test.strictEqual(resultingTSConfig.filesGlob[0], "../abtest/a*.ts", "expected modified glob (relative path)."); test.strictEqual(resultingTSConfig.files.length, 1, "expected one element."); test.strictEqual(resultingTSConfig.files[0], "../abtest/a.ts", "expected file (at relative path)."); delete (<any>grunt).pathsFilesGlobProperty; test.done(); }).catch((err) => {test.ifError(err); delete (<any>grunt).pathsFilesGlobProperty; test.done();}); }, "if no files and no exclude, *.ts and *.tsx will be included and files not added.": (test: nodeunit.Test) => { test.expect(5); const cfg = getConfig("minimalist"); cfg.tsconfig = './test/tsconfig/empty_object_literal_tsconfig.json'; const result = or.resolveAsync(null, cfg, "", null, null, grunt.file.expand).then((result) => { const resultingTSConfig = utils.readAndParseJSONFromFileSync(<string>cfg.tsconfig); test.ok(result.CompilationTasks[0].src.indexOf('test/tsconfig/otherFiles/this.ts') >= 0, 'expected this.ts'); test.ok(result.CompilationTasks[0].src.indexOf('test/tsconfig/otherFiles/that.ts') >= 0, 'expected that.ts'); test.ok(result.CompilationTasks[0].src.indexOf('test/tsconfig/otherFiles/other.ts') >= 0, 'expected other.ts'); test.ok(result.CompilationTasks[0].src.indexOf('test/tsconfig/files/validtsconfig.ts') >= 0, 'expected validconfig.ts'); test.ok(!('files' in resultingTSConfig), 'expected that grunt-ts would not add a files element.'); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "globs are evaluated and files maintained by default": (test: nodeunit.Test) => { test.expect(9); const cfg = getConfig("minimalist"); cfg.tsconfig = './test/tsconfig/simple_filesGlob_tsconfig.json'; const result = or.resolveAsync(null, cfg, "", null, null, grunt.file.expand).then((result) => { test.ok(result.CompilationTasks[0].src.indexOf('test/tsconfig/otherFiles/this.ts') >= 0); test.ok(result.CompilationTasks[0].src.indexOf('test/tsconfig/otherFiles/that.ts') >= 0); test.ok(result.CompilationTasks[0].src.indexOf('test/tsconfig/otherFiles/other.ts') >= 0); test.ok(result.CompilationTasks[0].src.indexOf('test/tsconfig/files/validtsconfig.ts') >= 0); const resultingTSConfig = utils.readAndParseJSONFromFileSync(<string>cfg.tsconfig); test.strictEqual(resultingTSConfig.files.length, 4, 'Expected four files.'); test.ok(resultingTSConfig.files.indexOf('otherFiles/this.ts') >= 0); test.ok(resultingTSConfig.files.indexOf('otherFiles/that.ts') >= 0); test.ok(resultingTSConfig.files.indexOf('otherFiles/other.ts') >= 0); test.ok(resultingTSConfig.files.indexOf('files/validtsconfig.ts') >= 0); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "option overwriteFilesGlob updates the filesGlob and the new glob results are included": (test: nodeunit.Test) => { test.expect(5); const cfg = getConfig("zoo"); cfg.tsconfig = { tsconfig: './test/tsconfig/simple_filesGlob_tsconfig.json', overwriteFilesGlob: true }; const result = or.resolveAsync(null, cfg, "", [], null, grunt.file.expand).then((result) => { test.ok(result.CompilationTasks[0].src.indexOf('test/simple/ts/zoo.ts') >= 0, 'expected to find zoo.ts'); test.strictEqual(result.CompilationTasks[0].src.length, 1); const resultingTSConfig = utils.readAndParseJSONFromFileSync((<ITSConfigSupport>cfg.tsconfig).tsconfig); test.strictEqual(resultingTSConfig.filesGlob[0],'../simple/ts/**/*.ts'); test.ok(resultingTSConfig.files.indexOf('../simple/ts/zoo.ts') >= 0); test.strictEqual(resultingTSConfig.files.length, 1, 'expected a single item in the files array'); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "omitting tsconfig property of tsconfig object defaults to 'tsconfig.json'": (test: nodeunit.Test) => { test.expect(4); const cfg: any = { tsconfig: { overwriteFilesGlob: false } }; const result = or.resolveAsync(null, cfg).then((result) => { test.strictEqual((<ITSConfigSupport>result.tsconfig).tsconfig, "tsconfig.json", "expected default to be set."); test.ok(result.CompilationTasks.length > 0, "expected some compilation tasks from default tsconfig.json"); test.strictEqual(result.errors.length, 0, "expected zero errors."); test.strictEqual(result.warnings.length, 0, "expected zero warnings."); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "four spaces indent is preserved when updating tsconfig": (test: nodeunit.Test) => { test.expect(1); const taskTargetConfig = getConfig("minimalist"); taskTargetConfig.tsconfig = './test/tsconfig/four_spaces_indent_tsconfig.json'; const result = or.resolveAsync(null, taskTargetConfig, "", null, null, grunt.file.expand).then((result: IGruntTSOptions) => { testExpectedFile(test, './test/tsconfig/four_spaces_indent_tsconfig.expected.json', false); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "tab indent is preserved when updating tsconfig": (test: nodeunit.Test) => { test.expect(1); const taskTargetConfig = getConfig("minimalist"); taskTargetConfig.tsconfig = './test/tsconfig/tab_indent_tsconfig.json'; const result = or.resolveAsync(null, taskTargetConfig, "", null, null, grunt.file.expand).then((result: IGruntTSOptions) => { testExpectedFile(test, './test/tsconfig/tab_indent_tsconfig.expected.json', false); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "three spaces indent is preserved when updating tsconfig": (test: nodeunit.Test) => { test.expect(1); const taskTargetConfig = getConfig("minimalist"); taskTargetConfig.tsconfig = './test/tsconfig/three_spaces_indent_tsconfig.json'; const result = or.resolveAsync(null, taskTargetConfig, "", null, null, grunt.file.expand).then((result: IGruntTSOptions) => { testExpectedFile(test, './test/tsconfig/three_spaces_indent_tsconfig.expected.json', false); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "crlf newline is preserved when updating tsconfig": (test: nodeunit.Test) => { test.expect(1); const taskTargetConfig = getConfig("minimalist"); taskTargetConfig.tsconfig = './test/tsconfig/crlf_newline_tsconfig.json'; const result = or.resolveAsync(null, taskTargetConfig, "", null, null, grunt.file.expand).then((result: IGruntTSOptions) => { testExpectedFile(test, './test/tsconfig/crlf_newline_tsconfig.expected.json', false); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "lf newline is preserved when updating tsconfig": (test: nodeunit.Test) => { test.expect(1); const taskTargetConfig = getConfig("minimalist"); taskTargetConfig.tsconfig = './test/tsconfig/lf_newline_tsconfig.json'; const result = or.resolveAsync(null, taskTargetConfig, "", null, null, grunt.file.expand).then((result: IGruntTSOptions) => { testExpectedFile(test, './test/tsconfig/lf_newline_tsconfig.expected.json', false); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "mixed indent uses most frequently detected indent when updating tsconfig": (test: nodeunit.Test) => { test.expect(1); const taskTargetConfig = getConfig("minimalist"); taskTargetConfig.tsconfig = './test/tsconfig/mixed_indent_tsconfig.json'; const result = or.resolveAsync(null, taskTargetConfig, "", null, null, grunt.file.expand).then((result: IGruntTSOptions) => { testExpectedFile(test, './test/tsconfig/mixed_indent_tsconfig.expected.json', false); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "mixed newline uses most frequently detected newline when updating tsconfig": (test: nodeunit.Test) => { test.expect(1); const taskTargetConfig = getConfig("minimalist"); taskTargetConfig.tsconfig = './test/tsconfig/mixed_newline_tsconfig.json'; const result = or.resolveAsync(null, taskTargetConfig, "", null, null, grunt.file.expand).then((result: IGruntTSOptions) => { testExpectedFile(test, './test/tsconfig/mixed_newline_tsconfig.expected.json', false); test.done(); }).catch((err) => {test.ifError(err); test.done();}); }, "tsconfig with extends and nostrictnull works as expected": function (test) { test.expect(4); var cfg = getConfig("minimalist"); cfg.tsconfig = { tsconfig: './test/tsconfig_artifact/extends/tsconfig.nostrictnull.json', }; var result = or.resolveAsync(null, cfg).then(function (result) { test.strictEqual(result.strictNullChecks, false, "expected to get strict null checks disabled."); test.strictEqual(result.noImplicitAny, true, "expected to get noImplicitAny from configs/base.json."); test.ok(result.CompilationTasks[0].src.indexOf('test/abtest/a.ts') > -1, "expected to see a.ts included."); test.ok(result.CompilationTasks[0].src.indexOf('test/abtest/b.ts') > -1, "expected to see b.ts included."); test.done(); }).catch(function (err) { test.ifError(err); test.done(); }); } } };
the_stack
module txt { export enum VerticalAlign { Top, CapHeight, Center, BaseLine, Bottom, XHeight, Ascent, Percent }; export class PathText extends createjs.Container { text:string = ""; characterCase:number = txt.Case.NORMAL; size:number = 12; font:string = "belinda"; tracking:number = 0; ligatures:boolean = false; minSize:number = null; maxTracking:number = null; fillColor:string = "#000"; strokeColor:string = null; strokeWidth:number = null; style:Style[] = null; debug:boolean = false; characters:txt.Character[]; block:createjs.Container; original:ConstructObj = null; autoExpand:boolean = false; autoReduce:boolean = false; overset:boolean = false; oversetIndex:number = null; pathPoints:txt.Path = null; path:string = ""; start:number = 0; end:number = null; flipped:boolean = false; fit:PathFit = txt.PathFit.Rainbow; align:PathAlign = txt.PathAlign.Center; valign:VerticalAlign = txt.VerticalAlign.BaseLine; missingGlyphs:any[] = null; renderCycle:boolean = true; valignPercent:number = 1; initialTracking:number = 0; initialOffset:number = 0; measured:boolean = false; oversetPotential:boolean = false; //accessibility accessibilityText:string = null; accessibilityPriority:number = 2; accessibilityId:number = null; constructor( props:ConstructObj = null ){ super(); if( props ){ this.original = props; this.set( props ); this.original.tracking = this.tracking; } if( this.style == null ){ txt.FontLoader.load( this , [ this.font ] ); }else{ var fonts = [ this.font ]; var styleLength = this.style.length; for( var i = 0; i < styleLength; ++i ){ if( this.style[ i ] != undefined ){ if( this.style[ i ].font != undefined ){ fonts.push( this.style[ i ].font ); } } } txt.FontLoader.load( this , fonts ); } this.pathPoints = new txt.Path( this.path , this.start , this.end , this.flipped , this.fit , this.align ); //console.log( this ); } complete(){} setPath( path:string ){ this.path = path; this.pathPoints.path = this.path; this.pathPoints.update(); } setStart( start:number ){ this.start = start; this.pathPoints.start = this.start; this.pathPoints.update(); } setEnd( end:number ){ this.end = end; this.pathPoints.end = this.end; this.pathPoints.update(); } setFlipped( flipped:boolean ){ this.flipped = flipped; this.pathPoints.flipped = this.flipped; this.pathPoints.update(); } setFit( fit:txt.PathFit = txt.PathFit.Rainbow ){ this.fit = fit; this.pathPoints.fit = this.fit; this.pathPoints.update(); } setAlign( align:PathAlign = txt.PathAlign.Center ){ this.align = align; this.pathPoints.align = this.align; this.pathPoints.update(); } fontLoaded(){ this.layout(); } render(){ this.getStage().update(); } getWidth():number { return this.pathPoints.realLength; } layout(){ //accessibility api txt.Accessibility.set( this ); this.overset = false; this.oversetIndex = null; this.removeAllChildren(); this.characters = []; this.missingGlyphs = null; this.measured = false; this.oversetPotential = false; if( this.debug == true ){ var s = new createjs.Shape(); s.graphics.beginStroke( "#FF0000" ); s.graphics.setStrokeStyle( 0.1 ); s.graphics.decodeSVGPath( this.path ); s.graphics.endFill(); s.graphics.endStroke(); this.addChild( s ); s = new createjs.Shape(); var pp = this.pathPoints.getRealPathPoint( 0 ); s.x = pp.x; s.y = pp.y; s.graphics.beginFill( "black" ); s.graphics.drawCircle( 0 , 0 , 2 ); this.addChild( s ); s = new createjs.Shape(); var pp = this.pathPoints.getRealPathPoint( this.pathPoints.start ); s.x = pp.x; s.y = pp.y; s.graphics.beginFill( "green" ); s.graphics.drawCircle( 0 , 0 , 2 ); this.addChild( s ); s = new createjs.Shape(); pp = this.pathPoints.getRealPathPoint( this.pathPoints.end ); s.x = pp.x; s.y = pp.y; s.graphics.beginFill( "red" ); s.graphics.drawCircle( 0 , 0 , 2 ); this.addChild( s ); s = new createjs.Shape(); pp = this.pathPoints.getRealPathPoint( this.pathPoints.center ); s.x = pp.x; s.y = pp.y; s.graphics.beginFill( "blue" ); s.graphics.drawCircle( 0 , 0 , 2 ); this.addChild( s ); } if( this.text === "" || this.text === undefined ){ this.render(); return; } this.block = new createjs.Container() this.addChild( this.block ); if( this.autoExpand === true || this.autoReduce === true ){ if( this.measure() === false ){ this.removeAllChildren(); return; } } if( this.renderCycle === false ){ this.removeAllChildren(); this.complete(); return; } if( this.characterLayout() === false ){ this.removeAllChildren(); return; } this.render(); this.complete(); } measure():boolean{ this.measured = true; //Extract orgin sizing from this.original to preserve //metrics. autoMeasure will change style properties //directly. Change this.original to rerender. var size = this.original.size; var len = this.text.length; var width = this.getWidth(); var defaultStyle = { size: this.original.size, font: this.original.font, tracking: this.original.tracking, characterCase: this.original.characterCase }; var currentStyle:any; var charCode:number = null; var font:txt.Font; var charMetrics = []; var largestFontSize = defaultStyle.size; //console.log( "LOOPCHAR===============" ); //console.log( " len: " + len ); for( var i = 0; i < len; i++ ){ charCode = this.text.charCodeAt(i); currentStyle = defaultStyle; if( this.original.style !== undefined && this.original.style[ i ] !== undefined ){ currentStyle = this.original.style[ i ]; // make sure style contains properties needed. if( currentStyle.size === undefined ) currentStyle.size = defaultStyle.size; if( currentStyle.font === undefined ) currentStyle.font = defaultStyle.font; if( currentStyle.tracking === undefined ) currentStyle.tracking = defaultStyle.tracking; } if( currentStyle.size > largestFontSize ){ largestFontSize = currentStyle.size; } font = txt.FontLoader.fonts[ currentStyle.font ]; //console.log( currentStyle.tracking , font.units ); charMetrics.push( { char: this.text[ i ], size: currentStyle.size, charCode:charCode, font: currentStyle.font, offset: font.glyphs[ charCode ].offset, units: font.units, tracking: this.trackingOffset( currentStyle.tracking , currentStyle.size , font.units ), kerning: font.glyphs[ charCode ].getKerning( this.getCharCodeAt( i + 1 ) , 1 ) }); //console.log( this.text[i] ); } //save space char using last known width/height var space:any = { char: " ", size: currentStyle.size, charCode: 32, font: currentStyle.font, offset: font.glyphs[ 32 ].offset, units: font.units, tracking: 0, kerning: 0 }; charMetrics[ charMetrics.length - 1 ].tracking=0; //charMetrics[ charMetrics.length-1 ].kerning=0; len = charMetrics.length; //measured without size var metricBaseWidth = 0; //measured at size var metricRealWidth = 0; //measured at size with tracking var metricRealWidthTracking = 0; var current = null; //console.log( " len: " + len ); //console.log( "LOOPMETRICS===============" ); for( var i = 0; i < len; i++ ){ current = charMetrics[ i ]; metricBaseWidth = metricBaseWidth + current.offset + current.kerning; metricRealWidth = metricRealWidth + ( ( current.offset + current.kerning ) * current.size ); metricRealWidthTracking = metricRealWidthTracking + ( ( current.offset + current.kerning + current.tracking ) * current.size ); //console.log( current.char ); } //console.log( "METRICS===============" ); //console.log( "mbw: " + metricBaseWidth ); //console.log( "mrw: " + metricRealWidth ); //console.log( "mrwt: " + metricRealWidthTracking ); //console.log( "widt4: " + this.getWidth() ); //console.log( " len: " + len ); //console.log( charMetrics ); //console.log( "======================" ); //size cases if( metricRealWidth > width ){ if( this.autoReduce === true ){ this.tracking = 0; this.size = this.original.size * width / ( metricRealWidth + ( space.offset * space.size ) ); if( this.minSize != null && this.size < this.minSize ){ this.size = this.minSize; if( this.renderCycle === false ){ this.overset = true; }else{ this.oversetPotential = true; } } //console.log( "REDUCE SIZE") return true; } //tracking cases }else{ var trackMetric = this.offsetTracking( ( width - metricRealWidth )/( len ) , current.size , current.units ); if( trackMetric < 0 ){ trackMetric = 0; } //autoexpand case if( trackMetric > this.original.tracking && this.autoExpand ){ if( this.maxTracking != null && trackMetric > this.maxTracking ){ this.tracking = this.maxTracking; }else{ this.tracking = trackMetric; } this.size = this.original.size; //console.log( "EXPAND TRACKING") return true; } //autoreduce tracking case if( trackMetric < this.original.tracking && this.autoReduce ){ if( this.maxTracking != null && trackMetric > this.maxTracking ){ this.tracking = this.maxTracking; }else{ this.tracking = trackMetric; } this.size = this.original.size; //console.log( "REDUCE TRACKING") return true; } } return true; } //place characters in words characterLayout():boolean { //char layout var len = this.text.length; var char:Character; var defaultStyle = { size: this.size, font: this.font, tracking: this.tracking, characterCase: this.characterCase, fillColor: this.fillColor, strokeColor: this.strokeColor, strokeWidth: this.strokeWidth }; var currentStyle = defaultStyle; var hPosition:number = 0; var charKern:number; var tracking:number; var angle:number; // loop over characters // place into lines for( var i = 0 ; i < len ; i++ ){ if( this.style !== null && this.style[ i ] !== undefined ){ currentStyle = this.style[ i ]; // make sure style contains properties needed. if( currentStyle.size === undefined ) currentStyle.size = defaultStyle.size; if( currentStyle.font === undefined ) currentStyle.font = defaultStyle.font; if( currentStyle.tracking === undefined ) currentStyle.tracking = defaultStyle.tracking; if( currentStyle.characterCase === undefined ) currentStyle.characterCase = defaultStyle.characterCase; if( currentStyle.fillColor === undefined ) currentStyle.fillColor = defaultStyle.fillColor; if( currentStyle.strokeColor === undefined ) currentStyle.strokeColor = defaultStyle.strokeColor; if( currentStyle.strokeWidth === undefined ) currentStyle.strokeWidth = defaultStyle.strokeWidth; } // newline if( this.text.charAt( i ) == "\n" ){ continue; } //runtime test for font if( txt.FontLoader.isLoaded( currentStyle.font ) === false ){ txt.FontLoader.load( this , [ currentStyle.font ] ); return false; } //initalize with initialTracking and initialOffset; if( hPosition == 0 ){ hPosition = this.initialOffset + this.trackingOffset( this.initialTracking , currentStyle.size , txt.FontLoader.getFont( currentStyle.font ).units ); } // create character char = new Character( this.text.charAt( i ) , currentStyle , i ); if( this.original.character ){ if( this.original.character.added ){ char.on( 'added' , this.original.character.added ); } if( this.original.character.click ){ char.on( 'click' , this.original.character.click ); } if( this.original.character.dblclick ){ char.on( 'dblclick' , this.original.character.dblclick ); } if( this.original.character.mousedown ){ char.on( 'mousedown' , this.original.character.mousedown ); } if( this.original.character.mouseout ){ char.on( 'mouseout' , this.original.character.mouseout ); } if( this.original.character.mouseover ){ char.on( 'mouseover' , this.original.character.mouseover ); } if( this.original.character.pressmove ){ char.on( 'pressmove' , this.original.character.pressmove ); } if( this.original.character.pressup ){ char.on( 'pressup' , this.original.character.pressup ); } if( this.original.character.removed ){ char.on( 'removed' , this.original.character.removed ); } if( this.original.character.rollout ){ char.on( 'rollout' , this.original.character.rollout ); } if( this.original.character.rollover ){ char.on( 'rollover' , this.original.character.rollover ); } if( this.original.character.tick ){ char.on( 'tick' , this.original.character.tick ); } } if( char.missing ){ if( this.missingGlyphs == null ){ this.missingGlyphs = []; } this.missingGlyphs.push( { position:i, character:this.text.charAt( i ), font:currentStyle.font } ); } //swap character if ligature //ligatures removed if tracking or this.ligatures is false if( currentStyle.tracking == 0 && this.ligatures == true ){ //1 char match var ligTarget = this.text.substr( i , 4 ); if( char._font.ligatures[ ligTarget.charAt( 0 ) ] ){ //2 char match if( char._font.ligatures[ ligTarget.charAt( 0 ) ][ ligTarget.charAt( 1 ) ] ){ //3 char match if( char._font.ligatures[ ligTarget.charAt( 0 ) ][ ligTarget.charAt( 1 ) ][ ligTarget.charAt( 2 ) ] ){ //4 char match if( char._font.ligatures[ ligTarget.charAt( 0 ) ][ ligTarget.charAt( 1 ) ][ ligTarget.charAt( 2 ) ][ ligTarget.charAt( 3 ) ] ){ //swap 4 char ligature char.setGlyph( char._font.ligatures[ ligTarget.charAt( 0 ) ][ ligTarget.charAt( 1 ) ][ ligTarget.charAt( 2 ) ][ ligTarget.charAt( 3 ) ].glyph ); i = i+3; }else{ //swap 3 char ligature char.setGlyph( char._font.ligatures[ ligTarget.charAt( 0 ) ][ ligTarget.charAt( 1 ) ][ ligTarget.charAt( 2 ) ].glyph ); i = i+2; } }else{ //swap 2 char ligature char.setGlyph( char._font.ligatures[ ligTarget.charAt( 0 ) ][ ligTarget.charAt( 1 ) ].glyph ); i = i+1; } } } } //char.hPosition = hPosition; // push character into block //this.characters.push( char ); //this.block.addChild( char ); if( this.overset == true ){ break; }else if( this.measured == true && hPosition + char.measuredWidth > this.getWidth() && this.oversetPotential == true ){ //char.hPosition = hPosition; //this.characters.push( char ); //this.block.addChild( char ); //this.block.removeChild(this.characters.pop() ); this.oversetIndex = i; this.overset = true; break; }else if( this.measured == false && hPosition + char.measuredWidth > this.getWidth() ){ //char.hPosition = hPosition; //this.characters.push( char ); //this.block.addChild( char ); //this.block.removeChild(this.characters.pop() ); this.oversetIndex = i; this.overset = true; break; }else{ char.hPosition = hPosition; this.characters.push( char ); this.block.addChild( char ); } //char.x = hPosition; hPosition = hPosition + ( char._glyph.offset * char.size ) + char.characterCaseOffset + char.trackingOffset() + char._glyph.getKerning( this.getCharCodeAt( i + 1 ) , char.size ); } len = this.characters.length; var pathPoint:any; var nextRotation = false; for( i = 0; i < len; i++ ){ char = <txt.Character>this.characters[ i ]; //console.log( this.getWidth() ); pathPoint = this.pathPoints.getPathPoint( char.hPosition , hPosition , char._glyph.offset * char.size ); //console.log( pathPoint ) //correct rotation around linesegments if( nextRotation == true ){ this.characters[ i-1 ].parent.rotation = pathPoint.rotation; nextRotation = false; } if( pathPoint.next == true ){ nextRotation = true; } char.rotation = pathPoint.rotation; //Baseline if( this.valign == txt.VerticalAlign.BaseLine ){ char.x = pathPoint.x; char.y = pathPoint.y; //reparent child into offset container if( pathPoint.offsetX ){ var offsetChild = new createjs.Container(); offsetChild.x = pathPoint.x offsetChild.y = pathPoint.y offsetChild.rotation = pathPoint.rotation; char.parent.removeChild( char ); offsetChild.addChild( char ); char.x = pathPoint.offsetX; char.y = 0; char.rotation = 0; this.addChild( offsetChild ); }else{ char.x = pathPoint.x; char.y = pathPoint.y; char.rotation = pathPoint.rotation; } }else{ var offsetChild = new createjs.Container(); offsetChild.x = pathPoint.x offsetChild.y = pathPoint.y offsetChild.rotation = pathPoint.rotation; char.parent.removeChild( char ); offsetChild.addChild( char ); char.x = 0; //vertical alignment if( this.valign == txt.VerticalAlign.Top ){ char.y = char.size; }else if( this.valign == txt.VerticalAlign.Bottom ){ char.y = char._font.descent / char._font.units * char.size; }else if( this.valign == txt.VerticalAlign.CapHeight ){ char.y = char._font[ 'cap-height' ] / char._font.units * char.size; }else if( this.valign == txt.VerticalAlign.XHeight ){ char.y = char._font[ 'x-height' ] / char._font.units * char.size; }else if( this.valign == txt.VerticalAlign.Ascent ){ char.y = char._font.ascent / char._font.units * char.size; }else if( this.valign == txt.VerticalAlign.Center ){ char.y = char._font[ 'cap-height' ] / char._font.units * char.size / 2; }else if( this.valign == txt.VerticalAlign.Percent ){ char.y = this.valignPercent * char.size; }else{ char.y = 0; } char.rotation = 0; this.addChild( offsetChild ); } } if( this.original.block ){ if( this.original.block.added ){ this.block.on( 'added' , this.original.block.added ); } if( this.original.block.click ){ this.block.on( 'click' , this.original.block.click ); } if( this.original.block.dblclick ){ this.block.on( 'dblclick' , this.original.block.dblclick ); } if( this.original.block.mousedown ){ this.block.on( 'mousedown' , this.original.block.mousedown ); } if( this.original.block.mouseout ){ this.block.on( 'mouseout' , this.original.block.mouseout ); } if( this.original.block.mouseover ){ this.block.on( 'mouseover' , this.original.block.mouseover ); } if( this.original.block.pressmove ){ this.block.on( 'pressmove' , this.original.block.pressmove ); } if( this.original.block.pressup ){ this.block.on( 'pressup' , this.original.block.pressup ); } if( this.original.block.removed ){ this.block.on( 'removed' , this.original.block.removed ); } if( this.original.block.rollout ){ this.block.on( 'rollout' , this.original.block.rollout ); } if( this.original.block.rollover ){ this.block.on( 'rollover' , this.original.block.rollover ); } if( this.original.block.tick ){ this.block.on( 'tick' , this.original.block.tick ); } } return true; } trackingOffset( tracking:number , size:number , units:number ):number { return size * ( 2.5 / units + 1 / 900 + tracking / 990 ); } offsetTracking( offset:number , size:number , units:number ):number { return Math.floor( ( offset - 2.5 / units - 1 / 900 ) * 990 / size ); } getCharCodeAt( index:number ):number { if( this.characterCase == txt.Case.NORMAL ){ return this.text.charAt( index ).charCodeAt( 0 ); }else if( this.characterCase == txt.Case.UPPER ){ return this.text.charAt( index ).toUpperCase().charCodeAt( 0 ); }else if( this.characterCase == txt.Case.LOWER ){ return this.text.charAt( index ).toLowerCase().charCodeAt( 0 ); }else if( this.characterCase == txt.Case.SMALL_CAPS ){ return this.text.charAt( index ).toUpperCase().charCodeAt( 0 ); }else{ //fallback case for unknown. return this.text.charAt( index ).charCodeAt( 0 ); } } } }
the_stack
import { window, commands, workspace } from 'vscode'; import StatusBar from '../utils/statusBarItem'; import Utilities from '../utils/Utilities'; import NpmData from './NpmData'; import getBuildCmnd from '../utils/config/build'; import getInfoCmnd from '../utils/config/info'; import { getServeCmnd, getServePortConfig } from '../utils/config/serve'; import { getDevelopPortConfig, getDevelopCmnd } from '../utils/config/develop'; import { NpmTreeItem } from '../utils/Interfaces'; // Defines the functionality of the Gatsby CLI Commands export default class GatsbyCli { private devServerStatus: boolean; private prodServerStatus: boolean; private buildStatus: boolean; initStatusBar: void; constructor() { // Defines the condition on which way to toggle statusBarItem this.devServerStatus = false; this.prodServerStatus = false; this.buildStatus = false; // Initializes the StatusBarItem this.initStatusBar = StatusBar.init(); this.toggleStatusBar = this.toggleStatusBar.bind(this); this.disposeServer = this.disposeServer.bind(this); this.develop = this.develop.bind(this); this.serve = this.serve.bind(this); this.build = this.build.bind(this); this.clean = this.clean.bind(this); } // ANCHOR: installs gatsby-cli for the user when install gatsby button is clicked async installGatsby() { // if a gatsby terminal isn't open, create a new terminal. Otherwise, use gatsbyhub terminal const activeTerminal = Utilities.getActiveTerminal(); // if windows user if (!process.env.USER) { activeTerminal.sendText('npm install -g gatsby-cli'); } else { // then it is linux or unnix based environment activeTerminal.sendText('sudo npm install -g gatsby-cli'); // Mac and Linux requrie password to install const inputPassword = await window.showInputBox({ password: true, placeHolder: 'Input administrator password', }); if (inputPassword !== undefined) activeTerminal.sendText(inputPassword); // if the password is wrong, show inputbox again // else, show terminal } activeTerminal.show(true); } // ANCHOR: /* ------------------ Logic for creating a new Gatsby site ------------------ */ /** creates a new site when 'Create New Site' button is clicked * currently uses default gatsby starter, but uses gatsby new url. see https://www.gatsbyjs.com/docs/gatsby-cli/ * note: new site will be created wherever the root directory is currently located * the user terminal should be at the directory user wishes to download the files. */ async createSite(starterObj?: NpmTreeItem): Promise<void> { // get GatsbyHub terminal or create a new terminal if it doesn't exist const activeTerminal = Utilities.getActiveTerminal(); // define string for button in information message const openFolderMsg = 'Open Different Folder'; const continueMsg = 'Continue'; const cancelMsg = 'Cancel'; /** * Check if the current workspace is a Gatsby project * If it is, don't let the user create another site in here * */ const gatsbyIsInitiated: boolean = await Utilities.checkIfGatsbySiteInitiated(); if (gatsbyIsInitiated) { const input = await window.showErrorMessage( "Can't create a site in a Gatsby Workspace. If you would like to start a new project, navigate to the parent directory and create a site there.", openFolderMsg, cancelMsg ); if (input && input === openFolderMsg) { commands.executeCommand('vscode.openFolder'); } return; } if (!starterObj) { const input = await window.showInformationMessage( 'This creates the default starter. If you would like a different starter, refer to the "Starters" menu.', 'Use default', 'Choose a different starter' ); if (input === 'Choose a different starter') return; } // tell user that new site will be created in current directory const choice = await window.showWarningMessage( `New Gatsby site will be created in current directory unless you open a different folder for your project`, openFolderMsg, continueMsg ); if (choice && choice === openFolderMsg) { commands.executeCommand('vscode.openFolder'); window.showWarningMessage('Make sure to create site again'); return; } // give user the option to create site in new folder instead // give user a place to write the name of their site const siteName = await window.showInputBox({ placeHolder: 'Enter Name of New Site', }); // send command to the terminal, if (siteName) { if (starterObj && starterObj.command) { const { repository } = starterObj.command.arguments[0].links; activeTerminal.sendText( `gatsby new ${siteName} ${repository} && cd ${siteName}` ); activeTerminal.sendText('code .'); activeTerminal.show(true); } else { activeTerminal.sendText(`gatsby new ${siteName} && cd ${siteName}`); activeTerminal.sendText('code .'); activeTerminal.show(true); } } else { window.showWarningMessage( 'Must enter a name for your new Gatsby project' ); } } // ANCHOR: /* --------------------- builds and packages Gatsby site -------------------- */ async build(): Promise<void> { const gatsbyIsInitiated: boolean = await Utilities.checkIfGatsbySiteInitiated(); // const siteIsBuilt: boolean = await Utilities.checkIfBuilt(); // NOTE not sure what to do with this yet // if (siteIsBuilt) { // this.buildStatus = true; // console.log('already built'); // return; // } if (!gatsbyIsInitiated) { const input = await window.showErrorMessage( 'Open up a new workspace containing only the site you are working on.', 'Change Workspace', 'Cancel' ); if (input && input === 'Change Workspace') { commands.executeCommand('vscode.openFolder'); } return; } const activeTerminal = Utilities.getActiveTerminal(); const build: string = getBuildCmnd(); activeTerminal.show(true); activeTerminal.sendText(build); this.buildStatus = true; setTimeout(() => { Utilities.checkIfBuilt(); }, 8000); } // ANCHOR: /* -------------------------- Handles info command -------------------------- */ info() { const activeTerminal = Utilities.getActiveTerminal(); const info: string = getInfoCmnd(); activeTerminal.show(true); activeTerminal.sendText(info); } // ANCHOR: /* -------------------------- Handles clean command ------------------------- */ clean() { const activeTerminal = Utilities.getActiveTerminal(); const clean = 'gatsby clean'; activeTerminal.show(true); activeTerminal.sendText(clean); this.buildStatus = false; Utilities.checkIfBuilt('cleaned'); } // ANCHOR: /* ---------- Logic handling the installation of Plugins and Themes --------- */ async install(plugin?: NpmTreeItem): Promise<void> { const activeTerminal = Utilities.getActiveTerminal(); const gatsbyIsInitiated: boolean = await Utilities.checkIfGatsbySiteInitiated(); if (!gatsbyIsInitiated) { const input = await window.showErrorMessage( 'Open up a new workspace containing only the site you are working on.', 'Change Workspace', 'Cancel' ); if (input && input === 'Change Workspace') { commands.executeCommand('vscode.openFolder'); } return; } if (plugin) { const { name, links } = plugin.command.arguments[0]; const installCmnd = (await NpmData.getNpmInstall(links.repository, links.homepage)) || `npm install ${name}`; activeTerminal.sendText(installCmnd); activeTerminal.show(true); // check for if "plugin" is a theme or actual plugin if (name.startsWith('gatsby-theme')) { window.showInformationMessage( 'Refer to this theme\'s documentation regarding implementation. Simply click on the theme\'s info icon in the "Themes" section.', 'OK' ); } else { window.showInformationMessage( 'Refer to this plugin\'s documentation regarding further configuration. Simply click on the plugin\'s info icon in the "Plugins" section.', 'OK' ); } } } /* -------------------------------------------------------------------------- */ /* Server Logic */ /* -------------------------------------------------------------------------- */ // ANCHOR - /* ------ Starts development server and opens project in a new browser ------ */ public async develop(): Promise<void> { // IF server is already running, throw error and exit if (this.devServerStatus) { window.showErrorMessage('Dev server already took off.'); return; } if (this.prodServerStatus) { const choice = await window.showErrorMessage( 'Production server is running. Do you want to shut it down?', 'Yes', 'No' ); if (choice && choice === 'Yes') { this.disposeServer(); } return; } const gatsbyIsInitiated: boolean = await Utilities.checkIfGatsbySiteInitiated(); if (!workspace.workspaceFolders) { window.showInformationMessage( 'Open a folder or workspace... (File -> Open Folder)' ); return; } if (!gatsbyIsInitiated) { const input = await window.showErrorMessage( 'Open up a new workspace containing only the site you are working on.', 'Change Workspace', 'Cancel' ); if (input && input === 'Change Workspace') { commands.executeCommand('vscode.openFolder'); } return; } const activeTerminal = Utilities.getActiveDevServerTerminal(); const port = getDevelopPortConfig(); const develop = getDevelopCmnd(); activeTerminal.sendText(`${develop}`); // change status bar to working message while server finishes developing StatusBar.working('Blast Off...'); // toggle statusBar after 3 seconds so it will dispose server if clicked again setTimeout(this.toggleStatusBar, 6000); window.showInformationMessage(`Starting up port:${port}`); activeTerminal.show(true); commands.executeCommand('setContext', 'serverIsRunning', true); } // ANCHOR: /* ------------------------ Handles the 'serve' command ------------------------ */ /** TODO * * Don't want graphiql button appearing for this server * Probably don't need to do anything with the status bar * */ public async serve(): Promise<void> { // IF server is already running, throw error and exit if (this.prodServerStatus) { window.showErrorMessage('Production server already took off.'); return; } if (this.devServerStatus) { const choice = await window.showErrorMessage( 'Dev server is running. Do you want to shut it down?', 'Yes', 'No' ); if (choice && choice === 'Yes') { this.disposeServer(); } return; } const gatsbyIsInitiated: boolean = await Utilities.checkIfGatsbySiteInitiated(); if (!gatsbyIsInitiated) { const input = await window.showErrorMessage( 'Open up a new workspace containing only the site you are working on.', 'Change Workspace', 'Cancel' ); if (input && input === 'Change Workspace') { commands.executeCommand('vscode.openFolder'); } return; } const input = await window.showWarningMessage( 'This serves the production build for testing purposes. Ensure the build command was run successfully before running this command.', 'Continue', 'Cancel' ); if (input !== 'Continue') return; const activeTerminal = Utilities.getActiveProdServerTerminal(); const prodPort: number = getServePortConfig(); const serve: string = getServeCmnd(); activeTerminal.show(true); activeTerminal.sendText(serve); window.showInformationMessage(`Starting up port:${prodPort}`); commands.executeCommand('setContext', 'prodServerIsRunning', true); this.prodServerStatus = true; } // ANCHOR: /* ---------- Disposes development server by disposing the terminal --------- */ public disposeServer(): void { const activeTerminal = Utilities.getActiveServer(); const devPort = getDevelopPortConfig(); const prodPort = getServePortConfig(); activeTerminal.dispose(); if (activeTerminal.name === 'GatsbyServer [Dev]') { // change status bar to working message while server finishes disposing StatusBar.working('Shutting Down...'); // toggle statusBar so it will develop if clicked again setTimeout(this.toggleStatusBar, 3000); window.showInformationMessage(`Shutting down port:${devPort}`); } else { window.showInformationMessage(`Shutting down port:${prodPort}`); this.prodServerStatus = false; } commands.executeCommand('setContext', 'serverIsRunning', false); commands.executeCommand('setContext', 'prodServerIsRunning', false); } /* -------------------------------------------------------------------------- */ /* Status Bar */ /* -------------------------------------------------------------------------- */ // ANCHOR: /* ---- toggles statusBar between developing server and disposing server ---- */ private toggleStatusBar(): void { const port = getDevelopPortConfig(); if (!this.devServerStatus) { StatusBar.offline(port); } else { StatusBar.online(); } this.devServerStatus = !this.devServerStatus; } // ANCHOR: /* ----------------------- Dispose the status bar item ---------------------- */ public dispose(): void { StatusBar.dispose(); } }
the_stack
// MIT License // Copyright (c) 2014 Chris McCord // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // minor tweaks to work within node for oorja const DEFAULT_VSN = "2.0.0" const SOCKET_STATES = {connecting: 0, open: 1, closing: 2, closed: 3} const DEFAULT_TIMEOUT = 10000 const WS_CLOSE_NORMAL = 1000 const CHANNEL_STATES = { closed: "closed", errored: "errored", joined: "joined", joining: "joining", leaving: "leaving", } const CHANNEL_EVENTS = { close: "phx_close", error: "phx_error", join: "phx_join", reply: "phx_reply", leave: "phx_leave" } const CHANNEL_LIFECYCLE_EVENTS = [ CHANNEL_EVENTS.close, CHANNEL_EVENTS.error, CHANNEL_EVENTS.join, CHANNEL_EVENTS.reply, CHANNEL_EVENTS.leave ] const TRANSPORTS = { longpoll: "longpoll", websocket: "websocket" } // wraps value in closure or returns closure let closure = (value) => { if(typeof value === "function"){ return value } else { let closure = function(){ return value } return closure } } /** * Initializes the Push * @param {Channel} channel - The Channel * @param {string} event - The event, for example `"phx_join"` * @param {Object} payload - The payload, for example `{user_id: 123}` * @param {number} timeout - The push timeout in milliseconds */ class Push { constructor(channel, event, payload, timeout){ this.channel = channel this.event = event this.payload = payload || function(){ return {} } this.receivedResp = null this.timeout = timeout this.timeoutTimer = null this.recHooks = [] this.sent = false } /** * * @param {number} timeout */ resend(timeout){ this.timeout = timeout this.reset() this.send() } /** * */ send(){ if(this.hasReceived("timeout")){ return } this.startTimeout() this.sent = true this.channel.socket.push({ topic: this.channel.topic, event: this.event, payload: this.payload(), ref: this.ref, join_ref: this.channel.joinRef() }) } /** * * @param {*} status * @param {*} callback */ receive(status, callback){ if(this.hasReceived(status)){ callback(this.receivedResp.response) } this.recHooks.push({status, callback}) return this } /** * @private */ reset(){ this.cancelRefEvent() this.ref = null this.refEvent = null this.receivedResp = null this.sent = false } /** * @private */ matchReceive({status, response, ref}){ this.recHooks.filter( h => h.status === status ) .forEach( h => h.callback(response) ) } /** * @private */ cancelRefEvent(){ if(!this.refEvent){ return } this.channel.off(this.refEvent) } /** * @private */ cancelTimeout(){ clearTimeout(this.timeoutTimer) this.timeoutTimer = null } /** * @private */ startTimeout(){ if(this.timeoutTimer){ this.cancelTimeout() } this.ref = this.channel.socket.makeRef() this.refEvent = this.channel.replyEventName(this.ref) this.channel.on(this.refEvent, payload => { this.cancelRefEvent() this.cancelTimeout() this.receivedResp = payload this.matchReceive(payload) }) this.timeoutTimer = setTimeout(() => { this.trigger("timeout", {}) }, this.timeout) } /** * @private */ hasReceived(status){ return this.receivedResp && this.receivedResp.status === status } /** * @private */ trigger(status, response){ this.channel.trigger(this.refEvent, {status, response}) } } /** * * @param {string} topic * @param {(Object|function)} params * @param {Socket} socket */ export class Channel { constructor(topic, params, socket) { this.state = CHANNEL_STATES.closed this.topic = topic this.params = closure(params || {}) this.socket = socket this.bindings = [] this.bindingRef = 0 this.timeout = this.socket.timeout this.joinedOnce = false this.joinPush = new Push(this, CHANNEL_EVENTS.join, this.params, this.timeout) this.pushBuffer = [] this.stateChangeRefs = []; this.rejoinTimer = new Timer(() => { if(this.socket.isConnected()){ this.rejoin() } }, this.socket.rejoinAfterMs) this.stateChangeRefs.push(this.socket.onError(() => this.rejoinTimer.reset())) this.stateChangeRefs.push(this.socket.onOpen(() => { this.rejoinTimer.reset() if(this.isErrored()){ this.rejoin() } }) ) this.joinPush.receive("ok", () => { this.state = CHANNEL_STATES.joined this.rejoinTimer.reset() this.pushBuffer.forEach( pushEvent => pushEvent.send() ) this.pushBuffer = [] }) this.joinPush.receive("error", () => { this.state = CHANNEL_STATES.errored if(this.socket.isConnected()){ this.rejoinTimer.scheduleTimeout() } }) this.onClose(() => { this.rejoinTimer.reset() if(this.socket.hasLogger()) this.socket.log("channel", `close ${this.topic} ${this.joinRef()}`) this.state = CHANNEL_STATES.closed this.socket.remove(this) }) this.onError(reason => { if(this.socket.hasLogger()) this.socket.log("channel", `error ${this.topic}`, reason) if(this.isJoining()){ this.joinPush.reset() } this.state = CHANNEL_STATES.errored if(this.socket.isConnected()){ this.rejoinTimer.scheduleTimeout() } }) this.joinPush.receive("timeout", () => { if(this.socket.hasLogger()) this.socket.log("channel", `timeout ${this.topic} (${this.joinRef()})`, this.joinPush.timeout) let leavePush = new Push(this, CHANNEL_EVENTS.leave, closure({}), this.timeout) leavePush.send() this.state = CHANNEL_STATES.errored this.joinPush.reset() if(this.socket.isConnected()){ this.rejoinTimer.scheduleTimeout() } }) this.on(CHANNEL_EVENTS.reply, (payload, ref) => { this.trigger(this.replyEventName(ref), payload) }) } /** * Join the channel * @param {integer} timeout * @returns {Push} */ join(timeout = this.timeout){ if(this.joinedOnce){ throw new Error(`tried to join multiple times. 'join' can only be called a single time per channel instance`) } else { this.timeout = timeout this.joinedOnce = true this.rejoin() return this.joinPush } } /** * Hook into channel close * @param {Function} callback */ onClose(callback){ this.on(CHANNEL_EVENTS.close, callback) } /** * Hook into channel errors * @param {Function} callback */ onError(callback){ return this.on(CHANNEL_EVENTS.error, reason => callback(reason)) } /** * Subscribes on channel events * * Subscription returns a ref counter, which can be used later to * unsubscribe the exact event listener * * @example * const ref1 = channel.on("event", do_stuff) * const ref2 = channel.on("event", do_other_stuff) * channel.off("event", ref1) * // Since unsubscription, do_stuff won't fire, * // while do_other_stuff will keep firing on the "event" * * @param {string} event * @param {Function} callback * @returns {integer} ref */ on(event, callback){ let ref = this.bindingRef++ this.bindings.push({event, ref, callback}) return ref } /** * Unsubscribes off of channel events * * Use the ref returned from a channel.on() to unsubscribe one * handler, or pass nothing for the ref to unsubscribe all * handlers for the given event. * * @example * // Unsubscribe the do_stuff handler * const ref1 = channel.on("event", do_stuff) * channel.off("event", ref1) * * // Unsubscribe all handlers from event * channel.off("event") * * @param {string} event * @param {integer} ref */ off(event, ref){ this.bindings = this.bindings.filter((bind) => { return !(bind.event === event && (typeof ref === "undefined" || ref === bind.ref)) }) } /** * @private */ canPush(){ return this.socket.isConnected() && this.isJoined() } /** * Sends a message `event` to phoenix with the payload `payload`. * Phoenix receives this in the `handle_in(event, payload, socket)` * function. if phoenix replies or it times out (default 10000ms), * then optionally the reply can be received. * * @example * channel.push("event") * .receive("ok", payload => console.log("phoenix replied:", payload)) * .receive("error", err => console.log("phoenix errored", err)) * .receive("timeout", () => console.log("timed out pushing")) * @param {string} event * @param {Object} payload * @param {number} [timeout] * @returns {Push} */ push(event, payload, timeout = this.timeout){ if(!this.joinedOnce){ throw new Error(`tried to push '${event}' to '${this.topic}' before joining. Use channel.join() before pushing events`) } let pushEvent = new Push(this, event, function(){ return payload }, timeout) if(this.canPush()){ pushEvent.send() } else { pushEvent.startTimeout() this.pushBuffer.push(pushEvent) } return pushEvent } /** Leaves the channel * * Unsubscribes from server events, and * instructs channel to terminate on server * * Triggers onClose() hooks * * To receive leave acknowledgements, use the `receive` * hook to bind to the server ack, ie: * * @example * channel.leave().receive("ok", () => alert("left!") ) * * @param {integer} timeout * @returns {Push} */ leave(timeout = this.timeout){ this.rejoinTimer.reset() this.joinPush.cancelTimeout() this.state = CHANNEL_STATES.leaving let onClose = () => { if(this.socket.hasLogger()) this.socket.log("channel", `leave ${this.topic}`) this.trigger(CHANNEL_EVENTS.close, "leave") } let leavePush = new Push(this, CHANNEL_EVENTS.leave, closure({}), timeout) leavePush.receive("ok", () => onClose() ) .receive("timeout", () => onClose() ) leavePush.send() if(!this.canPush()){ leavePush.trigger("ok", {}) } return leavePush } /** * Overridable message hook * * Receives all events for specialized message handling * before dispatching to the channel callbacks. * * Must return the payload, modified or unmodified * @param {string} event * @param {Object} payload * @param {integer} ref * @returns {Object} */ onMessage(event, payload, ref){ return payload } /** * @private */ isLifecycleEvent(event) { return CHANNEL_LIFECYCLE_EVENTS.indexOf(event) >= 0 } /** * @private */ isMember(topic, event, payload, joinRef){ if(this.topic !== topic){ return false } if(joinRef && joinRef !== this.joinRef() && this.isLifecycleEvent(event)){ if (this.socket.hasLogger()) this.socket.log("channel", "dropping outdated message", {topic, event, payload, joinRef}) return false } else { return true } } /** * @private */ joinRef(){ return this.joinPush.ref } /** * @private */ rejoin(timeout = this.timeout){ if(this.isLeaving()){ return } this.socket.leaveOpenTopic(this.topic) this.state = CHANNEL_STATES.joining this.joinPush.resend(timeout) } /** * @private */ trigger(event, payload, ref, joinRef){ let handledPayload = this.onMessage(event, payload, ref, joinRef) if(payload && !handledPayload){ throw new Error("channel onMessage callbacks must return the payload, modified or unmodified") } let eventBindings = this.bindings.filter(bind => bind.event === event) for (let i = 0; i < eventBindings.length; i++) { let bind = eventBindings[i] bind.callback(handledPayload, ref, joinRef || this.joinRef()) } } /** * @private */ replyEventName(ref){ return `chan_reply_${ref}` } /** * @private */ isClosed() { return this.state === CHANNEL_STATES.closed } /** * @private */ isErrored(){ return this.state === CHANNEL_STATES.errored } /** * @private */ isJoined() { return this.state === CHANNEL_STATES.joined } /** * @private */ isJoining(){ return this.state === CHANNEL_STATES.joining } /** * @private */ isLeaving(){ return this.state === CHANNEL_STATES.leaving } } /* The default serializer for encoding and decoding messages */ export let Serializer = { encode(msg, callback){ let payload = [ msg.join_ref, msg.ref, msg.topic, msg.event, msg.payload ] return callback(JSON.stringify(payload)) }, decode(rawPayload, callback){ let [join_ref, ref, topic, event, payload] = JSON.parse(rawPayload) return callback({join_ref, ref, topic, event, payload}) } } /** Initializes the Socket * * * For IE8 support use an ES5-shim (https://github.com/es-shims/es5-shim) * * @param {string} endPoint - The string WebSocket endpoint, ie, `"ws://example.com/socket"`, * `"wss://example.com"` * `"/socket"` (inherited host & protocol) * @param {Object} [opts] - Optional configuration * @param {string} [opts.transport] - The Websocket Transport, for example WebSocket or Phoenix.LongPoll. * * Defaults to WebSocket with automatic LongPoll fallback. * @param {Function} [opts.encode] - The function to encode outgoing messages. * * Defaults to JSON encoder. * * @param {Function} [opts.decode] - The function to decode incoming messages. * * Defaults to JSON: * * ```javascript * (payload, callback) => callback(JSON.parse(payload)) * ``` * * @param {number} [opts.timeout] - The default timeout in milliseconds to trigger push timeouts. * * Defaults `DEFAULT_TIMEOUT` * @param {number} [opts.heartbeatIntervalMs] - The millisec interval to send a heartbeat message * @param {number} [opts.reconnectAfterMs] - The optional function that returns the millsec * socket reconnect interval. * * Defaults to stepped backoff of: * * ```javascript * function(tries){ * return [10, 50, 100, 150, 200, 250, 500, 1000, 2000][tries - 1] || 5000 * } * ```` * * @param {number} [opts.rejoinAfterMs] - The optional function that returns the millsec * rejoin interval for individual channels. * * ```javascript * function(tries){ * return [1000, 2000, 5000][tries - 1] || 10000 * } * ```` * * @param {Function} [opts.logger] - The optional function for specialized logging, ie: * * ```javascript * function(kind, msg, data) { * console.log(`${kind}: ${msg}`, data) * } * ``` * * @param {number} [opts.longpollerTimeout] - The maximum timeout of a long poll AJAX request. * * Defaults to 20s (double the server long poll timer). * * @param {{Object|function)} [opts.params] - The optional params to pass when connecting * @param {string} [opts.binaryType] - The binary type to use for binary WebSocket frames. * * Defaults to "arraybuffer" * * @param {vsn} [opts.vsn] - The serializer's protocol version to send on connect. * * Defaults to DEFAULT_VSN. */ export class Socket { constructor(endPoint, opts = {}){ this.stateChangeCallbacks = {open: [], close: [], error: [], message: []} this.channels = [] this.sendBuffer = [] this.ref = 0 this.timeout = opts.timeout || DEFAULT_TIMEOUT this.transport = require("ws") this.defaultEncoder = Serializer.encode this.defaultDecoder = Serializer.decode this.closeWasClean = false this.unloaded = false this.binaryType = opts.binaryType || "arraybuffer" if(this.transport !== LongPoll){ this.encode = opts.encode || this.defaultEncoder this.decode = opts.decode || this.defaultDecoder } else { this.encode = this.defaultEncoder this.decode = this.defaultDecoder } this.heartbeatIntervalMs = opts.heartbeatIntervalMs || 30000 this.rejoinAfterMs = (tries) => { if(opts.rejoinAfterMs){ return opts.rejoinAfterMs(tries) } else { return [1000, 2000, 5000][tries - 1] || 10000 } } this.reconnectAfterMs = (tries) => { if(this.unloaded){ return 100 } if(opts.reconnectAfterMs){ return opts.reconnectAfterMs(tries) } else { return [10, 50, 100, 150, 200, 250, 500, 1000, 2000][tries - 1] || 5000 } } this.logger = opts.logger || null this.longpollerTimeout = opts.longpollerTimeout || 20000 this.params = closure(opts.params || {}) this.endPoint = `${endPoint}/${TRANSPORTS.websocket}` this.vsn = opts.vsn || DEFAULT_VSN this.heartbeatTimer = null this.pendingHeartbeatRef = null this.reconnectTimer = new Timer(() => { this.teardown(() => this.connect()) }, this.reconnectAfterMs) } /** * Returns the socket protocol * * @returns {string} */ protocol(){ return location.protocol.match(/^https/) ? "wss" : "ws" } /** * The fully qualifed socket url * * @returns {string} */ endPointURL(){ let uri = Ajax.appendParams( Ajax.appendParams(this.endPoint, this.params()), {vsn: this.vsn}) return uri; // if(uri.charAt(0) !== "/"){ return uri } // if(uri.charAt(1) === "/"){ return `${this.protocol()}:${uri}` } // return `${this.protocol()}://${location.host}${uri}` } /** * Disconnects the socket * * See https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes for valid status codes. * * @param {Function} callback - Optional callback which is called after socket is disconnected. * @param {integer} code - A status code for disconnection (Optional). * @param {string} reason - A textual description of the reason to disconnect. (Optional) */ disconnect(callback, code, reason){ this.closeWasClean = true this.reconnectTimer.reset() this.teardown(callback, code, reason) } /** * * @param {Object} params - The params to send when connecting, for example `{user_id: userToken}` * * Passing params to connect is deprecated; pass them in the Socket constructor instead: * `new Socket("/socket", {params: {user_id: userToken}})`. */ connect(params){ if(params){ console && console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor") this.params = closure(params) } if(this.conn){ return } this.closeWasClean = false this.conn = new this.transport(this.endPointURL()) this.conn.binaryType = this.binaryType this.conn.timeout = this.longpollerTimeout this.conn.onopen = () => this.onConnOpen() this.conn.onerror = error => this.onConnError(error) this.conn.onmessage = event => this.onConnMessage(event) this.conn.onclose = event => this.onConnClose(event) } /** * Logs the message. Override `this.logger` for specialized logging. noops by default * @param {string} kind * @param {string} msg * @param {Object} data */ log(kind, msg, data){ this.logger(kind, msg, data) } /** * Returns true if a logger has been set on this socket. */ hasLogger(){ return this.logger !== null } /** * Registers callbacks for connection open events * * @example socket.onOpen(function(){ console.info("the socket was opened") }) * * @param {Function} callback */ onOpen(callback){ let ref = this.makeRef() this.stateChangeCallbacks.open.push([ref, callback]) return ref } /** * Registers callbacks for connection close events * @param {Function} callback */ onClose(callback){ let ref = this.makeRef() this.stateChangeCallbacks.close.push([ref, callback]) return ref } /** * Registers callbacks for connection error events * * @example socket.onError(function(error){ alert("An error occurred") }) * * @param {Function} callback */ onError(callback){ let ref = this.makeRef() this.stateChangeCallbacks.error.push([ref, callback]) return ref } /** * Registers callbacks for connection message events * @param {Function} callback */ onMessage(callback){ let ref = this.makeRef() this.stateChangeCallbacks.message.push([ref, callback]) return ref } /** * @private */ onConnOpen(){ if(this.hasLogger()) this.log("transport", `connected to ${this.endPointURL()}`) this.unloaded = false this.closeWasClean = false this.flushSendBuffer() this.reconnectTimer.reset() this.resetHeartbeat() this.stateChangeCallbacks.open.forEach(([, callback]) => callback() ) } /** * @private */ resetHeartbeat(){ if(this.conn && this.conn.skipHeartbeat){ return } this.pendingHeartbeatRef = null clearInterval(this.heartbeatTimer) this.heartbeatTimer = setInterval(() => this.sendHeartbeat(), this.heartbeatIntervalMs) } teardown(callback, code, reason){ if (!this.conn) { return callback && callback() } this.waitForBufferDone(() => { if (this.conn) { if(code){ this.conn.close(code, reason || "") } else { this.conn.close() } } this.waitForSocketClosed(() => { if (this.conn) { this.conn.onclose = function(){} // noop this.conn = null } callback && callback() }) }) } waitForBufferDone(callback, tries = 1) { if (tries === 5 || !this.conn || !this.conn.bufferedAmount) { callback() return } setTimeout(() => { this.waitForBufferDone(callback, tries + 1) }, 150 * tries) } waitForSocketClosed(callback, tries = 1) { if (tries === 5 || !this.conn || this.conn.readyState === SOCKET_STATES.closed) { callback() return } setTimeout(() => { this.waitForSocketClosed(callback, tries + 1) }, 150 * tries) } onConnClose(event){ if (this.hasLogger()) this.log("transport", "close", event) this.triggerChanError() clearInterval(this.heartbeatTimer) if(!this.closeWasClean){ this.reconnectTimer.scheduleTimeout() } this.stateChangeCallbacks.close.forEach(([, callback]) => callback(event) ) } /** * @private */ onConnError(error){ if (this.hasLogger()) this.log("transport", error) this.triggerChanError() this.stateChangeCallbacks.error.forEach(([, callback]) => callback(error) ) } /** * @private */ triggerChanError(){ this.channels.forEach( channel => { if(!(channel.isErrored() || channel.isLeaving() || channel.isClosed())){ channel.trigger(CHANNEL_EVENTS.error) } }) } /** * @returns {string} */ connectionState(){ switch(this.conn && this.conn.readyState){ case SOCKET_STATES.connecting: return "connecting" case SOCKET_STATES.open: return "open" case SOCKET_STATES.closing: return "closing" default: return "closed" } } /** * @returns {boolean} */ isConnected(){ return this.connectionState() === "open" } /** * @private * * @param {Channel} */ remove(channel){ this.off(channel.stateChangeRefs) this.channels = this.channels.filter(c => c.joinRef() !== channel.joinRef()) } /** * Removes `onOpen`, `onClose`, `onError,` and `onMessage` registrations. * * @param {refs} - list of refs returned by calls to * `onOpen`, `onClose`, `onError,` and `onMessage` */ off(refs) { for(let key in this.stateChangeCallbacks){ this.stateChangeCallbacks[key] = this.stateChangeCallbacks[key].filter(([ref]) => { return refs.indexOf(ref) === -1 }) } } /** * Initiates a new channel for the given topic * * @param {string} topic * @param {Object} chanParams - Parameters for the channel * @returns {Channel} */ channel(topic, chanParams = {}){ let chan = new Channel(topic, chanParams, this) this.channels.push(chan) return chan } /** * @param {Object} data */ push(data){ if (this.hasLogger()) { let {topic, event, payload, ref, join_ref} = data this.log("push", `${topic} ${event} (${join_ref}, ${ref})`, payload) } if(this.isConnected()){ this.encode(data, result => this.conn.send(result)) } else { this.sendBuffer.push(() => this.encode(data, result => this.conn.send(result))) } } /** * Return the next message ref, accounting for overflows * @returns {string} */ makeRef(){ let newRef = this.ref + 1 if(newRef === this.ref){ this.ref = 0 } else { this.ref = newRef } return this.ref.toString() } sendHeartbeat(){ if(!this.isConnected()){ return } if(this.pendingHeartbeatRef){ this.pendingHeartbeatRef = null if (this.hasLogger()) this.log("transport", "heartbeat timeout. Attempting to re-establish connection") this.abnormalClose("heartbeat timeout") return } this.pendingHeartbeatRef = this.makeRef() this.push({topic: "phoenix", event: "heartbeat", payload: {}, ref: this.pendingHeartbeatRef}) } abnormalClose(reason){ this.closeWasClean = false this.conn.close(WS_CLOSE_NORMAL, reason) } flushSendBuffer(){ if(this.isConnected() && this.sendBuffer.length > 0){ this.sendBuffer.forEach( callback => callback() ) this.sendBuffer = [] } } onConnMessage(rawMessage){ this.decode(rawMessage.data, msg => { let {topic, event, payload, ref, join_ref} = msg if(ref && ref === this.pendingHeartbeatRef){ this.pendingHeartbeatRef = null } if (this.hasLogger()) this.log("receive", `${payload.status || ""} ${topic} ${event} ${ref && "(" + ref + ")" || ""}`, payload) for (let i = 0; i < this.channels.length; i++) { const channel = this.channels[i] if(!channel.isMember(topic, event, payload, join_ref)){ continue } channel.trigger(event, payload, ref, join_ref) } for (let i = 0; i < this.stateChangeCallbacks.message.length; i++) { let [, callback] = this.stateChangeCallbacks.message[i] callback(msg) } }) } leaveOpenTopic(topic){ let dupChannel = this.channels.find(c => c.topic === topic && (c.isJoined() || c.isJoining())) if(dupChannel){ if(this.hasLogger()) this.log("transport", `leaving duplicate topic "${topic}"`) dupChannel.leave() } } } export class LongPoll { constructor(endPoint){ this.endPoint = null this.token = null this.skipHeartbeat = true this.onopen = function(){} // noop this.onerror = function(){} // noop this.onmessage = function(){} // noop this.onclose = function(){} // noop this.pollEndpoint = this.normalizeEndpoint(endPoint) this.readyState = SOCKET_STATES.connecting this.poll() } normalizeEndpoint(endPoint){ return(endPoint .replace("ws://", "http://") .replace("wss://", "https://") .replace(new RegExp("(.*)\/" + TRANSPORTS.websocket), "$1/" + TRANSPORTS.longpoll)) } endpointURL(){ return Ajax.appendParams(this.pollEndpoint, {token: this.token}) } closeAndRetry(){ this.close() this.readyState = SOCKET_STATES.connecting } ontimeout(){ this.onerror("timeout") this.closeAndRetry() } poll(){ if(!(this.readyState === SOCKET_STATES.open || this.readyState === SOCKET_STATES.connecting)){ return } Ajax.request("GET", this.endpointURL(), "application/json", null, this.timeout, this.ontimeout.bind(this), (resp) => { if(resp){ var {status, token, messages} = resp this.token = token } else{ var status = 0 } switch(status){ case 200: messages.forEach(msg => this.onmessage({data: msg})) this.poll() break case 204: this.poll() break case 410: this.readyState = SOCKET_STATES.open this.onopen() this.poll() break case 403: this.onerror() this.close() break case 0: case 500: this.onerror() this.closeAndRetry() break default: throw new Error(`unhandled poll status ${status}`) } }) } send(body){ Ajax.request("POST", this.endpointURL(), "application/json", body, this.timeout, this.onerror.bind(this, "timeout"), (resp) => { if(!resp || resp.status !== 200){ this.onerror(resp && resp.status) this.closeAndRetry() } }) } close(code, reason){ this.readyState = SOCKET_STATES.closed this.onclose() } } export class Ajax { static request(method, endPoint, accept, body, timeout, ontimeout, callback){ if(global.XDomainRequest){ let req = new XDomainRequest() // IE8, IE9 this.xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback) } else { let req = new global.XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari this.xhrRequest(req, method, endPoint, accept, body, timeout, ontimeout, callback) } } static xdomainRequest(req, method, endPoint, body, timeout, ontimeout, callback){ req.timeout = timeout req.open(method, endPoint) req.onload = () => { let response = this.parseJSON(req.responseText) callback && callback(response) } if(ontimeout){ req.ontimeout = ontimeout } // Work around bug in IE9 that requires an attached onprogress handler req.onprogress = () => {} req.send(body) } static xhrRequest(req, method, endPoint, accept, body, timeout, ontimeout, callback){ req.open(method, endPoint, true) req.timeout = timeout req.setRequestHeader("Content-Type", accept) req.onerror = () => { callback && callback(null) } req.onreadystatechange = () => { if(req.readyState === this.states.complete && callback){ let response = this.parseJSON(req.responseText) callback(response) } } if(ontimeout){ req.ontimeout = ontimeout } req.send(body) } static parseJSON(resp){ if(!resp || resp === ""){ return null } try { return JSON.parse(resp) } catch(e) { console && console.log("failed to parse JSON response", resp) return null } } static serialize(obj, parentKey){ let queryStr = [] for(var key in obj){ if(!obj.hasOwnProperty(key)){ continue } let paramKey = parentKey ? `${parentKey}[${key}]` : key let paramVal = obj[key] if(typeof paramVal === "object"){ queryStr.push(this.serialize(paramVal, paramKey)) } else { queryStr.push(encodeURIComponent(paramKey) + "=" + encodeURIComponent(paramVal)) } } return queryStr.join("&") } static appendParams(url, params){ if(Object.keys(params).length === 0){ return url } let prefix = url.match(/\?/) ? "&" : "?" return `${url}${prefix}${this.serialize(params)}` } } Ajax.states = {complete: 4} /** * Initializes the Presence * @param {Channel} channel - The Channel * @param {Object} opts - The options, * for example `{events: {state: "state", diff: "diff"}}` */ export class Presence { constructor(channel, opts = {}){ let events = opts.events || {state: "presence_state", diff: "presence_diff"} this.state = {} this.pendingDiffs = [] this.channel = channel this.joinRef = null this.caller = { onJoin: function(){}, onLeave: function(){}, onSync: function(){} } this.channel.on(events.state, newState => { let {onJoin, onLeave, onSync} = this.caller this.joinRef = this.channel.joinRef() this.state = Presence.syncState(this.state, newState, onJoin, onLeave) this.pendingDiffs.forEach(diff => { this.state = Presence.syncDiff(this.state, diff, onJoin, onLeave) }) this.pendingDiffs = [] onSync() }) this.channel.on(events.diff, diff => { let {onJoin, onLeave, onSync} = this.caller if(this.inPendingSyncState()){ this.pendingDiffs.push(diff) } else { this.state = Presence.syncDiff(this.state, diff, onJoin, onLeave) onSync() } }) } onJoin(callback){ this.caller.onJoin = callback } onLeave(callback){ this.caller.onLeave = callback } onSync(callback){ this.caller.onSync = callback } list(by){ return Presence.list(this.state, by) } inPendingSyncState(){ return !this.joinRef || (this.joinRef !== this.channel.joinRef()) } // lower-level public static API /** * Used to sync the list of presences on the server * with the client's state. An optional `onJoin` and `onLeave` callback can * be provided to react to changes in the client's local presences across * disconnects and reconnects with the server. * * @returns {Presence} */ static syncState(currentState, newState, onJoin, onLeave){ let state = this.clone(currentState) let joins = {} let leaves = {} this.map(state, (key, presence) => { if(!newState[key]){ leaves[key] = presence } }) this.map(newState, (key, newPresence) => { let currentPresence = state[key] if(currentPresence){ let newRefs = newPresence.metas.map(m => m.phx_ref) let curRefs = currentPresence.metas.map(m => m.phx_ref) let joinedMetas = newPresence.metas.filter(m => curRefs.indexOf(m.phx_ref) < 0) let leftMetas = currentPresence.metas.filter(m => newRefs.indexOf(m.phx_ref) < 0) if(joinedMetas.length > 0){ joins[key] = newPresence joins[key].metas = joinedMetas } if(leftMetas.length > 0){ leaves[key] = this.clone(currentPresence) leaves[key].metas = leftMetas } } else { joins[key] = newPresence } }) return this.syncDiff(state, {joins: joins, leaves: leaves}, onJoin, onLeave) } /** * * Used to sync a diff of presence join and leave * events from the server, as they happen. Like `syncState`, `syncDiff` * accepts optional `onJoin` and `onLeave` callbacks to react to a user * joining or leaving from a device. * * @returns {Presence} */ static syncDiff(currentState, {joins, leaves}, onJoin, onLeave){ let state = this.clone(currentState) if(!onJoin){ onJoin = function(){} } if(!onLeave){ onLeave = function(){} } this.map(joins, (key, newPresence) => { let currentPresence = state[key] state[key] = newPresence if(currentPresence){ let joinedRefs = state[key].metas.map(m => m.phx_ref) let curMetas = currentPresence.metas.filter(m => joinedRefs.indexOf(m.phx_ref) < 0) state[key].metas.unshift(...curMetas) } onJoin(key, currentPresence, newPresence) }) this.map(leaves, (key, leftPresence) => { let currentPresence = state[key] if(!currentPresence){ return } let refsToRemove = leftPresence.metas.map(m => m.phx_ref) currentPresence.metas = currentPresence.metas.filter(p => { return refsToRemove.indexOf(p.phx_ref) < 0 }) onLeave(key, currentPresence, leftPresence) if(currentPresence.metas.length === 0){ delete state[key] } }) return state } /** * Returns the array of presences, with selected metadata. * * @param {Object} presences * @param {Function} chooser * * @returns {Presence} */ static list(presences, chooser){ if(!chooser){ chooser = function(key, pres){ return pres } } return this.map(presences, (key, presence) => { return chooser(key, presence) }) } // private static map(obj, func){ return Object.getOwnPropertyNames(obj).map(key => func(key, obj[key])) } static clone(obj){ return JSON.parse(JSON.stringify(obj)) } } /** * * Creates a timer that accepts a `timerCalc` function to perform * calculated timeout retries, such as exponential backoff. * * @example * let reconnectTimer = new Timer(() => this.connect(), function(tries){ * return [1000, 5000, 10000][tries - 1] || 10000 * }) * reconnectTimer.scheduleTimeout() // fires after 1000 * reconnectTimer.scheduleTimeout() // fires after 5000 * reconnectTimer.reset() * reconnectTimer.scheduleTimeout() // fires after 1000 * * @param {Function} callback * @param {Function} timerCalc */ class Timer { constructor(callback, timerCalc){ this.callback = callback this.timerCalc = timerCalc this.timer = null this.tries = 0 } reset(){ this.tries = 0 clearTimeout(this.timer) } /** * Cancels any previous scheduleTimeout and schedules callback */ scheduleTimeout(){ clearTimeout(this.timer) this.timer = setTimeout(() => { this.tries = this.tries + 1 this.callback() }, this.timerCalc(this.tries + 1)) } }
the_stack
import { Component, ChangeDetectionStrategy, Injectable, Optional } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { FieldWrapper, FormlyFieldConfig } from '@ngx-formly/core'; import { createFieldComponent, FormlyInputModule, createFieldChangesSpy } from '@ngx-formly/core/testing'; import { tick, fakeAsync } from '@angular/core/testing'; import { tap, map, shareReplay } from 'rxjs/operators'; import { FormlyFieldConfigCache } from '../models'; import { timer } from 'rxjs'; import { FieldType } from '../templates/field.type'; const renderComponent = (field: FormlyFieldConfig, opts: any = {}) => { const { config, ...options } = opts; return createFieldComponent(field, { imports: [FormlyInputModule], declarations: [FormlyWrapperFormFieldAsync, FormlyOnPushComponent, FormlyParentComponent, FormlyChildComponent], config: { types: [ { name: 'on-push', component: FormlyOnPushComponent, }, { name: 'parent', component: FormlyParentComponent, }, { name: 'child', component: FormlyChildComponent, }, ], wrappers: [ { name: 'form-field-async', component: FormlyWrapperFormFieldAsync, }, ], ...(config || {}), }, ...options, }); }; describe('FormlyField Component', () => { it('should add field className', () => { const { query } = renderComponent({ className: 'foo-class' }); expect(query('formly-field').attributes.class).toEqual('foo-class'); }); describe('host attrs', () => { it('should set style and class attrs on first render', () => { const { query } = renderComponent( { hide: true, className: 'foo' }, { config: { extras: { lazyRender: false } } }, ); expect(query('formly-field').attributes.class).toEqual('foo'); expect(query('formly-field').styles.display).toEqual('none'); }); it('should update style and class attrs on change', () => { const { field, query } = renderComponent({}, { config: { extras: { lazyRender: false } } }); expect(query('formly-field').attributes.class).toEqual(undefined); expect(query('formly-field').styles.display).toEqual(''); field.hide = true; field.className = 'foo'; expect(query('formly-field').attributes.class).toEqual('foo'); expect(query('formly-field').styles.display).toEqual('none'); }); it('should not override existing class', () => { const { query } = renderComponent({}, { template: '<formly-field class="foo" [field]="field"></formly-field>' }); expect(query('formly-field').attributes.class).toEqual('foo'); }); }); describe('disable renderFormlyFieldElement', () => { it('should not render content inside formly-field element', () => { const { query } = renderComponent({ type: 'input' }, { config: { extras: { renderFormlyFieldElement: false } } }); expect(query('formly-wrapper-form-field')).toBeDefined(); expect(query('formly-field > formly-wrapper-form-field')).toBeNull(); }); it('should apply className and styles to formly-field wrapper', () => { const { field, detectChanges, query } = renderComponent( { hide: true, type: 'input', className: 'foo', }, { config: { extras: { lazyRender: false, renderFormlyFieldElement: false } } }, ); const formlyField = query('formly-field'); const wrapper = query('formly-wrapper-form-field'); expect(formlyField.styles.display).toEqual(''); expect(formlyField.attributes.class).toEqual(undefined); expect(wrapper.styles.display).toEqual('none'); expect(wrapper.attributes.class).toEqual('foo'); field.hide = false; field.className = ''; detectChanges(); expect(wrapper.styles.display).toEqual(''); expect(wrapper.styles.display).toEqual(''); }); }); it('should call field hooks if set', () => { const f: FormlyFieldConfig = { hooks: { afterContentInit: () => {}, afterViewInit: () => {}, onInit: () => {}, onChanges: () => {}, onDestroy: () => {}, }, }; const hooks = f.hooks; Object.keys(f.hooks).forEach((hook) => { spyOn(hooks, hook as any); }); const { fixture, field } = renderComponent(f); fixture.destroy(); Object.keys(f.hooks).forEach((name) => { expect(hooks[name]).toHaveBeenCalledWith(field); }); }); it('should render field type without wrapper', () => { const { query } = renderComponent({ key: 'title', type: 'input', wrappers: [], }); expect(query('formly-wrapper-form-field')).toBeNull(); expect(query('formly-type-input')).not.toBeNull(); }); it('should render field component with wrapper', () => { const { query } = renderComponent({ key: 'title', type: 'input', wrappers: ['form-field'], }); expect(query('formly-wrapper-form-field')).not.toBeNull(); expect(query('formly-type-input')).not.toBeNull(); }); it('should not throw error when field is null', () => { const render = () => renderComponent(null); expect(render).not.toThrowError(); }); it('should render field component with async wrapper', () => { const { field, detectChanges, query } = renderComponent({ key: 'title', type: 'input', wrappers: ['form-field-async'], templateOptions: { render: false }, }); expect(query('formly-wrapper-form-field-async')).not.toBeNull(); expect(query('formly-type-input')).toBeNull(); field.templateOptions.render = true; detectChanges(); expect(query('formly-type-input')).not.toBeNull(); }); it('should lazy render field components by default', () => { const { field, detectChanges, query, fixture } = renderComponent({ key: 'title', type: 'input', hide: true, }); expect(query('formly-type-input')).toBeNull(); field.hide = false; detectChanges(); expect(query('formly-type-input')).not.toBeNull(); }); it('should add style display none to hidden field', () => { const { field, detectChanges, query } = renderComponent( { hide: true }, { config: { extras: { lazyRender: false } } }, ); const { styles } = query('formly-field'); expect(styles.display).toEqual('none'); field.hide = false; detectChanges(); expect(styles.display).toEqual(''); }); it('init hooks with observables', () => { const control = new FormControl(); const spy = jest.fn(); const initHookFn = (f: FormlyFieldConfig) => { return f.formControl.valueChanges.pipe(tap(spy)); }; const { fixture } = renderComponent({ key: 'title', type: 'input', formControl: control, modelOptions: {}, parent: { formControl: new FormGroup({}), }, hooks: { afterContentInit: initHookFn, afterViewInit: initHookFn, onInit: initHookFn, }, }); expect(spy).not.toHaveBeenCalled(); control.patchValue('test'); expect(spy).toHaveBeenCalledTimes(3); spy.mockReset(); fixture.destroy(); control.patchValue('test'); expect(spy).not.toHaveBeenCalled(); }); it('should render after onInit', () => { const { query } = renderComponent({ type: 'input', hooks: { onInit: (f: FormlyFieldConfigCache) => (f.formControl = new FormControl()), }, }); expect(query('formly-type-input')).not.toBeNull(); }); it('should render field type for each formly-field instance', () => { const { queryAll } = renderComponent( { type: 'input', formControl: new FormControl(), modelOptions: {}, templateOptions: { duplicate: true }, }, { template: ` <formly-field *ngIf="field.templateOptions.duplicate" [field]="field"></formly-field> <formly-field class="target" [field]="field"></formly-field> `, }, ); expect(queryAll('formly-type-input').length).toEqual(2); }); it('should update template options of OnPush FieldType #2191', async () => { const options$ = timer(0).pipe( map(() => [{ value: 5, label: 'Option 5' }]), shareReplay(1), ); const { field, query, detectChanges } = renderComponent({ key: 'push', type: 'on-push', templateOptions: { options: [{ value: 1, label: 'Option 1' }], }, expressionProperties: { 'templateOptions.options': options$, }, }); const onPushInstance = query('.to').nativeElement; expect(onPushInstance.textContent).toEqual( JSON.stringify( { ...field.templateOptions, options: [{ value: 1, label: 'Option 1' }], }, null, 2, ), ); await options$.toPromise(); detectChanges(); expect(onPushInstance.textContent).toEqual( JSON.stringify( { ...field.templateOptions, options: [{ value: 5, label: 'Option 5' }], }, null, 2, ), ); }); it('should take account of formState update', () => { const { field, query, detectChanges } = renderComponent({ key: 'push', type: 'on-push', templateOptions: {}, options: { formState: { foo: true } }, }); expect(query('.formState').nativeElement.textContent).toEqual(JSON.stringify({ foo: true }, null, 2)); field.options.formState.foo = false; detectChanges(); expect(query('.formState').nativeElement.textContent).toEqual(JSON.stringify({ foo: false }, null, 2)); }); describe('valueChanges', () => { it('should emit valueChanges on control value change', () => { const { field } = renderComponent({ key: 'foo', type: 'input', }); const [spy, subscription] = createFieldChangesSpy(field); field.formControl.setValue('First value'); expect(spy).toHaveBeenCalledTimes(1); expect(spy).toHaveBeenCalledWith({ value: 'First value', field, type: 'valueChanges' }); expect(field.model).toEqual({ foo: 'First value' }); subscription.unsubscribe(); }); it('should apply parsers to the emitted valueChanges', () => { const { field } = renderComponent({ key: 'foo', type: 'input', parsers: [Number], }); const [spy, subscription] = createFieldChangesSpy(field); field.formControl.setValue('15'); expect(spy).toHaveBeenCalledTimes(1); expect(spy).toHaveBeenCalledWith({ value: 15, field, type: 'valueChanges' }); subscription.unsubscribe(); }); it('should apply debounce to the emitted valueChanges', fakeAsync(() => { const { field } = renderComponent({ key: 'foo', type: 'input', modelOptions: { debounce: { default: 5 }, }, }); const [spy, subscription] = createFieldChangesSpy(field); field.formControl.setValue('15'); expect(spy).not.toHaveBeenCalled(); tick(6); expect(spy).toHaveBeenCalled(); subscription.unsubscribe(); })); it('should ignore default debounce when using "blur" or "submit"', () => { const { field } = renderComponent({ key: 'foo', type: 'input', modelOptions: { debounce: { default: 5 }, updateOn: 'blur', }, }); const [spy, subscription] = createFieldChangesSpy(field); field.formControl.setValue('15'); expect(spy).toHaveBeenCalled(); subscription.unsubscribe(); }); // https://github.com/ngx-formly/ngx-formly/issues/1857 it('should emit a valid model value when using square bracket notation for key', () => { const { field } = renderComponent({ key: 'o[0].0.name', type: 'input', }); field.formControl.setValue('***'); expect(field.parent.model).toEqual({ o: [[{ name: '***' }]] }); }); it('should emit a valid model value when using square bracket notation for a fieldGroup key', () => { const { field } = renderComponent({ key: 'group[0]', fieldGroup: [{ key: 'name', type: 'input' }], }); field.fieldGroup[0].formControl.setValue('***'); expect(field.parent.model).toEqual({ group: [{ name: '***' }] }); }); it('should emit valueChanges on group control value change', () => { const { field } = renderComponent({ key: 'foo', fieldGroup: [{ type: 'input', key: 'bar' }], }); const [spy, subscription] = createFieldChangesSpy(field); field.formControl.setValue({ bar: 'First value' }); expect(spy).toHaveBeenCalledTimes(1); expect(spy).toHaveBeenCalledWith({ value: 'First value', field: field.fieldGroup[0], type: 'valueChanges' }); expect(field.parent.model).toEqual({ foo: { bar: 'First value' } }); subscription.unsubscribe(); }); it('should emit `modelChange` when custom FormGroup change', () => { const { field } = renderComponent({ key: 'foo', formControl: new FormGroup({ bar: new FormControl(), }), }); const [spy, subscription] = createFieldChangesSpy(field); field.formControl.get('bar').setValue('foo'); expect(spy).toHaveBeenCalledTimes(1); expect(spy).toHaveBeenCalledWith({ value: { bar: 'foo' }, field, type: 'valueChanges' }); expect(field.parent.model).toEqual({ foo: { bar: 'foo' } }); subscription.unsubscribe(); }); it('should emit `modelChange` twice when key is duplicated', () => { const { field } = renderComponent({ fieldGroup: [ { key: 'title', type: 'input' }, { key: 'title', type: 'input' }, ], }); const [spy, subscription] = createFieldChangesSpy(field); field.formControl.get('title').setValue('***'); expect(spy).toHaveBeenCalledTimes(2); subscription.unsubscribe(); }); it('should keep the value in sync when using multiple fields with same key', () => { const { field, detectChanges, queryAll } = renderComponent({ fieldGroup: [ { key: 'title', type: 'input' }, { key: 'title', type: 'input' }, ], }); const inputs = queryAll<HTMLInputElement>('input'); inputs[0].triggerEventHandler('input', { target: { value: 'First' } }); detectChanges(); expect(field.formControl.value).toEqual({ title: 'First' }); expect(inputs[0].nativeElement.value).toEqual('First'); expect(inputs[1].nativeElement.value).toEqual('First'); }); }); describe('component-level injectors', () => { it('should inject parent service to child type', () => { // should inject `ParentService` in `ChildComponent` without raising an error const { field, query } = renderComponent({ type: 'parent', fieldGroup: [ { type: 'child', fieldGroup: [{ key: 'email', type: 'input' }], }, ], }); const childInstance: FormlyChildComponent = query('formly-child').componentInstance; expect(childInstance.parent).not.toBeNull(); expect(childInstance.wrapper).toBeNull(); }); it('should inject parent wrapper to child type', () => { const { field, query } = renderComponent({ wrappers: ['form-field-async'], templateOptions: { render: true }, fieldGroup: [ { type: 'child', fieldGroup: [{ key: 'email', type: 'input' }], }, ], }); // should inject `FormlyWrapperLabel` in `ChildComponent` without raising an error const childInstance: FormlyChildComponent = query('formly-child').componentInstance; expect(childInstance.wrapper).not.toBeNull(); expect(childInstance.parent).toBeNull(); }); }); }); @Component({ selector: 'formly-wrapper-form-field-async', template: ` <div *ngIf="to.render"> <ng-container #fieldComponent></ng-container> </div> `, }) class FormlyWrapperFormFieldAsync extends FieldWrapper {} @Component({ selector: 'formly-on-push-component', template: ` <div class="to">{{ to | json }}</div> <div class="formState">{{ formState | json }}</div> `, changeDetection: ChangeDetectionStrategy.OnPush, }) export class FormlyOnPushComponent extends FieldType {} @Injectable() export class ParentService {} @Component({ selector: 'formly-parent', template: ` <formly-field *ngFor="let f of field.fieldGroup" [field]="f"></formly-field> `, providers: [ParentService], }) export class FormlyParentComponent extends FieldType { constructor(public parent: ParentService) { super(); } } @Component({ selector: 'formly-child', template: ` <ng-content></ng-content> `, }) export class FormlyChildComponent extends FieldType { constructor(@Optional() public parent: ParentService, @Optional() public wrapper: FormlyWrapperFormFieldAsync) { super(); } }
the_stack
import {copyObject, deepCopy, diffArray, partition} from "../util/helpers"; import {ContentEdit} from "../data/content_edit"; import {__getProxyTarget} from "./readonly"; export interface UpdateLike<S> { // Sentinel field so we can distinguish an update from a value isStateUpdate: true // Apply the update to the given value, mutating in-place if possible. Return the updated value, and indicate using // the given latch whether a change was made. applyMutate(value: S): UpdateResult<S> } // Partial<V[]> confuses TypeScript – TS thinks it has iterators and array methods and such. // This is to avoid that. export type Partial1<S> = S extends (infer V)[] ? Record<number, V> : Partial<S>; // Types for expressing a mapping of keys to update results for those keys' values export type ObjectFieldUpdates<S> = { [K in keyof S]?: UpdateResult<S[K]>; } export type FieldUpdates<S> = S extends (infer V)[] ? Record<number, UpdateResult<V>> : ObjectFieldUpdates<S>; export interface UpdateResult<S> { update: UpdateLike<S> newValue: Readonly<S> // if S is a primitive, or the entire object was replaced, the previous value. // Otherwise, *this will be the same* as the new value (which was mutated!). oldValue?: Readonly<S> // A dict of values that this update removed from an object (if applicable) removedValues?: Partial1<S> // A dict of values that this update added to the object (if applicable) addedValues?: Partial1<S> // A dict of values that this update altered in the object (if applicable) changedValues?: Partial1<S> // A dict of child updates to fields of this object fieldUpdates?: FieldUpdates<S> } export const UpdateResult = Object.freeze({ addedOrChangedKeys<S>(result: UpdateResult<S>): (keyof S)[] { const updated: (keyof S)[] = []; if (result.addedValues) updated.push(...Object.keys(result.addedValues) as (keyof S)[]); if (result.changedValues) updated.push(...Object.keys(result.changedValues) as (keyof S)[]); return updated; } }) export type StateUpdate<S> = UpdateLike<S>; export abstract class Update<S> implements UpdateLike<S> { readonly isStateUpdate: true = true abstract applyMutate(value: S): UpdateResult<S> } export const NoUpdate = Object.freeze({ isStateUpdate: true, applyMutate(prev: any): UpdateResult<any> { return { update: NoUpdate, newValue: prev } } }) as UpdateLike<any>; function noChange<S>(value: S): UpdateResult<S> { return { update: NoUpdate, newValue: value } } function destroyed<S>(value: S): UpdateResult<S> { return { update: Destroy.Instance, newValue: undefined as any as S, oldValue: value, fieldUpdates: AllDestroyedUpdates as FieldUpdates<S> } } function setTo<S>(value: S, oldValue?: S): UpdateResult<S> { return new SetValue(value).applyPure(oldValue!); } export function childResult<S, K extends keyof S, V extends S[K] = S[K]>(result: UpdateResult<S>, key: K): UpdateResult<V> { const fieldUpdate: UpdateResult<S[K]> | undefined = (result.fieldUpdates as ObjectFieldUpdates<S>)?.[key]; if (fieldUpdate) { return fieldUpdate as UpdateResult<V>; } if (result.update instanceof SetValue) { return setTo(result.newValue[key], result.oldValue?.[key]) as UpdateResult<V>; } if (result.update instanceof Destroy) { return destroyed<S[K] | undefined>(result.oldValue?.[key]) as UpdateResult<V>; } return noChange(result.newValue[key]) as UpdateResult<V>; } const AllDestroyedUpdates: FieldUpdates<any> = new Proxy({}, { get(target: {}, p: PropertyKey, receiver: any): UpdateResult<any> { return { update: Destroy.Instance, newValue: undefined as unknown as Readonly<any>, fieldUpdates: AllDestroyedUpdates } } }) /** * A proxy which lazily answers questions about field updates in an array. * This is to avoid eagerly filling up a structure with updates, when they might not even be accessed. * @param arr The (mutated) array * @param minIdx The first index affected by the change * @param maxIdx The last index affected by the change * @param indexShift By how much the values in the array between those two indices shifted. */ function arrayFieldUpdates<V>(arr: V[], minIdx: number, maxIdx: number, indexShift: number): FieldUpdates<V[]> { const dict: Record<number, UpdateResult<V>> = {}; let enumerated: PropertyKey[] | undefined = undefined; const enumerate = (target: Record<number, UpdateResult<V>>): PropertyKey[] => { if (enumerated === undefined) { enumerated = []; for (let i = minIdx; i <= maxIdx; i++) { enumerated.push(i.toString(10)); } } return enumerated; } return new Proxy(dict, { get(target: Record<number, UpdateResult<V>>, idx: number, receiver: any): UpdateResult<V> { if (idx >= minIdx && idx <= maxIdx) { if (!target[idx]) { const oldValue = arr[idx - indexShift]; const newValue = arr[idx]; target[idx] = { update: setValue(newValue), newValue, oldValue } } return target[idx]; } return noChange(arr[idx]); }, has(target: Record<number, UpdateResult<V>>, idx: number): boolean { return idx >= minIdx && idx <= maxIdx; }, ownKeys: enumerate }) } export class RemoveKey<S, K extends keyof S> extends Update<S> { constructor(readonly key: K, private _value?: S[K]) { super() } static unapply<S, K extends keyof S>(inst: RemoveKey<S, K>): ConstructorParameters<typeof RemoveKey> { return [inst.key, inst.value] } get value(): S[K] | undefined { return this._value } applyMutate(value: S): UpdateResult<S> { if (value === null || value === undefined || !(this.key in value)) return noChange(value); const oldValue: S[K] = value[this.key]; delete value[this.key]; return { update: this, newValue: value, removedValues: { [this.key]: oldValue } as Partial1<S>, fieldUpdates: { [this.key]: destroyed(oldValue) } as FieldUpdates<S> }; } } export class UpdateKey<S, K extends keyof S> extends Update<S> { constructor(readonly key: K, private _update: UpdateLike<S[K]>) { super() } get update(): UpdateLike<S[K]> { return this._update; } applyMutate(oldValue: S): UpdateResult<S> { const childResult: UpdateResult<S[K]> = this._update.applyMutate(oldValue[this.key]); if (childResult.update === NoUpdate) return noChange(oldValue); const result: UpdateResult<S> = { update: this, newValue: oldValue, fieldUpdates: { [this.key]: childResult } as FieldUpdates<S> } if (!(this.key in oldValue)) { result.addedValues = { [this.key]: childResult.newValue } as Partial1<S>; } else if (childResult.update instanceof Destroy) { result.removedValues = { [this.key]: childResult.oldValue } as Partial1<S>; } else { result.changedValues = { [this.key]: childResult.newValue } as Partial1<S> } if (Object.isFrozen(oldValue)) { result.newValue = copyObject(oldValue, {[this.key]: childResult.newValue} as unknown as Partial<S>); } else if (childResult.update instanceof Destroy) { delete oldValue[this.key]; } else { oldValue[this.key] = childResult.newValue as S[K]; } return result; } } export class RemoveValue<V> extends Update<V[]> { constructor(readonly value: V, private _index: number) { super() } static unapply<V>(inst: RemoveValue<V>): ConstructorParameters<typeof RemoveValue> { return [inst.value, inst.index]; } get index(): number { return this._index; } applyMutate(arr: V[]): UpdateResult<V[]> { const idx = this._index; const len = arr.length; if (arr[idx] !== this.value) { throw new Error("RemoveValue is no longer valid as array has changed"); } arr.splice(idx, 1); return { update: this, newValue: arr, removedValues: { [this.index]: this.value }, get fieldUpdates() { return arrayFieldUpdates(arr, idx, len, -1) } }; } } export class InsertValue<V> extends Update<V[]> { constructor(readonly value: V, private _targetIndex?: number) { super() } static unapply<V>(inst: InsertValue<V>): ConstructorParameters<typeof InsertValue> { return [inst.value, inst.targetIndex] } get targetIndex(): number { return this._targetIndex! } applyMutate(arr: V[]): UpdateResult<V[]> { if (arr === undefined) { arr = []; } const targetIndex = this.targetIndex ?? arr.length; if (this._targetIndex !== undefined) { arr.splice(this.targetIndex, 0, this.value); } else { this._targetIndex = arr.length; arr.push(this.value); } return { update: this, newValue: arr, addedValues: { [targetIndex]: this.value }, get fieldUpdates() { return arrayFieldUpdates(arr, targetIndex, arr.length, 1) } }; } } export class MoveArrayValue<V> extends Update<V[]> { private movedElem?: V; constructor(readonly fromIndex: number, readonly toIndex: number) { super(); } static unapply<V>(inst: MoveArrayValue<V>): ConstructorParameters<typeof MoveArrayValue> { return [inst.fromIndex, inst.toIndex] } get movedValue(): V | undefined { return this.movedElem; } applyMutate(arr: V[]): UpdateResult<V[]> { if (this.fromIndex === this.toIndex) { return noChange(arr); } const minIdx = Math.min(this.fromIndex, this.toIndex); const maxIdx = Math.max(this.fromIndex, this.toIndex); const elem = this.movedElem = arr.splice(this.fromIndex, 1)[0]; const targetIdx = this.toIndex > this.fromIndex ? this.toIndex - 1 : this.toIndex arr.splice(this.toIndex, 0, elem); return { update: this, newValue: arr, get fieldUpdates() { return arrayFieldUpdates(arr, minIdx, maxIdx, 1) } }; } } export class ReplaceArrayValue<V> extends Update<V[]> { constructor(readonly value: V, private targetIndex: number) { super(); } static unapply<V>(inst: ReplaceArrayValue<V>): ConstructorParameters<typeof ReplaceArrayValue> { return [inst.value, inst.targetIndex] } applyMutate(arr: V[]): UpdateResult<V[]> { if (this.targetIndex >= arr.length) { throw new Error("ReplaceArrayValue is no longer valid as array has changed"); } const removedValue = arr.splice(this.targetIndex, 1, this.value)[0] const targetIndex = this.targetIndex; return { update: this, newValue: arr, addedValues: { [targetIndex]: this.value }, removedValues: { [targetIndex]: removedValue }, fieldUpdates: { [targetIndex]: setTo(this.value, removedValue) } } } } export class RenameKey<S, K0 extends keyof S, K1 extends keyof S, V extends S[K0] & S[K1]> extends Update<S> { constructor(readonly oldKey: K0, readonly newKey: K1) { super() } static unapply<S, K0 extends keyof S, K1 extends keyof S, V extends S[K0] & S[K1]>(inst: RenameKey<S, K0, K1, V>): ConstructorParameters<typeof RenameKey> { return [inst.oldKey, inst.newKey]; } applyMutate(obj: S): UpdateResult<S> { const value: V = obj[this.oldKey] as V; const replaced: V = (obj[this.oldKey] ?? value) as V; obj[this.newKey] = value; delete obj[this.oldKey]; return { update: this, newValue: obj, removedValues: { [this.oldKey]: value } as Partial1<S>, addedValues: { [this.newKey]: value } as Partial1<S>, fieldUpdates: { [this.oldKey]: destroyed(value), [this.newKey]: setTo(value, replaced) } as FieldUpdates<S> }; } } export class Destroy<S> extends Update<S | undefined> { constructor() { super() } static Instance: Destroy<any> = new Destroy(); static unapply<S>(inst: Destroy<S>): ConstructorParameters<typeof Destroy> { return [] } applyMutate(value: S | undefined): UpdateResult<S | undefined> { return { update: Destroy.Instance, newValue: undefined, oldValue: value, fieldUpdates: AllDestroyedUpdates as FieldUpdates<S> } } } export class SetValue<S> extends Update<S> { constructor(readonly value: S) { super() } // TODO: Extractable seems to be problematic on parametric data classes when primitive types are involved. static unapply<T>(inst: SetValue<T>): ConstructorParameters<typeof SetValue> { return [inst.value] } // if we set the value of an object state, find the keys that changed // this is done lazily, because the diff might not be used. // Method is private static because it should only be called from SetValue – that's the only case when we know // that old and new are not the same reference. private static objectDiffUpdates<S extends object>(update: UpdateLike<S>, oldObj: S, newObj: S): UpdateResult<S> { let removedValues: Partial<S> | undefined = undefined; let addedValues: Partial<S> | undefined = undefined; let changedValues: Partial<S> | undefined = undefined; let fieldUpdates: ObjectFieldUpdates<S> | undefined = undefined; let computed: boolean = false; function compute() { function addFieldUpdate<K extends keyof S>(key: K, fieldUpdate: UpdateResult<S[K]>) { fieldUpdates = fieldUpdates || {}; fieldUpdates[key] = fieldUpdate; } function addedValue<K extends keyof S>(key: K, fieldUpdate: UpdateResult<S[K]>) { addFieldUpdate(key, fieldUpdate); addedValues = addedValues || {}; addedValues[key] = fieldUpdate.newValue as S[K]; } function removedValue<K extends keyof S>(key: K, fieldUpdate: UpdateResult<S[K]>) { addFieldUpdate(key, fieldUpdate); removedValues = removedValues || {}; removedValues[key] = fieldUpdate.oldValue as S[K]; } function changedValue<K extends keyof S>(key: K, fieldUpdate: UpdateResult<S[K]>) { addFieldUpdate(key, fieldUpdate); changedValues = changedValues || {}; changedValues[key] = fieldUpdate.newValue as S[K]; } if (!oldObj) oldObj = {} as any as S; if (!newObj) newObj = {} as any as S; function computeUpdate<K extends keyof S>(key: K) { const oldHas = oldObj.hasOwnProperty(key); const newHas = newObj.hasOwnProperty(key); if (oldHas && !newHas) { removedValue(key, destroyed(oldObj[key])) } else if (oldObj[key] !== newObj[key]) { let fieldUpdate: UpdateResult<S[K]>; if (typeof oldObj[key] === 'object' && typeof newObj[key] === 'object') { fieldUpdate = SetValue.objectDiffUpdates<S[K] & object>( setValue(newObj[key] as S[K] & object) as UpdateLike<S[K] & object>, oldObj[key] as S[K] & object, newObj[key] as S[K] & object ) as UpdateResult<S[K]>; } else { fieldUpdate = setTo(newObj[key], oldObj[key]); } if (!oldHas) { addedValue(key, fieldUpdate); } else { changedValue(key, fieldUpdate); } } } const merged: S = {...oldObj, ...newObj}; for (const key in merged) { if (merged.hasOwnProperty(key)) { computeUpdate(key) } } } return { update, newValue: newObj, oldValue: oldObj, get removedValues() { if (!computed) compute(); return removedValues as Partial1<S> | undefined }, get addedValues() { if (!computed) compute(); return addedValues as Partial1<S> | undefined }, get changedValues() { if (!computed) compute(); return changedValues as Partial1<S> | undefined }, get fieldUpdates() { if (!computed) compute(); return fieldUpdates as FieldUpdates<S> | undefined; } } } applyPure(oldValue: S): UpdateResult<S> { if (oldValue === this.value) { return noChange(oldValue); } else if (typeof oldValue === 'object' || typeof this.value === 'object') { // @ts-ignore – it can't realize that S must extend object return SetValue.objectDiffUpdates<S>(this, oldValue, this.value); } else return this.applyPrimitive(oldValue); } applyPrimitive(oldValue: S): UpdateResult<S> { return { update: this, newValue: this.value, oldValue: oldValue } } applyMutate(oldValue: S): UpdateResult<S> { return this.applyPure(oldValue) } } export class EditString extends Update<string> { constructor(readonly edits: ContentEdit[]) { super(); } static unapply(inst: EditString): ConstructorParameters<typeof EditString> { return [inst.edits] } applyMutate(value: string): UpdateResult<string> { if (this.edits.length === 0) { return noChange(value); } let result = value; for (let i = 0; i < this.edits.length; i++) { result = this.edits[i].apply(result); } return { update: this, newValue: result, oldValue: value }; } } export type UpdatePartial<T> = { [P in keyof T]?: UpdateOf<T[P]> } export type UpdateOf<T> = T | UpdateLike<T> | UpdatePartial<T> export function isUpdateLike(value: any): value is UpdateLike<any> { return value && value.isStateUpdate } function isUpdatePartial<S>(value: UpdateOf<S>): value is UpdatePartial<S> { return value && typeof value === 'object' && !(value as any).isStateUpdate && (value as any).constructor === Object } class UpdateWith<S> extends Update<S> { constructor(readonly fieldUpdates: UpdateOf<S>) { super() } applyMutate(oldValue: S): UpdateResult<S> { let fieldUpdateResults: ObjectFieldUpdates<S> | undefined = undefined; let addedValues: Partial<S> | undefined = undefined; let removedValues: Partial<S> | undefined = undefined; let changedValues: Partial<S> | undefined = undefined; let anyChanged: boolean = false; const mustCopy = typeof oldValue === 'object' && Object.isFrozen(oldValue); const value: any = mustCopy ? {...oldValue} : oldValue || {}; const updates = this.fieldUpdates as any; if (typeof updates === 'object') { for (const prop in updates) { if (updates.hasOwnProperty(prop)) { const key = prop as keyof S; const update = (updates as any)[key]; const updateResult = update.applyMutate(value[key]); if (updateResult.update === NoUpdate) continue; anyChanged = true; fieldUpdateResults = fieldUpdateResults || {}; fieldUpdateResults[key] = updateResult; if (updateResult.update instanceof Destroy) { removedValues = removedValues || {}; removedValues[key] = updateResult.oldValue; delete value[key]; } else { if (!value.hasOwnProperty(key)) { addedValues = addedValues || {}; addedValues[key] = updateResult.newValue; } else { changedValues = changedValues || {}; changedValues[key] = updateResult.newValue; } value[key] = updateResult.newValue; } } } if (anyChanged) { if (mustCopy) { Object.setPrototypeOf(value, Object.getPrototypeOf(oldValue)); Object.freeze(value); } const update = { update: this, newValue: value, } as UpdateResult<S>; if (addedValues) update.addedValues = addedValues as Partial1<S>; if (removedValues) update.removedValues = removedValues as Partial1<S>; if (changedValues) update.changedValues = changedValues as Partial1<S>; if(fieldUpdateResults) update.fieldUpdates = fieldUpdateResults as FieldUpdates<S>; return update; } else { return noChange(oldValue); } } else if (oldValue === updates) { return noChange(oldValue) } else { return new SetValue(updates as S).applyPrimitive(oldValue) } } } /** * If the given update value is not already an update, return the update that it specifies. * If the update is a direct value, wrap it in SetValue. If the update is an object specifying updates to keys, * recursively transform the object's values to be Updates as well. */ export function valueToUpdate<S>(updates: UpdateOf<S>): StateUpdate<S> { if (isUpdateLike(updates)) { return updates; } else if (isUpdatePartial<S>(updates)) { const updates1 = updates as any; const onlyUpdates: UpdateOf<S> = {}; for (const prop in updates1) { if (updates1.hasOwnProperty(prop)) { const key = prop as keyof S; onlyUpdates[key] = valueToUpdate((updates as UpdatePartial<S>)[key]); if (onlyUpdates[key] === NoUpdate) { delete onlyUpdates[key] } } } return new UpdateWith(onlyUpdates); } else { return setValue(updates as S) } } /** * Constructors for state updates */ export function removeKey<S, K extends keyof S>(key: K): StateUpdate<S> { return new RemoveKey<S, K>(key); } export function renameKey<S, K0 extends keyof S, K1 extends keyof S, V extends S[K0] & S[K1]>(oldKey: K0, newKey: K1): StateUpdate<S> { return new RenameKey<S, K0, K1, V>(oldKey, newKey); } export function setValue<V, V1 extends V = V>(value: V1): StateUpdate<V> { return new SetValue(__getProxyTarget(value as V)) } export const setUndefined: StateUpdate<any> = new SetValue(undefined); export const setToUndefined: UpdateResult<any> = Object.freeze({ update: setUndefined, newValue: undefined as unknown as Readonly<any> }); export function setProperty<S, K extends keyof S, V extends S[K] = S[K]>(key: K, value: V): StateUpdate<S> { return new UpdateKey<S, K>(key, new SetValue<S[K]>(value)) } export function updateProperty<S, K extends keyof S>(key: K, update: UpdateOf<S[K]>): StateUpdate<S> { return new UpdateKey<S, K>(key, valueToUpdate(update)); } export function destroy<V>(): StateUpdate<V> { return Destroy.Instance as any as StateUpdate<V> } export function append<V, V1 extends V = V>(value: V1): StateUpdate<V[]> { return new InsertValue(value) as StateUpdate<V[]> } export function insert<V, V1 extends V = V>(value: V1, index: number): StateUpdate<V[]> { return new InsertValue<V>(value, index) } export function clearArray<V>(): StateUpdate<V[]> { // TODO: should this be its own op? return new SetValue<V[]>([]) } export function moveArrayValue<V>(fromIndex: number, toIndex: number): StateUpdate<V[]> { return new MoveArrayValue(fromIndex, toIndex) } export function replaceArrayValue<V>(value: V, index: number): StateUpdate<V[]> { return new ReplaceArrayValue(value, index) } export function editString(edits: ContentEdit[]): StateUpdate<string> { return new EditString(edits) } export function removeFromArray<V>(arr: Readonly<V[]>, value: V, compare?: (a: V, b: V) => boolean): StateUpdate<V[]> { value = __getProxyTarget(value); arr = __getProxyTarget(arr); const idx = compare ? arr.findIndex(v => compare(v, value)) : arr.indexOf(value); if (idx >= 0) { return new RemoveValue(value, idx); } return NoUpdate; } export function removeIndex<V>(arr: Readonly<V[]>, index: number): StateUpdate<V[]> { arr = __getProxyTarget(arr); if (arr.hasOwnProperty(index)) { return new RemoveValue(arr[index], index) } return NoUpdate } export function noUpdate<S>(): StateUpdate<S> { return NoUpdate; }
the_stack
import React from 'react'; import { act } from 'react-dom/test-utils'; import { ComponentRegistryImpl, ComponentRegistry, SlotLocation, AppConfig, IContextKeyService, CommandRegistry, ILoggerManagerClient, ViewContainerOptions, PreferenceService, Disposable, ClientApp, } from '@opensumi/ide-core-browser'; import { MockLoggerManageClient } from '@opensumi/ide-core-browser/__mocks__/logger'; import { useMockStorage } from '@opensumi/ide-core-browser/__mocks__/storage'; import { LayoutState } from '@opensumi/ide-core-browser/lib/layout/layout-state'; import { CommonServerPath, Deferred, OS } from '@opensumi/ide-core-common'; import { IMainLayoutService } from '@opensumi/ide-main-layout'; import { MainLayoutModule } from '@opensumi/ide-main-layout/lib/browser'; import { LayoutService } from '@opensumi/ide-main-layout/lib/browser/layout.service'; import { MainLayoutModuleContribution } from '@opensumi/ide-main-layout/lib/browser/main-layout.contribution'; import { IWorkspaceService } from '@opensumi/ide-workspace'; import { MockWorkspaceService } from '@opensumi/ide-workspace/lib/common/mocks'; import { MockInjector } from '../../../../tools/dev-tool/src/mock-injector'; import { MockContextKeyService } from '../../../monaco/__mocks__/monaco.context-key.service'; const MockView = (props) => <div>Test view{props.message && <p id='test-unique-id'>has prop.message</p>}</div>; jest.useFakeTimers(); describe('main layout test', () => { let service: LayoutService; let injector: MockInjector; const testToken = 'componentToken'; const uniqueToken = 'unique_component_token'; const testContainerId = 'unique_container_id'; const layoutNode = document.createElement('div'); const rendered = new Deferred<void>(); document.getElementById('main')!.appendChild(layoutNode); const timeoutIds: Set<NodeJS.Timer> = new Set(); beforeAll(async () => { const defered = new Deferred(); let timeCount = 0; window.requestAnimationFrame = (cb) => { const cancelToken = 111; const timeoutId = global.setTimeout(() => { timeCount += 30; cb(timeCount); timeoutIds.delete(timeoutId); }, 30); timeoutIds.add(timeoutId); return cancelToken; }; window.cancelAnimationFrame = () => { // mock cancelAnimationFrame }; // tslint:disable-next-line: only-arrow-functions (window as any).ResizeObserver = function () { this.observe = () => {}; this.disconnect = () => {}; this.unobserve = () => {}; return this; }; injector = new MockInjector(); const config: Partial<AppConfig> = { layoutConfig: { [SlotLocation.main]: { modules: [testToken], }, [SlotLocation.top]: { modules: [testToken], }, [SlotLocation.left]: { modules: [testToken], }, [SlotLocation.right]: { modules: [uniqueToken], }, [SlotLocation.bottom]: { modules: [testToken], }, [SlotLocation.statusBar]: { modules: [testToken], }, }, }; injector.overrideProviders( { token: IMainLayoutService, useClass: LayoutService, }, { token: ComponentRegistry, useClass: ComponentRegistryImpl, }, { token: IContextKeyService, useClass: MockContextKeyService, }, { token: IWorkspaceService, useClass: MockWorkspaceService, }, { token: PreferenceService, useValue: { ready: Promise.resolve(), get: () => undefined, onPreferenceChanged: () => Disposable.create(() => {}), onSpecificPreferenceChange: (func: any) => Disposable.create(() => {}), }, }, { token: ILoggerManagerClient, useClass: MockLoggerManageClient, }, { token: CommonServerPath, useValue: { async getBackendOS() { return Promise.resolve(OS.type()); }, }, }, MainLayoutModuleContribution, ); useMockStorage(injector); const registry: ComponentRegistry = injector.get(ComponentRegistry); registry.register( testToken, [ { component: MockView, id: 'test-view-id', }, ], { containerId: 'containerId', iconClass: 'testicon iconfont', priority: 10, title: 'test title', expanded: false, size: 300, initialProps: {}, activateKeyBinding: 'ctrlcmd+1', hidden: false, }, ); registry.register( uniqueToken, [ { component: MockView, id: 'test-view-id1', }, { component: MockView, id: 'test-view-id2', }, ], { containerId: testContainerId, iconClass: 'testicon iconfont', priority: 10, title: 'test title', expanded: false, size: 300, activateKeyBinding: 'ctrlcmd+1', hidden: false, }, ); await act(async () => { const app = new ClientApp({ modules: [MainLayoutModule], injector, didRendered: () => rendered.resolve(), ...config, }); app.start(document.getElementById('main')!).then(async () => { await rendered.promise; await service.viewReady.promise; defered.resolve(); }); service = injector.get(IMainLayoutService); // 测试环境下,readDom 的 render 回调的时候不知道为啥 render 还没执行到 tabbarRenderer,需要兼容下,先初始化好tababrService service.getTabbarService('left'); service.getTabbarService('right'); service.getTabbarService('bottom'); }); await defered.promise; }); afterAll(() => { if (timeoutIds.size > 0) { timeoutIds.forEach((t) => clearTimeout(t)); timeoutIds.clear(); } }); // main logic test it('containers in layout config should be registed', () => { const rightTabbarService = service.getTabbarService('right'); expect(rightTabbarService.visibleContainers.length).toEqual(1); const accordionService = service.getAccordionService(testContainerId); expect(accordionService.visibleViews.length).toEqual(2); }); // container api test start it('should be able to collect tabbar component at any time', () => { service.collectTabbarComponent( [ { component: MockView, id: 'test-view-id3', }, ], { containerId: 'container-before-render', title: 'test title', }, 'bottom', ); expect(service.getTabbarHandler('container-before-render')).toBeDefined(); }); it('should be able to init layout state storage & restore state & register toggle commands', async () => { const layoutState = injector.get(LayoutState); await layoutState.initStorage(); const contribution: MainLayoutModuleContribution = injector.get(MainLayoutModuleContribution); const registry = injector.get(CommandRegistry); contribution.registerCommands(registry); }); it('should be able to collect component as side container & get handler & manualy dispose', () => { const testContainerId2 = 'unique_container_id_2'; const options: ViewContainerOptions = { containerId: testContainerId2, iconClass: 'testicon iconfont', priority: 10, title: 'test title', expanded: false, size: 300, badge: '9', initialProps: { hello: 'world' }, activateKeyBinding: 'ctrlcmd+1', hidden: false, }; const handlerId = service.collectTabbarComponent( [ { component: MockView, id: 'test-view-id4', }, { component: MockView, id: 'test-view-id5', }, ], options, 'left', ); const handler = service.getTabbarHandler(handlerId)!; const tabbarService = service.getTabbarService('left'); expect(handler).toBeDefined(); const mockCb = jest.fn(); handler.onActivate(mockCb); handler.onInActivate(mockCb); handler.activate(); expect(tabbarService.currentContainerId).toEqual(testContainerId2); expect(handler.isActivated()).toBeTruthy(); handler.deactivate(); expect(handler.isActivated()).toBeFalsy(); expect(tabbarService.currentContainerId).toEqual(''); handler.disposeView('test-view-id4'); expect(handler.accordionService.views.length).toEqual(1); handler.hide(); expect(tabbarService.getContainerState(testContainerId2).hidden).toEqual(true); handler.show(); expect(tabbarService.getContainerState(testContainerId2).hidden).toEqual(false); expect(handler.isCollapsed('test-view-id5')).toBeFalsy(); handler.setCollapsed('test-view-id5', true); expect(handler.isCollapsed('test-view-id5')).toBeTruthy(); expect(mockCb).toBeCalledTimes(2); handler.setBadge('20'); handler.updateTitle('gggggggg'); jest.advanceTimersByTime(20); expect(tabbarService.getContainer(testContainerId2)!.options!.title).toEqual('gggggggg'); handler.updateViewTitle('test-view-id5', 'new title'); expect(handler.accordionService.views.find((view) => view.id === 'test-view-id5')?.name === 'new title'); handler.toggleViews(['test-view-id5'], false); expect(handler.accordionService.getViewState('test-view-id5').hidden).toBeTruthy(); handler.dispose(); expect(tabbarService.getContainer(testContainerId2)).toBeUndefined(); }); it('should be able to register React components as container directly', () => { const handlerId = service.collectTabbarComponent( [], { containerId: 'container-use-react', title: 'test title', component: MockView, initialProps: { message: 'hello world', }, }, 'bottom', ); const accordionService = service.getAccordionService('container-use-react'); expect(accordionService.views.length).toEqual(0); const handler = service.getTabbarHandler(handlerId); expect(handler).toBeDefined(); const testDom = document.getElementById('test-unique-id'); expect(testDom).toBeDefined(); }); it('should`t render tab view with hideTab option', () => { service.collectTabbarComponent( [], { containerId: 'containerWithTab', component: MockView, }, 'left', ); expect(document.getElementById('containerWithTab')).toBeDefined(); service.collectTabbarComponent( [], { containerId: 'containerWithoutTab', component: MockView, hideTab: true, }, 'left', ); expect(document.getElementById('containerWithoutTab')).toBeNull(); }); // view api test start it('should be able to collect view into existing container and replace & dispose existing view', async () => { const tmpViewId = 'test-view-id5'; const tmpDomId = 'test-dom-5'; service.collectViewComponent( { id: tmpViewId, component: MockView, }, testContainerId, { message: 'yes' }, ); act(() => { jest.advanceTimersByTime(10); }); const accordionService = service.getAccordionService(testContainerId); expect(accordionService.views.find((val) => val.id === tmpViewId)).toBeDefined(); service.replaceViewComponent( { id: tmpViewId, component: (props) => <h1 id={tmpDomId}>{props.id || 'no props'}</h1>, }, { id: 'hello world' }, ); act(() => { jest.advanceTimersByTime(10); }); // await wait(200); const newDom = document.getElementById(tmpDomId); expect(newDom).toBeDefined(); expect(newDom!.innerHTML).toEqual('hello world'); service.disposeViewComponent(tmpViewId); act(() => { jest.advanceTimersByTime(10); }); expect(accordionService.views.find((val) => val.id === tmpViewId)).toBeUndefined(); }); it('shouldn`t register empty tabbar component with hideIfEmpty option until valid view collected', () => { const emptyContainerId = 'emptyContainerId'; service.collectTabbarComponent([], { hideIfEmpty: true, containerId: emptyContainerId }, 'left'); const tabbarService = service.getTabbarService('left'); expect(tabbarService.getContainer(emptyContainerId)).toBeUndefined(); service.collectViewComponent({ id: 'testViewId', component: MockView }, emptyContainerId); expect(tabbarService.getContainer(emptyContainerId)).toBeDefined(); }); // toggle / expand api test it('toggle slot should work', () => { const rightTabbarService = service.getTabbarService('right'); // currentContainerId 空字符串表示当前未选中任何tab expect(rightTabbarService.currentContainerId).toEqual(''); service.toggleSlot('right'); act(() => { jest.advanceTimersByTime(10); }); // await wait(200); expect(rightTabbarService.currentContainerId).toBeTruthy(); act(() => { jest.advanceTimersByTime(10); }); // panel visible expect((document.getElementsByClassName(testContainerId)[0] as HTMLDivElement).style.zIndex).toEqual('1'); }); it('should be able to judge whether a tab panel is visible', () => { expect(service.isVisible('right')).toBeTruthy(); service.toggleSlot('right', false); act(() => { jest.advanceTimersByTime(10); }); expect(service.isVisible('right')).toBeFalsy(); }); });
the_stack
import * as assert from 'assert'; import { ITreeNode, ITreeFilter, TreeVisibility, ITreeElement } from 'vs/base/browser/ui/tree/tree'; import { IndexTreeModel, IIndexTreeNode, IList, IIndexTreeModelSpliceOptions } from 'vs/base/browser/ui/tree/indexTreeModel'; function toList<T>(arr: T[]): IList<T> { return { splice(start: number, deleteCount: number, elements: T[]): void { arr.splice(start, deleteCount, ...elements); }, updateElementHeight() { } }; } function toArray<T>(list: ITreeNode<T>[]): T[] { return list.map(i => i.element); } function toElements<T>(node: ITreeNode<T>): any { return node.children?.length ? { e: node.element, children: node.children.map(toElements) } : node.element; } const diffIdentityProvider = { getId: (n: number) => String(n) }; /** * Calls that test function twice, once with an empty options and * once with `diffIdentityProvider`. */ function withSmartSplice(fn: (options: IIndexTreeModelSpliceOptions<number, any>) => void) { fn({}); fn({ diffIdentityProvider }); } suite('IndexTreeModel', () => { test('ctor', () => { const list: ITreeNode<number>[] = []; const model = new IndexTreeModel<number>('test', toList(list), -1); assert(model); assert.strictEqual(list.length, 0); }); test('insert', () => withSmartSplice(options => { const list: ITreeNode<number>[] = []; const model = new IndexTreeModel<number>('test', toList(list), -1); model.splice([0], 0, [ { element: 0 }, { element: 1 }, { element: 2 } ], options); assert.deepStrictEqual(list.length, 3); assert.deepStrictEqual(list[0].element, 0); assert.deepStrictEqual(list[0].collapsed, false); assert.deepStrictEqual(list[0].depth, 1); assert.deepStrictEqual(list[1].element, 1); assert.deepStrictEqual(list[1].collapsed, false); assert.deepStrictEqual(list[1].depth, 1); assert.deepStrictEqual(list[2].element, 2); assert.deepStrictEqual(list[2].collapsed, false); assert.deepStrictEqual(list[2].depth, 1); })); test('deep insert', () => withSmartSplice(options => { const list: ITreeNode<number>[] = []; const model = new IndexTreeModel<number>('test', toList(list), -1); model.splice([0], 0, [ { element: 0, children: [ { element: 10 }, { element: 11 }, { element: 12 }, ] }, { element: 1 }, { element: 2 } ]); assert.deepStrictEqual(list.length, 6); assert.deepStrictEqual(list[0].element, 0); assert.deepStrictEqual(list[0].collapsed, false); assert.deepStrictEqual(list[0].depth, 1); assert.deepStrictEqual(list[1].element, 10); assert.deepStrictEqual(list[1].collapsed, false); assert.deepStrictEqual(list[1].depth, 2); assert.deepStrictEqual(list[2].element, 11); assert.deepStrictEqual(list[2].collapsed, false); assert.deepStrictEqual(list[2].depth, 2); assert.deepStrictEqual(list[3].element, 12); assert.deepStrictEqual(list[3].collapsed, false); assert.deepStrictEqual(list[3].depth, 2); assert.deepStrictEqual(list[4].element, 1); assert.deepStrictEqual(list[4].collapsed, false); assert.deepStrictEqual(list[4].depth, 1); assert.deepStrictEqual(list[5].element, 2); assert.deepStrictEqual(list[5].collapsed, false); assert.deepStrictEqual(list[5].depth, 1); })); test('deep insert collapsed', () => withSmartSplice(options => { const list: ITreeNode<number>[] = []; const model = new IndexTreeModel<number>('test', toList(list), -1); model.splice([0], 0, [ { element: 0, collapsed: true, children: [ { element: 10 }, { element: 11 }, { element: 12 }, ] }, { element: 1 }, { element: 2 } ], options); assert.deepStrictEqual(list.length, 3); assert.deepStrictEqual(list[0].element, 0); assert.deepStrictEqual(list[0].collapsed, true); assert.deepStrictEqual(list[0].depth, 1); assert.deepStrictEqual(list[1].element, 1); assert.deepStrictEqual(list[1].collapsed, false); assert.deepStrictEqual(list[1].depth, 1); assert.deepStrictEqual(list[2].element, 2); assert.deepStrictEqual(list[2].collapsed, false); assert.deepStrictEqual(list[2].depth, 1); })); test('delete', () => withSmartSplice(options => { const list: ITreeNode<number>[] = []; const model = new IndexTreeModel<number>('test', toList(list), -1); model.splice([0], 0, [ { element: 0 }, { element: 1 }, { element: 2 } ], options); assert.deepStrictEqual(list.length, 3); model.splice([1], 1, undefined, options); assert.deepStrictEqual(list.length, 2); assert.deepStrictEqual(list[0].element, 0); assert.deepStrictEqual(list[0].collapsed, false); assert.deepStrictEqual(list[0].depth, 1); assert.deepStrictEqual(list[1].element, 2); assert.deepStrictEqual(list[1].collapsed, false); assert.deepStrictEqual(list[1].depth, 1); model.splice([0], 2, undefined, options); assert.deepStrictEqual(list.length, 0); })); test('nested delete', () => withSmartSplice(options => { const list: ITreeNode<number>[] = []; const model = new IndexTreeModel<number>('test', toList(list), -1); model.splice([0], 0, [ { element: 0, children: [ { element: 10 }, { element: 11 }, { element: 12 }, ] }, { element: 1 }, { element: 2 } ], options); assert.deepStrictEqual(list.length, 6); model.splice([1], 2, undefined, options); assert.deepStrictEqual(list.length, 4); assert.deepStrictEqual(list[0].element, 0); assert.deepStrictEqual(list[0].collapsed, false); assert.deepStrictEqual(list[0].depth, 1); assert.deepStrictEqual(list[1].element, 10); assert.deepStrictEqual(list[1].collapsed, false); assert.deepStrictEqual(list[1].depth, 2); assert.deepStrictEqual(list[2].element, 11); assert.deepStrictEqual(list[2].collapsed, false); assert.deepStrictEqual(list[2].depth, 2); assert.deepStrictEqual(list[3].element, 12); assert.deepStrictEqual(list[3].collapsed, false); assert.deepStrictEqual(list[3].depth, 2); })); test('deep delete', () => withSmartSplice(options => { const list: ITreeNode<number>[] = []; const model = new IndexTreeModel<number>('test', toList(list), -1); model.splice([0], 0, [ { element: 0, children: [ { element: 10 }, { element: 11 }, { element: 12 }, ] }, { element: 1 }, { element: 2 } ], options); assert.deepStrictEqual(list.length, 6); model.splice([0], 1, undefined, options); assert.deepStrictEqual(list.length, 2); assert.deepStrictEqual(list[0].element, 1); assert.deepStrictEqual(list[0].collapsed, false); assert.deepStrictEqual(list[0].depth, 1); assert.deepStrictEqual(list[1].element, 2); assert.deepStrictEqual(list[1].collapsed, false); assert.deepStrictEqual(list[1].depth, 1); })); test('smart splice deep', () => { const list: ITreeNode<number>[] = []; const model = new IndexTreeModel<number>('test', toList(list), -1); model.splice([0], 0, [ { element: 0 }, { element: 1 }, { element: 2 }, { element: 3 }, ], { diffIdentityProvider }); assert.deepStrictEqual(list.filter(l => l.depth === 1).map(toElements), [ 0, 1, 2, 3, ]); model.splice([0], 3, [ { element: -0.5 }, { element: 0, children: [{ element: 0.1 }] }, { element: 1 }, { element: 2, children: [{ element: 2.1 }, { element: 2.2, children: [{ element: 2.21 }] }] }, ], { diffIdentityProvider, diffDepth: Infinity }); assert.deepStrictEqual(list.filter(l => l.depth === 1).map(toElements), [ -0.5, { e: 0, children: [0.1] }, 1, { e: 2, children: [2.1, { e: 2.2, children: [2.21] }] }, 3, ]); }); test('hidden delete', () => withSmartSplice(options => { const list: ITreeNode<number>[] = []; const model = new IndexTreeModel<number>('test', toList(list), -1); model.splice([0], 0, [ { element: 0, collapsed: true, children: [ { element: 10 }, { element: 11 }, { element: 12 }, ] }, { element: 1 }, { element: 2 } ], options); assert.deepStrictEqual(list.length, 3); model.splice([0, 1], 1, undefined, options); assert.deepStrictEqual(list.length, 3); model.splice([0, 0], 2, undefined, options); assert.deepStrictEqual(list.length, 3); })); test('collapse', () => withSmartSplice(options => { const list: ITreeNode<number>[] = []; const model = new IndexTreeModel<number>('test', toList(list), -1); model.splice([0], 0, [ { element: 0, children: [ { element: 10 }, { element: 11 }, { element: 12 }, ] }, { element: 1 }, { element: 2 } ], options); assert.deepStrictEqual(list.length, 6); model.setCollapsed([0], true); assert.deepStrictEqual(list.length, 3); assert.deepStrictEqual(list[0].element, 0); assert.deepStrictEqual(list[0].collapsed, true); assert.deepStrictEqual(list[0].depth, 1); assert.deepStrictEqual(list[1].element, 1); assert.deepStrictEqual(list[1].collapsed, false); assert.deepStrictEqual(list[1].depth, 1); assert.deepStrictEqual(list[2].element, 2); assert.deepStrictEqual(list[2].collapsed, false); assert.deepStrictEqual(list[2].depth, 1); })); test('updates collapsible', () => withSmartSplice(options => { const list: ITreeNode<number>[] = []; const model = new IndexTreeModel<number>('test', toList(list), -1); model.splice([0], 0, [ { element: 0, children: [ { element: 1 }, ] }, ], options); assert.strictEqual(list[0].collapsible, true); assert.strictEqual(list[1].collapsible, false); model.splice([0, 0], 1, [], options); { const [first, second] = list; assert.strictEqual(first.collapsible, false); assert.strictEqual(second, undefined); } model.splice([0, 0], 0, [{ element: 1 }], options); { const [first, second] = list; assert.strictEqual(first.collapsible, true); assert.strictEqual(second.collapsible, false); } })); test('expand', () => withSmartSplice(options => { const list: ITreeNode<number>[] = []; const model = new IndexTreeModel<number>('test', toList(list), -1); model.splice([0], 0, [ { element: 0, collapsed: true, children: [ { element: 10 }, { element: 11 }, { element: 12 }, ] }, { element: 1 }, { element: 2 } ], options); assert.deepStrictEqual(list.length, 3); model.setCollapsed([0], false); assert.deepStrictEqual(list.length, 6); assert.deepStrictEqual(list[0].element, 0); assert.deepStrictEqual(list[0].collapsed, false); assert.deepStrictEqual(list[0].depth, 1); assert.deepStrictEqual(list[1].element, 10); assert.deepStrictEqual(list[1].collapsed, false); assert.deepStrictEqual(list[1].depth, 2); assert.deepStrictEqual(list[2].element, 11); assert.deepStrictEqual(list[2].collapsed, false); assert.deepStrictEqual(list[2].depth, 2); assert.deepStrictEqual(list[3].element, 12); assert.deepStrictEqual(list[3].collapsed, false); assert.deepStrictEqual(list[3].depth, 2); assert.deepStrictEqual(list[4].element, 1); assert.deepStrictEqual(list[4].collapsed, false); assert.deepStrictEqual(list[4].depth, 1); assert.deepStrictEqual(list[5].element, 2); assert.deepStrictEqual(list[5].collapsed, false); assert.deepStrictEqual(list[5].depth, 1); })); test('smart diff consistency', () => { const times = 500; const minEdits = 1; const maxEdits = 10; const maxInserts = 5; for (let i = 0; i < times; i++) { const list: ITreeNode<number>[] = []; const options = { diffIdentityProvider: { getId: (n: number) => String(n) } }; const model = new IndexTreeModel<number>('test', toList(list), -1); const changes = []; const expected: number[] = []; let elementCounter = 0; for (let edits = Math.random() * (maxEdits - minEdits) + minEdits; edits > 0; edits--) { const spliceIndex = Math.floor(Math.random() * list.length); const deleteCount = Math.ceil(Math.random() * (list.length - spliceIndex)); const insertCount = Math.floor(Math.random() * maxInserts + 1); let inserts: ITreeElement<number>[] = []; for (let i = 0; i < insertCount; i++) { const element = elementCounter++; inserts.push({ element, children: [] }); } // move existing items if (Math.random() < 0.5) { const elements = list.slice(spliceIndex, spliceIndex + Math.floor(deleteCount / 2)); inserts.push(...elements.map(({ element }) => ({ element, children: [] }))); } model.splice([spliceIndex], deleteCount, inserts, options); expected.splice(spliceIndex, deleteCount, ...inserts.map(i => i.element)); const listElements = list.map(l => l.element); changes.push(`splice(${spliceIndex}, ${deleteCount}, [${inserts.map(e => e.element).join(', ')}]) -> ${listElements.join(', ')}`); assert.deepStrictEqual(expected, listElements, `Expected ${listElements.join(', ')} to equal ${expected.join(', ')}. Steps:\n\n${changes.join('\n')}`); } } }); test('collapse should recursively adjust visible count', () => { const list: ITreeNode<number>[] = []; const model = new IndexTreeModel<number>('test', toList(list), -1); model.splice([0], 0, [ { element: 1, children: [ { element: 11, children: [ { element: 111 } ] } ] }, { element: 2, children: [ { element: 21 } ] } ]); assert.deepStrictEqual(list.length, 5); assert.deepStrictEqual(toArray(list), [1, 11, 111, 2, 21]); model.setCollapsed([0, 0], true); assert.deepStrictEqual(list.length, 4); assert.deepStrictEqual(toArray(list), [1, 11, 2, 21]); model.setCollapsed([1], true); assert.deepStrictEqual(list.length, 3); assert.deepStrictEqual(toArray(list), [1, 11, 2]); }); test('setCollapsible', () => { const list: ITreeNode<number>[] = []; const model = new IndexTreeModel<number>('test', toList(list), -1); model.splice([0], 0, [ { element: 0, children: [ { element: 10 } ] } ]); assert.deepStrictEqual(list.length, 2); model.setCollapsible([0], false); assert.deepStrictEqual(list.length, 2); assert.deepStrictEqual(list[0].element, 0); assert.deepStrictEqual(list[0].collapsible, false); assert.deepStrictEqual(list[0].collapsed, false); assert.deepStrictEqual(list[1].element, 10); assert.deepStrictEqual(list[1].collapsible, false); assert.deepStrictEqual(list[1].collapsed, false); assert.deepStrictEqual(model.setCollapsed([0], true), false); assert.deepStrictEqual(list[0].element, 0); assert.deepStrictEqual(list[0].collapsible, false); assert.deepStrictEqual(list[0].collapsed, false); assert.deepStrictEqual(list[1].element, 10); assert.deepStrictEqual(list[1].collapsible, false); assert.deepStrictEqual(list[1].collapsed, false); assert.deepStrictEqual(model.setCollapsed([0], false), false); assert.deepStrictEqual(list[0].element, 0); assert.deepStrictEqual(list[0].collapsible, false); assert.deepStrictEqual(list[0].collapsed, false); assert.deepStrictEqual(list[1].element, 10); assert.deepStrictEqual(list[1].collapsible, false); assert.deepStrictEqual(list[1].collapsed, false); model.setCollapsible([0], true); assert.deepStrictEqual(list.length, 2); assert.deepStrictEqual(list[0].element, 0); assert.deepStrictEqual(list[0].collapsible, true); assert.deepStrictEqual(list[0].collapsed, false); assert.deepStrictEqual(list[1].element, 10); assert.deepStrictEqual(list[1].collapsible, false); assert.deepStrictEqual(list[1].collapsed, false); assert.deepStrictEqual(model.setCollapsed([0], true), true); assert.deepStrictEqual(list.length, 1); assert.deepStrictEqual(list[0].element, 0); assert.deepStrictEqual(list[0].collapsible, true); assert.deepStrictEqual(list[0].collapsed, true); assert.deepStrictEqual(model.setCollapsed([0], false), true); assert.deepStrictEqual(list[0].element, 0); assert.deepStrictEqual(list[0].collapsible, true); assert.deepStrictEqual(list[0].collapsed, false); assert.deepStrictEqual(list[1].element, 10); assert.deepStrictEqual(list[1].collapsible, false); assert.deepStrictEqual(list[1].collapsed, false); }); test('simple filter', () => { const list: ITreeNode<number>[] = []; const filter = new class implements ITreeFilter<number> { filter(element: number): TreeVisibility { return element % 2 === 0 ? TreeVisibility.Visible : TreeVisibility.Hidden; } }; const model = new IndexTreeModel<number>('test', toList(list), -1, { filter }); model.splice([0], 0, [ { element: 0, children: [ { element: 1 }, { element: 2 }, { element: 3 }, { element: 4 }, { element: 5 }, { element: 6 }, { element: 7 } ] } ]); assert.deepStrictEqual(list.length, 4); assert.deepStrictEqual(toArray(list), [0, 2, 4, 6]); model.setCollapsed([0], true); assert.deepStrictEqual(toArray(list), [0]); model.setCollapsed([0], false); assert.deepStrictEqual(toArray(list), [0, 2, 4, 6]); }); test('recursive filter on initial model', () => { const list: ITreeNode<number>[] = []; const filter = new class implements ITreeFilter<number> { filter(element: number): TreeVisibility { return element === 0 ? TreeVisibility.Recurse : TreeVisibility.Hidden; } }; const model = new IndexTreeModel<number>('test', toList(list), -1, { filter }); model.splice([0], 0, [ { element: 0, children: [ { element: 1 }, { element: 2 } ] } ]); assert.deepStrictEqual(toArray(list), []); }); test('refilter', () => { const list: ITreeNode<number>[] = []; let shouldFilter = false; const filter = new class implements ITreeFilter<number> { filter(element: number): TreeVisibility { return (!shouldFilter || element % 2 === 0) ? TreeVisibility.Visible : TreeVisibility.Hidden; } }; const model = new IndexTreeModel<number>('test', toList(list), -1, { filter }); model.splice([0], 0, [ { element: 0, children: [ { element: 1 }, { element: 2 }, { element: 3 }, { element: 4 }, { element: 5 }, { element: 6 }, { element: 7 } ] }, ]); assert.deepStrictEqual(toArray(list), [0, 1, 2, 3, 4, 5, 6, 7]); model.refilter(); assert.deepStrictEqual(toArray(list), [0, 1, 2, 3, 4, 5, 6, 7]); shouldFilter = true; model.refilter(); assert.deepStrictEqual(toArray(list), [0, 2, 4, 6]); shouldFilter = false; model.refilter(); assert.deepStrictEqual(toArray(list), [0, 1, 2, 3, 4, 5, 6, 7]); }); test('recursive filter', () => { const list: ITreeNode<string>[] = []; let query = new RegExp(''); const filter = new class implements ITreeFilter<string> { filter(element: string): TreeVisibility { return query.test(element) ? TreeVisibility.Visible : TreeVisibility.Recurse; } }; const model = new IndexTreeModel<string>('test', toList(list), 'root', { filter }); model.splice([0], 0, [ { element: 'vscode', children: [ { element: '.build' }, { element: 'git' }, { element: 'github', children: [ { element: 'calendar.yml' }, { element: 'endgame' }, { element: 'build.js' }, ] }, { element: 'build', children: [ { element: 'lib' }, { element: 'gulpfile.js' } ] } ] }, ]); assert.deepStrictEqual(list.length, 10); query = /build/; model.refilter(); assert.deepStrictEqual(toArray(list), ['vscode', '.build', 'github', 'build.js', 'build']); model.setCollapsed([0], true); assert.deepStrictEqual(toArray(list), ['vscode']); model.setCollapsed([0], false); assert.deepStrictEqual(toArray(list), ['vscode', '.build', 'github', 'build.js', 'build']); }); test('recursive filter with collapse', () => { const list: ITreeNode<string>[] = []; let query = new RegExp(''); const filter = new class implements ITreeFilter<string> { filter(element: string): TreeVisibility { return query.test(element) ? TreeVisibility.Visible : TreeVisibility.Recurse; } }; const model = new IndexTreeModel<string>('test', toList(list), 'root', { filter }); model.splice([0], 0, [ { element: 'vscode', children: [ { element: '.build' }, { element: 'git' }, { element: 'github', children: [ { element: 'calendar.yml' }, { element: 'endgame' }, { element: 'build.js' }, ] }, { element: 'build', children: [ { element: 'lib' }, { element: 'gulpfile.js' } ] } ] }, ]); assert.deepStrictEqual(list.length, 10); query = /gulp/; model.refilter(); assert.deepStrictEqual(toArray(list), ['vscode', 'build', 'gulpfile.js']); model.setCollapsed([0, 3], true); assert.deepStrictEqual(toArray(list), ['vscode', 'build']); model.setCollapsed([0], true); assert.deepStrictEqual(toArray(list), ['vscode']); }); test('recursive filter while collapsed', () => { const list: ITreeNode<string>[] = []; let query = new RegExp(''); const filter = new class implements ITreeFilter<string> { filter(element: string): TreeVisibility { return query.test(element) ? TreeVisibility.Visible : TreeVisibility.Recurse; } }; const model = new IndexTreeModel<string>('test', toList(list), 'root', { filter }); model.splice([0], 0, [ { element: 'vscode', collapsed: true, children: [ { element: '.build' }, { element: 'git' }, { element: 'github', children: [ { element: 'calendar.yml' }, { element: 'endgame' }, { element: 'build.js' }, ] }, { element: 'build', children: [ { element: 'lib' }, { element: 'gulpfile.js' } ] } ] }, ]); assert.deepStrictEqual(toArray(list), ['vscode']); query = /gulp/; model.refilter(); assert.deepStrictEqual(toArray(list), ['vscode']); model.setCollapsed([0], false); assert.deepStrictEqual(toArray(list), ['vscode', 'build', 'gulpfile.js']); model.setCollapsed([0], true); assert.deepStrictEqual(toArray(list), ['vscode']); query = new RegExp(''); model.refilter(); assert.deepStrictEqual(toArray(list), ['vscode']); model.setCollapsed([0], false); assert.deepStrictEqual(list.length, 10); }); suite('getNodeLocation', () => { test('simple', () => { const list: IIndexTreeNode<number>[] = []; const model = new IndexTreeModel<number>('test', toList(list), -1); model.splice([0], 0, [ { element: 0, children: [ { element: 10 }, { element: 11 }, { element: 12 }, ] }, { element: 1 }, { element: 2 } ]); assert.deepStrictEqual(model.getNodeLocation(list[0]), [0]); assert.deepStrictEqual(model.getNodeLocation(list[1]), [0, 0]); assert.deepStrictEqual(model.getNodeLocation(list[2]), [0, 1]); assert.deepStrictEqual(model.getNodeLocation(list[3]), [0, 2]); assert.deepStrictEqual(model.getNodeLocation(list[4]), [1]); assert.deepStrictEqual(model.getNodeLocation(list[5]), [2]); }); test('with filter', () => { const list: IIndexTreeNode<number>[] = []; const filter = new class implements ITreeFilter<number> { filter(element: number): TreeVisibility { return element % 2 === 0 ? TreeVisibility.Visible : TreeVisibility.Hidden; } }; const model = new IndexTreeModel<number>('test', toList(list), -1, { filter }); model.splice([0], 0, [ { element: 0, children: [ { element: 1 }, { element: 2 }, { element: 3 }, { element: 4 }, { element: 5 }, { element: 6 }, { element: 7 } ] } ]); assert.deepStrictEqual(model.getNodeLocation(list[0]), [0]); assert.deepStrictEqual(model.getNodeLocation(list[1]), [0, 1]); assert.deepStrictEqual(model.getNodeLocation(list[2]), [0, 3]); assert.deepStrictEqual(model.getNodeLocation(list[3]), [0, 5]); }); }); test('refilter with filtered out nodes', () => { const list: ITreeNode<string>[] = []; let query = new RegExp(''); const filter = new class implements ITreeFilter<string> { filter(element: string): boolean { return query.test(element); } }; const model = new IndexTreeModel<string>('test', toList(list), 'root', { filter }); model.splice([0], 0, [ { element: 'silver' }, { element: 'gold' }, { element: 'platinum' } ]); assert.deepStrictEqual(toArray(list), ['silver', 'gold', 'platinum']); query = /platinum/; model.refilter(); assert.deepStrictEqual(toArray(list), ['platinum']); model.splice([0], Number.POSITIVE_INFINITY, [ { element: 'silver' }, { element: 'gold' }, { element: 'platinum' } ]); assert.deepStrictEqual(toArray(list), ['platinum']); model.refilter(); assert.deepStrictEqual(toArray(list), ['platinum']); }); test('explicit hidden nodes should have renderNodeCount == 0, issue #83211', () => { const list: ITreeNode<string>[] = []; let query = new RegExp(''); const filter = new class implements ITreeFilter<string> { filter(element: string): boolean { return query.test(element); } }; const model = new IndexTreeModel<string>('test', toList(list), 'root', { filter }); model.splice([0], 0, [ { element: 'a', children: [{ element: 'aa' }] }, { element: 'b', children: [{ element: 'bb' }] } ]); assert.deepStrictEqual(toArray(list), ['a', 'aa', 'b', 'bb']); assert.deepStrictEqual(model.getListIndex([0]), 0); assert.deepStrictEqual(model.getListIndex([0, 0]), 1); assert.deepStrictEqual(model.getListIndex([1]), 2); assert.deepStrictEqual(model.getListIndex([1, 0]), 3); query = /b/; model.refilter(); assert.deepStrictEqual(toArray(list), ['b', 'bb']); assert.deepStrictEqual(model.getListIndex([0]), -1); assert.deepStrictEqual(model.getListIndex([0, 0]), -1); assert.deepStrictEqual(model.getListIndex([1]), 0); assert.deepStrictEqual(model.getListIndex([1, 0]), 1); }); });
the_stack
import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing'; import {addPackageToPackageJson} from '@angular/cdk/schematics/ng-add/package-config'; import {createTestCaseSetup, resolveBazelPath} from '@angular/cdk/schematics/testing'; import {readFileSync} from 'fs'; import {MIGRATION_PATH} from '../../../../paths'; // Copied from `cdk/testing/private` which is ESM-only at this point. We temporarily copy // this helper as the ESM/CJS interop for schematic code with `cdk/testing/private` is // significantly more difficult and prone to mistakes with file resolution in devkit rules. // TODO(ESM): use the helper from `cdk/testing` when devmode is equal to prodmode. export function dedent(strings: TemplateStringsArray, ...values: any[]) { let joinedString = ''; for (let i = 0; i < values.length; i++) { joinedString += `${strings[i]}${values[i]}`; } joinedString += strings[strings.length - 1]; const matches = joinedString.match(/^[ \t]*(?=\S)/gm); if (matches === null) { return joinedString; } const minLineIndent = Math.min(...matches.map(el => el.length)); const omitMinIndentRegex = new RegExp(`^[ \\t]{${minLineIndent}}`, 'gm'); return minLineIndent > 0 ? joinedString.replace(omitMinIndentRegex, '') : joinedString; } interface PackageJson { dependencies: Record<string, string | undefined>; } describe('v9 HammerJS removal', () => { const GESTURE_CONFIG_TEMPLATE_PATH = resolveBazelPath( __dirname, '../../../migrations/hammer-gestures-v9/gesture-config.template', ); let runner: SchematicTestRunner; let tree: UnitTestTree; let writeFile: (filePath: string, text: string) => void; let runMigration: () => Promise<{logOutput: string}>; beforeEach(async () => { const testSetup = await createTestCaseSetup('migration-v9', MIGRATION_PATH, []); runner = testSetup.runner; tree = testSetup.appTree; runMigration = testSetup.runFixers; writeFile = testSetup.writeFile; }); function appendContent(filePath: string, text: string) { writeFile(filePath, text + tree.readContent(filePath)); } function writeHammerTypes() { writeFile( '/node_modules/@types/hammerjs/index.d.ts', ` declare var Hammer: any; `, ); } function getDependencyVersion(name: string): string | undefined { return (JSON.parse(tree.readContent('/package.json')) as PackageJson).dependencies[name]; } it('should not throw if project tsconfig does not have explicit root file names', async () => { // Generates a second project in the workspace. This is necessary to ensure that the // migration runs logic to determine the correct workspace project. await runner .runExternalSchematicAsync( '@schematics/angular', 'application', {name: 'second-project'}, tree, ) .toPromise(); // Overwrite the default tsconfig to not specify any explicit source files. This replicates // the scenario observed in: https://github.com/angular/components/issues/18504. writeFile( '/projects/cdk-testing/tsconfig.app.json', JSON.stringify({ extends: '../../tsconfig.json', compilerOptions: { outDir: '../../out-tsc/app', types: [], }, }), ); addPackageToPackageJson(tree, 'hammerjs', '0.0.0'); await expectAsync(runMigration()).not.toBeRejected(); }); describe('hammerjs not used', () => { it('should remove hammerjs from "package.json" file', async () => { addPackageToPackageJson(tree, 'hammerjs', '0.0.0'); expect(getDependencyVersion('hammerjs')).toBe('0.0.0'); await runMigration(); expect(getDependencyVersion('hammerjs')).toBeUndefined(); // expect that there is a "node-package" install task. The task is // needed to update the lock file. expect(runner.tasks.some(t => t.name === 'node-package')).toBe(true); }); it('should remove import to load hammerjs', async () => { appendContent( '/projects/cdk-testing/src/main.ts', ` import 'hammerjs'; `, ); const {logOutput} = await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).not.toContain('hammerjs'); expect(logOutput).toContain( 'General notice: The HammerJS v9 migration for Angular Components is not able to ' + 'migrate tests. Please manually clean up tests in your project if they rely on HammerJS.', ); }); it('should remove empty named import to load hammerjs', async () => { appendContent( '/projects/cdk-testing/src/main.ts', ` import {} 'hammerjs'; `, ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).not.toContain('hammerjs'); }); it('should remove references to gesture config', async () => { writeFile( '/projects/cdk-testing/src/test.module.ts', dedent` import {NgModule} from '@angular/core'; import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; // some comment import {GestureConfig} from '@angular/material/core'; @NgModule({ providers: [ {provide: HAMMER_GESTURE_CONFIG, useClass: GestureConfig}, OtherProvider, ] }) export class TestModule {} `, ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/test.module.ts')).toContain(dedent` import {NgModule} from '@angular/core'; @NgModule({ providers: [ OtherProvider, ] }) export class TestModule {}`); }); it('should remove references to HammerModule', async () => { writeFile( '/projects/cdk-testing/src/test.module.ts', dedent` import {NgModule} from '@angular/core'; import { HAMMER_GESTURE_CONFIG, HammerModule } from '@angular/platform-browser'; // some comment import {GestureConfig} from '@angular/material/core'; @NgModule({ providers: [ {provide: HAMMER_GESTURE_CONFIG, useClass: GestureConfig}, OtherProvider, ], imports: [ HammerModule, OtherModule ], }) export class TestModule {} `, ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/test.module.ts')).toContain(dedent` import {NgModule} from '@angular/core'; @NgModule({ providers: [ OtherProvider, ], imports: [ OtherModule ], }) export class TestModule {}`); }); it('should remove references to gesture config if imports are aliased', async () => { writeFile( '/projects/cdk-testing/src/test.module.ts', dedent` import {NgModule} from '@angular/core'; import { HAMMER_GESTURE_CONFIG as configToken } from '@angular/platform-browser'; // some comment import {GestureConfig as gestureConfig} from '@angular/material/core'; @NgModule({ providers: [ {provide: configToken, useClass: gestureConfig}, OtherProvider, ] }) export class TestModule {} `, ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/test.module.ts')).toContain(dedent` import {NgModule} from '@angular/core'; @NgModule({ providers: [ OtherProvider, ] }) export class TestModule {}`); }); it('should report error if unable to remove reference to gesture config', async () => { writeFile( '/projects/cdk-testing/src/test.module.ts', dedent` import {NgModule} from '@angular/core'; import {NOT_KNOWN_TOKEN, HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {GestureConfig} from '@angular/material/core'; const myProvider = {provide: HAMMER_GESTURE_CONFIG, useClass: GestureConfig} @NgModule({ providers: [ {provide: NOT_KNOWN_TOKEN, useClass: GestureConfig}, {provide: HAMMER_GESTURE_CONFIG, useFactory: () => GestureConfig}, OtherProvider, ] }) export class TestModule { constructor() { doSomethingWith(GestureConfig); } } `, ); const {logOutput} = await runMigration(); expect(logOutput).toContain( `projects/cdk-testing/src/test.module.ts@5:20 - ` + `Unable to delete provider definition for "GestureConfig" completely. ` + `Please clean up the provider.`, ); expect(logOutput).toContain( `projects/cdk-testing/src/test.module.ts@9:42 - ` + `Cannot remove reference to "GestureConfig". Please remove manually.`, ); expect(logOutput).toContain( `projects/cdk-testing/src/test.module.ts@10:56 - ` + `Cannot remove reference to "GestureConfig". Please remove manually.`, ); expect(logOutput).toContain( `projects/cdk-testing/src/test.module.ts@16:21 - ` + `Cannot remove reference to "GestureConfig". Please remove manually.`, ); expect(tree.readContent('/projects/cdk-testing/src/test.module.ts')).toContain(dedent` import {NgModule} from '@angular/core'; import {NOT_KNOWN_TOKEN, HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; const myProvider = /* TODO: remove */ {} @NgModule({ providers: [ {provide: NOT_KNOWN_TOKEN, useClass: GestureConfig}, {provide: HAMMER_GESTURE_CONFIG, useFactory: () => GestureConfig}, OtherProvider, ] }) export class TestModule { constructor() { doSomethingWith(GestureConfig); } }`); }); it('should preserve import for hammer gesture token if used elsewhere', async () => { writeFile( '/projects/cdk-testing/src/test.module.ts', dedent` import {NgModule, Inject} from '@angular/core'; import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {GestureConfig} from '@angular/material/core'; @NgModule({ providers: [ {provide: ProviderAbove}, {provide: HAMMER_GESTURE_CONFIG, useClass: GestureConfig}, OtherProvider, ] }) export class TestModule { constructor(@Inject(HAMMER_GESTURE_CONFIG) config?: any) { console.log(config); } } `, ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/test.module.ts')).toContain(dedent` import {NgModule, Inject} from '@angular/core'; import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; @NgModule({ providers: [ {provide: ProviderAbove}, OtherProvider, ] }) export class TestModule {`); }); it('should remove import scripts in project index files if found', async () => { // tslint:disable:max-line-length writeFile( '/projects/cdk-testing/src/index.html', dedent` <!doctype html> <html lang="en"> <head> <title>Hello</title> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/core-js/latest/core.js"></script> <script type="text/javascript" src="node_modules/hammerjs/dist/hammer.js"></script> <script type="text/javascript" src="https://hammerjs.github.io/dist/hammer.min.js"></script> </head> <body> <app-root></app-root> </body> <script src="some-other-script.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/hammerjs/2.0.8/hammer.min.js"></script> </html> `, ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/index.html')).toContain(dedent` <!doctype html> <html lang="en"> <head> <title>Hello</title> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/core-js/latest/core.js"></script> </head> <body> <app-root></app-root> </body> <script src="some-other-script.js"></script> </html>`); // tslint:enable:max-line-length }); }); describe('hammerjs used programmatically', () => { beforeEach(() => { appendContent( '/projects/cdk-testing/src/main.ts', ` import 'hammerjs'; `, ); }); it('should detect global reference to Hammer through types', async () => { writeHammerTypes(); writeFile( '/projects/cdk-testing/src/app/hammer.ts', ` export function createHammerInstance(el: HTMLElement) { // this works since there are types for HammerJS installed. return new Hammer(el); } `, ); const {logOutput} = await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain(`import 'hammerjs';`); expect(logOutput).toContain( 'General notice: The HammerJS v9 migration for Angular Components is not able to ' + 'migrate tests. Please manually clean up tests in your project if they rely on the ' + 'deprecated Angular Material gesture config.', ); }); it('should ignore global reference to Hammer if not resolved to known types', async () => { writeHammerTypes(); writeFile( '/projects/cdk-testing/src/app/hammer.ts', ` import {Hammer} from 'workbench'; export function createWorkbenchHammer() { return new Hammer(); } `, ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).not.toContain( `import 'hammerjs';`, ); }); it('should not create gesture config if hammer is only used programmatically', async () => { writeFile( '/projects/cdk-testing/src/app/hammer.ts', ` export function createHammerInstance(el: HTMLElement) { return new (window as any).Hammer(el); } `, ); await runMigration(); expect(tree.exists('/projects/cdk-testing/src/gesture-config.ts')).toBe(false); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain(`import 'hammerjs';`); }); it('should remove gesture config setup if hammer is only used programmatically', async () => { writeFile( '/projects/cdk-testing/src/app/hammer.ts', ` export function createHammerInstance(el: HTMLElement) { return new (window as any).Hammer(el); } `, ); writeFile( '/projects/cdk-testing/src/test.module.ts', dedent` import {NgModule} from '@angular/core'; import {HAMMER_GESTURE_CONFIG, HammerModule} from '@angular/platform-browser'; import {GestureConfig} from '@angular/material/core'; @NgModule({ providers: [ {provide: HAMMER_GESTURE_CONFIG, useClass: GestureConfig}, OtherProvider, ], imports: [HammerModule], }) export class TestModule {} `, ); await runMigration(); expect(tree.exists('/projects/cdk-testing/src/gesture-config.ts')).toBe(false); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain(`import 'hammerjs';`); expect(tree.readContent('/projects/cdk-testing/src/test.module.ts')).toContain(dedent` import {NgModule} from '@angular/core'; @NgModule({ providers: [ OtherProvider, ], imports: [], }) export class TestModule {}`); }); }); describe('used in template with standard HammerJS events', () => { beforeEach(() => { appendContent( '/projects/cdk-testing/src/main.ts', ` import 'hammerjs'; `, ); }); it('should not create gesture config file', async () => { writeFile( '/projects/cdk-testing/src/app/app.component.html', ` <span (panstart)="onPanStart()"></span> `, ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain(`import 'hammerjs';`); expect(tree.exists('/projects/cdk-testing/src/gesture-config.ts')).toBe(false); }); it('should not setup custom gesture config provider in root module', async () => { writeFile( '/projects/cdk-testing/src/app/app.component.html', ` <span (panstart)="onPanStart()"></span> `, ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/app/app.module.ts')).toContain(dedent`\ import { NgModule } from '@angular/core'; import { BrowserModule, HammerModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HammerModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }`); }); it('should remove references to the deprecated gesture config', async () => { writeFile( '/projects/cdk-testing/src/app/app.component.html', ` <span (panstart)="onPanStart()"></span> `, ); writeFile( '/projects/cdk-testing/src/test.module.ts', dedent` import {NgModule} from '@angular/core'; import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {GestureConfig} from '@angular/material/core'; @NgModule({ providers: [{provide: HAMMER_GESTURE_CONFIG, useClass: GestureConfig}] }) export class TestModule {} `, ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/test.module.ts')).toContain(dedent` import {NgModule} from '@angular/core'; @NgModule({ providers: [] }) export class TestModule {}`); }); }); describe('used in template with custom Material gesture events', () => { beforeEach(() => { appendContent( '/projects/cdk-testing/src/main.ts', ` import 'hammerjs'; `, ); }); it('should create gesture config file', async () => { writeFile( '/projects/cdk-testing/src/app/app.component.html', ` <span (panstart)="onPanStart()"> <span (longpress)="onPress()"></span> </span> `, ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain(`import 'hammerjs';`); expect(tree.exists('/projects/cdk-testing/src/gesture-config.ts')).toBe(true); expect(tree.readContent('/projects/cdk-testing/src/gesture-config.ts')).toBe( readFileSync(GESTURE_CONFIG_TEMPLATE_PATH, 'utf8'), ); }); it('should create gesture config file if used in inline template', async () => { writeFile( '/projects/cdk-testing/src/app/test.component.ts', ` import {Component} from '@angular/core'; @Component({ template: \`<span (slide)="onSlide()"></span>\` }) export class TestComponent {} `, ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain(`import 'hammerjs';`); expect(tree.exists('/projects/cdk-testing/src/gesture-config.ts')).toBe(true); expect(tree.readContent('/projects/cdk-testing/src/gesture-config.ts')).toBe( readFileSync(GESTURE_CONFIG_TEMPLATE_PATH, 'utf8'), ); }); it('should print a notice message if hammer is only used in template', async () => { writeFile( '/projects/cdk-testing/src/app/app.component.html', ` <!-- This event could also be a component output! So it's ambiguous unless we instantiate the AOT compiler to understand how the template will be interpreted. This is out of scope for this migration and in the worst case we just keep HammerJS.. and the app will continue to work. --> <my-comp (slide)="onSlide()"></my-comp> `, ); const {logOutput} = await runMigration(); expect(logOutput).toContain( 'The HammerJS v9 migration for Angular Components migrated the project to ' + 'keep HammerJS installed, but detected ambiguous usage of HammerJS. Please manually ' + 'check if you can remove HammerJS from your application.', ); }); it('should create gesture config file if used in template and programmatically', async () => { writeFile( '/projects/cdk-testing/src/app/app.component.html', ` <span (slide)="onSlide($event)"></span> `, ); writeFile( '/projects/cdk-testing/src/app/hammer.ts', ` export function createHammerInstance(el: HTMLElement) { return new (window as any).Hammer(el); } `, ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain(`import 'hammerjs';`); expect(tree.exists('/projects/cdk-testing/src/gesture-config.ts')).toBe(true); expect(tree.readContent('/projects/cdk-testing/src/gesture-config.ts')).toBe( readFileSync(GESTURE_CONFIG_TEMPLATE_PATH, 'utf8'), ); }); it('should create gesture config file with different name if it would conflict', async () => { writeFile( '/projects/cdk-testing/src/app/app.component.html', ` <span (slideright)="onSlideRight()"></span> `, ); // unlikely case that someone has a file named "gesture-config" in the // project sources root. Though we want to perform the migration // successfully so we just generate a unique file name. writeFile('/projects/cdk-testing/src/gesture-config.ts', ''); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain(`import 'hammerjs';`); expect(tree.exists('/projects/cdk-testing/src/gesture-config-1.ts')).toBe(true); expect(tree.readContent('/projects/cdk-testing/src/gesture-config-1.ts')).toBe( readFileSync(GESTURE_CONFIG_TEMPLATE_PATH, 'utf8'), ); }); it('should rewrite references to gesture config', async () => { writeFile( '/projects/cdk-testing/src/app/app.component.html', ` <span (slidestart)="onSlideStart()"></span> `, ); writeFile( '/projects/cdk-testing/src/nested/test.module.ts', dedent` import {NgModule} from '@angular/core'; import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {GestureConfig} from '@angular/material/core'; // some-comment @NgModule({ providers: [ {provide: HAMMER_GESTURE_CONFIG, useClass: GestureConfig}, OtherProvider, ] }) export class TestModule {} `, ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain(`import 'hammerjs';`); expect(tree.exists('/projects/cdk-testing/src/gesture-config.ts')).toBe(true); expect(tree.readContent('/projects/cdk-testing/src/nested/test.module.ts')).toContain(dedent` import {NgModule} from '@angular/core'; import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import { GestureConfig } from "../gesture-config"; // some-comment @NgModule({ providers: [ {provide: HAMMER_GESTURE_CONFIG, useClass: GestureConfig}, OtherProvider, ] }) export class TestModule {}`); }); it('should rewrite references to gesture config without causing conflicts', async () => { writeFile( '/projects/cdk-testing/src/app/app.component.html', ` <span (slideend)="onSlideEnd()"></span> `, ); writeFile( '/projects/cdk-testing/src/test.module.ts', dedent` import {NgModule} from '@angular/core'; import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {GestureConfig} from 'ngx-hammer-events'; import * as core from '@angular/material/core'; @NgModule({ providers: [ {provide: HAMMER_GESTURE_CONFIG, useClass: core.GestureConfig}, ] }) export class TestModule {} `, ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain(`import 'hammerjs';`); expect(tree.exists('/projects/cdk-testing/src/gesture-config.ts')).toBe(true); expect(tree.readContent('/projects/cdk-testing/src/test.module.ts')).toContain(dedent` import {NgModule} from '@angular/core'; import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {GestureConfig} from 'ngx-hammer-events'; import * as core from '@angular/material/core'; import { GestureConfig as GestureConfig_1 } from "./gesture-config"; @NgModule({ providers: [ {provide: HAMMER_GESTURE_CONFIG, useClass: GestureConfig_1}, ] }) export class TestModule {}`); }); it('should set up Hammer gestures in app module', async () => { writeFile( '/projects/cdk-testing/src/app/app.component.html', ` <span (longpress)="onLongPress($event)"></span> `, ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain(`import 'hammerjs';`); expect(tree.exists('/projects/cdk-testing/src/gesture-config.ts')).toBe(true); // tslint:disable:max-line-length expect(tree.readContent('/projects/cdk-testing/src/app/app.module.ts')).toContain(dedent`\ import { NgModule } from '@angular/core'; import { BrowserModule, HAMMER_GESTURE_CONFIG, HammerModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { GestureConfig } from "../gesture-config"; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HammerModule ], providers: [ { provide: HAMMER_GESTURE_CONFIG, useClass: GestureConfig } ], bootstrap: [AppComponent] }) export class AppModule { }`); // tslint:enable:max-line-length }); it( 'should add gesture config provider to app module if module is referenced through ' + 're-exports in bootstrap', async () => { writeFile( '/projects/cdk-testing/src/app/app.component.html', ` <span (slide)="onSlide($event)"></span> `, ); writeFile( '/projects/cdk-testing/src/main.ts', ` import 'hammerjs'; import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule) .catch(err => console.error(err)); `, ); writeFile('/projects/cdk-testing/src/app/index.ts', `export * from './app.module';`); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain( `import 'hammerjs';`, ); expect(tree.exists('/projects/cdk-testing/src/gesture-config.ts')).toBe(true); // tslint:disable:max-line-length expect(tree.readContent('/projects/cdk-testing/src/app/app.module.ts')).toContain(dedent`\ import { NgModule } from '@angular/core'; import { BrowserModule, HAMMER_GESTURE_CONFIG, HammerModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; import { GestureConfig } from "../gesture-config"; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HammerModule ], providers: [ { provide: HAMMER_GESTURE_CONFIG, useClass: GestureConfig } ], bootstrap: [AppComponent] }) export class AppModule { }`); // tslint:enable:max-line-length }, ); it('should not add gesture config provider multiple times if already provided', async () => { writeFile( '/projects/cdk-testing/src/app/app.component.html', ` <span (slide)="onSlide($event)"></span> `, ); writeFile( '/projects/cdk-testing/src/app/app.module.ts', dedent` import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {GestureConfig} from '@angular/material/core'; @NgModule({ providers: [ { provide: HAMMER_GESTURE_CONFIG, useClass: GestureConfig }, ], }) export class AppModule {}`, ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain(`import 'hammerjs';`); expect(tree.exists('/projects/cdk-testing/src/gesture-config.ts')).toBe(true); expect(tree.readContent('/projects/cdk-testing/src/app/app.module.ts')).toContain(dedent` import { HAMMER_GESTURE_CONFIG, HammerModule } from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import { GestureConfig } from "../gesture-config"; @NgModule({ providers: [ { provide: HAMMER_GESTURE_CONFIG, useClass: GestureConfig }, ], imports: [ HammerModule ], }) export class AppModule {}`); }); it('should not add HammerModule multiple times if already provided', async () => { writeFile( '/projects/cdk-testing/src/app/app.component.html', ` <span (slide)="onSlide($event)"></span> `, ); writeFile( '/projects/cdk-testing/src/app/app.module.ts', dedent` import {HammerModule as myHammerModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; @NgModule({ imports: [myHammerModule], }) export class AppModule {} `, ); await runMigration(); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain(`import 'hammerjs';`); expect(tree.exists('/projects/cdk-testing/src/gesture-config.ts')).toBe(true); // tslint:disable:max-line-length expect(tree.readContent('/projects/cdk-testing/src/app/app.module.ts')).toContain(dedent` import { HammerModule as myHammerModule, HAMMER_GESTURE_CONFIG } from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import { GestureConfig } from "../gesture-config"; @NgModule({ imports: [myHammerModule], providers: [ { provide: HAMMER_GESTURE_CONFIG, useClass: GestureConfig } ], }) export class AppModule {}`); // tslint:enable:max-line-length }); }); it('should not remove hammerjs if test target compilation scope does not contain hammerjs usage', async () => { addPackageToPackageJson(tree, 'hammerjs', '0.0.0'); expect(getDependencyVersion('hammerjs')).toBe('0.0.0'); // we simulate a case where a component does not have any tests for. In that case, // the test target compilation scope does not include "test.component.ts" and the // migration would detect **no** usage of HammerJS, hence removing it. This is // something we avoid by just ignoring test target compilation scopes. writeFile( '/projects/cdk-testing/src/app/test.component.ts', ` import {Component} from '@angular/core'; @Component({ template: \`<span (slide)="onSlide()"></span>\` }) export class TestComponent {} `, ); await runMigration(); expect(getDependencyVersion('hammerjs')).toBe('0.0.0'); }); it( 'should not remove hammerjs from "package.json" file if used in one project while ' + 'unused in other project', async () => { addPackageToPackageJson(tree, 'hammerjs', '0.0.0'); expect(getDependencyVersion('hammerjs')).toBe('0.0.0'); await runner .runExternalSchematicAsync( '@schematics/angular', 'application', {name: 'second-project'}, tree, ) .toPromise(); // Ensure the "second-project" will be detected with using HammerJS. writeFile( '/projects/second-project/src/main.ts', ` new (window as any).Hammer(document.body); `, ); await runMigration(); expect(runner.tasks.some(t => t.name === 'node-package')).toBe(false); expect(getDependencyVersion('hammerjs')).toBe('0.0.0'); }, ); describe('with custom gesture config', () => { beforeEach(() => { addPackageToPackageJson(tree, 'hammerjs', '0.0.0'); appendContent('/projects/cdk-testing/src/main.ts', `import 'hammerjs';`); }); it('should not setup copied gesture config if hammer is used in template', async () => { writeFile( '/projects/cdk-testing/src/test.component.ts', dedent` import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {CustomGestureConfig} from "../gesture-config"; @NgModule({ providers: [ { provide: HAMMER_GESTURE_CONFIG, useClass: CustomGestureConfig }, ], }) export class TestModule {} `, ); writeFile( '/projects/cdk-testing/src/app/app.component.html', ` <span (longpress)="onPress()"></span> `, ); await runMigration(); expect(tree.exists('/projects/cdk-testing/src/gesture-config.ts')).toBe(false); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain('hammerjs'); expect(runner.tasks.some(t => t.name === 'node-package')).toBe(false); expect(tree.readContent('/projects/cdk-testing/src/test.component.ts')).toContain(dedent` import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {CustomGestureConfig} from "../gesture-config"; @NgModule({ providers: [ { provide: HAMMER_GESTURE_CONFIG, useClass: CustomGestureConfig }, ], }) export class TestModule {}`); }); it( 'should warn if hammer is used in template and references to Material gesture config ' + 'were detected', async () => { writeFile( '/projects/cdk-testing/src/test.component.ts', dedent` import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {CustomGestureConfig} from "../gesture-config"; @NgModule({ providers: [ { provide: HAMMER_GESTURE_CONFIG, useClass: CustomGestureConfig }, ], }) export class TestModule {} `, ); const subModuleFileContent = dedent` import {NgModule} from '@angular/core'; import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {GestureConfig} from '@angular/material/core'; @NgModule({ providers: [ { provide: HAMMER_GESTURE_CONFIG, useClass: GestureConfig }, ], }) export class SubModule {} `; writeFile('/projects/cdk-testing/src/sub.module.ts', subModuleFileContent); writeFile( '/projects/cdk-testing/src/app/app.component.html', ` <span (longpress)="onPress()"></span> `, ); const {logOutput} = await runMigration(); expect(logOutput).toContain( 'This target cannot be migrated completely. Please manually remove references ' + 'to the deprecated Angular Material gesture config.', ); expect(runner.tasks.some(t => t.name === 'node-package')).toBe(false); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain('hammerjs'); expect(tree.readContent('/projects/cdk-testing/src/test.component.ts')).toContain(dedent` import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {CustomGestureConfig} from "../gesture-config"; @NgModule({ providers: [ { provide: HAMMER_GESTURE_CONFIG, useClass: CustomGestureConfig }, ], }) export class TestModule {}`); expect(tree.readContent('/projects/cdk-testing/src/sub.module.ts')).toBe( subModuleFileContent, ); }, ); it('should not remove hammerjs if no usage could be detected', async () => { writeFile( '/projects/cdk-testing/src/test.component.ts', dedent` import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {CustomGestureConfig} from "../gesture-config"; @NgModule({ providers: [ { provide: HAMMER_GESTURE_CONFIG, useClass: CustomGestureConfig }, ], }) export class TestModule {} `, ); writeFile( '/projects/cdk-testing/src/sub.component.ts', dedent` import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {GestureConfig} from '@angular/material/core'; @NgModule({ providers: [ { provide: HAMMER_GESTURE_CONFIG, useClass: GestureConfig }, ], }) export class SubModule {} `, ); const {logOutput} = await runMigration(); expect(logOutput).toContain( 'This target cannot be migrated completely, but all references to the ' + 'deprecated Angular Material gesture have been removed.', ); expect(runner.tasks.some(t => t.name === 'node-package')).toBe(false); expect(tree.readContent('/projects/cdk-testing/src/main.ts')).toContain('hammerjs'); expect(tree.readContent('/projects/cdk-testing/src/test.component.ts')).toContain(dedent` import {HAMMER_GESTURE_CONFIG} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {CustomGestureConfig} from "../gesture-config"; @NgModule({ providers: [ { provide: HAMMER_GESTURE_CONFIG, useClass: CustomGestureConfig }, ], }) export class TestModule {}`); expect(tree.readContent('/projects/cdk-testing/src/sub.component.ts')).toContain(dedent` import {NgModule} from '@angular/core'; @NgModule({ providers: [ ], }) export class SubModule {}`); }); }); });
the_stack
import './commands'; import * as path from 'path'; import * as url from 'url'; import { addNotification, azureLoggedInUserChanged, isMac, newNotification, rememberBounds, setOpenUrl, updateNewTunnelInfo, updateTunnelError, updateTunnelStatus, Notification, PersistentSettings, SharedConstants, TunnelError, TunnelInfo, TunnelStatus, } from '@bfemulator/app-shared'; import { app, BrowserWindow, nativeTheme, Rectangle, screen } from 'electron'; import { CommandServiceImpl, CommandServiceInstance } from '@bfemulator/sdk-shared'; import { AppUpdater } from './appUpdater'; import * as commandLine from './commandLine'; import { Protocol } from './constants'; import { Emulator } from './emulator'; import './fetchProxy'; import { Window } from './platform/window'; import { dispatch, getSettings, store } from './state/store'; import { TelemetryService } from './telemetry'; import { botListsAreDifferent, ensureStoragePath, saveSettings, writeFile } from './utils'; import { openFileFromCommandLine } from './utils/openFileFromCommandLine'; import { sendNotificationToClient } from './utils/sendNotificationToClient'; import { WindowManager } from './windowManager'; import { ProtocolHandler } from './protocolHandler'; import { WebSocketServer } from './server/webSocketServer'; const genericTunnelError = 'Oops.. Your ngrok tunnel seems to have an error. Please check the Ngrok Status Viewer for more details'; // start app startup timer const beginStartupTime = Date.now(); // ----------------------------------------------------------------------------- (process as NodeJS.EventEmitter).on('uncaughtException', (error: Error) => { // eslint-disable-next-line no-console console.error(error); }); // ----------------------------------------------------------------------------- // TODO - localization if (app) { app.setName('Bot Framework Emulator'); } let protocolUsed = false; // Parse command line commandLine.parseArgs(); function windowIsOffScreen(windowBounds: Rectangle): boolean { const nearestDisplay = screen.getDisplayMatching(windowBounds).workArea; return ( windowBounds.x > nearestDisplay.x + nearestDisplay.width || windowBounds.x + windowBounds.width < nearestDisplay.x || windowBounds.y > nearestDisplay.y + nearestDisplay.height || windowBounds.y + windowBounds.height < nearestDisplay.y ); } class SplashScreen { private static splashWindow: BrowserWindow; public static show(mainBrowserWindow: BrowserWindow) { if (this.splashWindow) { return; } this.splashWindow = new BrowserWindow({ show: false, width: 400, height: 300, center: true, frame: false, }); const splashPage = process.env.ELECTRON_TARGET_URL ? `${process.env.ELECTRON_TARGET_URL}splash.html` : url.format({ protocol: 'file', slashes: true, pathname: require.resolve('@bfemulator/client/public/splash.html'), }); this.splashWindow.loadURL(splashPage); this.splashWindow.once('ready-to-show', () => { // only show if the main window still hasn't loaded if (!mainBrowserWindow.isVisible()) { this.splashWindow.show(); } else { this.hide(); } }); } public static hide() { if (!this.splashWindow) { return; } this.splashWindow.destroy(); this.splashWindow = null; } } class EmulatorApplication { @CommandServiceInstance() public commandService: CommandServiceImpl; public mainBrowserWindow: BrowserWindow; public mainWindow: Window; public windowManager = new WindowManager(); private botsRef = store.getState().bot.botFiles; private fileToOpen: string; constructor() { Emulator.initialize(); this.initializeNgrokListeners(); this.initializeAppListeners(); this.initializeSystemPreferencesListeners(); store.subscribe(this.storeSubscriptionHandler); } private initializeBrowserWindowListeners() { this.mainBrowserWindow.once('close', this.onBrowserWindowClose); this.mainBrowserWindow.once('ready-to-show', this.onBrowserWindowReadyToShow); this.mainBrowserWindow.on('restore', this.onBrowserWindowRestore); this.mainBrowserWindow.on('closed', this.onBrowserWindowClosed); this.mainBrowserWindow.on('move', this.rememberCurrentBounds); this.mainBrowserWindow.on('restore', this.rememberCurrentBounds); } private initializeNgrokListeners() { Emulator.getInstance().ngrok.ngrokEmitter.on('onTunnelError', this.onTunnelError); Emulator.getInstance().ngrok.ngrokEmitter.on('onNewTunnelConnected', this.onNewTunnelConnected); Emulator.getInstance().ngrok.ngrokEmitter.on('onTunnelStatusPing', this.onTunnelStatusPing); } private initializeSystemPreferencesListeners() { nativeTheme.on('updated', this.onInvertedColorSchemeChanged); } private initializeAppListeners() { app.on('activate', this.onAppActivate); app.on('ready', this.onAppReady); app.on('open-file', this.onAppOpenFile); app.on('open-url', this.onAppOpenUrl); app.on('will-quit', this.onAppWillQuit); } // Main browser window listeners private onBrowserWindowClose = async (event: Event) => { const { azure } = getSettings(); if (azure.signedInUser && !azure.persistLogin) { event.preventDefault(); await this.commandService.call(SharedConstants.Commands.Azure.SignUserOutOfAzure, false); } saveSettings<PersistentSettings>('server.json', getSettings()); app.quit(); }; private onBrowserWindowReadyToShow = async () => { this.onInvertedColorSchemeChanged(); const { zoomLevel } = getSettings().windowState; this.mainWindow.webContents.setZoomLevel(zoomLevel); SplashScreen.hide(); this.mainBrowserWindow.show(); // Start auto-updater await AppUpdater.startup(); // Renew arm token await this.renewArmToken(); await WebSocketServer.init(); if (this.fileToOpen) { await openFileFromCommandLine(this.fileToOpen, this.commandService); this.fileToOpen = null; } // log app startup time in seconds const endStartupTime = Date.now(); const startupTime = (endStartupTime - beginStartupTime) / 1000; const launchedByProtocol = process.argv.some(arg => arg.includes(Protocol)) || protocolUsed; TelemetryService.trackEvent('app_launch', { method: launchedByProtocol ? 'protocol' : 'binary', startupTime, }); }; private onBrowserWindowRestore = () => { if (windowIsOffScreen(this.mainWindow.browserWindow.getBounds())) { const currentBounds = this.mainWindow.browserWindow.getBounds(); let display = screen.getAllDisplays().find(displayArg => displayArg.id === getSettings().windowState.displayId); display = display || screen.getDisplayMatching(currentBounds); this.mainWindow.browserWindow.setPosition(display.workArea.x, display.workArea.y); const bounds = { displayId: display.id, width: currentBounds.width, height: currentBounds.height, left: display.workArea.x, top: display.workArea.y, }; dispatch(rememberBounds(bounds)); } }; private onBrowserWindowClosed = () => { this.windowManager.closeAll(); this.mainWindow = null; }; private rememberCurrentBounds = () => { const currentBounds = this.mainWindow.browserWindow.getBounds(); const bounds = { displayId: screen.getDisplayMatching(currentBounds).id, width: currentBounds.width, height: currentBounds.height, left: currentBounds.x, top: currentBounds.y, }; dispatch(rememberBounds(bounds)); }; private onTunnelStatusPing = async (status: TunnelStatus) => { dispatch(updateTunnelStatus({ tunnelStatus: status })); }; private onNewTunnelConnected = async (tunnelInfo: TunnelInfo) => { dispatch(updateNewTunnelInfo(tunnelInfo)); }; private onTunnelError = async (response: TunnelError) => { const { Commands } = SharedConstants; dispatch(updateTunnelError({ ...response })); const ngrokNotification: Notification = newNotification(genericTunnelError); dispatch(addNotification(ngrokNotification.id)); this.commandService.call(Commands.Ngrok.OpenStatusViewer, false); ngrokNotification.addButton('Debug Console', () => { this.commandService.remoteCall(Commands.Notifications.Remove, ngrokNotification.id); this.commandService.call(Commands.Ngrok.OpenStatusViewer); }); await sendNotificationToClient(ngrokNotification, this.commandService); Emulator.getInstance().ngrok.broadcastNgrokError(genericTunnelError); }; private onInvertedColorSchemeChanged = () => { const { theme, availableThemes } = getSettings().windowState; const themeInfo = availableThemes.find(availableTheme => availableTheme.name === theme); const isHighContrast = nativeTheme.shouldUseInvertedColorScheme; const themeName = isHighContrast ? 'high-contrast' : themeInfo.name; const themeComponents = isHighContrast ? path.join('.', 'themes', 'high-contrast.css') : themeInfo.href; this.commandService.remoteCall(SharedConstants.Commands.UI.SwitchTheme, themeName, themeComponents); }; // App listeners private onAppReady = () => { if (this.mainBrowserWindow) { return; } this.mainBrowserWindow = new BrowserWindow({ show: false, backgroundColor: '#f7f7f7', width: 1400, height: 920, webPreferences: { enableRemoteModule: true, nodeIntegration: true, webviewTag: true }, }); this.initializeBrowserWindowListeners(); this.mainWindow = new Window(this.mainBrowserWindow); Emulator.getInstance().initServer({ fetch, logService: this.mainWindow.logService }); if (process.env.NODE_ENV !== 'test') { SplashScreen.show(this.mainBrowserWindow); } const page = process.env.ELECTRON_TARGET_URL || url.format({ protocol: 'file', slashes: true, pathname: require.resolve('@bfemulator/client/public/index.html'), }); if (/^http:\/\//.test(page)) { // eslint-disable-next-line no-console console.warn(`Loading emulator code from ${page}`); } this.mainBrowserWindow.loadURL(page); this.mainBrowserWindow.setTitle(app.getName()); }; private onAppActivate = () => { this.onAppReady(); }; private onAppWillQuit = () => { WebSocketServer.cleanup(); }; private onAppOpenUrl = (event: Event, url: string): void => { event.preventDefault(); if (isMac()) { protocolUsed = true; if (this.mainWindow && this.mainWindow.webContents) { // the app is already running, send a message containing the url to the renderer process ProtocolHandler.parseProtocolUrlAndDispatch(url); } else { // the app is not yet running, so store the url so the UI can request it later store.dispatch(setOpenUrl(url)); } } }; private onAppOpenFile = async (event: Event, file: string) => { if (!this.mainWindow || !this.commandService) { this.fileToOpen = file; } else { await openFileFromCommandLine(file, this.commandService); } }; private storeSubscriptionHandler = () => { const state = store.getState(); // if the bots list changed, write it to disk const bots = state.bot.botFiles.filter(botFile => !!botFile); if (botListsAreDifferent(this.botsRef, bots)) { const botsJson = { bots }; const botsJsonPath = path.join(ensureStoragePath(), 'bots.json'); try { // write bots list writeFile(botsJsonPath, botsJson); // update cached version to check against for changes this.botsRef = bots; } catch (e) { // eslint-disable-next-line no-console console.error('Error writing bot list to disk: ', e); } } }; private async renewArmToken() { const { persistLogin, signedInUser } = getSettings().azure; if (persistLogin && signedInUser) { const result = await this.commandService.registry.getCommand(SharedConstants.Commands.Azure.RetrieveArmToken)( true ); if (result && 'access_token' in result) { await this.commandService.remoteCall(SharedConstants.Commands.UI.ArmTokenReceivedOnStartup, result); } else if (!result) { store.dispatch(azureLoggedInUserChanged('')); await this.commandService.call(SharedConstants.Commands.Electron.UpdateFileMenu); } } } } export const emulatorApplication = new EmulatorApplication();
the_stack
import { EventEmitter } from 'events' import * as rlp from 'rlp' import * as util from '../util' import BufferList = require('bl') import ms from 'ms' import { debug as createDebugLogger } from 'debug' import Common from '@ethereumjs/common' import { ECIES } from './ecies' import { ETH, LES } from '../' import { int2buffer, buffer2int, formatLogData } from '../util' import { Socket } from 'net' const debug = createDebugLogger('devp2p:rlpx:peer') const verbose = createDebugLogger('verbose').enabled export const BASE_PROTOCOL_VERSION = 4 export const BASE_PROTOCOL_LENGTH = 16 export const PING_INTERVAL = ms('15s') export enum PREFIXES { HELLO = 0x00, DISCONNECT = 0x01, PING = 0x02, PONG = 0x03 } export enum DISCONNECT_REASONS { DISCONNECT_REQUESTED = 0x00, NETWORK_ERROR = 0x01, PROTOCOL_ERROR = 0x02, USELESS_PEER = 0x03, TOO_MANY_PEERS = 0x04, ALREADY_CONNECTED = 0x05, INCOMPATIBLE_VERSION = 0x06, INVALID_IDENTITY = 0x07, CLIENT_QUITTING = 0x08, UNEXPECTED_IDENTITY = 0x09, SAME_IDENTITY = 0x0a, TIMEOUT = 0x0b, SUBPROTOCOL_ERROR = 0x10 } export type HelloMsg = { 0: Buffer 1: Buffer 2: Buffer[][] 3: Buffer 4: Buffer length: 5 } export interface ProtocolDescriptor { protocol?: any offset: number length?: number } export interface ProtocolConstructor { new (...args: any[]): any } export interface Capabilities { name: string version: number length: number constructor: ProtocolConstructor } export interface Hello { protocolVersion: number clientId: string capabilities: Capabilities[] port: number id: Buffer } export class Peer extends EventEmitter { _clientId: Buffer _capabilities?: Capabilities[] _common: Common _port: number _id: Buffer _remoteClientIdFilter: any _remoteId: Buffer _EIP8: Buffer _eciesSession: ECIES _state: string _weHello: HelloMsg | null _hello: Hello | null _nextPacketSize: number _socket: Socket _socketData: BufferList _pingIntervalId: NodeJS.Timeout | null _pingTimeoutId: NodeJS.Timeout | null _closed: boolean _connected: boolean _disconnectReason?: DISCONNECT_REASONS _disconnectWe: any _pingTimeout: number _protocols: ProtocolDescriptor[] constructor(options: any) { super() // hello data this._clientId = options.clientId this._capabilities = options.capabilities this._common = options.common this._port = options.port this._id = options.id this._remoteClientIdFilter = options.remoteClientIdFilter // ECIES session this._remoteId = options.remoteId this._EIP8 = options.EIP8 !== undefined ? options.EIP8 : true this._eciesSession = new ECIES(options.privateKey, this._id, this._remoteId) // Auth, Ack, Header, Body this._state = 'Auth' this._weHello = null this._hello = null this._nextPacketSize = 307 // socket this._socket = options.socket this._socketData = new BufferList() this._socket.on('data', this._onSocketData.bind(this)) this._socket.on('error', (err: Error) => this.emit('error', err)) this._socket.once('close', this._onSocketClose.bind(this)) this._connected = false this._closed = false this._disconnectWe = null this._pingIntervalId = null this._pingTimeout = options.timeout this._pingTimeoutId = null // sub-protocols this._protocols = [] // send AUTH if outgoing connection if (this._remoteId !== null) { this._sendAuth() } } /** * Send AUTH message */ _sendAuth() { if (this._closed) return debug( `Send auth (EIP8: ${this._EIP8}) to ${this._socket.remoteAddress}:${this._socket.remotePort}` ) if (this._EIP8) { const authEIP8 = this._eciesSession.createAuthEIP8() if (!authEIP8) return this._socket.write(authEIP8) } else { const authNonEIP8 = this._eciesSession.createAuthNonEIP8() if (!authNonEIP8) return this._socket.write(authNonEIP8) } this._state = 'Ack' this._nextPacketSize = 210 } /** * Send ACK message */ _sendAck() { if (this._closed) return debug( `Send ack (EIP8: ${this._eciesSession._gotEIP8Auth}) to ${this._socket.remoteAddress}:${this._socket.remotePort}` ) if (this._eciesSession._gotEIP8Auth) { const ackEIP8 = this._eciesSession.createAckEIP8() if (!ackEIP8) return this._socket.write(ackEIP8) } else { const ackOld = this._eciesSession.createAckOld() if (!ackOld) return this._socket.write(ackOld) } this._state = 'Header' this._nextPacketSize = 32 this._sendHello() } /** * Create message HEADER and BODY and send to socket * Also called from SubProtocol context * @param code * @param data */ _sendMessage(code: number, data: Buffer) { if (this._closed) return false const msg = Buffer.concat([rlp.encode(code), data]) const header = this._eciesSession.createHeader(msg.length) if (!header) return this._socket.write(header) const body = this._eciesSession.createBody(msg) if (!body) return this._socket.write(body) return true } /** * Send HELLO message */ _sendHello() { debug(`Send HELLO to ${this._socket.remoteAddress}:${this._socket.remotePort}`) const payload: HelloMsg = [ int2buffer(BASE_PROTOCOL_VERSION), this._clientId, this._capabilities!.map((obj: any) => [Buffer.from(obj.name), int2buffer(obj.version)]), this._port === null ? Buffer.allocUnsafe(0) : int2buffer(this._port), this._id ] if (!this._closed) { if (this._sendMessage(PREFIXES.HELLO, rlp.encode(payload as any))) { this._weHello = payload } if (this._hello) { this.emit('connect') } } } /** * Send DISCONNECT message * @param reason */ _sendDisconnect(reason: DISCONNECT_REASONS) { debug( `Send DISCONNECT to ${this._socket.remoteAddress}:${ this._socket.remotePort } (reason: ${this.getDisconnectPrefix(reason)})` ) const data = rlp.encode(reason) if (!this._sendMessage(PREFIXES.DISCONNECT, data)) return this._disconnectReason = reason this._disconnectWe = true this._closed = true setTimeout(() => this._socket.end(), ms('2s')) } /** * Send PING message */ _sendPing() { debug(`Send PING to ${this._socket.remoteAddress}:${this._socket.remotePort}`) const data = rlp.encode([]) if (!this._sendMessage(PREFIXES.PING, data)) return clearTimeout(this._pingTimeoutId!) this._pingTimeoutId = setTimeout(() => { this.disconnect(DISCONNECT_REASONS.TIMEOUT) }, this._pingTimeout) } /** * Send PONG message */ _sendPong() { debug(`Send PONG to ${this._socket.remoteAddress}:${this._socket.remotePort}`) const data = rlp.encode([]) this._sendMessage(PREFIXES.PONG, data) } /** * AUTH message received */ _handleAuth() { const bytesCount = this._nextPacketSize const parseData = this._socketData.slice(0, bytesCount) if (!this._eciesSession._gotEIP8Auth) { if (parseData.slice(0, 1) === Buffer.from('04', 'hex')) { this._eciesSession.parseAuthPlain(parseData) } else { this._eciesSession._gotEIP8Auth = true this._nextPacketSize = util.buffer2int(this._socketData.slice(0, 2)) + 2 return } } else { this._eciesSession.parseAuthEIP8(parseData) } this._state = 'Header' this._nextPacketSize = 32 process.nextTick(() => this._sendAck()) this._socketData.consume(bytesCount) } /** * ACK message received */ _handleAck() { const bytesCount = this._nextPacketSize const parseData = this._socketData.slice(0, bytesCount) if (!this._eciesSession._gotEIP8Ack) { if (parseData.slice(0, 1) === Buffer.from('04', 'hex')) { this._eciesSession.parseAckPlain(parseData) debug( `Received ack (old format) from ${this._socket.remoteAddress}:${this._socket.remotePort}` ) } else { this._eciesSession._gotEIP8Ack = true this._nextPacketSize = util.buffer2int(this._socketData.slice(0, 2)) + 2 return } } else { this._eciesSession.parseAckEIP8(parseData) debug(`Received ack (EIP8) from ${this._socket.remoteAddress}:${this._socket.remotePort}`) } this._state = 'Header' this._nextPacketSize = 32 process.nextTick(() => this._sendHello()) this._socketData.consume(bytesCount) } /** * HELLO message received */ _handleHello(payload: any) { this._hello = { protocolVersion: buffer2int(payload[0]), clientId: payload[1].toString(), capabilities: payload[2].map((item: any) => { return { name: item[0].toString(), version: buffer2int(item[1]) } }), port: buffer2int(payload[3]), id: payload[4] } if (this._remoteId === null) { this._remoteId = Buffer.from(this._hello.id) } else if (!this._remoteId.equals(this._hello.id)) { return this.disconnect(DISCONNECT_REASONS.INVALID_IDENTITY) } if (this._remoteClientIdFilter) { for (const filterStr of this._remoteClientIdFilter) { if (this._hello.clientId.toLowerCase().includes(filterStr.toLowerCase())) { return this.disconnect(DISCONNECT_REASONS.USELESS_PEER) } } } const shared: any = {} for (const item of this._hello.capabilities) { for (const obj of this._capabilities!) { if (obj.name !== item.name || obj.version !== item.version) continue if (shared[obj.name] && shared[obj.name].version > obj.version) continue shared[obj.name] = obj } } let offset = BASE_PROTOCOL_LENGTH this._protocols = Object.keys(shared) .map(key => shared[key]) .sort((obj1, obj2) => (obj1.name < obj2.name ? -1 : 1)) .map(obj => { const _offset = offset offset += obj.length const SubProtocol = obj.constructor const protocol = new SubProtocol(obj.version, this, (code: number, data: Buffer) => { if (code > obj.length) throw new Error('Code out of range') this._sendMessage(_offset + code, data) }) return { protocol, offset: _offset, length: obj.length } }) if (this._protocols.length === 0) { return this.disconnect(DISCONNECT_REASONS.USELESS_PEER) } this._connected = true this._pingIntervalId = setInterval(() => this._sendPing(), PING_INTERVAL) if (this._weHello) { this.emit('connect') } } /** * DISCONNECT message received * @param payload */ _handleDisconnect(payload: any) { this._closed = true this._disconnectReason = payload[0].length === 0 ? 0 : payload[0][0] debug( `DISCONNECT reason: ${DISCONNECT_REASONS[this._disconnectReason as number]} ${ this._socket.remoteAddress }:${this._socket.remotePort}` ) this._disconnectWe = false this._socket.end() } /** * PING message received */ _handlePing() { this._sendPong() } /** * PONG message received */ _handlePong() { clearTimeout(this._pingTimeoutId!) } /** * Message handling, called from a SubProtocol context * @param code * @param msg */ _handleMessage(code: PREFIXES, msg: Buffer) { const payload = rlp.decode(msg) switch (code) { case PREFIXES.HELLO: this._handleHello(payload) break case PREFIXES.DISCONNECT: this._handleDisconnect(payload) break case PREFIXES.PING: this._handlePing() break case PREFIXES.PONG: this._handlePong() break } } /** * Handle message header */ _handleHeader() { const bytesCount = this._nextPacketSize const parseData = this._socketData.slice(0, bytesCount) debug(`Received header ${this._socket.remoteAddress}:${this._socket.remotePort}`) const size = this._eciesSession.parseHeader(parseData) if (!size) { debug('invalid header size!') return } this._state = 'Body' this._nextPacketSize = size + 16 if (size % 16 > 0) this._nextPacketSize += 16 - (size % 16) this._socketData.consume(bytesCount) } /** * Handle message body */ _handleBody() { const bytesCount = this._nextPacketSize const parseData = this._socketData.slice(0, bytesCount) const body = this._eciesSession.parseBody(parseData) if (!body) { debug('empty body!') return } debug( `Received body ${this._socket.remoteAddress}:${this._socket.remotePort} ${formatLogData( body.toString('hex'), verbose )}` ) this._state = 'Header' this._nextPacketSize = 32 // RLP hack let code = body[0] if (code === 0x80) code = 0 if (code !== PREFIXES.HELLO && code !== PREFIXES.DISCONNECT && this._hello === null) { return this.disconnect(DISCONNECT_REASONS.PROTOCOL_ERROR) } const obj = this._getProtocol(code) if (obj === undefined) return this.disconnect(DISCONNECT_REASONS.PROTOCOL_ERROR) const msgCode = code - obj.offset const prefix = this.getMsgPrefix(msgCode) debug( `Received ${prefix} (message code: ${code} - ${obj.offset} = ${msgCode}) ${this._socket.remoteAddress}:${this._socket.remotePort}` ) try { obj.protocol._handleMessage(msgCode, body.slice(1)) } catch (err) { this.disconnect(DISCONNECT_REASONS.SUBPROTOCOL_ERROR) debug(`Error on peer subprotocol message handling: ${err}`) this.emit('error', err) } this._socketData.consume(bytesCount) } /** * Process socket data * @param data */ _onSocketData(data: Buffer) { if (this._closed) return this._socketData.append(data) while (this._socketData.length >= this._nextPacketSize) { try { switch (this._state) { case 'Auth': this._handleAuth() break case 'Ack': this._handleAck() break case 'Header': this._handleHeader() break case 'Body': this._handleBody() break } } catch (err) { debug(`Error on peer socket data handling: ${err}`) this.emit('error', err) } } } /** * React to socket being closed */ _onSocketClose() { clearInterval(this._pingIntervalId!) clearTimeout(this._pingTimeoutId!) this._closed = true if (this._connected) this.emit('close', this._disconnectReason, this._disconnectWe) } _getProtocol(code: number): ProtocolDescriptor | undefined { if (code < BASE_PROTOCOL_LENGTH) return { protocol: this, offset: 0 } for (const obj of this._protocols) { if (code >= obj.offset && code < obj.offset + obj.length!) return obj } } getId() { if (this._remoteId === null) return null return Buffer.from(this._remoteId) } getHelloMessage() { return this._hello } getProtocols<T extends ETH | LES>(): T[] { return this._protocols.map(obj => obj.protocol) } getMsgPrefix(code: PREFIXES): string { return PREFIXES[code] } getDisconnectPrefix(code: DISCONNECT_REASONS): string { return DISCONNECT_REASONS[code] } disconnect(reason: DISCONNECT_REASONS = DISCONNECT_REASONS.DISCONNECT_REQUESTED) { this._sendDisconnect(reason) } }
the_stack
import { player, saveSynergy, blankSave, reloadShit, format } from './Synergism'; import { testing, version } from './Config'; import { getElementById } from './Utility'; import LZString from 'lz-string'; import { achievementaward } from './Achievements'; import { Player } from './types/Synergism'; import { Synergism } from './Events'; import { Alert, Confirm, Prompt } from './UpdateHTML'; import { quarkHandler } from './Quark'; import { shopData } from './Shop'; import { addTimers } from './Helper'; import { toggleSubTab, toggleTabs } from './Toggles'; import { btoa } from './Utility'; import { DOMCacheGetOrSet } from './Cache/DOM'; import { Globals as G} from './Variables' const format24 = new Intl.DateTimeFormat("EN-GB", { year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", hour12: false, minute: "2-digit", second: "2-digit" }) const format12 = new Intl.DateTimeFormat("EN-GB", { year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", hour12: true, minute: "2-digit", second: "2-digit" }) const getRealTime = (use12 = false) => { const format = use12 ? format12 : format24; const datePartsArr = format .formatToParts(new Date()) .filter((x) => x.type !== "literal") .map(p => ({ [p.type]: p.value })); const dateParts = Object.assign({}, ...datePartsArr) as Record<string, string>; const period = use12 ? ` ${dateParts.dayPeriod.toUpperCase()}` : ''; return `${dateParts.year}-${dateParts.month}-${dateParts.day} ${dateParts.hour}_${dateParts.minute}_${dateParts.second}${period}`; } export const updateSaveString = (input: HTMLInputElement) => { const value = input.value.slice(0, 100); player.saveString = value; } const saveFilename = () => { const s = player.saveString const t = s.replace(/\$(.*?)\$/g, (_, b) => { switch (b) { case 'VERSION': return `v${version}`; case 'TIME': return getRealTime(); case 'TIME12': return getRealTime(true); } }); return t; } export const exportSynergism = async () => { player.offlinetick = Date.now(); const quarkData = quarkHandler(); if (quarkData.gain >= 1) { player.worlds.add(quarkData.gain); player.quarkstimer = (player.quarkstimer % (3600 / quarkData.perHour)) } saveSynergy(); const toClipboard = getElementById<HTMLInputElement>('saveType').checked; const save = localStorage.getItem('Synergysave2'); if ('clipboard' in navigator && toClipboard) { await navigator.clipboard.writeText(save) .catch(e => console.error(e)); } else if (toClipboard) { // Old browsers (legacy Edge, Safari 13.0) const textArea = document.createElement('textarea'); textArea.value = save; textArea.setAttribute('style', 'top: 0; left: 0; position: fixed;'); document.body.appendChild(textArea); textArea.focus(); textArea.select(); try { document.execCommand('copy'); } catch (_) { console.error("Failed to copy savegame to clipboard."); } document.body.removeChild(textArea); } else { const a = document.createElement('a'); a.setAttribute('href', 'data:text/plain;charset=utf-8,' + save); a.setAttribute('download', saveFilename()); a.setAttribute('id', 'downloadSave'); // "Starting in Firefox 75, the click() function works even when the element is not attached to a DOM tree." // https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click // so let's have it work on older versions of Firefox, doesn't change functionality. document.body.appendChild(a); a.click(); document.body.removeChild(a); } DOMCacheGetOrSet("exportinfo").textContent = toClipboard ? 'Copied save to your clipboard!' : 'Savefile copied to file!'; } export const resetGame = async () => { const a = window.crypto.getRandomValues(new Uint16Array(1))[0] % 16; const b = window.crypto.getRandomValues(new Uint16Array(1))[0] % 16; const result = await Prompt(`Answer the question to confirm you'd like to reset: what is ${a}+${b}? (Hint: ${a+b})`) if (+result !== a + b) { return Alert(`Answer was wrong, not resetting!`); } const hold = Object.assign({}, blankSave, { codes: Array.from(blankSave.codes) }) as Player; //Reset Displays toggleTabs("buildings"); toggleSubTab(1, 0); //Import Game void importSynergism(btoa(JSON.stringify(hold)), true); } export const importSynergism = (input: string, reset = false) => { if (typeof input !== 'string') { return Alert('Invalid character, could not save! 😕'); } const d = LZString.decompressFromBase64(input); const f = d ? JSON.parse(d) as Player : JSON.parse(atob(input)) as Player; if ( (f.exporttest === "YES!" || f.exporttest === true) || (f.exporttest === false && testing) || (f.exporttest === 'NO!' && testing) ) { localStorage.setItem('Synergysave2', btoa(JSON.stringify(f))); localStorage.setItem('saveScumIsCheating', Date.now().toString()); document.body.classList.add('loading'); return reloadShit(reset); } else { return Alert(`You are attempting to load a testing file in a non-testing version!`); } } export const promocodes = async () => { const input = await Prompt('Got a code? Great! Enter it in (CaSe SeNsItIvE). \n [Note to viewer: this is for events and certain always-active codes. \n May I suggest you type in "synergism2021" or "add" perchance?]'); const el = DOMCacheGetOrSet("promocodeinfo"); if (input === null) { return Alert('Alright, come back soon!') } if (input === "synergism2021" && !player.codes.get(1)) { player.codes.set(1, true); player.runeshards += 25; player.worlds.add(50); el.textContent = "Promo Code 'synergism2021' Applied! +25 Offerings, +50 Quarks" } else if (input === ":unsmith:" && player.achievements[243] < 1) { achievementaward(243); el.textContent = "It's Spaghetti Time! [Awarded an achievement!!!]"; } else if (input === ":antismith:" && player.achievements[244] < 1) { achievementaward(244); el.textContent = "Hey, isn't this just a reference to Antimatter Dimensions? Shh. [Awarded an achievement!!!]"; } else if(input === 'Khafra' && !player.codes.get(26)) { player.codes.set(26, true); const quarks = Math.floor(Math.random() * (400 - 100 + 1) + 100); player.worlds.add(quarks); el.textContent = 'Khafra has blessed you with ' + quarks + ' quarks!'; } else if(input === 'getout2021' && !player.codes.get(36)) { player.codes.set(36, true); const rewards = dailyCodeReward(); const quarkMultiplier = 20 + 30 * player.singularityCount player.worlds.add(quarkMultiplier * rewards.quarks) player.goldenQuarks += 40 * rewards.goldenQuarks const goldenQuarksText = (rewards.goldenQuarks > 0) ? `and ${format(40 * rewards.goldenQuarks, 0, true)} Golden Quarks` : ''; return Alert(`Here's to a better 2022! You have gained ${format(quarkMultiplier * rewards.quarks, 0, true)} Quarks ${goldenQuarksText} based on your progress!`) } else if (input.toLowerCase() === 'daily' && !player.dailyCodeUsed) { player.dailyCodeUsed = true; const rewards = dailyCodeReward(); const quarkMultiplier = 1 + 3 * Math.min(33, player.singularityCount) player.worlds.add(rewards.quarks * quarkMultiplier) player.goldenQuarks += rewards.goldenQuarks const goldenQuarksText = (rewards.goldenQuarks > 0) ? `and ${format(rewards.goldenQuarks, 0, true)} Golden Quarks` : ''; return Alert(`Thank you for playing today! You have gained ${format(rewards.quarks * quarkMultiplier, 0, true)} Quarks ${goldenQuarksText} based on your progress!`) } else if(input.toLowerCase() === 'add') { const hour = 3600000 const timeToNextHour = Math.floor(hour + player.rngCode - Date.now())/1000 if(player.rngCode >= (Date.now() - hour)) { // 1 hour el.textContent = `You do not have an 'Add' code attempt! You will gain 1 in ${timeToNextHour} seconds.`; return; } const possibleAmount = Math.floor(Math.min(24 + 2 * player.shopUpgrades.calculator2, (Date.now() - player.rngCode) / hour)) const attemptsUsed = await Prompt(`You can use up to ${possibleAmount} attempts at once. How many would you like to use?`); if (attemptsUsed === null) { return Alert(`No worries, you didn't lose any of your uses! Come back later!`); } const toUse = Number(attemptsUsed); if ( Number.isNaN(toUse) || !Number.isInteger(toUse) || toUse <= 0 ) return Alert(`Hey! That's not a valid number!`); const realAttemptsUsed = Math.min(possibleAmount, toUse); let mult = Math.max(0.4 + 0.02 * player.shopUpgrades.calculator3, 2/5 + (window.crypto.getRandomValues(new Uint16Array(2))[0] % 128) / 640); // [0.4, 0.6], slightly biased in favor of 0.4. =) mult *= 1 + 0.14 * player.shopUpgrades.calculator // Calculator Shop Upgrade (+14% / level) mult *= (player.shopUpgrades.calculator2 === shopData['calculator2'].maxLevel)? 1.25: 1; // Calculator 2 Max Level (+25%) const quarkBase = quarkHandler().perHour const actualQuarks = Math.floor(quarkBase * mult * realAttemptsUsed) const patreonBonus = Math.floor(actualQuarks * (player.worlds.BONUS / 100)); const [first, second] = window.crypto.getRandomValues(new Uint8Array(2)); //Allows storage of up to (24 + 2 * calc2 levels) Add Codes, lol! const v = Math.max(Date.now() - (24 + 2 * player.shopUpgrades.calculator2 - realAttemptsUsed) * hour, player.rngCode + hour * realAttemptsUsed); const remaining = Math.floor((Date.now() - v) / hour) const timeToNext = Math.floor((hour - (Date.now() - v - hour * remaining)) / 1000) // Calculator 3: Adds ascension timer. const ascensionTimer = (player.shopUpgrades.calculator3 > 0) ? 'Thanks to PL-AT Ω you have also gained ' + format(60 * player.shopUpgrades.calculator3 * realAttemptsUsed) + ' real-life seconds to your Ascension Timer!' : ''; // Calculator Maxed: you don't need to insert anything! if (player.shopUpgrades.calculator === shopData['calculator'].maxLevel) { player.worlds.add(actualQuarks); addTimers('ascension', 60 * player.shopUpgrades.calculator3 * realAttemptsUsed) player.rngCode = v; return Alert(`Your calculator figured out that ${first} + ${second} = ${first + second} on its own, so you were awarded ${actualQuarks + patreonBonus} quarks ` + `[${ patreonBonus } from Patreon Boost]! ${ ascensionTimer } You have ${ remaining } uses of Add.You will gain 1 in ${ timeToNext.toLocaleString(navigator.language) } seconds.`); } // If your calculator isn't maxed but has levels, it will provide the solution. const solution = (player.shopUpgrades.calculator > 0) ? 'The answer is ' + (first + second) + ' according to your calculator.' : ''; const addPrompt = await Prompt(`For ${actualQuarks + patreonBonus} quarks or nothing: What is ${first} + ${second}? ${solution}`); if (addPrompt === null) { return Alert(`No worries, you didn't lose any of your uses! Come back later!`); } player.rngCode = v; if(first + second === +addPrompt) { player.worlds.add(actualQuarks); addTimers('ascension', 60 * player.shopUpgrades.calculator3) await Alert(`You were awarded ${actualQuarks + patreonBonus} quarks [${patreonBonus} from Patreon Boost]! ${ascensionTimer} You have ${remaining} uses of Add. ` + `You will gain 1 in ${ timeToNext.toLocaleString(navigator.language) } seconds.`); } else { await Alert(`You guessed ${addPrompt}, but the answer was ${first + second}. You have ${remaining} uses of Add. You will gain 1 in ${timeToNext.toLocaleString(navigator.language)} seconds.`); } } else if (input === 'sub') { const amount = 1 + window.crypto.getRandomValues(new Uint16Array(1))[0] % 16; // [1, 16] const quarks = Number(player.worlds); await Alert(`Thanks for using the "sub" code! I've taken away ${amount} quarks! :)`); if (quarks < amount) await Alert(`I gave you ${amount - quarks} quarks so I could take ${amount} away.`); player.worlds.sub(quarks < amount ? amount - quarks : amount); } else if (input === 'gamble') { if ( typeof player.skillCode === 'number' || typeof localStorage.getItem('saveScumIsCheating') === 'string' ) { if ( (Date.now() - player.skillCode) / 1000 < 3600 || (Date.now() - Number(localStorage.getItem('saveScumIsCheating'))) / 1000 < 3600 ) { return el.textContent = 'Wait a little bit. We\'ll get back to you when you\'re ready to lose again.'; } } const confirmed = await Confirm(`Are you sure? The house always wins!`); if (!confirmed) return el.textContent = 'Scared? You should be!'; const bet = Number(await Prompt('How many quarks are you putting up?')); if (Number.isNaN(bet) || bet <= 0) return el.textContent = 'Can\'t bet that!'; else if (bet > 1e4) return el.textContent = `Due to cheaters, you can only bet 10k max.`; else if (Number(player.worlds) < bet) return el.textContent = 'Can\'t bet what you don\'t have.'; localStorage.setItem('saveScumIsCheating', Date.now().toString()); const dice = window.crypto.getRandomValues(new Uint8Array(1))[0] % 6 + 1; // [1, 6] if (dice === 1) { const won = bet * .25; // lmao player.worlds.add(won); player.skillCode = Date.now(); return el.textContent = `You won. The Syncasino offers you a grand total of 25% of the pot! [+${won} quarks]`; } player.worlds.sub(bet); el.textContent = `Try again... you can do it! [-${bet} quarks]`; } else if (input === 'time') { if ((Date.now() - player.promoCodeTiming.time) / 1000 < 3600) { return Confirm(` If you imported a save, you cannot use this code for 15 minutes to prevent cheaters. Otherwise, you must wait an hour between each use. `); } const random = Math.random() * 15000; // random time within 15 seconds const start = Date.now(); await Confirm( `Click the button within the next 15 seconds to test your luck!` + ` If you click within 500 ms of a randomly generated time, you will win a prize!` ); const diff = Math.abs(Date.now() - (start + random)); player.promoCodeTiming.time = Date.now(); if (diff <= 500) { player.worlds.add(500); return Confirm(`You clicked at the right time! [+500 Quarkies]`); } else { return Confirm(`You didn't guess within the correct times, try again soon!`); } } else { el.textContent = "Your code is either invalid or already used. Try again!" } saveSynergy(); // should fix refresh bug where you can continuously enter promocodes Synergism.emit('promocode', input); setTimeout(function () { el.textContent = '' }, 15000); } function dailyCodeReward() { let quarks = 0 let goldenQuarks = 0 const ascended = player.ascensionCount > 0; const singularity = player.singularityCount > 0; if (player.reincarnationCount > 0 || ascended || singularity) quarks += 20 if (player.challengecompletions[6] > 0 || ascended || singularity) quarks += 20 // 40 if (player.challengecompletions[7] > 0 || ascended || singularity) quarks += 30 // 70 if (player.challengecompletions[8] > 0 || ascended || singularity) quarks += 30 // 100 if (player.challengecompletions[9] > 0 || ascended || singularity) quarks += 40 // 140 if (player.challengecompletions[10] > 0 || ascended || singularity) quarks += 60 // 200 if (ascended || singularity) quarks += 50 // 250 if (player.challengecompletions[11] > 0 || singularity) quarks += 50 // 300 if (player.challengecompletions[12] > 0 || singularity) quarks += 50 // 350 if (player.challengecompletions[13] > 0 || singularity) quarks += 50 // 400 if (player.challengecompletions[14] > 0 || singularity) quarks += 100 // 500 if (player.researches[200] === G['researchMaxLevels'][200]) quarks += 250 // 750 if (player.cubeUpgrades[50] === 100000) quarks += 250 // 1000 if (player.platonicUpgrades[5] > 0) quarks += 250 // 1250 if (player.platonicUpgrades[10] > 0) quarks += 500 // 1750 if (player.platonicUpgrades[15] > 0) quarks += 750 // 2500 if (player.challenge15Exponent > 1e18) quarks += Math.floor(1000 * (Math.log10(player.challenge15Exponent) - 18)) // at least 2500 if (player.platonicUpgrades[20] > 0) quarks += 2500 // at least 5k if (singularity) goldenQuarks += 2 + 3 * player.singularityCount return { quarks: quarks, goldenQuarks: goldenQuarks, } }
the_stack
/* eslint-disable @typescript-eslint/class-name-casing */ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-empty-interface */ /* eslint-disable @typescript-eslint/no-namespace */ /* eslint-disable no-irregular-whitespace */ import { OAuth2Client, JWT, Compute, UserRefreshClient, BaseExternalAccountClient, GaxiosPromise, GoogleConfigurable, createAPIRequest, MethodOptions, StreamMethodOptions, GlobalOptions, GoogleAuth, BodyResponseCallback, APIRequestContext, } from 'googleapis-common'; import {Readable} from 'stream'; export namespace firebaseappcheck_v1 { export interface Options extends GlobalOptions { version: 'v1'; } interface StandardParameters { /** * Auth client or API Key for the request */ auth?: | string | OAuth2Client | JWT | Compute | UserRefreshClient | BaseExternalAccountClient | GoogleAuth; /** * V1 error format. */ '$.xgafv'?: string; /** * OAuth access token. */ access_token?: string; /** * Data format for response. */ alt?: string; /** * JSONP */ callback?: string; /** * Selector specifying which fields to include in a partial response. */ fields?: string; /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; } /** * Firebase App Check API * * Firebase App Check works alongside other Firebase services to help protect your backend resources from abuse, such as billing fraud or phishing. * * @example * ```js * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * ``` */ export class Firebaseappcheck { context: APIRequestContext; jwks: Resource$Jwks; projects: Resource$Projects; constructor(options: GlobalOptions, google?: GoogleConfigurable) { this.context = { _options: options || {}, google, }; this.jwks = new Resource$Jwks(this.context); this.projects = new Resource$Projects(this.context); } } /** * An app's App Attest configuration object. This configuration controls certain properties of the `AppCheckToken` returned by ExchangeAppAttestAttestation and ExchangeAppAttestAssertion, such as its ttl. Note that the Team ID registered with your app is used as part of the validation process. Please register it via the Firebase Console or programmatically via the [Firebase Management Service](https://firebase.google.com/docs/projects/api/reference/rest/v11/projects.iosApps/patch). */ export interface Schema$GoogleFirebaseAppcheckV1AppAttestConfig { /** * Required. The relative resource name of the App Attest configuration object, in the format: ``` projects/{project_number\}/apps/{app_id\}/appAttestConfig ``` */ name?: string | null; /** * Specifies the duration for which App Check tokens exchanged from App Attest artifacts will be valid. If unset, a default value of 1 hour is assumed. Must be between 30 minutes and 7 days, inclusive. */ tokenTtl?: string | null; } /** * Encapsulates an *App Check token*, which are used to access Firebase services protected by App Check. */ export interface Schema$GoogleFirebaseAppcheckV1AppCheckToken { /** * The App Check token. App Check tokens are signed [JWTs](https://tools.ietf.org/html/rfc7519) containing claims that identify the attested app and Firebase project. This token is used to access Firebase services protected by App Check. These tokens can also be [verified by your own custom backends](https://firebase.google.com/docs/app-check/custom-resource-backend) using the Firebase Admin SDK. */ token?: string | null; /** * The duration from the time this token is minted until its expiration. This field is intended to ease client-side token management, since the client may have clock skew, but is still able to accurately measure a duration. */ ttl?: string | null; } /** * Response message for the BatchGetAppAttestConfigs method. */ export interface Schema$GoogleFirebaseAppcheckV1BatchGetAppAttestConfigsResponse { /** * AppAttestConfigs retrieved. */ configs?: Schema$GoogleFirebaseAppcheckV1AppAttestConfig[]; } /** * Response message for the BatchGetDeviceCheckConfigs method. */ export interface Schema$GoogleFirebaseAppcheckV1BatchGetDeviceCheckConfigsResponse { /** * DeviceCheckConfigs retrieved. */ configs?: Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig[]; } /** * Response message for the BatchGetPlayIntegrityConfigs method. */ export interface Schema$GoogleFirebaseAppcheckV1BatchGetPlayIntegrityConfigsResponse { /** * PlayIntegrityConfigs retrieved. */ configs?: Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig[]; } /** * Response message for the BatchGetRecaptchaEnterpriseConfigs method. */ export interface Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaEnterpriseConfigsResponse { /** * RecaptchaEnterpriseConfigs retrieved. */ configs?: Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig[]; } /** * Response message for the BatchGetRecaptchaV3Configs method. */ export interface Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaV3ConfigsResponse { /** * RecaptchaV3Configs retrieved. */ configs?: Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config[]; } /** * Response message for the BatchGetSafetyNetConfigs method. */ export interface Schema$GoogleFirebaseAppcheckV1BatchGetSafetyNetConfigsResponse { /** * SafetyNetConfigs retrieved. */ configs?: Schema$GoogleFirebaseAppcheckV1SafetyNetConfig[]; } /** * Request message for the BatchUpdateServices method. */ export interface Schema$GoogleFirebaseAppcheckV1BatchUpdateServicesRequest { /** * Required. The request messages specifying the Services to update. A maximum of 100 objects can be updated in a batch. */ requests?: Schema$GoogleFirebaseAppcheckV1UpdateServiceRequest[]; /** * Optional. A comma-separated list of names of fields in the Services to update. Example: `display_name`. If the `update_mask` field is set in both this request and any of the UpdateServiceRequest messages, they must match or the entire batch fails and no updates will be committed. */ updateMask?: string | null; } /** * Response message for the BatchUpdateServices method. */ export interface Schema$GoogleFirebaseAppcheckV1BatchUpdateServicesResponse { /** * Service objects after the updates have been applied. */ services?: Schema$GoogleFirebaseAppcheckV1Service[]; } /** * A *debug token* is a secret used during the development or integration testing of an app. It essentially allows the development or integration testing to bypass app attestation while still allowing App Check to enforce protection on supported production Firebase services. */ export interface Schema$GoogleFirebaseAppcheckV1DebugToken { /** * Required. A human readable display name used to identify this debug token. */ displayName?: string | null; /** * Required. The relative resource name of the debug token, in the format: ``` projects/{project_number\}/apps/{app_id\}/debugTokens/{debug_token_id\} ``` */ name?: string | null; /** * Required. Input only. Immutable. The secret token itself. Must be provided during creation, and must be a UUID4, case insensitive. This field is immutable once set, and cannot be provided during an UpdateDebugToken request. You can, however, delete this debug token using DeleteDebugToken to revoke it. For security reasons, this field will never be populated in any response. */ token?: string | null; } /** * An app's DeviceCheck configuration object. This configuration is used by ExchangeDeviceCheckToken to validate device tokens issued to apps by DeviceCheck. It also controls certain properties of the returned `AppCheckToken`, such as its ttl. Note that the Team ID registered with your app is used as part of the validation process. Please register it via the Firebase Console or programmatically via the [Firebase Management Service](https://firebase.google.com/docs/projects/api/reference/rest/v11/projects.iosApps/patch). */ export interface Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig { /** * Required. The key identifier of a private key enabled with DeviceCheck, created in your Apple Developer account. */ keyId?: string | null; /** * Required. The relative resource name of the DeviceCheck configuration object, in the format: ``` projects/{project_number\}/apps/{app_id\}/deviceCheckConfig ``` */ name?: string | null; /** * Required. Input only. The contents of the private key (`.p8`) file associated with the key specified by `key_id`. For security reasons, this field will never be populated in any response. */ privateKey?: string | null; /** * Output only. Whether the `private_key` field was previously set. Since we will never return the `private_key` field, this field is the only way to find out whether it was previously set. */ privateKeySet?: boolean | null; /** * Specifies the duration for which App Check tokens exchanged from DeviceCheck tokens will be valid. If unset, a default value of 1 hour is assumed. Must be between 30 minutes and 7 days, inclusive. */ tokenTtl?: string | null; } /** * Request message for the ExchangeAppAttestAssertion method. */ export interface Schema$GoogleFirebaseAppcheckV1ExchangeAppAttestAssertionRequest { /** * Required. The artifact returned by a previous call to ExchangeAppAttestAttestation. */ artifact?: string | null; /** * Required. The CBOR-encoded assertion returned by the client-side App Attest API. */ assertion?: string | null; /** * Required. A one-time challenge returned by an immediately prior call to GenerateAppAttestChallenge. */ challenge?: string | null; } /** * Request message for the ExchangeAppAttestAttestation method. */ export interface Schema$GoogleFirebaseAppcheckV1ExchangeAppAttestAttestationRequest { /** * Required. The App Attest statement returned by the client-side App Attest API. This is a base64url encoded CBOR object in the JSON response. */ attestationStatement?: string | null; /** * Required. A one-time challenge returned by an immediately prior call to GenerateAppAttestChallenge. */ challenge?: string | null; /** * Required. The key ID generated by App Attest for the client app. */ keyId?: string | null; } /** * Response message for the ExchangeAppAttestAttestation method. */ export interface Schema$GoogleFirebaseAppcheckV1ExchangeAppAttestAttestationResponse { /** * Encapsulates an App Check token. */ appCheckToken?: Schema$GoogleFirebaseAppcheckV1AppCheckToken; /** * An artifact that can be used in future calls to ExchangeAppAttestAssertion. */ artifact?: string | null; } /** * Request message for the ExchangeCustomToken method. */ export interface Schema$GoogleFirebaseAppcheckV1ExchangeCustomTokenRequest { /** * Required. A custom token signed using your project's Admin SDK service account credentials. */ customToken?: string | null; } /** * Request message for the ExchangeDebugToken method. */ export interface Schema$GoogleFirebaseAppcheckV1ExchangeDebugTokenRequest { /** * Required. A debug token secret. This string must match a debug token secret previously created using CreateDebugToken. */ debugToken?: string | null; } /** * Request message for the ExchangeDeviceCheckToken method. */ export interface Schema$GoogleFirebaseAppcheckV1ExchangeDeviceCheckTokenRequest { /** * Required. The `device_token` as returned by Apple's client-side [DeviceCheck API](https://developer.apple.com/documentation/devicecheck/dcdevice). This is the base64 encoded `Data` (Swift) or `NSData` (ObjC) object. */ deviceToken?: string | null; } /** * Request message for the ExchangePlayIntegrityToken method. */ export interface Schema$GoogleFirebaseAppcheckV1ExchangePlayIntegrityTokenRequest { /** * Required. The [integrity verdict response token from Play Integrity](https://developer.android.com/google/play/integrity/verdict#decrypt-verify) issued to your app. */ playIntegrityToken?: string | null; } /** * Request message for the ExchangeRecaptchaEnterpriseToken method. */ export interface Schema$GoogleFirebaseAppcheckV1ExchangeRecaptchaEnterpriseTokenRequest { /** * Required. The reCAPTCHA token as returned by the [reCAPTCHA Enterprise JavaScript API](https://cloud.google.com/recaptcha-enterprise/docs/instrument-web-pages). */ recaptchaEnterpriseToken?: string | null; } /** * Request message for the ExchangeRecaptchaV3Token method. */ export interface Schema$GoogleFirebaseAppcheckV1ExchangeRecaptchaV3TokenRequest { /** * Required. The reCAPTCHA token as returned by the [reCAPTCHA v3 JavaScript API](https://developers.google.com/recaptcha/docs/v3). */ recaptchaV3Token?: string | null; } /** * Request message for the ExchangeSafetyNetToken method. */ export interface Schema$GoogleFirebaseAppcheckV1ExchangeSafetyNetTokenRequest { /** * Required. The [SafetyNet attestation response](https://developer.android.com/training/safetynet/attestation#request-attestation-step) issued to your app. */ safetyNetToken?: string | null; } /** * Request message for the GenerateAppAttestChallenge method. */ export interface Schema$GoogleFirebaseAppcheckV1GenerateAppAttestChallengeRequest {} /** * Response message for the GenerateAppAttestChallenge method. */ export interface Schema$GoogleFirebaseAppcheckV1GenerateAppAttestChallengeResponse { /** * A one-time use challenge for the client to pass to the App Attest API. */ challenge?: string | null; /** * The duration from the time this challenge is minted until its expiration. This field is intended to ease client-side token management, since the client may have clock skew, but is still able to accurately measure a duration. */ ttl?: string | null; } /** * Request message for the GeneratePlayIntegrityChallenge method. */ export interface Schema$GoogleFirebaseAppcheckV1GeneratePlayIntegrityChallengeRequest {} /** * Response message for the GeneratePlayIntegrityChallenge method. */ export interface Schema$GoogleFirebaseAppcheckV1GeneratePlayIntegrityChallengeResponse { /** * A one-time use [challenge](https://developer.android.com/google/play/integrity/verdict#protect-against-replay-attacks) for the client to pass to the Play Integrity API. */ challenge?: string | null; /** * The duration from the time this challenge is minted until its expiration. This field is intended to ease client-side token management, since the client may have clock skew, but is still able to accurately measure a duration. */ ttl?: string | null; } /** * Response message for the ListDebugTokens method. */ export interface Schema$GoogleFirebaseAppcheckV1ListDebugTokensResponse { /** * The DebugTokens retrieved. */ debugTokens?: Schema$GoogleFirebaseAppcheckV1DebugToken[]; /** * If the result list is too large to fit in a single response, then a token is returned. If the string is empty or omitted, then this response is the last page of results. This token can be used in a subsequent call to ListDebugTokens to find the next group of DebugTokens. Page tokens are short-lived and should not be persisted. */ nextPageToken?: string | null; } /** * Response message for the ListServices method. */ export interface Schema$GoogleFirebaseAppcheckV1ListServicesResponse { /** * If the result list is too large to fit in a single response, then a token is returned. If the string is empty or omitted, then this response is the last page of results. This token can be used in a subsequent call to ListServices to find the next group of Services. Page tokens are short-lived and should not be persisted. */ nextPageToken?: string | null; /** * The Services retrieved. */ services?: Schema$GoogleFirebaseAppcheckV1Service[]; } /** * An app's Play Integrity configuration object. This configuration controls certain properties of the `AppCheckToken` returned by ExchangePlayIntegrityToken, such as its ttl. Note that your registered SHA-256 certificate fingerprints are used to validate tokens issued by the Play Integrity API; please register them via the Firebase Console or programmatically via the [Firebase Management Service](https://firebase.google.com/docs/projects/api/reference/rest/v1beta1/projects.androidApps.sha/create). */ export interface Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig { /** * Required. The relative resource name of the Play Integrity configuration object, in the format: ``` projects/{project_number\}/apps/{app_id\}/playIntegrityConfig ``` */ name?: string | null; /** * Specifies the duration for which App Check tokens exchanged from Play Integrity tokens will be valid. If unset, a default value of 1 hour is assumed. Must be between 30 minutes and 7 days, inclusive. */ tokenTtl?: string | null; } /** * A JWK as specified by [section 4 of RFC 7517](https://tools.ietf.org/html/rfc7517#section-4) and [section 6.3.1 of RFC 7518](https://tools.ietf.org/html/rfc7518#section-6.3.1). */ export interface Schema$GoogleFirebaseAppcheckV1PublicJwk { /** * See [section 4.4 of RFC 7517](https://tools.ietf.org/html/rfc7517#section-4.4). */ alg?: string | null; /** * See [section 6.3.1.2 of RFC 7518](https://tools.ietf.org/html/rfc7518#section-6.3.1.2). */ e?: string | null; /** * See [section 4.5 of RFC 7517](https://tools.ietf.org/html/rfc7517#section-4.5). */ kid?: string | null; /** * See [section 4.1 of RFC 7517](https://tools.ietf.org/html/rfc7517#section-4.1). */ kty?: string | null; /** * See [section 6.3.1.1 of RFC 7518](https://tools.ietf.org/html/rfc7518#section-6.3.1.1). */ n?: string | null; /** * See [section 4.2 of RFC 7517](https://tools.ietf.org/html/rfc7517#section-4.2). */ use?: string | null; } /** * The currently active set of public keys that can be used to verify App Check tokens. This object is a JWK set as specified by [section 5 of RFC 7517](https://tools.ietf.org/html/rfc7517#section-5). For security, the response **must not** be cached for longer than six hours. */ export interface Schema$GoogleFirebaseAppcheckV1PublicJwkSet { /** * The set of public keys. See [section 5.1 of RFC 7517](https://tools.ietf.org/html/rfc7517#section-5). */ keys?: Schema$GoogleFirebaseAppcheckV1PublicJwk[]; } /** * An app's reCAPTCHA Enterprise configuration object. This configuration is used by ExchangeRecaptchaEnterpriseToken to validate reCAPTCHA tokens issued to apps by reCAPTCHA Enterprise. It also controls certain properties of the returned `AppCheckToken`, such as its ttl. */ export interface Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig { /** * Required. The relative resource name of the reCAPTCHA Enterprise configuration object, in the format: ``` projects/{project_number\}/apps/{app_id\}/recaptchaEnterpriseConfig ``` */ name?: string | null; /** * The score-based site key [created in reCAPTCHA Enterprise](https://cloud.google.com/recaptcha-enterprise/docs/create-key#creating_a_site_key) used to [invoke reCAPTCHA and generate the reCAPTCHA tokens](https://cloud.google.com/recaptcha-enterprise/docs/instrument-web-pages) for your application. Important: This is *not* the `site_secret` (as it is in reCAPTCHA v3), but rather your score-based reCAPTCHA Enterprise site key. */ siteKey?: string | null; /** * Specifies the duration for which App Check tokens exchanged from reCAPTCHA Enterprise tokens will be valid. If unset, a default value of 1 hour is assumed. Must be between 30 minutes and 7 days, inclusive. */ tokenTtl?: string | null; } /** * An app's reCAPTCHA v3 configuration object. This configuration is used by ExchangeRecaptchaV3Token to validate reCAPTCHA tokens issued to apps by reCAPTCHA v3. It also controls certain properties of the returned `AppCheckToken`, such as its ttl. */ export interface Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config { /** * Required. The relative resource name of the reCAPTCHA v3 configuration object, in the format: ``` projects/{project_number\}/apps/{app_id\}/recaptchaV3Config ``` */ name?: string | null; /** * Required. Input only. The site secret used to identify your service for reCAPTCHA v3 verification. For security reasons, this field will never be populated in any response. */ siteSecret?: string | null; /** * Output only. Whether the `site_secret` field was previously set. Since we will never return the `site_secret` field, this field is the only way to find out whether it was previously set. */ siteSecretSet?: boolean | null; /** * Specifies the duration for which App Check tokens exchanged from reCAPTCHA tokens will be valid. If unset, a default value of 1 day is assumed. Must be between 30 minutes and 7 days, inclusive. */ tokenTtl?: string | null; } /** * An app's SafetyNet configuration object. This configuration controls certain properties of the `AppCheckToken` returned by ExchangeSafetyNetToken, such as its ttl. Note that your registered SHA-256 certificate fingerprints are used to validate tokens issued by SafetyNet; please register them via the Firebase Console or programmatically via the [Firebase Management Service](https://firebase.google.com/docs/projects/api/reference/rest/v11/projects.androidApps.sha/create). */ export interface Schema$GoogleFirebaseAppcheckV1SafetyNetConfig { /** * Required. The relative resource name of the SafetyNet configuration object, in the format: ``` projects/{project_number\}/apps/{app_id\}/safetyNetConfig ``` */ name?: string | null; /** * Specifies the duration for which App Check tokens exchanged from SafetyNet tokens will be valid. If unset, a default value of 1 hour is assumed. Must be between 30 minutes and 7 days, inclusive. */ tokenTtl?: string | null; } /** * The enforcement configuration for a Firebase service supported by App Check. */ export interface Schema$GoogleFirebaseAppcheckV1Service { /** * Required. The App Check enforcement mode for this service. */ enforcementMode?: string | null; /** * Required. The relative resource name of the service configuration object, in the format: ``` projects/{project_number\}/services/{service_id\} ``` Note that the `service_id` element must be a supported service ID. Currently, the following service IDs are supported: * `firebasestorage.googleapis.com` (Cloud Storage for Firebase) * `firebasedatabase.googleapis.com` (Firebase Realtime Database) * `firestore.googleapis.com` (Cloud Firestore) */ name?: string | null; } /** * Request message for the UpdateService method as well as an individual update message for the BatchUpdateServices method. */ export interface Schema$GoogleFirebaseAppcheckV1UpdateServiceRequest { /** * Required. The Service to update. The Service's `name` field is used to identify the Service to be updated, in the format: ``` projects/{project_number\}/services/{service_id\} ``` Note that the `service_id` element must be a supported service ID. Currently, the following service IDs are supported: * `firebasestorage.googleapis.com` (Cloud Storage for Firebase) * `firebasedatabase.googleapis.com` (Firebase Realtime Database) * `firestore.googleapis.com` (Cloud Firestore) */ service?: Schema$GoogleFirebaseAppcheckV1Service; /** * Required. A comma-separated list of names of fields in the Service to update. Example: `enforcement_mode`. */ updateMask?: string | null; } /** * A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); \} */ export interface Schema$GoogleProtobufEmpty {} export class Resource$Jwks { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Returns a public JWK set as specified by [RFC 7517](https://tools.ietf.org/html/rfc7517) that can be used to verify App Check tokens. Exactly one of the public keys in the returned set will successfully validate any App Check token that is currently valid. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.jwks.get({ * // Required. The relative resource name to the public JWK set. Must always be exactly the string `jwks`. * name: 'jwks', * }); * console.log(res.data); * * // Example response * // { * // "keys": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Jwks$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Jwks$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1PublicJwkSet>; get( params: Params$Resource$Jwks$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Jwks$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PublicJwkSet>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PublicJwkSet> ): void; get( params: Params$Resource$Jwks$Get, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PublicJwkSet> ): void; get( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PublicJwkSet> ): void; get( paramsOrCallback?: | Params$Resource$Jwks$Get | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PublicJwkSet> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PublicJwkSet> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PublicJwkSet> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1PublicJwkSet> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Jwks$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Jwks$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1PublicJwkSet>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1PublicJwkSet>( parameters ); } } } export interface Params$Resource$Jwks$Get extends StandardParameters { /** * Required. The relative resource name to the public JWK set. Must always be exactly the string `jwks`. */ name?: string; } export class Resource$Projects { context: APIRequestContext; apps: Resource$Projects$Apps; services: Resource$Projects$Services; constructor(context: APIRequestContext) { this.context = context; this.apps = new Resource$Projects$Apps(this.context); this.services = new Resource$Projects$Services(this.context); } } export class Resource$Projects$Apps { context: APIRequestContext; appAttestConfig: Resource$Projects$Apps$Appattestconfig; debugTokens: Resource$Projects$Apps$Debugtokens; deviceCheckConfig: Resource$Projects$Apps$Devicecheckconfig; playIntegrityConfig: Resource$Projects$Apps$Playintegrityconfig; recaptchaEnterpriseConfig: Resource$Projects$Apps$Recaptchaenterpriseconfig; recaptchaV3Config: Resource$Projects$Apps$Recaptchav3config; safetyNetConfig: Resource$Projects$Apps$Safetynetconfig; constructor(context: APIRequestContext) { this.context = context; this.appAttestConfig = new Resource$Projects$Apps$Appattestconfig( this.context ); this.debugTokens = new Resource$Projects$Apps$Debugtokens(this.context); this.deviceCheckConfig = new Resource$Projects$Apps$Devicecheckconfig( this.context ); this.playIntegrityConfig = new Resource$Projects$Apps$Playintegrityconfig( this.context ); this.recaptchaEnterpriseConfig = new Resource$Projects$Apps$Recaptchaenterpriseconfig(this.context); this.recaptchaV3Config = new Resource$Projects$Apps$Recaptchav3config( this.context ); this.safetyNetConfig = new Resource$Projects$Apps$Safetynetconfig( this.context ); } /** * Accepts an App Attest assertion and an artifact previously obtained from ExchangeAppAttestAttestation and verifies those with Apple. If valid, returns an AppCheckToken. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.exchangeAppAttestAssertion({ * // Required. The relative resource name of the iOS app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. * app: 'projects/my-project/apps/my-app', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "artifact": "my_artifact", * // "assertion": "my_assertion", * // "challenge": "my_challenge" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "token": "my_token", * // "ttl": "my_ttl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ exchangeAppAttestAssertion( params: Params$Resource$Projects$Apps$Exchangeappattestassertion, options: StreamMethodOptions ): GaxiosPromise<Readable>; exchangeAppAttestAssertion( params?: Params$Resource$Projects$Apps$Exchangeappattestassertion, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppCheckToken>; exchangeAppAttestAssertion( params: Params$Resource$Projects$Apps$Exchangeappattestassertion, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; exchangeAppAttestAssertion( params: Params$Resource$Projects$Apps$Exchangeappattestassertion, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeAppAttestAssertion( params: Params$Resource$Projects$Apps$Exchangeappattestassertion, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeAppAttestAssertion( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeAppAttestAssertion( paramsOrCallback?: | Params$Resource$Projects$Apps$Exchangeappattestassertion | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Exchangeappattestassertion; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Exchangeappattestassertion; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+app}:exchangeAppAttestAssertion').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['app'], pathParams: ['app'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppCheckToken>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppCheckToken>( parameters ); } } /** * Accepts an App Attest CBOR attestation and verifies it with Apple using your preconfigured team and bundle IDs. If valid, returns an attestation artifact that can later be exchanged for an AppCheckToken using ExchangeAppAttestAssertion. For convenience and performance, this method's response object will also contain an AppCheckToken (if the verification is successful). * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.exchangeAppAttestAttestation( * { * // Required. The relative resource name of the iOS app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. * app: 'projects/my-project/apps/my-app', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "attestationStatement": "my_attestationStatement", * // "challenge": "my_challenge", * // "keyId": "my_keyId" * // } * }, * } * ); * console.log(res.data); * * // Example response * // { * // "appCheckToken": {}, * // "artifact": "my_artifact" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ exchangeAppAttestAttestation( params: Params$Resource$Projects$Apps$Exchangeappattestattestation, options: StreamMethodOptions ): GaxiosPromise<Readable>; exchangeAppAttestAttestation( params?: Params$Resource$Projects$Apps$Exchangeappattestattestation, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1ExchangeAppAttestAttestationResponse>; exchangeAppAttestAttestation( params: Params$Resource$Projects$Apps$Exchangeappattestattestation, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; exchangeAppAttestAttestation( params: Params$Resource$Projects$Apps$Exchangeappattestattestation, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ExchangeAppAttestAttestationResponse>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ExchangeAppAttestAttestationResponse> ): void; exchangeAppAttestAttestation( params: Params$Resource$Projects$Apps$Exchangeappattestattestation, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ExchangeAppAttestAttestationResponse> ): void; exchangeAppAttestAttestation( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ExchangeAppAttestAttestationResponse> ): void; exchangeAppAttestAttestation( paramsOrCallback?: | Params$Resource$Projects$Apps$Exchangeappattestattestation | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ExchangeAppAttestAttestationResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ExchangeAppAttestAttestationResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ExchangeAppAttestAttestationResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1ExchangeAppAttestAttestationResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Exchangeappattestattestation; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Exchangeappattestattestation; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+app}:exchangeAppAttestAttestation').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['app'], pathParams: ['app'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1ExchangeAppAttestAttestationResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1ExchangeAppAttestAttestationResponse>( parameters ); } } /** * Validates a custom token signed using your project's Admin SDK service account credentials. If valid, returns an AppCheckToken. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.exchangeCustomToken({ * // Required. The relative resource name of the app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. * app: 'projects/my-project/apps/my-app', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "customToken": "my_customToken" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "token": "my_token", * // "ttl": "my_ttl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ exchangeCustomToken( params: Params$Resource$Projects$Apps$Exchangecustomtoken, options: StreamMethodOptions ): GaxiosPromise<Readable>; exchangeCustomToken( params?: Params$Resource$Projects$Apps$Exchangecustomtoken, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppCheckToken>; exchangeCustomToken( params: Params$Resource$Projects$Apps$Exchangecustomtoken, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; exchangeCustomToken( params: Params$Resource$Projects$Apps$Exchangecustomtoken, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeCustomToken( params: Params$Resource$Projects$Apps$Exchangecustomtoken, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeCustomToken( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeCustomToken( paramsOrCallback?: | Params$Resource$Projects$Apps$Exchangecustomtoken | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Exchangecustomtoken; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Exchangecustomtoken; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+app}:exchangeCustomToken').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['app'], pathParams: ['app'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppCheckToken>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppCheckToken>( parameters ); } } /** * Validates a debug token secret that you have previously created using CreateDebugToken. If valid, returns an AppCheckToken. Note that a restrictive quota is enforced on this method to prevent accidental exposure of the app to abuse. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.exchangeDebugToken({ * // Required. The relative resource name of the app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. * app: 'projects/my-project/apps/my-app', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "debugToken": "my_debugToken" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "token": "my_token", * // "ttl": "my_ttl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ exchangeDebugToken( params: Params$Resource$Projects$Apps$Exchangedebugtoken, options: StreamMethodOptions ): GaxiosPromise<Readable>; exchangeDebugToken( params?: Params$Resource$Projects$Apps$Exchangedebugtoken, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppCheckToken>; exchangeDebugToken( params: Params$Resource$Projects$Apps$Exchangedebugtoken, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; exchangeDebugToken( params: Params$Resource$Projects$Apps$Exchangedebugtoken, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeDebugToken( params: Params$Resource$Projects$Apps$Exchangedebugtoken, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeDebugToken( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeDebugToken( paramsOrCallback?: | Params$Resource$Projects$Apps$Exchangedebugtoken | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Exchangedebugtoken; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Exchangedebugtoken; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+app}:exchangeDebugToken').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['app'], pathParams: ['app'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppCheckToken>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppCheckToken>( parameters ); } } /** * Accepts a [`device_token`](https://developer.apple.com/documentation/devicecheck/dcdevice) issued by DeviceCheck, and attempts to validate it with Apple. If valid, returns an AppCheckToken. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.exchangeDeviceCheckToken({ * // Required. The relative resource name of the iOS app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. * app: 'projects/my-project/apps/my-app', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "deviceToken": "my_deviceToken" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "token": "my_token", * // "ttl": "my_ttl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ exchangeDeviceCheckToken( params: Params$Resource$Projects$Apps$Exchangedevicechecktoken, options: StreamMethodOptions ): GaxiosPromise<Readable>; exchangeDeviceCheckToken( params?: Params$Resource$Projects$Apps$Exchangedevicechecktoken, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppCheckToken>; exchangeDeviceCheckToken( params: Params$Resource$Projects$Apps$Exchangedevicechecktoken, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; exchangeDeviceCheckToken( params: Params$Resource$Projects$Apps$Exchangedevicechecktoken, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeDeviceCheckToken( params: Params$Resource$Projects$Apps$Exchangedevicechecktoken, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeDeviceCheckToken( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeDeviceCheckToken( paramsOrCallback?: | Params$Resource$Projects$Apps$Exchangedevicechecktoken | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Exchangedevicechecktoken; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Exchangedevicechecktoken; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+app}:exchangeDeviceCheckToken').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['app'], pathParams: ['app'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppCheckToken>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppCheckToken>( parameters ); } } /** * Validates an [integrity verdict response token from Play Integrity](https://developer.android.com/google/play/integrity/verdict#decrypt-verify). If valid, returns an AppCheckToken. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.exchangePlayIntegrityToken({ * // Required. The relative resource name of the Android app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. * app: 'projects/my-project/apps/my-app', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "playIntegrityToken": "my_playIntegrityToken" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "token": "my_token", * // "ttl": "my_ttl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ exchangePlayIntegrityToken( params: Params$Resource$Projects$Apps$Exchangeplayintegritytoken, options: StreamMethodOptions ): GaxiosPromise<Readable>; exchangePlayIntegrityToken( params?: Params$Resource$Projects$Apps$Exchangeplayintegritytoken, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppCheckToken>; exchangePlayIntegrityToken( params: Params$Resource$Projects$Apps$Exchangeplayintegritytoken, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; exchangePlayIntegrityToken( params: Params$Resource$Projects$Apps$Exchangeplayintegritytoken, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangePlayIntegrityToken( params: Params$Resource$Projects$Apps$Exchangeplayintegritytoken, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangePlayIntegrityToken( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangePlayIntegrityToken( paramsOrCallback?: | Params$Resource$Projects$Apps$Exchangeplayintegritytoken | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Exchangeplayintegritytoken; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Exchangeplayintegritytoken; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+app}:exchangePlayIntegrityToken').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['app'], pathParams: ['app'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppCheckToken>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppCheckToken>( parameters ); } } /** * Validates a [reCAPTCHA Enterprise response token](https://cloud.google.com/recaptcha-enterprise/docs/create-assessment#retrieve_token). If valid, returns an AppCheckToken. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await firebaseappcheck.projects.apps.exchangeRecaptchaEnterpriseToken({ * // Required. The relative resource name of the web app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. * app: 'projects/my-project/apps/my-app', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "recaptchaEnterpriseToken": "my_recaptchaEnterpriseToken" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "token": "my_token", * // "ttl": "my_ttl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ exchangeRecaptchaEnterpriseToken( params: Params$Resource$Projects$Apps$Exchangerecaptchaenterprisetoken, options: StreamMethodOptions ): GaxiosPromise<Readable>; exchangeRecaptchaEnterpriseToken( params?: Params$Resource$Projects$Apps$Exchangerecaptchaenterprisetoken, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppCheckToken>; exchangeRecaptchaEnterpriseToken( params: Params$Resource$Projects$Apps$Exchangerecaptchaenterprisetoken, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; exchangeRecaptchaEnterpriseToken( params: Params$Resource$Projects$Apps$Exchangerecaptchaenterprisetoken, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeRecaptchaEnterpriseToken( params: Params$Resource$Projects$Apps$Exchangerecaptchaenterprisetoken, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeRecaptchaEnterpriseToken( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeRecaptchaEnterpriseToken( paramsOrCallback?: | Params$Resource$Projects$Apps$Exchangerecaptchaenterprisetoken | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Exchangerecaptchaenterprisetoken; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Exchangerecaptchaenterprisetoken; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1/{+app}:exchangeRecaptchaEnterpriseToken' ).replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options ), params, requiredParams: ['app'], pathParams: ['app'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppCheckToken>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppCheckToken>( parameters ); } } /** * Validates a [reCAPTCHA v3 response token](https://developers.google.com/recaptcha/docs/v3). If valid, returns an AppCheckToken. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.exchangeRecaptchaV3Token({ * // Required. The relative resource name of the web app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. * app: 'projects/my-project/apps/my-app', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "recaptchaV3Token": "my_recaptchaV3Token" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "token": "my_token", * // "ttl": "my_ttl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ exchangeRecaptchaV3Token( params: Params$Resource$Projects$Apps$Exchangerecaptchav3token, options: StreamMethodOptions ): GaxiosPromise<Readable>; exchangeRecaptchaV3Token( params?: Params$Resource$Projects$Apps$Exchangerecaptchav3token, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppCheckToken>; exchangeRecaptchaV3Token( params: Params$Resource$Projects$Apps$Exchangerecaptchav3token, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; exchangeRecaptchaV3Token( params: Params$Resource$Projects$Apps$Exchangerecaptchav3token, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeRecaptchaV3Token( params: Params$Resource$Projects$Apps$Exchangerecaptchav3token, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeRecaptchaV3Token( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeRecaptchaV3Token( paramsOrCallback?: | Params$Resource$Projects$Apps$Exchangerecaptchav3token | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Exchangerecaptchav3token; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Exchangerecaptchav3token; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+app}:exchangeRecaptchaV3Token').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['app'], pathParams: ['app'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppCheckToken>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppCheckToken>( parameters ); } } /** * Validates a [SafetyNet token](https://developer.android.com/training/safetynet/attestation#request-attestation-step). If valid, returns an AppCheckToken. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.exchangeSafetyNetToken({ * // Required. The relative resource name of the Android app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. * app: 'projects/my-project/apps/my-app', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "safetyNetToken": "my_safetyNetToken" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "token": "my_token", * // "ttl": "my_ttl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ exchangeSafetyNetToken( params: Params$Resource$Projects$Apps$Exchangesafetynettoken, options: StreamMethodOptions ): GaxiosPromise<Readable>; exchangeSafetyNetToken( params?: Params$Resource$Projects$Apps$Exchangesafetynettoken, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppCheckToken>; exchangeSafetyNetToken( params: Params$Resource$Projects$Apps$Exchangesafetynettoken, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; exchangeSafetyNetToken( params: Params$Resource$Projects$Apps$Exchangesafetynettoken, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeSafetyNetToken( params: Params$Resource$Projects$Apps$Exchangesafetynettoken, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeSafetyNetToken( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> ): void; exchangeSafetyNetToken( paramsOrCallback?: | Params$Resource$Projects$Apps$Exchangesafetynettoken | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppCheckToken> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Exchangesafetynettoken; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Exchangesafetynettoken; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+app}:exchangeSafetyNetToken').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['app'], pathParams: ['app'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppCheckToken>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppCheckToken>( parameters ); } } /** * Generates a challenge that protects the integrity of an immediately following call to ExchangeAppAttestAttestation or ExchangeAppAttestAssertion. A challenge should not be reused for multiple calls. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.generateAppAttestChallenge({ * // Required. The relative resource name of the iOS app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. * app: 'projects/my-project/apps/my-app', * * // Request body metadata * requestBody: { * // request body parameters * // {} * }, * }); * console.log(res.data); * * // Example response * // { * // "challenge": "my_challenge", * // "ttl": "my_ttl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ generateAppAttestChallenge( params: Params$Resource$Projects$Apps$Generateappattestchallenge, options: StreamMethodOptions ): GaxiosPromise<Readable>; generateAppAttestChallenge( params?: Params$Resource$Projects$Apps$Generateappattestchallenge, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1GenerateAppAttestChallengeResponse>; generateAppAttestChallenge( params: Params$Resource$Projects$Apps$Generateappattestchallenge, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; generateAppAttestChallenge( params: Params$Resource$Projects$Apps$Generateappattestchallenge, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1GenerateAppAttestChallengeResponse>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1GenerateAppAttestChallengeResponse> ): void; generateAppAttestChallenge( params: Params$Resource$Projects$Apps$Generateappattestchallenge, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1GenerateAppAttestChallengeResponse> ): void; generateAppAttestChallenge( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1GenerateAppAttestChallengeResponse> ): void; generateAppAttestChallenge( paramsOrCallback?: | Params$Resource$Projects$Apps$Generateappattestchallenge | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1GenerateAppAttestChallengeResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1GenerateAppAttestChallengeResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1GenerateAppAttestChallengeResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1GenerateAppAttestChallengeResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Generateappattestchallenge; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Generateappattestchallenge; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+app}:generateAppAttestChallenge').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['app'], pathParams: ['app'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1GenerateAppAttestChallengeResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1GenerateAppAttestChallengeResponse>( parameters ); } } /** * Generates a challenge that protects the integrity of an immediately following integrity verdict request to the Play Integrity API. The next call to ExchangePlayIntegrityToken using the resulting integrity token will verify the presence and validity of the challenge. A challenge should not be reused for multiple calls. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await firebaseappcheck.projects.apps.generatePlayIntegrityChallenge({ * // Required. The relative resource name of the app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. * app: 'projects/my-project/apps/my-app', * * // Request body metadata * requestBody: { * // request body parameters * // {} * }, * }); * console.log(res.data); * * // Example response * // { * // "challenge": "my_challenge", * // "ttl": "my_ttl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ generatePlayIntegrityChallenge( params: Params$Resource$Projects$Apps$Generateplayintegritychallenge, options: StreamMethodOptions ): GaxiosPromise<Readable>; generatePlayIntegrityChallenge( params?: Params$Resource$Projects$Apps$Generateplayintegritychallenge, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1GeneratePlayIntegrityChallengeResponse>; generatePlayIntegrityChallenge( params: Params$Resource$Projects$Apps$Generateplayintegritychallenge, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; generatePlayIntegrityChallenge( params: Params$Resource$Projects$Apps$Generateplayintegritychallenge, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1GeneratePlayIntegrityChallengeResponse>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1GeneratePlayIntegrityChallengeResponse> ): void; generatePlayIntegrityChallenge( params: Params$Resource$Projects$Apps$Generateplayintegritychallenge, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1GeneratePlayIntegrityChallengeResponse> ): void; generatePlayIntegrityChallenge( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1GeneratePlayIntegrityChallengeResponse> ): void; generatePlayIntegrityChallenge( paramsOrCallback?: | Params$Resource$Projects$Apps$Generateplayintegritychallenge | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1GeneratePlayIntegrityChallengeResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1GeneratePlayIntegrityChallengeResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1GeneratePlayIntegrityChallengeResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1GeneratePlayIntegrityChallengeResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Generateplayintegritychallenge; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Generateplayintegritychallenge; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1/{+app}:generatePlayIntegrityChallenge' ).replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options ), params, requiredParams: ['app'], pathParams: ['app'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1GeneratePlayIntegrityChallengeResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1GeneratePlayIntegrityChallengeResponse>( parameters ); } } } export interface Params$Resource$Projects$Apps$Exchangeappattestassertion extends StandardParameters { /** * Required. The relative resource name of the iOS app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. */ app?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1ExchangeAppAttestAssertionRequest; } export interface Params$Resource$Projects$Apps$Exchangeappattestattestation extends StandardParameters { /** * Required. The relative resource name of the iOS app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. */ app?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1ExchangeAppAttestAttestationRequest; } export interface Params$Resource$Projects$Apps$Exchangecustomtoken extends StandardParameters { /** * Required. The relative resource name of the app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. */ app?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1ExchangeCustomTokenRequest; } export interface Params$Resource$Projects$Apps$Exchangedebugtoken extends StandardParameters { /** * Required. The relative resource name of the app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. */ app?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1ExchangeDebugTokenRequest; } export interface Params$Resource$Projects$Apps$Exchangedevicechecktoken extends StandardParameters { /** * Required. The relative resource name of the iOS app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. */ app?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1ExchangeDeviceCheckTokenRequest; } export interface Params$Resource$Projects$Apps$Exchangeplayintegritytoken extends StandardParameters { /** * Required. The relative resource name of the Android app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. */ app?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1ExchangePlayIntegrityTokenRequest; } export interface Params$Resource$Projects$Apps$Exchangerecaptchaenterprisetoken extends StandardParameters { /** * Required. The relative resource name of the web app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. */ app?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1ExchangeRecaptchaEnterpriseTokenRequest; } export interface Params$Resource$Projects$Apps$Exchangerecaptchav3token extends StandardParameters { /** * Required. The relative resource name of the web app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. */ app?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1ExchangeRecaptchaV3TokenRequest; } export interface Params$Resource$Projects$Apps$Exchangesafetynettoken extends StandardParameters { /** * Required. The relative resource name of the Android app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. */ app?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1ExchangeSafetyNetTokenRequest; } export interface Params$Resource$Projects$Apps$Generateappattestchallenge extends StandardParameters { /** * Required. The relative resource name of the iOS app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. */ app?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1GenerateAppAttestChallengeRequest; } export interface Params$Resource$Projects$Apps$Generateplayintegritychallenge extends StandardParameters { /** * Required. The relative resource name of the app, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` If necessary, the `project_number` element can be replaced with the project ID of the Firebase project. Learn more about using project identifiers in Google's [AIP 2510](https://google.aip.dev/cloud/2510) standard. */ app?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1GeneratePlayIntegrityChallengeRequest; } export class Resource$Projects$Apps$Appattestconfig { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Atomically gets the AppAttestConfigs for the specified list of apps. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.appAttestConfig.batchGet({ * // Required. The relative resource names of the AppAttestConfigs to retrieve, in the format ``` projects/{project_number\}/apps/{app_id\}/appAttestConfig ``` A maximum of 100 objects can be retrieved in a batch. * names: 'placeholder-value', * // Required. The parent project name shared by all AppAttestConfigs being retrieved, in the format ``` projects/{project_number\} ``` The parent collection in the `name` field of any resource being retrieved must match this field, or the entire batch fails. * parent: 'projects/my-project', * }); * console.log(res.data); * * // Example response * // { * // "configs": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ batchGet( params: Params$Resource$Projects$Apps$Appattestconfig$Batchget, options: StreamMethodOptions ): GaxiosPromise<Readable>; batchGet( params?: Params$Resource$Projects$Apps$Appattestconfig$Batchget, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1BatchGetAppAttestConfigsResponse>; batchGet( params: Params$Resource$Projects$Apps$Appattestconfig$Batchget, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; batchGet( params: Params$Resource$Projects$Apps$Appattestconfig$Batchget, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetAppAttestConfigsResponse>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetAppAttestConfigsResponse> ): void; batchGet( params: Params$Resource$Projects$Apps$Appattestconfig$Batchget, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetAppAttestConfigsResponse> ): void; batchGet( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetAppAttestConfigsResponse> ): void; batchGet( paramsOrCallback?: | Params$Resource$Projects$Apps$Appattestconfig$Batchget | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetAppAttestConfigsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetAppAttestConfigsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetAppAttestConfigsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1BatchGetAppAttestConfigsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Appattestconfig$Batchget; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Appattestconfig$Batchget; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1/{+parent}/apps/-/appAttestConfig:batchGet' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1BatchGetAppAttestConfigsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1BatchGetAppAttestConfigsResponse>( parameters ); } } /** * Gets the AppAttestConfig for the specified app. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.appAttestConfig.get({ * // Required. The relative resource name of the AppAttestConfig, in the format: ``` projects/{project_number\}/apps/{app_id\}/appAttestConfig ``` * name: 'projects/my-project/apps/my-app/appAttestConfig', * }); * console.log(res.data); * * // Example response * // { * // "name": "my_name", * // "tokenTtl": "my_tokenTtl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Apps$Appattestconfig$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Apps$Appattestconfig$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppAttestConfig>; get( params: Params$Resource$Projects$Apps$Appattestconfig$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Apps$Appattestconfig$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppAttestConfig>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppAttestConfig> ): void; get( params: Params$Resource$Projects$Apps$Appattestconfig$Get, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppAttestConfig> ): void; get( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppAttestConfig> ): void; get( paramsOrCallback?: | Params$Resource$Projects$Apps$Appattestconfig$Get | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppAttestConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppAttestConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppAttestConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppAttestConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Appattestconfig$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Appattestconfig$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppAttestConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppAttestConfig>( parameters ); } } /** * Updates the AppAttestConfig for the specified app. While this configuration is incomplete or invalid, the app will be unable to exchange AppAttest tokens for App Check tokens. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.appAttestConfig.patch({ * // Required. The relative resource name of the App Attest configuration object, in the format: ``` projects/{project_number\}/apps/{app_id\}/appAttestConfig ``` * name: 'projects/my-project/apps/my-app/appAttestConfig', * // Required. A comma-separated list of names of fields in the AppAttestConfig Gets to update. Example: `token_ttl`. * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "name": "my_name", * // "tokenTtl": "my_tokenTtl" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "name": "my_name", * // "tokenTtl": "my_tokenTtl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Projects$Apps$Appattestconfig$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Projects$Apps$Appattestconfig$Patch, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppAttestConfig>; patch( params: Params$Resource$Projects$Apps$Appattestconfig$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Projects$Apps$Appattestconfig$Patch, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppAttestConfig>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppAttestConfig> ): void; patch( params: Params$Resource$Projects$Apps$Appattestconfig$Patch, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppAttestConfig> ): void; patch( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppAttestConfig> ): void; patch( paramsOrCallback?: | Params$Resource$Projects$Apps$Appattestconfig$Patch | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppAttestConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppAttestConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1AppAttestConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1AppAttestConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Appattestconfig$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Appattestconfig$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppAttestConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1AppAttestConfig>( parameters ); } } } export interface Params$Resource$Projects$Apps$Appattestconfig$Batchget extends StandardParameters { /** * Required. The relative resource names of the AppAttestConfigs to retrieve, in the format ``` projects/{project_number\}/apps/{app_id\}/appAttestConfig ``` A maximum of 100 objects can be retrieved in a batch. */ names?: string[]; /** * Required. The parent project name shared by all AppAttestConfigs being retrieved, in the format ``` projects/{project_number\} ``` The parent collection in the `name` field of any resource being retrieved must match this field, or the entire batch fails. */ parent?: string; } export interface Params$Resource$Projects$Apps$Appattestconfig$Get extends StandardParameters { /** * Required. The relative resource name of the AppAttestConfig, in the format: ``` projects/{project_number\}/apps/{app_id\}/appAttestConfig ``` */ name?: string; } export interface Params$Resource$Projects$Apps$Appattestconfig$Patch extends StandardParameters { /** * Required. The relative resource name of the App Attest configuration object, in the format: ``` projects/{project_number\}/apps/{app_id\}/appAttestConfig ``` */ name?: string; /** * Required. A comma-separated list of names of fields in the AppAttestConfig Gets to update. Example: `token_ttl`. */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1AppAttestConfig; } export class Resource$Projects$Apps$Debugtokens { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Creates a new DebugToken for the specified app. For security reasons, after the creation operation completes, the `token` field cannot be updated or retrieved, but you can revoke the debug token using DeleteDebugToken. Each app can have a maximum of 20 debug tokens. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.debugTokens.create({ * // Required. The relative resource name of the parent app in which the specified DebugToken will be created, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` * parent: 'projects/my-project/apps/my-app', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "displayName": "my_displayName", * // "name": "my_name", * // "token": "my_token" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "displayName": "my_displayName", * // "name": "my_name", * // "token": "my_token" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ create( params: Params$Resource$Projects$Apps$Debugtokens$Create, options: StreamMethodOptions ): GaxiosPromise<Readable>; create( params?: Params$Resource$Projects$Apps$Debugtokens$Create, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1DebugToken>; create( params: Params$Resource$Projects$Apps$Debugtokens$Create, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; create( params: Params$Resource$Projects$Apps$Debugtokens$Create, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken> ): void; create( params: Params$Resource$Projects$Apps$Debugtokens$Create, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken> ): void; create( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken> ): void; create( paramsOrCallback?: | Params$Resource$Projects$Apps$Debugtokens$Create | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1DebugToken> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Debugtokens$Create; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Debugtokens$Create; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/debugTokens').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1DebugToken>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1DebugToken>( parameters ); } } /** * Deletes the specified DebugToken. A deleted debug token cannot be used to exchange for an App Check token. Use this method when you suspect the secret `token` has been compromised or when you no longer need the debug token. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.debugTokens.delete({ * // Required. The relative resource name of the DebugToken to delete, in the format: ``` projects/{project_number\}/apps/{app_id\}/debugTokens/{debug_token_id\} ``` * name: 'projects/my-project/apps/my-app/debugTokens/my-debugToken', * }); * console.log(res.data); * * // Example response * // {} * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ delete( params: Params$Resource$Projects$Apps$Debugtokens$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Projects$Apps$Debugtokens$Delete, options?: MethodOptions ): GaxiosPromise<Schema$GoogleProtobufEmpty>; delete( params: Params$Resource$Projects$Apps$Debugtokens$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Projects$Apps$Debugtokens$Delete, options: MethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty>, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; delete( params: Params$Resource$Projects$Apps$Debugtokens$Delete, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; delete(callback: BodyResponseCallback<Schema$GoogleProtobufEmpty>): void; delete( paramsOrCallback?: | Params$Resource$Projects$Apps$Debugtokens$Delete | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleProtobufEmpty> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Debugtokens$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Debugtokens$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleProtobufEmpty>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleProtobufEmpty>(parameters); } } /** * Gets the specified DebugToken. For security reasons, the `token` field is never populated in the response. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.debugTokens.get({ * // Required. The relative resource name of the debug token, in the format: ``` projects/{project_number\}/apps/{app_id\}/debugTokens/{debug_token_id\} ``` * name: 'projects/my-project/apps/my-app/debugTokens/my-debugToken', * }); * console.log(res.data); * * // Example response * // { * // "displayName": "my_displayName", * // "name": "my_name", * // "token": "my_token" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Apps$Debugtokens$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Apps$Debugtokens$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1DebugToken>; get( params: Params$Resource$Projects$Apps$Debugtokens$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Apps$Debugtokens$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken> ): void; get( params: Params$Resource$Projects$Apps$Debugtokens$Get, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken> ): void; get( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken> ): void; get( paramsOrCallback?: | Params$Resource$Projects$Apps$Debugtokens$Get | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1DebugToken> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Debugtokens$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Debugtokens$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1DebugToken>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1DebugToken>( parameters ); } } /** * Lists all DebugTokens for the specified app. For security reasons, the `token` field is never populated in the response. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.debugTokens.list({ * // The maximum number of DebugTokens to return in the response. Note that an app can have at most 20 debug tokens. The server may return fewer than this at its own discretion. If no value is specified (or too large a value is specified), the server will impose its own limit. * pageSize: 'placeholder-value', * // Token returned from a previous call to ListDebugTokens indicating where in the set of DebugTokens to resume listing. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to ListDebugTokens must match the call that provided the page token; if they do not match, the result is undefined. * pageToken: 'placeholder-value', * // Required. The relative resource name of the parent app for which to list each associated DebugToken, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` * parent: 'projects/my-project/apps/my-app', * }); * console.log(res.data); * * // Example response * // { * // "debugTokens": [], * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Projects$Apps$Debugtokens$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Projects$Apps$Debugtokens$List, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1ListDebugTokensResponse>; list( params: Params$Resource$Projects$Apps$Debugtokens$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Projects$Apps$Debugtokens$List, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ListDebugTokensResponse>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ListDebugTokensResponse> ): void; list( params: Params$Resource$Projects$Apps$Debugtokens$List, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ListDebugTokensResponse> ): void; list( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ListDebugTokensResponse> ): void; list( paramsOrCallback?: | Params$Resource$Projects$Apps$Debugtokens$List | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ListDebugTokensResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ListDebugTokensResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ListDebugTokensResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1ListDebugTokensResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Debugtokens$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Debugtokens$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/debugTokens').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1ListDebugTokensResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1ListDebugTokensResponse>( parameters ); } } /** * Updates the specified DebugToken. For security reasons, the `token` field cannot be updated, nor will it be populated in the response, but you can revoke the debug token using DeleteDebugToken. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.debugTokens.patch({ * // Required. The relative resource name of the debug token, in the format: ``` projects/{project_number\}/apps/{app_id\}/debugTokens/{debug_token_id\} ``` * name: 'projects/my-project/apps/my-app/debugTokens/my-debugToken', * // Required. A comma-separated list of names of fields in the DebugToken to update. Example: `display_name`. * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "displayName": "my_displayName", * // "name": "my_name", * // "token": "my_token" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "displayName": "my_displayName", * // "name": "my_name", * // "token": "my_token" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Projects$Apps$Debugtokens$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Projects$Apps$Debugtokens$Patch, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1DebugToken>; patch( params: Params$Resource$Projects$Apps$Debugtokens$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Projects$Apps$Debugtokens$Patch, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken> ): void; patch( params: Params$Resource$Projects$Apps$Debugtokens$Patch, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken> ): void; patch( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken> ): void; patch( paramsOrCallback?: | Params$Resource$Projects$Apps$Debugtokens$Patch | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DebugToken> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1DebugToken> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Debugtokens$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Debugtokens$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1DebugToken>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1DebugToken>( parameters ); } } } export interface Params$Resource$Projects$Apps$Debugtokens$Create extends StandardParameters { /** * Required. The relative resource name of the parent app in which the specified DebugToken will be created, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` */ parent?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1DebugToken; } export interface Params$Resource$Projects$Apps$Debugtokens$Delete extends StandardParameters { /** * Required. The relative resource name of the DebugToken to delete, in the format: ``` projects/{project_number\}/apps/{app_id\}/debugTokens/{debug_token_id\} ``` */ name?: string; } export interface Params$Resource$Projects$Apps$Debugtokens$Get extends StandardParameters { /** * Required. The relative resource name of the debug token, in the format: ``` projects/{project_number\}/apps/{app_id\}/debugTokens/{debug_token_id\} ``` */ name?: string; } export interface Params$Resource$Projects$Apps$Debugtokens$List extends StandardParameters { /** * The maximum number of DebugTokens to return in the response. Note that an app can have at most 20 debug tokens. The server may return fewer than this at its own discretion. If no value is specified (or too large a value is specified), the server will impose its own limit. */ pageSize?: number; /** * Token returned from a previous call to ListDebugTokens indicating where in the set of DebugTokens to resume listing. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to ListDebugTokens must match the call that provided the page token; if they do not match, the result is undefined. */ pageToken?: string; /** * Required. The relative resource name of the parent app for which to list each associated DebugToken, in the format: ``` projects/{project_number\}/apps/{app_id\} ``` */ parent?: string; } export interface Params$Resource$Projects$Apps$Debugtokens$Patch extends StandardParameters { /** * Required. The relative resource name of the debug token, in the format: ``` projects/{project_number\}/apps/{app_id\}/debugTokens/{debug_token_id\} ``` */ name?: string; /** * Required. A comma-separated list of names of fields in the DebugToken to update. Example: `display_name`. */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1DebugToken; } export class Resource$Projects$Apps$Devicecheckconfig { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Atomically gets the DeviceCheckConfigs for the specified list of apps. For security reasons, the `private_key` field is never populated in the response. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.deviceCheckConfig.batchGet({ * // Required. The relative resource names of the DeviceCheckConfigs to retrieve, in the format ``` projects/{project_number\}/apps/{app_id\}/deviceCheckConfig ``` A maximum of 100 objects can be retrieved in a batch. * names: 'placeholder-value', * // Required. The parent project name shared by all DeviceCheckConfigs being retrieved, in the format ``` projects/{project_number\} ``` The parent collection in the `name` field of any resource being retrieved must match this field, or the entire batch fails. * parent: 'projects/my-project', * }); * console.log(res.data); * * // Example response * // { * // "configs": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ batchGet( params: Params$Resource$Projects$Apps$Devicecheckconfig$Batchget, options: StreamMethodOptions ): GaxiosPromise<Readable>; batchGet( params?: Params$Resource$Projects$Apps$Devicecheckconfig$Batchget, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1BatchGetDeviceCheckConfigsResponse>; batchGet( params: Params$Resource$Projects$Apps$Devicecheckconfig$Batchget, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; batchGet( params: Params$Resource$Projects$Apps$Devicecheckconfig$Batchget, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetDeviceCheckConfigsResponse>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetDeviceCheckConfigsResponse> ): void; batchGet( params: Params$Resource$Projects$Apps$Devicecheckconfig$Batchget, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetDeviceCheckConfigsResponse> ): void; batchGet( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetDeviceCheckConfigsResponse> ): void; batchGet( paramsOrCallback?: | Params$Resource$Projects$Apps$Devicecheckconfig$Batchget | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetDeviceCheckConfigsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetDeviceCheckConfigsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetDeviceCheckConfigsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1BatchGetDeviceCheckConfigsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Devicecheckconfig$Batchget; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Devicecheckconfig$Batchget; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1/{+parent}/apps/-/deviceCheckConfig:batchGet' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1BatchGetDeviceCheckConfigsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1BatchGetDeviceCheckConfigsResponse>( parameters ); } } /** * Gets the DeviceCheckConfig for the specified app. For security reasons, the `private_key` field is never populated in the response. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.deviceCheckConfig.get({ * // Required. The relative resource name of the DeviceCheckConfig, in the format: ``` projects/{project_number\}/apps/{app_id\}/deviceCheckConfig ``` * name: 'projects/my-project/apps/my-app/deviceCheckConfig', * }); * console.log(res.data); * * // Example response * // { * // "keyId": "my_keyId", * // "name": "my_name", * // "privateKey": "my_privateKey", * // "privateKeySet": false, * // "tokenTtl": "my_tokenTtl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Apps$Devicecheckconfig$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Apps$Devicecheckconfig$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig>; get( params: Params$Resource$Projects$Apps$Devicecheckconfig$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Apps$Devicecheckconfig$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig> ): void; get( params: Params$Resource$Projects$Apps$Devicecheckconfig$Get, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig> ): void; get( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig> ): void; get( paramsOrCallback?: | Params$Resource$Projects$Apps$Devicecheckconfig$Get | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Devicecheckconfig$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Devicecheckconfig$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig>( parameters ); } } /** * Updates the DeviceCheckConfig for the specified app. While this configuration is incomplete or invalid, the app will be unable to exchange DeviceCheck tokens for App Check tokens. For security reasons, the `private_key` field is never populated in the response. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.deviceCheckConfig.patch({ * // Required. The relative resource name of the DeviceCheck configuration object, in the format: ``` projects/{project_number\}/apps/{app_id\}/deviceCheckConfig ``` * name: 'projects/my-project/apps/my-app/deviceCheckConfig', * // Required. A comma-separated list of names of fields in the DeviceCheckConfig Gets to update. Example: `key_id,private_key`. * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "keyId": "my_keyId", * // "name": "my_name", * // "privateKey": "my_privateKey", * // "privateKeySet": false, * // "tokenTtl": "my_tokenTtl" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "keyId": "my_keyId", * // "name": "my_name", * // "privateKey": "my_privateKey", * // "privateKeySet": false, * // "tokenTtl": "my_tokenTtl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Projects$Apps$Devicecheckconfig$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Projects$Apps$Devicecheckconfig$Patch, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig>; patch( params: Params$Resource$Projects$Apps$Devicecheckconfig$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Projects$Apps$Devicecheckconfig$Patch, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig> ): void; patch( params: Params$Resource$Projects$Apps$Devicecheckconfig$Patch, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig> ): void; patch( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig> ): void; patch( paramsOrCallback?: | Params$Resource$Projects$Apps$Devicecheckconfig$Patch | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Devicecheckconfig$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Devicecheckconfig$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig>( parameters ); } } } export interface Params$Resource$Projects$Apps$Devicecheckconfig$Batchget extends StandardParameters { /** * Required. The relative resource names of the DeviceCheckConfigs to retrieve, in the format ``` projects/{project_number\}/apps/{app_id\}/deviceCheckConfig ``` A maximum of 100 objects can be retrieved in a batch. */ names?: string[]; /** * Required. The parent project name shared by all DeviceCheckConfigs being retrieved, in the format ``` projects/{project_number\} ``` The parent collection in the `name` field of any resource being retrieved must match this field, or the entire batch fails. */ parent?: string; } export interface Params$Resource$Projects$Apps$Devicecheckconfig$Get extends StandardParameters { /** * Required. The relative resource name of the DeviceCheckConfig, in the format: ``` projects/{project_number\}/apps/{app_id\}/deviceCheckConfig ``` */ name?: string; } export interface Params$Resource$Projects$Apps$Devicecheckconfig$Patch extends StandardParameters { /** * Required. The relative resource name of the DeviceCheck configuration object, in the format: ``` projects/{project_number\}/apps/{app_id\}/deviceCheckConfig ``` */ name?: string; /** * Required. A comma-separated list of names of fields in the DeviceCheckConfig Gets to update. Example: `key_id,private_key`. */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1DeviceCheckConfig; } export class Resource$Projects$Apps$Playintegrityconfig { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Atomically gets the PlayIntegrityConfigs for the specified list of apps. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.playIntegrityConfig.batchGet( * { * // Required. The relative resource names of the PlayIntegrityConfigs to retrieve, in the format ``` projects/{project_number\}/apps/{app_id\}/playIntegrityConfig ``` A maximum of 100 objects can be retrieved in a batch. * names: 'placeholder-value', * // Required. The parent project name shared by all PlayIntegrityConfigs being retrieved, in the format ``` projects/{project_number\} ``` The parent collection in the `name` field of any resource being retrieved must match this field, or the entire batch fails. * parent: 'projects/my-project', * } * ); * console.log(res.data); * * // Example response * // { * // "configs": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ batchGet( params: Params$Resource$Projects$Apps$Playintegrityconfig$Batchget, options: StreamMethodOptions ): GaxiosPromise<Readable>; batchGet( params?: Params$Resource$Projects$Apps$Playintegrityconfig$Batchget, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1BatchGetPlayIntegrityConfigsResponse>; batchGet( params: Params$Resource$Projects$Apps$Playintegrityconfig$Batchget, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; batchGet( params: Params$Resource$Projects$Apps$Playintegrityconfig$Batchget, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetPlayIntegrityConfigsResponse>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetPlayIntegrityConfigsResponse> ): void; batchGet( params: Params$Resource$Projects$Apps$Playintegrityconfig$Batchget, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetPlayIntegrityConfigsResponse> ): void; batchGet( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetPlayIntegrityConfigsResponse> ): void; batchGet( paramsOrCallback?: | Params$Resource$Projects$Apps$Playintegrityconfig$Batchget | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetPlayIntegrityConfigsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetPlayIntegrityConfigsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetPlayIntegrityConfigsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1BatchGetPlayIntegrityConfigsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Playintegrityconfig$Batchget; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Playintegrityconfig$Batchget; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1/{+parent}/apps/-/playIntegrityConfig:batchGet' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1BatchGetPlayIntegrityConfigsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1BatchGetPlayIntegrityConfigsResponse>( parameters ); } } /** * Gets the PlayIntegrityConfig for the specified app. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.playIntegrityConfig.get({ * // Required. The relative resource name of the PlayIntegrityConfig, in the format: ``` projects/{project_number\}/apps/{app_id\}/playIntegrityConfig ``` * name: 'projects/my-project/apps/my-app/playIntegrityConfig', * }); * console.log(res.data); * * // Example response * // { * // "name": "my_name", * // "tokenTtl": "my_tokenTtl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Apps$Playintegrityconfig$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Apps$Playintegrityconfig$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig>; get( params: Params$Resource$Projects$Apps$Playintegrityconfig$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Apps$Playintegrityconfig$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig> ): void; get( params: Params$Resource$Projects$Apps$Playintegrityconfig$Get, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig> ): void; get( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig> ): void; get( paramsOrCallback?: | Params$Resource$Projects$Apps$Playintegrityconfig$Get | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Playintegrityconfig$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Playintegrityconfig$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig>( parameters ); } } /** * Updates the PlayIntegrityConfig for the specified app. While this configuration is incomplete or invalid, the app will be unable to exchange Play Integrity tokens for App Check tokens. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.playIntegrityConfig.patch({ * // Required. The relative resource name of the Play Integrity configuration object, in the format: ``` projects/{project_number\}/apps/{app_id\}/playIntegrityConfig ``` * name: 'projects/my-project/apps/my-app/playIntegrityConfig', * // Required. A comma-separated list of names of fields in the PlayIntegrityConfig Gets to update. Example: `token_ttl`. * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "name": "my_name", * // "tokenTtl": "my_tokenTtl" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "name": "my_name", * // "tokenTtl": "my_tokenTtl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Projects$Apps$Playintegrityconfig$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Projects$Apps$Playintegrityconfig$Patch, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig>; patch( params: Params$Resource$Projects$Apps$Playintegrityconfig$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Projects$Apps$Playintegrityconfig$Patch, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig> ): void; patch( params: Params$Resource$Projects$Apps$Playintegrityconfig$Patch, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig> ): void; patch( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig> ): void; patch( paramsOrCallback?: | Params$Resource$Projects$Apps$Playintegrityconfig$Patch | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Playintegrityconfig$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Playintegrityconfig$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig>( parameters ); } } } export interface Params$Resource$Projects$Apps$Playintegrityconfig$Batchget extends StandardParameters { /** * Required. The relative resource names of the PlayIntegrityConfigs to retrieve, in the format ``` projects/{project_number\}/apps/{app_id\}/playIntegrityConfig ``` A maximum of 100 objects can be retrieved in a batch. */ names?: string[]; /** * Required. The parent project name shared by all PlayIntegrityConfigs being retrieved, in the format ``` projects/{project_number\} ``` The parent collection in the `name` field of any resource being retrieved must match this field, or the entire batch fails. */ parent?: string; } export interface Params$Resource$Projects$Apps$Playintegrityconfig$Get extends StandardParameters { /** * Required. The relative resource name of the PlayIntegrityConfig, in the format: ``` projects/{project_number\}/apps/{app_id\}/playIntegrityConfig ``` */ name?: string; } export interface Params$Resource$Projects$Apps$Playintegrityconfig$Patch extends StandardParameters { /** * Required. The relative resource name of the Play Integrity configuration object, in the format: ``` projects/{project_number\}/apps/{app_id\}/playIntegrityConfig ``` */ name?: string; /** * Required. A comma-separated list of names of fields in the PlayIntegrityConfig Gets to update. Example: `token_ttl`. */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1PlayIntegrityConfig; } export class Resource$Projects$Apps$Recaptchaenterpriseconfig { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Atomically gets the RecaptchaEnterpriseConfigs for the specified list of apps. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await firebaseappcheck.projects.apps.recaptchaEnterpriseConfig.batchGet({ * // Required. The relative resource names of the RecaptchaEnterpriseConfigs to retrieve, in the format: ``` projects/{project_number\}/apps/{app_id\}/recaptchaEnterpriseConfig ``` A maximum of 100 objects can be retrieved in a batch. * names: 'placeholder-value', * // Required. The parent project name shared by all RecaptchaEnterpriseConfigs being retrieved, in the format ``` projects/{project_number\} ``` The parent collection in the `name` field of any resource being retrieved must match this field, or the entire batch fails. * parent: 'projects/my-project', * }); * console.log(res.data); * * // Example response * // { * // "configs": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ batchGet( params: Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Batchget, options: StreamMethodOptions ): GaxiosPromise<Readable>; batchGet( params?: Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Batchget, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaEnterpriseConfigsResponse>; batchGet( params: Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Batchget, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; batchGet( params: Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Batchget, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaEnterpriseConfigsResponse>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaEnterpriseConfigsResponse> ): void; batchGet( params: Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Batchget, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaEnterpriseConfigsResponse> ): void; batchGet( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaEnterpriseConfigsResponse> ): void; batchGet( paramsOrCallback?: | Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Batchget | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaEnterpriseConfigsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaEnterpriseConfigsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaEnterpriseConfigsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaEnterpriseConfigsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Batchget; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Batchget; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1/{+parent}/apps/-/recaptchaEnterpriseConfig:batchGet' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaEnterpriseConfigsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaEnterpriseConfigsResponse>( parameters ); } } /** * Gets the RecaptchaEnterpriseConfig for the specified app. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await firebaseappcheck.projects.apps.recaptchaEnterpriseConfig.get({ * // Required. The relative resource name of the RecaptchaEnterpriseConfig, in the format: ``` projects/{project_number\}/apps/{app_id\}/recaptchaEnterpriseConfig ``` * name: 'projects/my-project/apps/my-app/recaptchaEnterpriseConfig', * }); * console.log(res.data); * * // Example response * // { * // "name": "my_name", * // "siteKey": "my_siteKey", * // "tokenTtl": "my_tokenTtl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig>; get( params: Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig> ): void; get( params: Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Get, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig> ): void; get( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig> ): void; get( paramsOrCallback?: | Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Get | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig>( parameters ); } } /** * Updates the RecaptchaEnterpriseConfig for the specified app. While this configuration is incomplete or invalid, the app will be unable to exchange reCAPTCHA Enterprise tokens for App Check tokens. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = * await firebaseappcheck.projects.apps.recaptchaEnterpriseConfig.patch({ * // Required. The relative resource name of the reCAPTCHA Enterprise configuration object, in the format: ``` projects/{project_number\}/apps/{app_id\}/recaptchaEnterpriseConfig ``` * name: 'projects/my-project/apps/my-app/recaptchaEnterpriseConfig', * // Required. A comma-separated list of names of fields in the RecaptchaEnterpriseConfig to update. Example: `site_key`. * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "name": "my_name", * // "siteKey": "my_siteKey", * // "tokenTtl": "my_tokenTtl" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "name": "my_name", * // "siteKey": "my_siteKey", * // "tokenTtl": "my_tokenTtl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Patch, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig>; patch( params: Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Patch, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig> ): void; patch( params: Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Patch, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig> ): void; patch( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig> ): void; patch( paramsOrCallback?: | Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Patch | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig>( parameters ); } } } export interface Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Batchget extends StandardParameters { /** * Required. The relative resource names of the RecaptchaEnterpriseConfigs to retrieve, in the format: ``` projects/{project_number\}/apps/{app_id\}/recaptchaEnterpriseConfig ``` A maximum of 100 objects can be retrieved in a batch. */ names?: string[]; /** * Required. The parent project name shared by all RecaptchaEnterpriseConfigs being retrieved, in the format ``` projects/{project_number\} ``` The parent collection in the `name` field of any resource being retrieved must match this field, or the entire batch fails. */ parent?: string; } export interface Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Get extends StandardParameters { /** * Required. The relative resource name of the RecaptchaEnterpriseConfig, in the format: ``` projects/{project_number\}/apps/{app_id\}/recaptchaEnterpriseConfig ``` */ name?: string; } export interface Params$Resource$Projects$Apps$Recaptchaenterpriseconfig$Patch extends StandardParameters { /** * Required. The relative resource name of the reCAPTCHA Enterprise configuration object, in the format: ``` projects/{project_number\}/apps/{app_id\}/recaptchaEnterpriseConfig ``` */ name?: string; /** * Required. A comma-separated list of names of fields in the RecaptchaEnterpriseConfig to update. Example: `site_key`. */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1RecaptchaEnterpriseConfig; } export class Resource$Projects$Apps$Recaptchav3config { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Atomically gets the RecaptchaV3Configs for the specified list of apps. For security reasons, the `site_secret` field is never populated in the response. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.recaptchaV3Config.batchGet({ * // Required. The relative resource names of the RecaptchaV3Configs to retrieve, in the format: ``` projects/{project_number\}/apps/{app_id\}/recaptchaV3Config ``` A maximum of 100 objects can be retrieved in a batch. * names: 'placeholder-value', * // Required. The parent project name shared by all RecaptchaV3Configs being retrieved, in the format ``` projects/{project_number\} ``` The parent collection in the `name` field of any resource being retrieved must match this field, or the entire batch fails. * parent: 'projects/my-project', * }); * console.log(res.data); * * // Example response * // { * // "configs": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ batchGet( params: Params$Resource$Projects$Apps$Recaptchav3config$Batchget, options: StreamMethodOptions ): GaxiosPromise<Readable>; batchGet( params?: Params$Resource$Projects$Apps$Recaptchav3config$Batchget, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaV3ConfigsResponse>; batchGet( params: Params$Resource$Projects$Apps$Recaptchav3config$Batchget, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; batchGet( params: Params$Resource$Projects$Apps$Recaptchav3config$Batchget, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaV3ConfigsResponse>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaV3ConfigsResponse> ): void; batchGet( params: Params$Resource$Projects$Apps$Recaptchav3config$Batchget, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaV3ConfigsResponse> ): void; batchGet( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaV3ConfigsResponse> ): void; batchGet( paramsOrCallback?: | Params$Resource$Projects$Apps$Recaptchav3config$Batchget | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaV3ConfigsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaV3ConfigsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaV3ConfigsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaV3ConfigsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Recaptchav3config$Batchget; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Recaptchav3config$Batchget; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1/{+parent}/apps/-/recaptchaV3Config:batchGet' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaV3ConfigsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1BatchGetRecaptchaV3ConfigsResponse>( parameters ); } } /** * Gets the RecaptchaV3Config for the specified app. For security reasons, the `site_secret` field is never populated in the response. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.recaptchaV3Config.get({ * // Required. The relative resource name of the RecaptchaV3Config, in the format: ``` projects/{project_number\}/apps/{app_id\}/recaptchaV3Config ``` * name: 'projects/my-project/apps/my-app/recaptchaV3Config', * }); * console.log(res.data); * * // Example response * // { * // "name": "my_name", * // "siteSecret": "my_siteSecret", * // "siteSecretSet": false, * // "tokenTtl": "my_tokenTtl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Apps$Recaptchav3config$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Apps$Recaptchav3config$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config>; get( params: Params$Resource$Projects$Apps$Recaptchav3config$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Apps$Recaptchav3config$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config> ): void; get( params: Params$Resource$Projects$Apps$Recaptchav3config$Get, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config> ): void; get( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config> ): void; get( paramsOrCallback?: | Params$Resource$Projects$Apps$Recaptchav3config$Get | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Recaptchav3config$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Recaptchav3config$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config>( parameters ); } } /** * Updates the RecaptchaV3Config for the specified app. While this configuration is incomplete or invalid, the app will be unable to exchange reCAPTCHA tokens for App Check tokens. For security reasons, the `site_secret` field is never populated in the response. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.recaptchaV3Config.patch({ * // Required. The relative resource name of the reCAPTCHA v3 configuration object, in the format: ``` projects/{project_number\}/apps/{app_id\}/recaptchaV3Config ``` * name: 'projects/my-project/apps/my-app/recaptchaV3Config', * // Required. A comma-separated list of names of fields in the RecaptchaV3Config to update. Example: `site_secret`. * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "name": "my_name", * // "siteSecret": "my_siteSecret", * // "siteSecretSet": false, * // "tokenTtl": "my_tokenTtl" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "name": "my_name", * // "siteSecret": "my_siteSecret", * // "siteSecretSet": false, * // "tokenTtl": "my_tokenTtl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Projects$Apps$Recaptchav3config$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Projects$Apps$Recaptchav3config$Patch, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config>; patch( params: Params$Resource$Projects$Apps$Recaptchav3config$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Projects$Apps$Recaptchav3config$Patch, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config> ): void; patch( params: Params$Resource$Projects$Apps$Recaptchav3config$Patch, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config> ): void; patch( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config> ): void; patch( paramsOrCallback?: | Params$Resource$Projects$Apps$Recaptchav3config$Patch | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Recaptchav3config$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Recaptchav3config$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config>( parameters ); } } } export interface Params$Resource$Projects$Apps$Recaptchav3config$Batchget extends StandardParameters { /** * Required. The relative resource names of the RecaptchaV3Configs to retrieve, in the format: ``` projects/{project_number\}/apps/{app_id\}/recaptchaV3Config ``` A maximum of 100 objects can be retrieved in a batch. */ names?: string[]; /** * Required. The parent project name shared by all RecaptchaV3Configs being retrieved, in the format ``` projects/{project_number\} ``` The parent collection in the `name` field of any resource being retrieved must match this field, or the entire batch fails. */ parent?: string; } export interface Params$Resource$Projects$Apps$Recaptchav3config$Get extends StandardParameters { /** * Required. The relative resource name of the RecaptchaV3Config, in the format: ``` projects/{project_number\}/apps/{app_id\}/recaptchaV3Config ``` */ name?: string; } export interface Params$Resource$Projects$Apps$Recaptchav3config$Patch extends StandardParameters { /** * Required. The relative resource name of the reCAPTCHA v3 configuration object, in the format: ``` projects/{project_number\}/apps/{app_id\}/recaptchaV3Config ``` */ name?: string; /** * Required. A comma-separated list of names of fields in the RecaptchaV3Config to update. Example: `site_secret`. */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1RecaptchaV3Config; } export class Resource$Projects$Apps$Safetynetconfig { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Atomically gets the SafetyNetConfigs for the specified list of apps. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.safetyNetConfig.batchGet({ * // Required. The relative resource names of the SafetyNetConfigs to retrieve, in the format ``` projects/{project_number\}/apps/{app_id\}/safetyNetConfig ``` A maximum of 100 objects can be retrieved in a batch. * names: 'placeholder-value', * // Required. The parent project name shared by all SafetyNetConfigs being retrieved, in the format ``` projects/{project_number\} ``` The parent collection in the `name` field of any resource being retrieved must match this field, or the entire batch fails. * parent: 'projects/my-project', * }); * console.log(res.data); * * // Example response * // { * // "configs": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ batchGet( params: Params$Resource$Projects$Apps$Safetynetconfig$Batchget, options: StreamMethodOptions ): GaxiosPromise<Readable>; batchGet( params?: Params$Resource$Projects$Apps$Safetynetconfig$Batchget, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1BatchGetSafetyNetConfigsResponse>; batchGet( params: Params$Resource$Projects$Apps$Safetynetconfig$Batchget, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; batchGet( params: Params$Resource$Projects$Apps$Safetynetconfig$Batchget, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetSafetyNetConfigsResponse>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetSafetyNetConfigsResponse> ): void; batchGet( params: Params$Resource$Projects$Apps$Safetynetconfig$Batchget, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetSafetyNetConfigsResponse> ): void; batchGet( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetSafetyNetConfigsResponse> ): void; batchGet( paramsOrCallback?: | Params$Resource$Projects$Apps$Safetynetconfig$Batchget | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetSafetyNetConfigsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetSafetyNetConfigsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchGetSafetyNetConfigsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1BatchGetSafetyNetConfigsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Safetynetconfig$Batchget; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Safetynetconfig$Batchget; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: ( rootUrl + '/v1/{+parent}/apps/-/safetyNetConfig:batchGet' ).replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1BatchGetSafetyNetConfigsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1BatchGetSafetyNetConfigsResponse>( parameters ); } } /** * Gets the SafetyNetConfig for the specified app. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.safetyNetConfig.get({ * // Required. The relative resource name of the SafetyNetConfig, in the format: ``` projects/{project_number\}/apps/{app_id\}/safetyNetConfig ``` * name: 'projects/my-project/apps/my-app/safetyNetConfig', * }); * console.log(res.data); * * // Example response * // { * // "name": "my_name", * // "tokenTtl": "my_tokenTtl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Apps$Safetynetconfig$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Apps$Safetynetconfig$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig>; get( params: Params$Resource$Projects$Apps$Safetynetconfig$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Apps$Safetynetconfig$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig> ): void; get( params: Params$Resource$Projects$Apps$Safetynetconfig$Get, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig> ): void; get( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig> ): void; get( paramsOrCallback?: | Params$Resource$Projects$Apps$Safetynetconfig$Get | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Safetynetconfig$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Safetynetconfig$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig>( parameters ); } } /** * Updates the SafetyNetConfig for the specified app. While this configuration is incomplete or invalid, the app will be unable to exchange SafetyNet tokens for App Check tokens. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.apps.safetyNetConfig.patch({ * // Required. The relative resource name of the SafetyNet configuration object, in the format: ``` projects/{project_number\}/apps/{app_id\}/safetyNetConfig ``` * name: 'projects/my-project/apps/my-app/safetyNetConfig', * // Required. A comma-separated list of names of fields in the SafetyNetConfig Gets to update. Example: `token_ttl`. * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "name": "my_name", * // "tokenTtl": "my_tokenTtl" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "name": "my_name", * // "tokenTtl": "my_tokenTtl" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Projects$Apps$Safetynetconfig$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Projects$Apps$Safetynetconfig$Patch, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig>; patch( params: Params$Resource$Projects$Apps$Safetynetconfig$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Projects$Apps$Safetynetconfig$Patch, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig> ): void; patch( params: Params$Resource$Projects$Apps$Safetynetconfig$Patch, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig> ): void; patch( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig> ): void; patch( paramsOrCallback?: | Params$Resource$Projects$Apps$Safetynetconfig$Patch | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Apps$Safetynetconfig$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Apps$Safetynetconfig$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1SafetyNetConfig>( parameters ); } } } export interface Params$Resource$Projects$Apps$Safetynetconfig$Batchget extends StandardParameters { /** * Required. The relative resource names of the SafetyNetConfigs to retrieve, in the format ``` projects/{project_number\}/apps/{app_id\}/safetyNetConfig ``` A maximum of 100 objects can be retrieved in a batch. */ names?: string[]; /** * Required. The parent project name shared by all SafetyNetConfigs being retrieved, in the format ``` projects/{project_number\} ``` The parent collection in the `name` field of any resource being retrieved must match this field, or the entire batch fails. */ parent?: string; } export interface Params$Resource$Projects$Apps$Safetynetconfig$Get extends StandardParameters { /** * Required. The relative resource name of the SafetyNetConfig, in the format: ``` projects/{project_number\}/apps/{app_id\}/safetyNetConfig ``` */ name?: string; } export interface Params$Resource$Projects$Apps$Safetynetconfig$Patch extends StandardParameters { /** * Required. The relative resource name of the SafetyNet configuration object, in the format: ``` projects/{project_number\}/apps/{app_id\}/safetyNetConfig ``` */ name?: string; /** * Required. A comma-separated list of names of fields in the SafetyNetConfig Gets to update. Example: `token_ttl`. */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1SafetyNetConfig; } export class Resource$Projects$Services { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Atomically updates the specified Service configurations. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.services.batchUpdate({ * // Required. The parent project name shared by all Service configurations being updated, in the format ``` projects/{project_number\} ``` The parent collection in the `name` field of any resource being updated must match this field, or the entire batch fails. * parent: 'projects/my-project', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "requests": [], * // "updateMask": "my_updateMask" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "services": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ batchUpdate( params: Params$Resource$Projects$Services$Batchupdate, options: StreamMethodOptions ): GaxiosPromise<Readable>; batchUpdate( params?: Params$Resource$Projects$Services$Batchupdate, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1BatchUpdateServicesResponse>; batchUpdate( params: Params$Resource$Projects$Services$Batchupdate, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; batchUpdate( params: Params$Resource$Projects$Services$Batchupdate, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchUpdateServicesResponse>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchUpdateServicesResponse> ): void; batchUpdate( params: Params$Resource$Projects$Services$Batchupdate, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchUpdateServicesResponse> ): void; batchUpdate( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchUpdateServicesResponse> ): void; batchUpdate( paramsOrCallback?: | Params$Resource$Projects$Services$Batchupdate | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchUpdateServicesResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchUpdateServicesResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1BatchUpdateServicesResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1BatchUpdateServicesResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Services$Batchupdate; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Services$Batchupdate; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/services:batchUpdate').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1BatchUpdateServicesResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1BatchUpdateServicesResponse>( parameters ); } } /** * Gets the Service configuration for the specified service name. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.services.get({ * // Required. The relative resource name of the Service to retrieve, in the format: ``` projects/{project_number\}/services/{service_id\} ``` Note that the `service_id` element must be a supported service ID. Currently, the following service IDs are supported: * `firebasestorage.googleapis.com` (Cloud Storage for Firebase) * `firebasedatabase.googleapis.com` (Firebase Realtime Database) * `firestore.googleapis.com` (Cloud Firestore) * name: 'projects/my-project/services/my-service', * }); * console.log(res.data); * * // Example response * // { * // "enforcementMode": "my_enforcementMode", * // "name": "my_name" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Services$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Services$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1Service>; get( params: Params$Resource$Projects$Services$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Services$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1Service>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1Service> ): void; get( params: Params$Resource$Projects$Services$Get, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1Service> ): void; get( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1Service> ): void; get( paramsOrCallback?: | Params$Resource$Projects$Services$Get | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1Service> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1Service> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1Service> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1Service> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Services$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Services$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1Service>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1Service>( parameters ); } } /** * Lists all Service configurations for the specified project. Only Services which were explicitly configured using UpdateService or BatchUpdateServices will be returned. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.services.list({ * // The maximum number of Services to return in the response. Only explicitly configured services are returned. The server may return fewer than this at its own discretion. If no value is specified (or too large a value is specified), the server will impose its own limit. * pageSize: 'placeholder-value', * // Token returned from a previous call to ListServices indicating where in the set of Services to resume listing. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to ListServices must match the call that provided the page token; if they do not match, the result is undefined. * pageToken: 'placeholder-value', * // Required. The relative resource name of the parent project for which to list each associated Service, in the format: ``` projects/{project_number\} ``` * parent: 'projects/my-project', * }); * console.log(res.data); * * // Example response * // { * // "nextPageToken": "my_nextPageToken", * // "services": [] * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Projects$Services$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Projects$Services$List, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1ListServicesResponse>; list( params: Params$Resource$Projects$Services$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Projects$Services$List, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ListServicesResponse>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ListServicesResponse> ): void; list( params: Params$Resource$Projects$Services$List, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ListServicesResponse> ): void; list( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ListServicesResponse> ): void; list( paramsOrCallback?: | Params$Resource$Projects$Services$List | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ListServicesResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ListServicesResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1ListServicesResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1ListServicesResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Services$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Services$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/services').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1ListServicesResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1ListServicesResponse>( parameters ); } } /** * Updates the specified Service configuration. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/firebaseappcheck.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const firebaseappcheck = google.firebaseappcheck('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: [ * 'https://www.googleapis.com/auth/cloud-platform', * 'https://www.googleapis.com/auth/firebase', * ], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await firebaseappcheck.projects.services.patch({ * // Required. The relative resource name of the service configuration object, in the format: ``` projects/{project_number\}/services/{service_id\} ``` Note that the `service_id` element must be a supported service ID. Currently, the following service IDs are supported: * `firebasestorage.googleapis.com` (Cloud Storage for Firebase) * `firebasedatabase.googleapis.com` (Firebase Realtime Database) * `firestore.googleapis.com` (Cloud Firestore) * name: 'projects/my-project/services/my-service', * // Required. A comma-separated list of names of fields in the Service to update. Example: `enforcement_mode`. * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "enforcementMode": "my_enforcementMode", * // "name": "my_name" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "enforcementMode": "my_enforcementMode", * // "name": "my_name" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Projects$Services$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Projects$Services$Patch, options?: MethodOptions ): GaxiosPromise<Schema$GoogleFirebaseAppcheckV1Service>; patch( params: Params$Resource$Projects$Services$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Projects$Services$Patch, options: | MethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1Service>, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1Service> ): void; patch( params: Params$Resource$Projects$Services$Patch, callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1Service> ): void; patch( callback: BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1Service> ): void; patch( paramsOrCallback?: | Params$Resource$Projects$Services$Patch | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1Service> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1Service> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleFirebaseAppcheckV1Service> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleFirebaseAppcheckV1Service> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Services$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Services$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://firebaseappcheck.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleFirebaseAppcheckV1Service>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleFirebaseAppcheckV1Service>( parameters ); } } } export interface Params$Resource$Projects$Services$Batchupdate extends StandardParameters { /** * Required. The parent project name shared by all Service configurations being updated, in the format ``` projects/{project_number\} ``` The parent collection in the `name` field of any resource being updated must match this field, or the entire batch fails. */ parent?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1BatchUpdateServicesRequest; } export interface Params$Resource$Projects$Services$Get extends StandardParameters { /** * Required. The relative resource name of the Service to retrieve, in the format: ``` projects/{project_number\}/services/{service_id\} ``` Note that the `service_id` element must be a supported service ID. Currently, the following service IDs are supported: * `firebasestorage.googleapis.com` (Cloud Storage for Firebase) * `firebasedatabase.googleapis.com` (Firebase Realtime Database) * `firestore.googleapis.com` (Cloud Firestore) */ name?: string; } export interface Params$Resource$Projects$Services$List extends StandardParameters { /** * The maximum number of Services to return in the response. Only explicitly configured services are returned. The server may return fewer than this at its own discretion. If no value is specified (or too large a value is specified), the server will impose its own limit. */ pageSize?: number; /** * Token returned from a previous call to ListServices indicating where in the set of Services to resume listing. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to ListServices must match the call that provided the page token; if they do not match, the result is undefined. */ pageToken?: string; /** * Required. The relative resource name of the parent project for which to list each associated Service, in the format: ``` projects/{project_number\} ``` */ parent?: string; } export interface Params$Resource$Projects$Services$Patch extends StandardParameters { /** * Required. The relative resource name of the service configuration object, in the format: ``` projects/{project_number\}/services/{service_id\} ``` Note that the `service_id` element must be a supported service ID. Currently, the following service IDs are supported: * `firebasestorage.googleapis.com` (Cloud Storage for Firebase) * `firebasedatabase.googleapis.com` (Firebase Realtime Database) * `firestore.googleapis.com` (Cloud Firestore) */ name?: string; /** * Required. A comma-separated list of names of fields in the Service to update. Example: `enforcement_mode`. */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$GoogleFirebaseAppcheckV1Service; } }
the_stack
import { Component } from "@angular/core"; import { RouterExtensions } from "@nativescript/angular"; import { StateTransferService } from "~/app/services/state-transfer.service"; import { ScannedItemManagerService, ScannedItem } from "../services/scanned-item-manager.service"; import { GrocyService } from "~/app/services/grocy.service"; import { GrocyLocation, GrocyQuantityUnit, GrocyProduct } from "~/app/services/grocy.interfaces"; import { EventData } from "@nativescript/core"; import { ListPicker } from "@nativescript/core"; import { SwipeGestureEventData, SwipeDirection } from "@nativescript/core"; import { slideOutLeftAnimation } from "~/app/utilities/animations"; import { Observable, of } from "rxjs"; import { tap, catchError, mergeMap, switchMap, mapTo } from "rxjs/operators"; import { OpenFoodFactsService } from "~/app/services/openfoodfacts.service"; import { UPCItemDbService } from "~/app/services/upcitemdb.service"; import { UPCDatabaseService } from "~/app/services/upcdatabase.service"; import { HttpErrorResponse } from "@angular/common/http"; interface InprogresProduct { barcode: string; name: string; location: GrocyLocation | null; purchaseQuantityUnits: GrocyQuantityUnit | null; consumeQuantityUnits: GrocyQuantityUnit | null; quantityUnitFactor: number; goodForever: boolean; bestBeforeDays: number; minStockAmount: number; goodForeverAfterOpen: boolean; bestBeforeDaysAfterOpen: number; goodForeverAfterThawing: boolean; bestBeforeDaysAfterThawing: number; goodForeverAfterFreezing: boolean; bestBeforeDaysAfterFreezing: number; createNewParentProduct: boolean; newParentProductName: string | null; newParentProductMinimumStockAmount: number; parentProduct: GrocyProduct | null; parent_product_id: string | number | null; } const nullProduct: GrocyProduct = { id: "-1", name: "-- No Parent Product --", description: "", min_stock_amount: 0, quantity_unit_id_stock: -1, quantity_unit_id_purchase: -1, quantity_unit_factor_purchase_to_stock: 0, location_id: 0, default_best_before_days: 0, default_best_before_days_after_open: 0, default_best_before_days_after_thawing: 0, default_best_before_days_after_freezing: 0, parent_product_id: null }; @Component({ selector: "ns-product-quick-create", templateUrl: "./product-quick-create.component.html", styleUrls: ["./product-quick-create.component.scss"], animations: [ slideOutLeftAnimation ] }) export class ProductQuickCreateComponent { // To whoever is reading this, boy did this get away! // This is the most painful part of getting people started // // I swear to god I'm going to rewrite it at some point get selectedLocationIdx() { return this._selectedLocationIdx; } set selectedLocationIdx(value) { this._selectedLocationIdx = value; this.product.location = this.locations[value]; } get selectedProductIdx() { return this._selectedProductIdx; } set selectedProductIdx(value) { this._selectedProductIdx = value; this.product.parentProduct = this.filteredProducts[value]; } get currentStep() { return this.stepOrder[this.stepIdx]; } get locations(): GrocyLocation[] { return this._locations; } set locations(value: GrocyLocation[]) { this._locations = value; this.locationNames = value.map(l => l.name); } stepValid = { name: () => this.product.name.length > 0 && !this.nameIsTaken(this.product.name), location: () => !!this.product.location, purchase_quantity: () => !!this.product.purchaseQuantityUnits, consume_quantity: () => !!this.product.consumeQuantityUnits, quantity_unit_factor: () => this.product.quantityUnitFactor >= 1, minimumStockAmount: () => this.product.minStockAmount >= 0, bestBeforeDays: () => true, parentProduct: () => true, earlySave: () => true, bestBeforeDaysAfterOpen: () => true, bestBeforeDaysAfterThawing: () => this.product.bestBeforeDaysAfterThawing >= 0, bestBeforeDaysAfterFreezing: () => this.product.bestBeforeDaysAfterFreezing >= 0, saveConfirmation: () => true, saving: () => true }; stepOrder = [ "name", "location", "purchase_quantity", "consume_quantity", "quantity_unit_factor", "bestBeforeDays", "bestBeforeDaysAfterOpen", "parentProduct", "minimumStockAmount", "earlySave", "bestBeforeDaysAfterThawing", "bestBeforeDaysAfterFreezing", "saveConfirmation", "saving" ]; stepIdx = 0; saveStatus = ""; alternateNamesSearched = false; alternateNames: Record<string, string> = {}; scannedItemManager: ScannedItemManagerService; scannedItems: ScannedItem[] = []; idxUnderEdit = -1; locationNames: string[] = []; products: GrocyProduct[] = []; filteredProducts: GrocyProduct[] = []; filteredProductNames: string[] = []; quantityUnits: GrocyQuantityUnit[] = []; quantityUnitNames: string[] = []; navigationEnabled = true; product: InprogresProduct = this.buildEmptyProduct(); private _locations: GrocyLocation[] = []; private _selectedLocationIdx = 0; private _selectedProductIdx = 0; constructor( private routerExtensions: RouterExtensions, private stateTransfer: StateTransferService, private grocyService: GrocyService, private openFoodFacts: OpenFoodFactsService, private upcItemDbService: UPCItemDbService, private upcDatabase: UPCDatabaseService ) { const val = this.stateTransfer.readAndClearState(); if (val && val.type === "productQuickCreate") { this.scannedItemManager = val.scannedItemManager; this.scannedItems = val.scannedItems; } this.grocyService.locations().subscribe(locs => { this.locations = locs; this.preSelectLocation(); this.nextScannedItem(); }); this.grocyService.allProducts().subscribe(p => { this.products = [nullProduct, ...p]; this.productFilterUpdated(""); }); this.grocyService.quantityUnits().subscribe(qus => { this.quantityUnits = qus; this.quantityUnitNames = qus.map(l => l.name); }); } isStepValid(stepName: string) { return this.stepValid[stepName](); } goToStep(stepName: string) { this.stepIdx = this.stepOrder.indexOf(stepName); } nextStepFromParentProduct() { this.nextStep(this.hasParentProduct() ? 2 : 1); } nextStep(by = 1) { const stepValidator = this.stepValid[this.stepOrder[this.stepIdx]]; if (!this.navigationEnabled) { console.log("navigation disabled"); return; } if (stepValidator && stepValidator()) { const newIdx = this.stepIdx + by; if (newIdx >= 0 && newIdx < this.stepOrder.length - 1) { this.stepIdx = newIdx; } } else { console.log("Step not valid"); } } onSwipe(evt: SwipeGestureEventData) { if (evt.direction === SwipeDirection.left) { this.nextStep(); } else if (evt.direction === SwipeDirection.right) { this.nextStep(-1); } } nextScannedItem() { this.idxUnderEdit += 1; const nextItem = this.scannedItems[this.idxUnderEdit]; if (!nextItem) { this.routerExtensions.back(); } this.saveStatus = "Getting ready to save"; this.alternateNamesSearched = false; this.alternateNames = {}; this.product = { ...this.buildEmptyProduct(), name: nextItem.externalProduct ? nextItem.externalProduct.name : "", barcode: nextItem.barcode, location: nextItem.location || null }; this.preSelectLocation(); } addBarcodeToExistingProduct() { const conflict = this.nameConflicts(); if (conflict) { const loc = this.locations.find(p => Number(p.id) === conflict.location_id); this.grocyService.addBarcodeToProduct(conflict.id, this.product.barcode) .subscribe(_ => { this.updateScannedItem(conflict, loc); this.nextScannedItem(); }); } } useName(newName: string) { this.product.name = newName; } nameIsTaken(str: string) { return !!this.products.find(p => p.name.toLowerCase() === str.toLowerCase()); } isCurrentUserNameInput(name: string) { return name.toLowerCase() === this.product.name.toLowerCase(); } nameConflicts(): GrocyProduct | null { return this.products.find(p => this.isCurrentUserNameInput(p.name)) || null; } preSelectLocation() { if (this.product.location) { const idx = this.locations.findIndex( a => a.id === this.product.location.id ); if (idx) { this.selectedLocationIdx = idx; } } } valueAdjuster( attr: "bestBeforeDays" | "bestBeforeDaysAfterOpen" | "bestBeforeDaysAfterThawing" | "bestBeforeDaysAfterFreezing", val: number ) { this.product[attr] += val; } onSelectedPurchaseQUChanged(evt: EventData) { const picker = <ListPicker>evt.object; this.product.purchaseQuantityUnits = this.quantityUnits[picker.selectedIndex]; } onSelectedConsumeQUChanged(evt: EventData) { const picker = <ListPicker>evt.object; this.product.consumeQuantityUnits = this.quantityUnits[picker.selectedIndex]; } createNewLocation() { this.stateTransfer.setState({ type: "locationCreation", callback: l => { this.product.location = l; this.locations = [l, ...this.locations]; this.nextStep(); } }); this.routerExtensions.navigate(["/locations/create"]); } conditionalConsume() { if (this.product.consumeQuantityUnits.id !== this.product.purchaseQuantityUnits.id) { this.nextStep(); } else { this.nextStep(2); } } quantityConversionText() { if (this.product.consumeQuantityUnits && this.product.purchaseQuantityUnits) { return `How many ${this.product.consumeQuantityUnits.name_plural} per ${this.product.purchaseQuantityUnits.name}`; } else { return `error`; } } productFilterUpdated(filter: string) { this.filteredProducts = this.products.filter(i => { return i.name.toLowerCase().indexOf(filter.toLowerCase()) > -1; }); this.filteredProductNames = this.filteredProducts.map(p => p.name); } updateScannedItem(product: GrocyProduct, location: GrocyLocation) { this.scannedItemManager.assignProductToBarcode( this.product.barcode, product, 0, location, ); } saveProduct() { this.goToStep("saving"); this.createParentProduct().pipe( tap(_ => this.saveStatus = "Creating Product"), mergeMap(_ => this.createNewProduct()), tap(p => this.updateScannedItem(p, this.product.location)), tap(_ => this.saveStatus = "Done"), catchError((e: Error | HttpErrorResponse) => { let errMsg = `There was an error saving the product: ${e.message}`; if (e instanceof HttpErrorResponse) { errMsg += JSON.stringify(e.error); } this.saveStatus = errMsg; throw e; }) ).subscribe(_ => { this.saveStatus = "Product Created"; setTimeout(() => { this.nextScannedItem(); this.goToStep("name"); }, 500); }); } createNewProduct() { return this.grocyService.createProduct({ ...this.createProductBaseParams(), name: this.product.name, cumulate_min_stock_amount_of_sub_products: false, min_stock_amount: this.product.minStockAmount, parent_product_id: this.product.parent_product_id, }).pipe( switchMap(r => this.grocyService.createProductBarcode({ product_id: r.id, amount: `${this.product.quantityUnitFactor}`, qu_id: this.product.purchaseQuantityUnits.id, barcode: this.product.barcode, }).pipe(mapTo(r)) ) ); } hasParentProduct() { const pProduct = this.product.parentProduct; return (pProduct && pProduct !== nullProduct) || (this.product.createNewParentProduct && this.product.newParentProductName !== ""); } createParentProduct(): Observable<any> { const pProduct = this.product.parentProduct; if (pProduct && pProduct !== nullProduct) { this.product.parent_product_id = pProduct.id; return of(""); } else if (this.product.createNewParentProduct && this.product.newParentProductName !== "") { this.saveStatus = "Creating Parent Product"; return this.grocyService.createProduct({ ...this.createProductBaseParams(), name: this.product.newParentProductName, min_stock_amount: this.product.newParentProductMinimumStockAmount, cumulate_min_stock_amount_of_sub_products: true }).pipe( tap(r => { this.products = [...this.products, r]; this.product.parent_product_id = r.id; this.product.parentProduct = r; this.saveStatus = "Parent Product Created"; }), catchError(e => { this.saveStatus = "An error was encountered saving the parent product"; console.log(e); throw e; }) ); } else { return of(""); } } numberOfAlternativeNames(): number { return Object.keys(this.alternateNames).length; } findOtherNames() { this.alternateNamesSearched = true; this.upcDatabase.lookForBarcode(this.product.barcode) .subscribe(r => { this.alternateNames["UPC Database"] = r.name; }); this.upcItemDbService.lookForBarcode(this.product.barcode) .subscribe(r => { this.alternateNames["UPC Item DB"] = r.name; }); this.openFoodFacts.searchForBarcode(this.product.barcode) .subscribe(r => { this.alternateNames["Open Food Facts"] = r.name; }); } private createProductBaseParams() { return { description: "", location_id: this.product.location.id, quantity_unit_id_purchase: Number(this.product.purchaseQuantityUnits.id), quantity_unit_id_stock: Number(this.product.consumeQuantityUnits.id), quantity_unit_factor_purchase_to_stock: this.product.quantityUnitFactor, default_best_before_days: this.product.goodForever ? -1 : this.product.bestBeforeDays, default_best_before_days_after_open: this.product.goodForeverAfterOpen ? -1 : this.product.bestBeforeDaysAfterOpen, default_best_before_days_after_thawing: this.product.goodForeverAfterThawing ? -1 : this.product.bestBeforeDaysAfterThawing, default_best_before_days_after_freezing: this.product.goodForeverAfterFreezing ? -1 : this.product.bestBeforeDaysAfterFreezing }; } private buildEmptyProduct(): InprogresProduct { return { barcode: "", name: "", location: null, purchaseQuantityUnits: null, consumeQuantityUnits: null, quantityUnitFactor: 1, bestBeforeDays: 0, minStockAmount: 0, goodForever: false, goodForeverAfterOpen: false, bestBeforeDaysAfterOpen: 0, goodForeverAfterThawing: false, bestBeforeDaysAfterThawing: 0, goodForeverAfterFreezing: false, bestBeforeDaysAfterFreezing: 0, createNewParentProduct: false, parentProduct: null, newParentProductName: null, newParentProductMinimumStockAmount: 0, parent_product_id: null }; } }
the_stack
import * as h from '../helpers'; describe('Tabs', () => { before(() => { h.stories.visit(); }); ['Basic', 'Named Tabs'].forEach(story => { context(`given the [Components/Containers/Tabs/React, ${story}] story is rendered`, () => { beforeEach(() => { h.stories.load('Components/Containers/Tabs/React', story); }); it('should pass axe checks', () => { cy.checkA11y(); }); it('should have an element with a role of "tablist"', () => { cy.findByRole('tablist').should('be.visible'); }); it('should have elements with a role of "tab" inside the "tablist"', () => { cy.findByRole('tablist') .findByRole('tab', {name: 'First Tab'}) .should('be.visible'); }); it('should have "aria-selected=true" for the first tab', () => { cy.findByRole('tab', {name: 'First Tab'}).should('have.attr', 'aria-selected', 'true'); }); it('should not have "aria-selected" for the second tab', () => { cy.findByRole('tab', {name: 'Second Tab'}).should('have.attr', 'aria-selected', 'false'); }); it('should not have tabindex=-1 on the first tab', () => { cy.findByRole('tab', {name: 'First Tab'}).should('not.have.attr', 'tabindex', '-1'); }); it('should have "tabindex=-1" on the second tab', () => { cy.findByRole('tab', {name: 'Second Tab'}).should('have.attr', 'tabindex', '-1'); }); it('should have an id on the first tab', () => { cy.findByRole('tab', {name: 'First Tab'}).should('have.attr', 'id'); }); it('should label the tab panel "First Tab"', () => { cy.findByRole('tabpanel', {name: 'First Tab'}).should('be.visible'); }); it('should have an "aria-controls" on the first tab', () => { cy.findByRole('tab', {name: 'First Tab'}).should('have.attr', 'aria-controls'); }); it('should have an "aria-controls" that matches the first tab panel', () => { cy.findByRole('tab', {name: 'First Tab'}).then($tab => { const id = $tab.attr('aria-controls'); cy.findByRole('tabpanel', {name: 'First Tab'}).should('have.attr', 'id', id); }); }); it('should have a default cursor for the (active) first tab', () => { cy.findByRole('tab', {name: 'First Tab'}).should('have.css', 'cursor', 'default'); }); it('should have a pointer cursor for the second tab', () => { cy.findByRole('tab', {name: 'Second Tab'}).should('have.css', 'cursor', 'pointer'); }); context('when the first tab is active and focused', () => { beforeEach(() => { cy.findByRole('tab', {name: 'First Tab'}) .click() .focus(); }); context('when the tab key is pressed', () => { beforeEach(() => { cy.tab(); }); it('should move focus to the tabpanel', () => { cy.findByRole('tabpanel', {name: 'First Tab'}) .should('have.focus') .and('contain', 'Contents of First Tab'); }); }); context('when the right arrow key is pressed', () => { beforeEach(() => { cy.focused().type('{rightarrow}'); }); it('should have tabindex=-1 on the first tab', () => { cy.findByRole('tab', {name: 'First Tab'}).should('have.attr', 'tabindex', '-1'); }); it('should not have tabindex=-1 on the second tab', () => { cy.findByRole('tab', {name: 'Second Tab'}).should('not.have.attr', 'tabindex', '-1'); }); it('should focus on the second tab', () => { cy.findByRole('tab', {name: 'Second Tab'}).should('have.focus'); }); context('when the space key is pressed', () => { beforeEach(() => { cy.focused().type(' '); }); it('should not have "aria-selected" on the first tab', () => { cy.findByRole('tab', {name: 'First Tab'}).should( 'have.attr', 'aria-selected', 'false' ); }); it('should have "aria-selected=true" on the second tab', () => { cy.findByRole('tab', {name: 'Second Tab'}).should( 'have.attr', 'aria-selected', 'true' ); }); }); context('when the enter key is pressed', () => { beforeEach(() => { cy.focused().type('{enter}'); }); it('should not have "aria-selected" on the first tab', () => { cy.findByRole('tab', {name: 'First Tab'}).should( 'have.attr', 'aria-selected', 'false' ); }); it('should have "aria-selected=true" on the second tab', () => { cy.findByRole('tab', {name: 'Second Tab'}).should( 'have.attr', 'aria-selected', 'true' ); }); }); context('when the tab key is pressed', () => { beforeEach(() => { cy.tab(); }); it('should focus on the tab panel of the first tab', () => { cy.findByRole('tabpanel', {name: 'First Tab'}).should('have.focus'); }); // verify the original intent is no longer a tab stop context('when shift + tab keys are pressed', () => { beforeEach(() => { cy.tab({shift: true}); }); it('should not have tabindex=-1 on the first tab', () => { cy.findByRole('tab', {name: 'First Tab'}).should('not.have.attr', 'tabindex', '-1'); }); it('should set "tabindex=-1" on the second tab', () => { cy.findByRole('tab', {name: 'Second Tab'}).should('have.attr', 'tabindex', '-1'); }); it('should focus on the first tab', () => { cy.findByRole('tab', {name: 'First Tab'}).should('have.focus'); }); }); }); }); context('when the left arrow is pressed', () => { beforeEach(() => { cy.focused().type('{leftarrow}'); }); it('should have tabindex=-1 on the first tab', () => { cy.findByRole('tab', {name: 'First Tab'}).should('have.attr', 'tabindex', '-1'); }); it('should not have tabindex=-1 on the last tab', () => { cy.findByRole('tab', {name: 'Fifth Tab'}).should('not.have.attr', 'tabindex', '-1'); }); it('should focus on the last tab', () => { cy.findByRole('tab', {name: 'Fifth Tab'}).should('have.focus'); }); }); }); context('when the fifth tab is clicked', () => { beforeEach(() => { cy.findByRole('tab', {name: 'Fifth Tab'}).click(); }); it('should show the contents of the fifth tab', () => { cy.findByRole('tabpanel', {name: 'Fifth Tab'}) .should('be.visible') .and('contain', 'Contents of Fifth Tab'); }); context('when the right arrow key is pressed', () => { beforeEach(() => { cy.focused().type('{rightarrow}'); }); it('should not have tabindex=-1 on the first tab', () => { cy.findByRole('tab', {name: 'First Tab'}).should('not.have.attr', 'tabindex', '-1'); }); it('should set "tabindex=-1" on the last tab', () => { cy.findByRole('tab', {name: 'Fifth Tab'}).should('have.attr', 'tabindex', '-1'); }); }); }); }); }); context('given the [Components/Containers/Tabs/React, DisabledTab] story is rendered', () => { beforeEach(() => { cy.loadStory('Components/Containers/Tabs/React', 'DisabledTab'); }); context('when the Disabled Tab is clicked', () => { beforeEach(() => { cy.findByRole('tab', {name: 'Disabled Tab'}).click(); }); it('should not set "[aria-selected=true]" on the Disabled Tab', () => { cy.findByRole('tab', {name: 'Disabled Tab'}).should( 'not.have.attr', 'aria-selected', 'true' ); }); it('should leave the first tab selected', () => { cy.findByRole('tabpanel').should('contain', 'Contents of First Tab'); }); }); context('when the first tab is active and focused', () => { beforeEach(() => { cy.findByRole('tab', {name: 'First Tab'}) .click() .focus(); }); context('when the right arrow key is pressed', () => { beforeEach(() => { cy.focused().type('{rightarrow}'); }); it('should focus on the Disabled Tab', () => { cy.findByRole('tab', {name: 'Disabled Tab'}).should('have.focus'); }); context('when the enter key is pressed', () => { beforeEach(() => { cy.focused().type('{enter}'); }); it('should not set "[aria-selected=true]" on the Disabled Tab', () => { cy.findByRole('tab', {name: 'Disabled Tab'}).should( 'not.have.attr', 'aria-selected', 'true' ); }); it('should leave the first tab selected', () => { cy.findByRole('tabpanel').should('contain', 'Contents of First Tab'); }); }); }); }); }); context('given the [Components/Containers/Tabs/React, DynamicTabs] story is rendered', () => { beforeEach(() => { h.stories.load('Components/Containers/Tabs/React', 'DynamicTabs'); }); context('when "Add Tab" is clicked', () => { beforeEach(() => { cy.findByRole('tab', {name: 'Add Tab'}).click(); }); it('should focus on "Add Tab"', () => { cy.findByRole('tab', {name: 'Add Tab'}).should('have.focus'); }); context('when the left arrow key is pressed', () => { beforeEach(() => { cy.focused().type('{leftarrow}'); }); it('should focus on Tab 4', () => { cy.findByRole('tab', {name: 'Tab 4'}).should('be.focused'); }); }); }); context('when "Tab 1" is activated', () => { beforeEach(() => { cy.findByRole('tab', {name: 'Tab 1'}).click(); }); context('then the Delete key is pressed', () => { beforeEach(() => { cy.focused().type('{del}'); }); // Tab activation should move to the right if activated tab is removed it('should have "aria-selected=true" for "Tab 2"', () => { cy.findByRole('tab', {name: 'Tab 2'}).should('have.attr', 'aria-selected', 'true'); }); it('should show "Tab 2" contents', () => { cy.findByRole('tabpanel', {name: 'Tab 2'}).should('contain', 'Contents of Tab 2'); }); }); }); context('when "Tab 3" is activated', () => { beforeEach(() => { cy.findByRole('tab', {name: 'Tab 3'}).click(); }); context('then the left arrow key is pressed', () => { beforeEach(() => { cy.focused().type('{leftarrow}'); }); context('then the Delete key is pressed', () => { beforeEach(() => { cy.focused().type('{del}'); }); it('should remove "Tab 2"', () => { cy.findByRole('tab', {name: 'Tab 2'}).should('not.exist'); }); // Focus moves to the right if focused tab is deleted it('should move focus to "Tab 3"', () => { cy.findByRole('tab', {name: 'Tab 3'}).should('have.focus'); }); // Tab activation should not change if a non-activated tab is deleted it('should have "aria-selected=true" for "Tab 3"', () => { cy.findByRole('tab', {name: 'Tab 3'}).should('have.attr', 'aria-selected', 'true'); }); it('should show "Tab 3" contents', () => { cy.findByRole('tabpanel', {name: 'Tab 3'}).should('contain', 'Contents of Tab 3'); }); context('then the Delete key is pressed again', () => { beforeEach(() => { cy.focused().type('{del}'); }); // Focus moves to the right if focused tab is deleted again it('should move focus to "Add Tab"', () => { cy.findByRole('tab', {name: 'Add Tab'}).should('have.focus'); }); }); }); }); context('then the left arrow key is pressed twice', () => { beforeEach(() => { cy.focused().type('{leftarrow}{leftarrow}'); }); context('then the Delete key is pressed', () => { beforeEach(() => { cy.focused().type('{del}'); }); it('should remove "Tab 1"', () => { cy.findByRole('tab', {name: 'Tab 1'}).should('not.exist'); }); it('should move focus to "Tab 2"', () => { cy.findByRole('tab', {name: 'Tab 2'}).should('have.focus'); }); // Tab activation should not change if a non-activated tab is deleted it('should have "aria-selected=true" for "Tab 3"', () => { cy.findByRole('tab', {name: 'Tab 3'}).should('have.attr', 'aria-selected', 'true'); }); it('should show "Tab 3" contents', () => { cy.findByRole('tabpanel', {name: 'Tab 3'}).should('contain', 'Contents of Tab 3'); }); }); }); }); }); context('given the [Components/Containers/Tabs/React, LeftToRight] story is rendered', () => { beforeEach(() => { h.stories.load('Components/Containers/Tabs/React', 'RightToLeft'); }); context('when the first tab is active and focused', () => { beforeEach(() => { cy.findByRole('tab', {name: 'ראשון'}) .click() .focus(); }); context('when the tab key is pressed', () => { beforeEach(() => { cy.tab(); }); it('should move focus to the tabpanel', () => { cy.findByRole('tabpanel', {name: 'ראשון'}) .should('have.focus') .and('contain', 'תוכן הראשון'); }); }); context('when the left arrow key is pressed', () => { beforeEach(() => { cy.focused().type('{leftarrow}'); }); it('should have tabindex=-1 on the first tab', () => { cy.findByRole('tab', {name: 'ראשון'}).should('have.attr', 'tabindex', '-1'); }); it('should not have tabindex=-1 on the second tab', () => { cy.findByRole('tab', {name: 'שְׁנִיָה'}).should('not.have.attr', 'tabindex', '-1'); }); it('should focus on the second tab', () => { cy.findByRole('tab', {name: 'שְׁנִיָה'}).should('have.focus'); }); context('when the space key is pressed', () => { beforeEach(() => { cy.focused().type(' '); }); it('should not have "aria-selected" on the first tab', () => { cy.findByRole('tab', {name: 'ראשון'}).should('have.attr', 'aria-selected', 'false'); }); it('should have "aria-selected=true" on the second tab', () => { cy.findByRole('tab', {name: 'שְׁנִיָה'}).should('have.attr', 'aria-selected', 'true'); }); }); }); context('when the right arrow is pressed', () => { beforeEach(() => { cy.focused().type('{rightarrow}'); }); it('should have tabindex=-1 on the first tab', () => { cy.findByRole('tab', {name: 'ראשון'}).should('have.attr', 'tabindex', '-1'); }); it('should not have tabindex=-1 on the last tab', () => { cy.findByRole('tab', {name: 'חמישי'}).should('not.have.attr', 'tabindex', '-1'); }); it('should focus on the last tab', () => { cy.findByRole('tab', {name: 'חמישי'}).should('have.focus'); }); }); }); }); context('when [Components/Containers/Tabs/React, OverflowTabs] story is rendered', () => { beforeEach(() => { h.stories.load('Components/Containers/Tabs/React', 'OverflowTabs'); }); it('should pass axe checks', () => { cy.checkA11y(); }); it('should not show the "More" button', () => { cy.findByRole('button', {name: 'More'}).should('not.exist'); }); context('when the "First Tab" is focused', () => { beforeEach(() => { cy.findByRole('tab', {name: 'First Tab'}) .click() .focus(); }); context('when the Tab key is pressed', () => { beforeEach(() => { cy.focused().tab(); }); it('should focus on the tab panel', () => { cy.findByRole('tabpanel', {name: 'First Tab'}).should('have.focus'); }); }); }); context('when tab list container is only 500px wide', () => { beforeEach(() => { cy.findByRole('button', {name: '500px'}).click(); }); it('should pass axe checks', () => { cy.checkA11y(); }); it('should show the "More" button', () => { cy.findByRole('button', {name: 'More'}).should('exist'); }); context('when the "First Tab" is focused', () => { beforeEach(() => { cy.findByRole('tab', {name: 'First Tab'}) .click() .focus(); }); context('when the Tab key is pressed', () => { beforeEach(() => { cy.focused().tab(); }); it('should focus on the "More" button', () => { cy.findByRole('button', {name: 'More'}).should('have.focus'); }); }); }); context('when the "More" button is clicked', () => { beforeEach(() => { cy.findByRole('button', {name: 'More'}).click(); }); it('should show the Tab overflow menu', () => { cy.findByRole('menu', {name: 'More'}).should('exist'); }); context('when the "Sixth Tab" is clicked', () => { beforeEach(() => { cy.findByRole('menuitem', {name: 'Sixth Tab'}).click(); }); it('should select the Sixth Tab', () => { cy.findByRole('tab', {name: 'Sixth Tab'}).should('have.attr', 'aria-selected', 'true'); }); it('should move focus back to the "More" button', () => { cy.findByRole('button', {name: 'More'}).should('have.focus'); }); }); }); }); }); });
the_stack
import {EntityMetadata} from "../metadata/EntityMetadata"; import {MissingPrimaryColumnError} from "../error/MissingPrimaryColumnError"; import {CircularRelationsError} from "../error/CircularRelationsError"; import {DepGraph} from "../util/DepGraph"; import {Driver} from "../driver/Driver"; import {DataTypeNotSupportedError} from "../error/DataTypeNotSupportedError"; import {ColumnType} from "../driver/types/ColumnTypes"; import {MongoDriver} from "../driver/mongodb/MongoDriver"; import {SqlServerDriver} from "../driver/sqlserver/SqlServerDriver"; import {MysqlDriver} from "../driver/mysql/MysqlDriver"; import {NoConnectionOptionError} from "../error/NoConnectionOptionError"; import {InitializedRelationError} from "../error/InitializedRelationError"; import {AuroraDataApiDriver} from "../driver/aurora-data-api/AuroraDataApiDriver"; /// todo: add check if there are multiple tables with the same name /// todo: add checks when generated column / table names are too long for the specific driver // todo: type in function validation, inverse side function validation // todo: check on build for duplicate names, since naming checking was removed from MetadataStorage // todo: duplicate name checking for: table, relation, column, index, naming strategy, join tables/columns? // todo: check if multiple tree parent metadatas in validator // todo: tree decorators can be used only on closure table (validation) // todo: throw error if parent tree metadata was not specified in a closure table // todo: MetadataArgsStorage: type in function validation, inverse side function validation // todo: MetadataArgsStorage: check on build for duplicate names, since naming checking was removed from MetadataStorage // todo: MetadataArgsStorage: duplicate name checking for: table, relation, column, index, naming strategy, join tables/columns? // todo: MetadataArgsStorage: check for duplicate targets too since this check has been removed too // todo: check if relation decorator contains primary: true and nullable: true // todo: check column length, precision. scale // todo: MySQL index can be unique or spatial or fulltext /** * Validates built entity metadatas. */ export class EntityMetadataValidator { // ------------------------------------------------------------------------- // Public Methods // ------------------------------------------------------------------------- /** * Validates all given entity metadatas. */ validateMany(entityMetadatas: EntityMetadata[], driver: Driver) { entityMetadatas.forEach(entityMetadata => this.validate(entityMetadata, entityMetadatas, driver)); this.validateDependencies(entityMetadatas); this.validateEagerRelations(entityMetadatas); } /** * Validates given entity metadata. */ validate(entityMetadata: EntityMetadata, allEntityMetadatas: EntityMetadata[], driver: Driver) { // check if table metadata has an id if (!entityMetadata.primaryColumns.length && !entityMetadata.isJunction) throw new MissingPrimaryColumnError(entityMetadata); // validate if table is using inheritance it has a discriminator // also validate if discriminator values are not empty and not repeated if (entityMetadata.inheritancePattern === "STI") { if (!entityMetadata.discriminatorColumn) throw new Error(`Entity ${entityMetadata.name} using single-table inheritance, it should also have a discriminator column. Did you forget to put discriminator column options?`); if (["", undefined, null].indexOf(entityMetadata.discriminatorValue) !== -1) throw new Error(`Entity ${entityMetadata.name} has empty discriminator value. Discriminator value should not be empty.`); const sameDiscriminatorValueEntityMetadata = allEntityMetadatas.find(metadata => { return metadata !== entityMetadata && metadata.discriminatorValue === entityMetadata.discriminatorValue; }); if (sameDiscriminatorValueEntityMetadata) throw new Error(`Entities ${entityMetadata.name} and ${sameDiscriminatorValueEntityMetadata.name} as equal discriminator values. Make sure their discriminator values are not equal using @DiscriminatorValue decorator.`); } entityMetadata.relationCounts.forEach(relationCount => { if (relationCount.relation.isManyToOne || relationCount.relation.isOneToOne) throw new Error(`Relation count can not be implemented on ManyToOne or OneToOne relations.`); }); if (!(driver instanceof MongoDriver)) { entityMetadata.columns.forEach(column => { const normalizedColumn = driver.normalizeType(column) as ColumnType; if (driver.supportedDataTypes.indexOf(normalizedColumn) === -1) throw new DataTypeNotSupportedError(column, normalizedColumn, driver.options.type); if (column.length && driver.withLengthColumnTypes.indexOf(normalizedColumn) === -1) throw new Error(`Column ${column.propertyName} of Entity ${entityMetadata.name} does not support length property.`); }); } if (driver instanceof MysqlDriver || driver instanceof AuroraDataApiDriver) { const generatedColumns = entityMetadata.columns.filter(column => column.isGenerated && column.generationStrategy !== "uuid"); if (generatedColumns.length > 1) throw new Error(`Error in ${entityMetadata.name} entity. There can be only one auto-increment column in MySql table.`); } // for mysql we are able to not define a default selected database, instead all entities can have their database // defined in their decorators. To make everything work either all entities must have database define and we // can live without database set in the connection options, either database in the connection options must be set if (driver instanceof MysqlDriver) { const metadatasWithDatabase = allEntityMetadatas.filter(metadata => metadata.database); if (metadatasWithDatabase.length === 0 && !driver.database) throw new NoConnectionOptionError("database"); } if (driver instanceof SqlServerDriver) { const charsetColumns = entityMetadata.columns.filter(column => column.charset); if (charsetColumns.length > 1) throw new Error(`Character set specifying is not supported in Sql Server`); } // check if relations are all without initialized properties const entityInstance = entityMetadata.create(); entityMetadata.relations.forEach(relation => { if (relation.isManyToMany || relation.isOneToMany) { // we skip relations for which persistence is disabled since initialization in them cannot harm somehow if (relation.persistenceEnabled === false) return; // get entity relation value and check if its an array const relationInitializedValue = relation.getEntityValue(entityInstance); if (relationInitializedValue instanceof Array) throw new InitializedRelationError(relation); } }); // validate relations entityMetadata.relations.forEach(relation => { // check join tables: // using JoinTable is possible only on one side of the many-to-many relation // todo(dima): fix // if (relation.joinTable) { // if (!relation.isManyToMany) // throw new UsingJoinTableIsNotAllowedError(entityMetadata, relation); // // if there is inverse side of the relation, then check if it does not have join table too // if (relation.hasInverseSide && relation.inverseRelation.joinTable) // throw new UsingJoinTableOnlyOnOneSideAllowedError(entityMetadata, relation); // } // check join columns: // using JoinColumn is possible only on one side of the relation and on one-to-one, many-to-one relation types // first check if relation is one-to-one or many-to-one // todo(dima): fix /*if (relation.joinColumn) { // join column can be applied only on one-to-one and many-to-one relations if (!relation.isOneToOne && !relation.isManyToOne) throw new UsingJoinColumnIsNotAllowedError(entityMetadata, relation); // if there is inverse side of the relation, then check if it does not have join table too if (relation.hasInverseSide && relation.inverseRelation.joinColumn && relation.isOneToOne) throw new UsingJoinColumnOnlyOnOneSideAllowedError(entityMetadata, relation); // check if join column really has referenced column if (relation.joinColumn && !relation.joinColumn.referencedColumn) throw new Error(`Join column does not have referenced column set`); } // if its a one-to-one relation and JoinColumn is missing on both sides of the relation // or its one-side relation without JoinColumn we should give an error if (!relation.joinColumn && relation.isOneToOne && (!relation.hasInverseSide || !relation.inverseRelation.joinColumn)) throw new MissingJoinColumnError(entityMetadata, relation);*/ // if its a many-to-many relation and JoinTable is missing on both sides of the relation // or its one-side relation without JoinTable we should give an error // todo(dima): fix it // if (!relation.joinTable && relation.isManyToMany && (!relation.hasInverseSide || !relation.inverseRelation.joinTable)) // throw new MissingJoinTableError(entityMetadata, relation); // todo: validate if its one-to-one and side which does not have join column MUST have inverse side // todo: validate if its many-to-many and side which does not have join table MUST have inverse side // todo: if there is a relation, and inverse side is specified only on one side, shall we give error // todo: with message like: "Inverse side is specified only on one side of the relationship. Specify on other side too to prevent confusion". // todo: add validation if there two entities with the same target, and show error message with description of the problem (maybe file was renamed/moved but left in output directory) // todo: check if there are multiple columns on the same column applied. // todo: check column type if is missing in relational databases (throw new Error(`Column type of ${type} cannot be determined.`);) // todo: include driver-specific checks. for example in mongodb empty prefixes are not allowed // todo: if multiple columns with same name - throw exception, including cases when columns are in embeds with same prefixes or without prefix at all // todo: if multiple primary key used, at least one of them must be unique or @Index decorator must be set on entity // todo: check if entity with duplicate names, some decorators exist }); // make sure cascade remove is not set for both sides of relationships (can be set in OneToOne decorators) entityMetadata.relations.forEach(relation => { const isCircularCascadeRemove = relation.isCascadeRemove && relation.inverseRelation && relation.inverseRelation!.isCascadeRemove; if (isCircularCascadeRemove) throw new Error(`Relation ${entityMetadata.name}#${relation.propertyName} and ${relation.inverseRelation!.entityMetadata.name}#${relation.inverseRelation!.propertyName} both has cascade remove set. ` + `This may lead to unexpected circular removals. Please set cascade remove only from one side of relationship.`); }); // todo: maybe better just deny removal from one to one relation without join column? entityMetadata.eagerRelations.forEach(relation => { }); } /** * Validates dependencies of the entity metadatas. */ protected validateDependencies(entityMetadatas: EntityMetadata[]) { const graph = new DepGraph(); entityMetadatas.forEach(entityMetadata => { graph.addNode(entityMetadata.name); }); entityMetadatas.forEach(entityMetadata => { entityMetadata.relationsWithJoinColumns .filter(relation => !relation.isNullable) .forEach(relation => { graph.addDependency(entityMetadata.name, relation.inverseEntityMetadata.name); }); }); try { graph.overallOrder(); } catch (err) { throw new CircularRelationsError(err.toString().replace("Error: Dependency Cycle Found: ", "")); } } /** * Validates eager relations to prevent circular dependency in them. */ protected validateEagerRelations(entityMetadatas: EntityMetadata[]) { entityMetadatas.forEach(entityMetadata => { entityMetadata.eagerRelations.forEach(relation => { if (relation.inverseRelation && relation.inverseRelation.isEager) throw new Error(`Circular eager relations are disallowed. ` + `${entityMetadata.targetName}#${relation.propertyPath} contains "eager: true", and its inverse side ` + `${relation.inverseEntityMetadata.targetName}#${relation.inverseRelation.propertyPath} contains "eager: true" as well.` + ` Remove "eager: true" from one side of the relation.`); }); }); } }
the_stack
import { OrderErrorCode, AddressTypeEnum, GiftCardEventsEnum, OrderDiscountType, DiscountValueTypeEnum, OrderEventsEmailsEnum, OrderEventsEnum, FulfillmentStatus, PaymentChargeStatusEnum, WarehouseClickAndCollectOptionEnum, OrderStatus, OrderAction, JobStatusEnum } from "./../../types/globalTypes"; // ==================================================== // GraphQL mutation operation: OrderConfirm // ==================================================== export interface OrderConfirm_orderConfirm_errors { __typename: "OrderError"; code: OrderErrorCode; field: string | null; addressType: AddressTypeEnum | null; } export interface OrderConfirm_orderConfirm_order_metadata { __typename: "MetadataItem"; key: string; value: string; } export interface OrderConfirm_orderConfirm_order_privateMetadata { __typename: "MetadataItem"; key: string; value: string; } export interface OrderConfirm_orderConfirm_order_billingAddress_country { __typename: "CountryDisplay"; code: string; country: string; } export interface OrderConfirm_orderConfirm_order_billingAddress { __typename: "Address"; city: string; cityArea: string; companyName: string; country: OrderConfirm_orderConfirm_order_billingAddress_country; countryArea: string; firstName: string; id: string; lastName: string; phone: string | null; postalCode: string; streetAddress1: string; streetAddress2: string; } export interface OrderConfirm_orderConfirm_order_giftCards_events_balance_initialBalance { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_giftCards_events_balance_currentBalance { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_giftCards_events_balance_oldInitialBalance { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_giftCards_events_balance_oldCurrentBalance { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_giftCards_events_balance { __typename: "GiftCardEventBalance"; initialBalance: OrderConfirm_orderConfirm_order_giftCards_events_balance_initialBalance | null; currentBalance: OrderConfirm_orderConfirm_order_giftCards_events_balance_currentBalance; oldInitialBalance: OrderConfirm_orderConfirm_order_giftCards_events_balance_oldInitialBalance | null; oldCurrentBalance: OrderConfirm_orderConfirm_order_giftCards_events_balance_oldCurrentBalance | null; } export interface OrderConfirm_orderConfirm_order_giftCards_events { __typename: "GiftCardEvent"; id: string; type: GiftCardEventsEnum | null; orderId: string | null; balance: OrderConfirm_orderConfirm_order_giftCards_events_balance | null; } export interface OrderConfirm_orderConfirm_order_giftCards { __typename: "GiftCard"; events: OrderConfirm_orderConfirm_order_giftCards_events[]; } export interface OrderConfirm_orderConfirm_order_discounts_amount { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_discounts { __typename: "OrderDiscount"; id: string; type: OrderDiscountType; calculationMode: DiscountValueTypeEnum; value: any; reason: string | null; amount: OrderConfirm_orderConfirm_order_discounts_amount; } export interface OrderConfirm_orderConfirm_order_events_discount_amount { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_events_discount_oldAmount { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_events_discount { __typename: "OrderEventDiscountObject"; valueType: DiscountValueTypeEnum; value: any; reason: string | null; amount: OrderConfirm_orderConfirm_order_events_discount_amount | null; oldValueType: DiscountValueTypeEnum | null; oldValue: any | null; oldAmount: OrderConfirm_orderConfirm_order_events_discount_oldAmount | null; } export interface OrderConfirm_orderConfirm_order_events_relatedOrder { __typename: "Order"; id: string; number: string | null; } export interface OrderConfirm_orderConfirm_order_events_user { __typename: "User"; id: string; email: string; firstName: string; lastName: string; } export interface OrderConfirm_orderConfirm_order_events_app { __typename: "App"; id: string; name: string | null; appUrl: string | null; } export interface OrderConfirm_orderConfirm_order_events_lines_discount_amount { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_events_lines_discount_oldAmount { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_events_lines_discount { __typename: "OrderEventDiscountObject"; valueType: DiscountValueTypeEnum; value: any; reason: string | null; amount: OrderConfirm_orderConfirm_order_events_lines_discount_amount | null; oldValueType: DiscountValueTypeEnum | null; oldValue: any | null; oldAmount: OrderConfirm_orderConfirm_order_events_lines_discount_oldAmount | null; } export interface OrderConfirm_orderConfirm_order_events_lines_orderLine { __typename: "OrderLine"; id: string; productName: string; variantName: string; } export interface OrderConfirm_orderConfirm_order_events_lines { __typename: "OrderEventOrderLineObject"; quantity: number | null; itemName: string | null; discount: OrderConfirm_orderConfirm_order_events_lines_discount | null; orderLine: OrderConfirm_orderConfirm_order_events_lines_orderLine | null; } export interface OrderConfirm_orderConfirm_order_events { __typename: "OrderEvent"; id: string; amount: number | null; shippingCostsIncluded: boolean | null; date: any | null; email: string | null; emailType: OrderEventsEmailsEnum | null; invoiceNumber: string | null; discount: OrderConfirm_orderConfirm_order_events_discount | null; relatedOrder: OrderConfirm_orderConfirm_order_events_relatedOrder | null; message: string | null; quantity: number | null; transactionReference: string | null; type: OrderEventsEnum | null; user: OrderConfirm_orderConfirm_order_events_user | null; app: OrderConfirm_orderConfirm_order_events_app | null; lines: (OrderConfirm_orderConfirm_order_events_lines | null)[] | null; } export interface OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_variant_preorder { __typename: "PreorderData"; endDate: any | null; } export interface OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_variant { __typename: "ProductVariant"; id: string; quantityAvailable: number; preorder: OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_variant_preorder | null; } export interface OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_unitDiscount { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_undiscountedUnitPrice_gross { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_undiscountedUnitPrice_net { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_undiscountedUnitPrice { __typename: "TaxedMoney"; currency: string; gross: OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_undiscountedUnitPrice_gross; net: OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_undiscountedUnitPrice_net; } export interface OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_unitPrice_gross { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_unitPrice_net { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_unitPrice { __typename: "TaxedMoney"; gross: OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_unitPrice_gross; net: OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_unitPrice_net; } export interface OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_thumbnail { __typename: "Image"; url: string; } export interface OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine { __typename: "OrderLine"; id: string; isShippingRequired: boolean; variant: OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_variant | null; productName: string; productSku: string | null; quantity: number; quantityFulfilled: number; quantityToFulfill: number; unitDiscount: OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_unitDiscount; unitDiscountValue: any; unitDiscountReason: string | null; unitDiscountType: DiscountValueTypeEnum | null; undiscountedUnitPrice: OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_undiscountedUnitPrice; unitPrice: OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_unitPrice; thumbnail: OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine_thumbnail | null; } export interface OrderConfirm_orderConfirm_order_fulfillments_lines { __typename: "FulfillmentLine"; id: string; quantity: number; orderLine: OrderConfirm_orderConfirm_order_fulfillments_lines_orderLine | null; } export interface OrderConfirm_orderConfirm_order_fulfillments_warehouse { __typename: "Warehouse"; id: string; name: string; } export interface OrderConfirm_orderConfirm_order_fulfillments { __typename: "Fulfillment"; id: string; lines: (OrderConfirm_orderConfirm_order_fulfillments_lines | null)[] | null; fulfillmentOrder: number; status: FulfillmentStatus; trackingNumber: string; warehouse: OrderConfirm_orderConfirm_order_fulfillments_warehouse | null; } export interface OrderConfirm_orderConfirm_order_lines_variant_preorder { __typename: "PreorderData"; endDate: any | null; } export interface OrderConfirm_orderConfirm_order_lines_variant { __typename: "ProductVariant"; id: string; quantityAvailable: number; preorder: OrderConfirm_orderConfirm_order_lines_variant_preorder | null; } export interface OrderConfirm_orderConfirm_order_lines_unitDiscount { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_lines_undiscountedUnitPrice_gross { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_lines_undiscountedUnitPrice_net { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_lines_undiscountedUnitPrice { __typename: "TaxedMoney"; currency: string; gross: OrderConfirm_orderConfirm_order_lines_undiscountedUnitPrice_gross; net: OrderConfirm_orderConfirm_order_lines_undiscountedUnitPrice_net; } export interface OrderConfirm_orderConfirm_order_lines_unitPrice_gross { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_lines_unitPrice_net { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_lines_unitPrice { __typename: "TaxedMoney"; gross: OrderConfirm_orderConfirm_order_lines_unitPrice_gross; net: OrderConfirm_orderConfirm_order_lines_unitPrice_net; } export interface OrderConfirm_orderConfirm_order_lines_thumbnail { __typename: "Image"; url: string; } export interface OrderConfirm_orderConfirm_order_lines { __typename: "OrderLine"; id: string; isShippingRequired: boolean; variant: OrderConfirm_orderConfirm_order_lines_variant | null; productName: string; productSku: string | null; quantity: number; quantityFulfilled: number; quantityToFulfill: number; unitDiscount: OrderConfirm_orderConfirm_order_lines_unitDiscount; unitDiscountValue: any; unitDiscountReason: string | null; unitDiscountType: DiscountValueTypeEnum | null; undiscountedUnitPrice: OrderConfirm_orderConfirm_order_lines_undiscountedUnitPrice; unitPrice: OrderConfirm_orderConfirm_order_lines_unitPrice; thumbnail: OrderConfirm_orderConfirm_order_lines_thumbnail | null; } export interface OrderConfirm_orderConfirm_order_shippingAddress_country { __typename: "CountryDisplay"; code: string; country: string; } export interface OrderConfirm_orderConfirm_order_shippingAddress { __typename: "Address"; city: string; cityArea: string; companyName: string; country: OrderConfirm_orderConfirm_order_shippingAddress_country; countryArea: string; firstName: string; id: string; lastName: string; phone: string | null; postalCode: string; streetAddress1: string; streetAddress2: string; } export interface OrderConfirm_orderConfirm_order_deliveryMethod_ShippingMethod { __typename: "ShippingMethod"; id: string; } export interface OrderConfirm_orderConfirm_order_deliveryMethod_Warehouse { __typename: "Warehouse"; id: string; clickAndCollectOption: WarehouseClickAndCollectOptionEnum; } export type OrderConfirm_orderConfirm_order_deliveryMethod = OrderConfirm_orderConfirm_order_deliveryMethod_ShippingMethod | OrderConfirm_orderConfirm_order_deliveryMethod_Warehouse; export interface OrderConfirm_orderConfirm_order_shippingMethod { __typename: "ShippingMethod"; id: string; } export interface OrderConfirm_orderConfirm_order_shippingPrice_gross { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_shippingPrice { __typename: "TaxedMoney"; gross: OrderConfirm_orderConfirm_order_shippingPrice_gross; } export interface OrderConfirm_orderConfirm_order_subtotal_gross { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_subtotal_net { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_subtotal { __typename: "TaxedMoney"; gross: OrderConfirm_orderConfirm_order_subtotal_gross; net: OrderConfirm_orderConfirm_order_subtotal_net; } export interface OrderConfirm_orderConfirm_order_total_gross { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_total_net { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_total_tax { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_total { __typename: "TaxedMoney"; gross: OrderConfirm_orderConfirm_order_total_gross; net: OrderConfirm_orderConfirm_order_total_net; tax: OrderConfirm_orderConfirm_order_total_tax; } export interface OrderConfirm_orderConfirm_order_totalAuthorized { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_totalCaptured { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_undiscountedTotal_net { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_undiscountedTotal_gross { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_undiscountedTotal { __typename: "TaxedMoney"; net: OrderConfirm_orderConfirm_order_undiscountedTotal_net; gross: OrderConfirm_orderConfirm_order_undiscountedTotal_gross; } export interface OrderConfirm_orderConfirm_order_user { __typename: "User"; id: string; email: string; } export interface OrderConfirm_orderConfirm_order_availableShippingMethods_price { __typename: "Money"; amount: number; currency: string; } export interface OrderConfirm_orderConfirm_order_availableShippingMethods { __typename: "ShippingMethod"; id: string; name: string; price: OrderConfirm_orderConfirm_order_availableShippingMethods_price | null; } export interface OrderConfirm_orderConfirm_order_invoices { __typename: "Invoice"; id: string; number: string | null; createdAt: any; url: string | null; status: JobStatusEnum; } export interface OrderConfirm_orderConfirm_order_channel { __typename: "Channel"; isActive: boolean; id: string; name: string; currencyCode: string; slug: string; } export interface OrderConfirm_orderConfirm_order { __typename: "Order"; id: string; metadata: (OrderConfirm_orderConfirm_order_metadata | null)[]; privateMetadata: (OrderConfirm_orderConfirm_order_privateMetadata | null)[]; billingAddress: OrderConfirm_orderConfirm_order_billingAddress | null; giftCards: (OrderConfirm_orderConfirm_order_giftCards | null)[] | null; isShippingRequired: boolean; canFinalize: boolean; created: any; customerNote: string; discounts: OrderConfirm_orderConfirm_order_discounts[] | null; events: (OrderConfirm_orderConfirm_order_events | null)[] | null; fulfillments: (OrderConfirm_orderConfirm_order_fulfillments | null)[]; lines: (OrderConfirm_orderConfirm_order_lines | null)[]; number: string | null; isPaid: boolean; paymentStatus: PaymentChargeStatusEnum; shippingAddress: OrderConfirm_orderConfirm_order_shippingAddress | null; deliveryMethod: OrderConfirm_orderConfirm_order_deliveryMethod | null; shippingMethod: OrderConfirm_orderConfirm_order_shippingMethod | null; shippingMethodName: string | null; collectionPointName: string | null; shippingPrice: OrderConfirm_orderConfirm_order_shippingPrice; status: OrderStatus; subtotal: OrderConfirm_orderConfirm_order_subtotal; total: OrderConfirm_orderConfirm_order_total; actions: (OrderAction | null)[]; totalAuthorized: OrderConfirm_orderConfirm_order_totalAuthorized; totalCaptured: OrderConfirm_orderConfirm_order_totalCaptured; undiscountedTotal: OrderConfirm_orderConfirm_order_undiscountedTotal; user: OrderConfirm_orderConfirm_order_user | null; userEmail: string | null; availableShippingMethods: (OrderConfirm_orderConfirm_order_availableShippingMethods | null)[] | null; invoices: (OrderConfirm_orderConfirm_order_invoices | null)[] | null; channel: OrderConfirm_orderConfirm_order_channel; } export interface OrderConfirm_orderConfirm { __typename: "OrderConfirm"; errors: OrderConfirm_orderConfirm_errors[]; order: OrderConfirm_orderConfirm_order | null; } export interface OrderConfirm { orderConfirm: OrderConfirm_orderConfirm | null; } export interface OrderConfirmVariables { id: string; }
the_stack
import * as chalk from "chalk"; import { assert } from "node-opcua-assert"; import { NodeClass, QualifiedNameLike } from "node-opcua-data-model"; import { StructuredTypeSchema } from "node-opcua-factory"; import { AttributeIds } from "node-opcua-data-model"; import { DataValue, DataValueLike } from "node-opcua-data-value"; import { ExtensionObject } from "node-opcua-extension-object"; import { ExpandedNodeId, NodeId } from "node-opcua-nodeid"; import { NumericRange } from "node-opcua-numeric-range"; import { StatusCodes } from "node-opcua-status-code"; import { DataTypeDefinition, StructureDefinition, StructureField } from "node-opcua-types"; import { DataType } from "node-opcua-variant"; import { UAObject, ISessionContext, UADataType, UAVariable, BaseNode } from "node-opcua-address-space-base"; import { SessionContext } from "../source/session_context"; import { BaseNodeImpl } from "./base_node_impl"; import { BaseNode_References_toString, BaseNode_toString, ToStringBuilder, ToStringOption } from "./base_node_private"; import * as tools from "./tool_isSupertypeOf"; import { get_subtypeOf } from "./tool_isSupertypeOf"; import { get_subtypeOfObj } from "./tool_isSupertypeOf"; import { BaseNode_getCache } from "./base_node_private"; export type ExtensionObjectConstructor = new (options: any) => ExtensionObject; export interface ExtensionObjectConstructorFuncWithSchema extends ExtensionObjectConstructor { schema: StructuredTypeSchema; possibleFields: string[]; encodingDefaultBinary: ExpandedNodeId; encodingDefaultXml: ExpandedNodeId; } export interface UADataTypeImpl { _extensionObjectConstructor: ExtensionObjectConstructorFuncWithSchema; } export interface IEnumItem { name: string; value: number; } export interface EnumerationInfo { nameIndex: { [id: string]: IEnumItem }; valueIndex: { [id: number]: IEnumItem }; } function findBasicDataType(dataType: UADataType): DataType { if (dataType.nodeId.namespace === 0 && dataType.nodeId.value <= 25) { // we have a well-known DataType return dataType.nodeId.value as DataType; } return findBasicDataType(dataType.subtypeOfObj as UADataType); } export class UADataTypeImpl extends BaseNodeImpl implements UADataType { public readonly nodeClass = NodeClass.DataType; public readonly definitionName: string = ""; public readonly symbolicName: string; /** * returns true if this is a super type of baseType * * @example * * var dataTypeDouble = addressSpace.findDataType("Double"); * var dataTypeNumber = addressSpace.findDataType("Number"); * assert(dataTypeDouble.isSupertypeOf(dataTypeNumber)); * assert(!dataTypeNumber.isSupertypeOf(dataTypeDouble)); * */ public get subtypeOf(): NodeId | null { return get_subtypeOf.call(this); } public get subtypeOfObj(): UADataType | null { return get_subtypeOfObj.call(this) as any as UADataType; } public isSupertypeOf = tools.construct_isSupertypeOf<UADataType>(UADataTypeImpl); public readonly isAbstract: boolean; private enumStrings?: any; private enumValues?: any; private $definition?: DataTypeDefinition; private $fullDefinition?: DataTypeDefinition; constructor(options: any) { super(options); this.$definition = options.$definition; this.isAbstract = options.isAbstract === null ? false : options.isAbstract; this.symbolicName = options.symbolicName || this.browseName.name!; } public get basicDataType(): DataType { return findBasicDataType(this); } public readAttribute( context: ISessionContext | null, attributeId: AttributeIds, indexRange?: NumericRange, dataEncoding?: QualifiedNameLike | null ): DataValue { assert(!context || context instanceof SessionContext); const options: DataValueLike = {}; switch (attributeId) { case AttributeIds.IsAbstract: options.statusCode = StatusCodes.Good; options.value = { dataType: DataType.Boolean, value: !!this.isAbstract }; break; case AttributeIds.DataTypeDefinition: { const _definition = this._getDefinition(true); if (_definition !== null) { options.value = { dataType: DataType.ExtensionObject, value: _definition }; } else { options.statusCode = StatusCodes.BadAttributeIdInvalid; } } break; default: return super.readAttribute(context, attributeId, indexRange, dataEncoding); } return new DataValue(options); } public getEncodingDefinition(encoding_name: string): string | null { const encodingNode = this.getEncodingNode(encoding_name); if (!encodingNode) { throw new Error("Cannot find Encoding for " + encoding_name); } const indexRange = new NumericRange(); const descriptionNodeRef = encodingNode.findReferences("HasDescription")[0]!; const descriptionNode = this.addressSpace.findNode(descriptionNodeRef.nodeId) as UAVariable; if (!descriptionNode) { return null; } const dataValue = descriptionNode.readValue(SessionContext.defaultContext, indexRange); return dataValue.value.value.toString() || null; } public getEncodingNode(encoding_name: string): UAObject | null { const _cache = BaseNode_getCache(this); const key = encoding_name + "Node"; if (_cache[key] === undefined) { assert(encoding_name === "Default Binary" || encoding_name === "Default XML" || encoding_name === "Default JSON"); // could be binary or xml const refs = this.findReferences("HasEncoding", true); const addressSpace = this.addressSpace; const encoding = refs .map((ref) => addressSpace.findNode(ref.nodeId)) .filter((obj: any) => obj !== null) .filter((obj: any) => obj.browseName.toString() === encoding_name); const node = encoding.length === 0 ? null : (encoding[0] as UAObject); _cache[key] = node; } return _cache[key]; } public getEncodingNodeId(encoding_name: string): ExpandedNodeId | null { const _cache = BaseNode_getCache(this); const key = encoding_name + "NodeId"; if (_cache[key] === undefined) { const encoding = this.getEncodingNode(encoding_name); if (encoding) { const namespaceUri = this.addressSpace.getNamespaceUri(encoding.nodeId.namespace); _cache[key] = ExpandedNodeId.fromNodeId(encoding.nodeId, namespaceUri); } else { _cache[key] = null; } } return _cache[key]; } /** * returns the encoding of this node's * TODO objects have 2 encodings : XML and Binaries */ public get binaryEncoding(): BaseNode | null { return this.getEncodingNode("Default Binary"); } public get binaryEncodingDefinition(): string | null { return this.getEncodingDefinition("Default Binary"); } public get binaryEncodingNodeId(): ExpandedNodeId | null { return this.getEncodingNodeId("Default Binary"); } public get xmlEncoding(): BaseNode | null { return this.getEncodingNode("Default XML"); } public get xmlEncodingNodeId(): ExpandedNodeId | null { return this.getEncodingNodeId("Default XML"); } public get xmlEncodingDefinition(): string | null { return this.getEncodingDefinition("Default XML"); } public get jsonEncoding(): BaseNode | null { return this.getEncodingNode("Default JSON"); } public get jsonEncodingNodeId(): ExpandedNodeId | null { return this.getEncodingNodeId("Default JSON"); } // public get jsonEncodingDefinition(): string | null { // return this.getEncodingDefinition("Default JSON"); // } public _getEnumerationInfo(): EnumerationInfo { let definition = []; if (this.enumStrings) { const enumStrings = this.enumStrings.readValue().value.value; assert(Array.isArray(enumStrings)); definition = enumStrings.map((e: any, index: number) => { return { name: e.text, value: index }; }); } else if (this.enumValues) { assert(this.enumValues, "must have a enumValues property"); const enumValues = this.enumValues.readValue().value.value; assert(Array.isArray(enumValues)); definition = enumValues.map((e: any) => { return { name: e.displayName.text, value: e.value[1] }; }); } // construct nameIndex and valueIndex const indexes: EnumerationInfo = { nameIndex: {}, valueIndex: {} }; for (const e of definition) { indexes.nameIndex[e.name] = e; indexes.valueIndex[e.value] = e; } return indexes; } public _getDefinition(mergeWithBase: boolean): DataTypeDefinition | null { if (this.$fullDefinition !== undefined) { return mergeWithBase ? this.$fullDefinition : this.$definition!; } if (!this.$definition) { const structure = this.addressSpace.findDataType("Structure")!; if (!structure) { return null; } if (this.isSupertypeOf(structure)) { // <Definition> tag was missing in XML file as it was empty this.$definition = new StructureDefinition({}); } } // https://reference.opcfoundation.org/v104/Core/docs/Part3/8.49/#Table34 // The list of fields that make up the data type. // This definition assumes the structure has a sequential layout. // The StructureField DataType is defined in 8.51. // For Structures derived from another Structure DataType this list shall begin with the fields // of the baseDataType followed by the fields of this StructureDefinition. // from OPC Unified Architecture, Part 6 86 Release 1.04 // A DataTypeDefinition defines an abstract representation of _a UADataType that can be used by // design tools to automatically create serialization code. The fields in the DataTypeDefinition type // are defined in Table F.12. const _definition = this.$definition || null; if (_definition && _definition instanceof StructureDefinition && this.binaryEncodingNodeId) { _definition.defaultEncodingId = this.binaryEncodingNodeId!; const subtype = this.subtypeOf; if (subtype) { _definition.baseDataType = subtype; } } this.$fullDefinition = this.$definition?.clone(); let _baseDefinition: DataTypeDefinition | null = null; if (this.subtypeOfObj) { _baseDefinition = (this.subtypeOfObj as UADataTypeImpl)._getDefinition(mergeWithBase); } if (this.$fullDefinition && this.$definition instanceof StructureDefinition && _baseDefinition) { const b = _baseDefinition as StructureDefinition; if (b.fields?.length) { const f = this.$fullDefinition as StructureDefinition; f.fields = (<StructureField[]>[]).concat(b.fields!, f.fields!); } } return mergeWithBase ? this.$fullDefinition || null : this.$definition || null; } public getDefinition(): DataTypeDefinition { const d = this._getDefinition(true); if (!d) { throw new Error("DataType has no definition property"); } return d; } public install_extra_properties(): void { // } public toString(): string { const options = new ToStringBuilder(); DataType_toString.call(this, options); return options.toString(); } } function dataTypeDefinition_toString(this: UADataTypeImpl, options: ToStringOption) { const definition = this._getDefinition(false); if (!definition) { return; } const output = definition.toString(); options.add(options.padding + chalk.yellow(" Definition : ")); for (const str of output.split("\n")) { options.add(options.padding + chalk.yellow(" : " + str)); } } export function DataType_toString(this: UADataTypeImpl, options: ToStringOption): void { BaseNode_toString.call(this, options); options.add(options.padding + chalk.yellow(" isAbstract : " + this.isAbstract)); options.add(options.padding + chalk.yellow(" definitionName : " + this.definitionName)); options.add( options.padding + chalk.yellow(" binaryEncodingNodeId: ") + (this.binaryEncodingNodeId ? this.binaryEncodingNodeId.toString() : "<none>") ); options.add( options.padding + chalk.yellow(" xmlEncodingNodeId : ") + (this.xmlEncodingNodeId ? this.xmlEncodingNodeId.toString() : "<none>") ); if (this.subtypeOfObj) { options.add( options.padding + chalk.yellow(" subtypeOfObj : ") + (this.subtypeOfObj ? this.subtypeOfObj.browseName.toString() : "") ); } // references BaseNode_References_toString.call(this, options); dataTypeDefinition_toString.call(this, options); }
the_stack
import rule from "../../src/rules/ts-use-interface-parameters"; import { RuleTester } from "eslint"; //------------------------------------------------------------------------------ // Example class & interface //------------------------------------------------------------------------------ const example = `class A { message: string } interface B { message: string } interface B2 { message: B } interface B3 { message: A } interface B4 { message: A[] } interface B5 { message: Array<A> } `; //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ const ruleTester = new RuleTester({ parser: require.resolve("@typescript-eslint/parser"), parserOptions: { createDefaultProgram: true, project: "./tsconfig.json" } }); ruleTester.run("ts-use-interface-parameters", rule, { valid: [ // single parameter { // function declaration code: `${example}function func3(b: B): void { console.log(b); }`, filename: "src/test.ts" }, { // class method code: `${example}class C { method1(b: B): void { console.log(b); } }`, filename: "src/test.ts" }, // multiple parameters { // function declaration code: `${example}function func6(b1: B, b2: B): void { console.log(b); }`, filename: "src/test.ts" }, { // class method code: `${example}class C { method2(b1: B, b2: B): void { console.log(b); } }`, filename: "src/test.ts" }, // overloads { // class methods code: `${example}class C { overloadMethod(a: A): void { console.log(a); }; overloadMethod(b: B): void { console.log(b); }; }`, filename: "src/test.ts" }, { // function declaration code: `${example}function overloadDeclaration(a: A): void { console.log(a); }; function overloadDeclaration(b: B): void { console.log(b); }`, filename: "src/test.ts" }, // nested objects { // class methods code: `${example}class C { nestedMethod(b: B2): void { console.log(b); }; }`, filename: "src/test.ts" }, { // function declaration code: `${example}function nestedDeclaration(b: B2): void { console.log(b); }`, filename: "src/test.ts" }, // optional parameters { // class methods code: `${example}class C { nestedMethod(b: B, a?: A): void { console.log(b); a && console.log(a); }; }`, filename: "src/test.ts" }, { // function declaration code: `${example}function nestedDeclaration(b: B, a?: A): void { console.log(b); a && console.log(a); }`, filename: "src/test.ts" }, // array parameters [] { // class method code: `${example}class C { arrayMethod(b: B[]): void { console.log(b); }; }`, filename: "src/test.ts" }, { // function declaration code: `${example}function arrayDeclaration(b: B[]): void { console.log(b); }`, filename: "src/test.ts" }, // array parameters Array<> { // class method code: `${example}class C { array2Method(b: Array<B>): void { console.log(b); }; }`, filename: "src/test.ts" }, { // function declaration code: `${example}function array2Declaration(b: Array<B>): void { console.log(b); }`, filename: "src/test.ts" }, // private method { code: `${example}class { private pMethod(a: A): void { console.log(a); } }`, filename: "src/test.ts" }, // not in src { // function declaration code: `${example}function func3(a: A): void { console.log(a); }`, filename: "tests/test.ts" }, { // class method code: `${example}class C { method1(b: A): void { console.log(a); } }`, filename: "tests/test.ts" } ], invalid: [ // single parameter { // function declaration code: `${example}function func9(a: A): void { console.log(a); }`, filename: "src/test.ts", errors: [ { message: "type A of parameter a of function func9 is a class or contains a class as a member" } ] }, { // class method code: `${example}class { method3(a: A): void { console.log(a); } }`, filename: "src/test.ts", errors: [ { message: "type A of parameter a of function method3 is a class or contains a class as a member" } ] }, // one interface, one class { // function declaration code: `${example}function func12(a: A, b: B): void { console.log(a, b); }`, filename: "src/test.ts", errors: [ { message: "type A of parameter a of function func12 is a class or contains a class as a member" } ] }, { // class method code: `${example}class { method4(a: A, b: B): void { console.log(a, b); } }`, filename: "src/test.ts", errors: [ { message: "type A of parameter a of function method4 is a class or contains a class as a member" } ] }, // multiple classes { // function declaration code: `${example}function func15(a1: A, a2: A): void { console.log(a1, a2); }`, filename: "src/test.ts", errors: [ { message: "type A of parameter a1 of function func15 is a class or contains a class as a member" }, { message: "type A of parameter a2 of function func15 is a class or contains a class as a member" } ] }, { // class method code: `${example}class { method3(a1: A, a2: A): void { console.log(a1, a2); } }`, filename: "src/test.ts", errors: [ { message: "type A of parameter a1 of function method3 is a class or contains a class as a member" }, { message: "type A of parameter a2 of function method3 is a class or contains a class as a member" } ] }, // bad overloads { // class methods code: `${example}class C { overloadMethodBad(a: A): void { console.log(a); } overloadMethodBad(a1: A, a2: A): void { console.log(a1, a2); }; }`, filename: "src/test.ts", errors: [ { message: "type A of parameter a of function overloadMethodBad is a class or contains a class as a member" }, { message: "type A of parameter a1 of function overloadMethodBad is a class or contains a class as a member" }, { message: "type A of parameter a2 of function overloadMethodBad is a class or contains a class as a member" } ] }, { // function declaration code: `${example}function overloadDeclarationBad(a: A): void { console.log(a); } function overloadDeclarationBad(a1: A, a2: A): void { console.log(a1, a2); }`, filename: "src/test.ts", errors: [ { message: "type A of parameter a of function overloadDeclarationBad is a class or contains a class as a member" }, { message: "type A of parameter a1 of function overloadDeclarationBad is a class or contains a class as a member" }, { message: "type A of parameter a2 of function overloadDeclarationBad is a class or contains a class as a member" } ] }, // nested objects { // class methods code: `${example}class C { nestedMethodBad(b: B3): void { console.log(b); }; }`, filename: "src/test.ts", errors: [ { message: "type B3 of parameter b of function nestedMethodBad is a class or contains a class as a member" } ] }, { // function declaration code: `${example}function nestedDeclarationBad(b: B3): void { console.log(b); }`, filename: "src/test.ts", errors: [ { message: "type B3 of parameter b of function nestedDeclarationBad is a class or contains a class as a member" } ] }, { // Anonymous function export code: `${example} export default function(b: B3) : void { console.log(b); }`, filename: "src/tests.ts", errors: [ { message: "type B3 of parameter b of function <anonymous> is a class or contains a class as a member" } ] }, // array parameters [] { // class method code: `${example}class C { arrayMethodBad(a: A[]): void { console.log(a); }; }`, filename: "src/test.ts", errors: [ { message: "type A of parameter a of function arrayMethodBad is a class or contains a class as a member" } ] }, { // function declaration code: `${example}function arrayDeclarationBad(a: A[]): void { console.log(a); }`, filename: "src/test.ts", errors: [ { message: "type A of parameter a of function arrayDeclarationBad is a class or contains a class as a member" } ] }, // nested array parameters [] { // class method code: `${example}class C { nestedArrayMethodBad(a: B4): void { console.log(a); }; }`, filename: "src/test.ts", errors: [ { message: "type B4 of parameter a of function nestedArrayMethodBad is a class or contains a class as a member" } ] }, { // function declaration code: `${example}function nestedArrayDeclarationBad(a: B4): void { console.log(a); }`, filename: "src/test.ts", errors: [ { message: "type B4 of parameter a of function nestedArrayDeclarationBad is a class or contains a class as a member" } ] }, // array parameters Array<> { // class method code: `${example}class C { array2MethodBad(a: Array<A>): void { console.log(a); }; }`, filename: "src/test.ts", errors: [ { message: "type A of parameter a of function array2MethodBad is a class or contains a class as a member" } ] }, { // function declaration code: `${example}function array2DeclarationBad(a: Array<A>): void { console.log(a); }`, filename: "src/test.ts", errors: [ { message: "type A of parameter a of function array2DeclarationBad is a class or contains a class as a member" } ] }, // nested array parameters Array<> { // class method code: `${example}class C { nestedArray2MethodBad(a: B5): void { console.log(a); }; }`, filename: "src/test.ts", errors: [ { message: "type B5 of parameter a of function nestedArray2MethodBad is a class or contains a class as a member" } ] }, { // function declaration code: `${example}function nestedArray2DeclarationBad(a: B5): void { console.log(a); }`, filename: "src/test.ts", errors: [ { message: "type B5 of parameter a of function nestedArray2DeclarationBad is a class or contains a class as a member" } ] } ] });
the_stack
import { Canvas } from '@antv/g-canvas'; import { Shape, Node, Util } from '@antv/g6-core'; import { Graph, Global } from '../../../src'; import '../../../src'; import { IGroup } from '@antv/g-base'; const { translate } = Util; const div = document.createElement('div'); div.id = 'node-shape'; document.body.appendChild(div); const canvas = new Canvas({ container: 'node-shape', width: 500, height: 500, }); describe('shape node test', () => { describe('basic method test', () => { it('get factory', () => { const factory = Shape.getFactory('node'); expect(factory).not.toBe(undefined); }); it('get default', () => { const factory = Shape.getFactory('node'); const shape = factory.getShape(); expect(shape.type).toBe('circle'); }); }); describe('nodes test', () => { const factory = Shape.getFactory('node'); it('circle no label', () => { const group = canvas.addGroup(); translate(group, { x: 50, y: 50 }); const shape = factory.draw( 'circle', { size: 40, color: 'red', }, group, ); canvas.draw(); expect(shape.attr('r')).toBe(20); expect(group.getCount()).toBe(1); }); it('circle with label', () => { const group = canvas.addGroup(); translate(group, { x: 50, y: 100 }); factory.draw( 'circle', { size: 20, color: 'blue', label: '你好,我好,大家好', labelCfg: { position: 'top', }, }, group, ); canvas.draw(); expect(group.getCount()).toBe(2); }); it('rect', () => { const group = canvas.addGroup({ id: 'rect', }); translate(group, { x: 100, y: 100 }); const shape = factory.draw( 'rect', { size: [40, 20], color: 'yellow', label: 'rect', labelCfg: { style: { fill: 'white', }, }, style: { fill: 'red', }, }, group, ); canvas.draw(); expect(shape.attr('x')).toBe(-20); expect(shape.attr('y')).toBe(-10); const label = group.get('children')[1]; expect(label.attr('fill')).toBe('white'); expect(group.getCount()).toBe(2); }); it('image', () => { const group = canvas.addGroup(); translate(group, { x: 150, y: 100 }); const shape = factory.draw( 'image', { size: [40, 20], label: 'my custom image', type: 'image', img: 'https://img.alicdn.com/tfs/TB1_uT8a5ERMeJjSspiXXbZLFXa-143-59.png', }, group, ); canvas.draw(); expect(shape.attr('x')).toBe(-20); expect(shape.attr('y')).toBe(-10); expect(shape.attr('img')).not.toBe(undefined); const label = group.get('children')[1]; expect(label.attr('x')).toBe(0); expect(label.attr('y')).toBe(10 + Global.nodeLabel.offset); expect(group.getCount()).toBe(2); }); it('update', () => { const group = canvas.addGroup({ id: 'rect', }); // 伪造 item, 仅测试接口和图形的变化,不测试一致性 const item = new Node({ model: { size: [40, 20], color: 'yellow', type: 'rect', labelCfg: { style: { fill: 'white', }, }, style: { fill: 'red', }, }, group, }); factory.baseUpdate( 'rect', { size: [100, 50], style: { fill: 'red', }, }, item, ); const shape = group.get('children')[0]; expect(shape.attr('x')).toBe(-50); expect(shape.attr('y')).toBe(-25); expect(shape.attr('width')).toBe(100); expect(group.getCount()).toBe(1); factory.baseUpdate( 'rect', { size: [50, 30], style: { fill: 'red', }, label: 'new rect', }, item, ); expect(group.getCount()).toBe(2); const label = group.get('children')[1]; expect(label.attr('text')).toBe('new rect'); factory.baseUpdate( 'rect', { size: [50, 30], style: { fill: 'red', }, label: 'old rect', }, item, ); expect(label.attr('text')).toBe('old rect'); item.update({ style: { fill: 'steelblue', }, }); expect(shape.attr('fill')).toBe('steelblue'); canvas.draw(); }); it('active', () => { const rectGroup = canvas.findById('rect') as IGroup; // 伪造 item, 仅测试接口和图形的变化,不测试一致性 const item = new Node({ model: { id: 'rectnode', size: [40, 20], type: 'rect', stateStyles: { active: { fillOpacity: 0.8, }, }, }, group: rectGroup, }); const shape = rectGroup.get('children')[0]; expect(shape.attr('fillOpacity')).toBe(1); factory.setState('rectnode', 'active', true, item); expect(shape.attr('fillOpacity')).not.toBe(1); factory.setState('rectnode', 'active', false, item); expect(shape.attr('fillOpacity')).toBe(1); }); it('selected', () => { const group = canvas.addGroup({ id: 'rect', }); // 伪造 item, 仅测试接口和图形的变化,不测试一致性 const item = new Node({ model: { id: 'node', stateStyles: { selected: { lineWidth: 2, }, }, }, group, }); const shape = group.get('children')[0]; expect(shape.attr('lineWidth')).toBe(1); factory.setState('node', 'selected', true, item); expect(shape.attr('lineWidth')).toBe(2); factory.setState('node', 'selected', false, item); expect(shape.attr('lineWidth')).toBe(1); }); it('label position', () => { const group = canvas.addGroup(); translate(group, { x: 200, y: 200 }); const model = { size: [60, 20], color: 'green', label: 'ellipse position', labelCfg: { position: 'top', offset: 4, }, }; factory.draw('ellipse', model, group); // 伪造 item const item = new Node({ model, group, }); let label = group.get('children')[1]; expect(label.attr('x')).toBe(0); expect(label.attr('y')).toBe(-10 - Global.nodeLabel.offset); factory.baseUpdate( 'ellipse', { size: [60, 20], color: 'red', label: 'ellipse position', labelCfg: { position: 'left', }, }, item, ); label = group.get('children')[1]; expect(label.attr('y')).toBe(0); expect(label.attr('x')).toBe(-30 - Global.nodeLabel.offset); factory.baseUpdate( 'ellipse', { size: [60, 20], color: 'green', label: 'ellipse position', labelCfg: { position: 'right', }, }, item, ); expect(label.attr('y')).toBe(0); expect(label.attr('x')).toBe(30 + Global.nodeLabel.offset); factory.baseUpdate( 'ellipse', { size: [60, 20], color: 'green', label: 'ellipse position', labelCfg: { position: 'right', offset: 20, }, }, item, ); expect(label.attr('y')).toBe(0); expect(label.attr('x')).toBe(30 + 20); factory.baseUpdate( 'ellipse', { size: [60, 20], color: 'green', label: 'ellipse position', labelCfg: { position: 'right', offset: 0, }, }, item, ); expect(label.attr('y')).toBe(0); expect(label.attr('x')).toBe(30); canvas.draw(); }); it('clear', () => { canvas.destroy(); }); it('rect linkPoints update from show to hide', () => { const graph = new Graph({ container: div, width: 500, height: 500, }); const data = { nodes: [ { id: 'node', label: 'rect', linkPoints: { top: true, bottom: true, }, type: 'rect', x: 100, y: 200, }, ], }; graph.data(data); graph.render(); const node = graph.getNodes()[0]; const group = node.get('group'); // rect + label + linkPoints * 2 expect(group.getCount()).toEqual(4); node.update({ linkPoints: { top: false, }, }); const topPoint = group.find((g) => { return g.get('className') === 'link-point-top'; }); expect(topPoint).toBe(null); const bottomPoint = group.find((g) => { return g.get('className') === 'link-point-bottom'; }); expect(bottomPoint).not.toBe(null); node.update({ linkPoints: { left: true, right: true, size: 10, fill: '#f00', stroke: '#0f0', lineWidth: 2, }, }); const leftPoint = group.find((g) => { return g.get('className') === 'link-point-left'; }); expect(leftPoint).not.toBe(null); expect(leftPoint.attr('r')).toBe(5); expect(leftPoint.attr('fill')).toBe('#f00'); expect(leftPoint.attr('stroke')).toBe('#0f0'); expect(leftPoint.attr('lineWidth')).toBe(2); const rightPoint = group.find((g) => { return g.get('className') === 'link-point-right'; }); expect(rightPoint).not.toBe(null); node.update({ linkPoints: { left: false, top: true, size: 10, fill: '#f00', stroke: '#0f0', lineWidth: 2, }, }); const leftPoint2 = group.find((g) => { return g.get('className') === 'link-point-left'; }); expect(leftPoint2).toBe(null); const topPoint2 = group.find((g) => { return g.get('className') === 'link-point-top'; }); expect(topPoint2).not.toBe(null); const rightPoint2 = group.find((g) => { return g.get('className') === 'link-point-right'; }); expect(rightPoint2).not.toBe(null); node.update({ linkPoints: { stroke: '#000', }, }); const bottomPoint2 = group.find((g) => { return g.get('className') === 'link-point-bottom'; }); expect(bottomPoint2.attr('r')).toBe(5); expect(bottomPoint2.attr('fill')).toBe('#f00'); expect(bottomPoint2.attr('stroke')).toBe('#000'); graph.destroy(); expect(graph.destroyed).toBe(true); }); it('ellipse linkPoints update from show to hide', () => { const graph = new Graph({ container: div, width: 500, height: 500, }); const data = { nodes: [ { id: 'node', label: 'ellipse', linkPoints: { top: true, bottom: true, }, type: 'ellipse', x: 100, y: 200, }, ], }; graph.data(data); graph.render(); const node = graph.getNodes()[0]; const group = node.get('group'); // rect + label + linkPoints * 2 expect(group.getCount()).toEqual(4); node.update({ linkPoints: { top: false, }, }); const topPoint = group.find((g) => { return g.get('className') === 'link-point-top'; }); expect(topPoint).toBe(null); const bottomPoint = group.find((g) => { return g.get('className') === 'link-point-bottom'; }); expect(bottomPoint).not.toBe(null); node.update({ linkPoints: { left: true, right: true, size: 10, fill: '#f00', stroke: '#0f0', lineWidth: 2, }, }); const leftPoint = group.find((g) => { return g.get('className') === 'link-point-left'; }); expect(leftPoint).not.toBe(null); expect(leftPoint.attr('r')).toBe(5); expect(leftPoint.attr('fill')).toBe('#f00'); expect(leftPoint.attr('stroke')).toBe('#0f0'); expect(leftPoint.attr('lineWidth')).toBe(2); const rightPoint = group.find((g) => { return g.get('className') === 'link-point-right'; }); expect(rightPoint).not.toBe(null); node.update({ linkPoints: { left: false, top: true, size: 10, fill: '#f00', stroke: '#0f0', lineWidth: 2, }, }); const leftPoint2 = group.find((g) => { return g.get('className') === 'link-point-left'; }); expect(leftPoint2).toBe(null); const topPoint2 = group.find((g) => { return g.get('className') === 'link-point-top'; }); expect(topPoint2).not.toBe(null); const rightPoint2 = group.find((g) => { return g.get('className') === 'link-point-right'; }); expect(rightPoint2).not.toBe(null); node.update({ linkPoints: { stroke: '#000', }, }); const bottomPoint2 = group.find((g) => { return g.get('className') === 'link-point-bottom'; }); expect(bottomPoint2.attr('r')).toBe(5); expect(bottomPoint2.attr('fill')).toBe('#f00'); expect(bottomPoint2.attr('stroke')).toBe('#000'); graph.destroy(); expect(graph.destroyed).toBe(true); }); it('diamond linkPoints update from show to hide', () => { const graph = new Graph({ container: div, width: 500, height: 500, }); const data = { nodes: [ { id: 'node', label: 'diamond', linkPoints: { top: true, bottom: true, }, type: 'diamond', x: 100, y: 200, }, ], }; graph.data(data); graph.render(); const node = graph.getNodes()[0]; const group = node.get('group'); // rect + label + linkPoints * 2 expect(group.getCount()).toEqual(4); node.update({ linkPoints: { top: false, }, }); const topPoint = group.find((g) => { return g.get('className') === 'link-point-top'; }); expect(topPoint).toBe(null); const bottomPoint = group.find((g) => { return g.get('className') === 'link-point-bottom'; }); expect(bottomPoint).not.toBe(null); node.update({ linkPoints: { left: true, right: true, size: 10, fill: '#f00', stroke: '#0f0', lineWidth: 2, }, }); const leftPoint = group.find((g) => { return g.get('className') === 'link-point-left'; }); expect(leftPoint).not.toBe(null); expect(leftPoint.attr('r')).toBe(5); expect(leftPoint.attr('fill')).toBe('#f00'); expect(leftPoint.attr('stroke')).toBe('#0f0'); expect(leftPoint.attr('lineWidth')).toBe(2); const rightPoint = group.find((g) => { return g.get('className') === 'link-point-right'; }); expect(rightPoint).not.toBe(null); node.update({ linkPoints: { left: false, top: true, size: 10, fill: '#f00', stroke: '#0f0', lineWidth: 2, }, }); const leftPoint2 = group.find((g) => { return g.get('className') === 'link-point-left'; }); expect(leftPoint2).toBe(null); const topPoint2 = group.find((g) => { return g.get('className') === 'link-point-top'; }); expect(topPoint2).not.toBe(null); const rightPoint2 = group.find((g) => { return g.get('className') === 'link-point-right'; }); expect(rightPoint2).not.toBe(null); node.update({ linkPoints: { stroke: '#000', }, }); const bottomPoint2 = group.find((g) => { return g.get('className') === 'link-point-bottom'; }); expect(bottomPoint2.attr('r')).toBe(5); expect(bottomPoint2.attr('fill')).toBe('#f00'); expect(bottomPoint2.attr('stroke')).toBe('#000'); graph.destroy(); expect(graph.destroyed).toBe(true); }); it('circle linkPoints update from show to hide', () => { const graph = new Graph({ container: div, width: 500, height: 500, }); const data = { nodes: [ { id: 'node', label: 'circle', linkPoints: { top: true, bottom: true, }, type: 'circle', x: 100, y: 200, }, ], }; graph.data(data); graph.render(); const node = graph.getNodes()[0]; const group = node.get('group'); // rect + label + linkPoints * 2 expect(group.getCount()).toEqual(4); node.update({ linkPoints: { top: false, }, }); const topPoint = group.find((g) => { return g.get('className') === 'link-point-top'; }); expect(topPoint).toBe(null); const bottomPoint = group.find((g) => { return g.get('className') === 'link-point-bottom'; }); expect(bottomPoint).not.toBe(null); node.update({ linkPoints: { left: true, right: true, size: 10, fill: '#f00', stroke: '#0f0', lineWidth: 2, }, }); const leftPoint = group.find((g) => g.get('className') === 'link-point-left'); console.log('leftPoint', leftPoint, group); expect(leftPoint).not.toBe(null); expect(leftPoint.attr('r')).toBe(5); expect(leftPoint.attr('fill')).toBe('#f00'); expect(leftPoint.attr('stroke')).toBe('#0f0'); expect(leftPoint.attr('lineWidth')).toBe(2); const rightPoint = group.find((g) => { return g.get('className') === 'link-point-right'; }); expect(rightPoint).not.toBe(null); node.update({ linkPoints: { left: false, top: true, size: 10, fill: '#f00', stroke: '#0f0', lineWidth: 2, }, }); const leftPoint2 = group.find((g) => g.get('className') === 'link-point-left'); expect(leftPoint2).toBe(null); const topPoint2 = group.find((g) => g.get('className') === 'link-point-top'); expect(topPoint2).not.toBe(null); const rightPoint2 = group.find((g) => { return g.get('className') === 'link-point-right'; }); expect(rightPoint2).not.toBe(null); node.update({ linkPoints: { stroke: '#000', }, }); const bottomPoint2 = group.find((g) => { return g.get('className') === 'link-point-bottom'; }); expect(bottomPoint2.attr('r')).toBe(5); expect(bottomPoint2.attr('fill')).toBe('#f00'); expect(bottomPoint2.attr('stroke')).toBe('#000'); graph.destroy(); expect(graph.destroyed).toBe(true); }); }); });
the_stack