text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { BML } from "./interface/DOM"; import { Interpreter } from "./interpreter/interpreter"; import { Resources } from "./resource"; interface BMLEvent { type: string; target: HTMLElement | null; } type BMLObjectElement = HTMLObjectElement; interface BMLIntrinsicEvent extends BMLEvent { keyCode: number; } interface BMLBeventEvent extends BMLEvent { status: number; privateData: string; esRef: string; messageId: number; messageVersion: number; messageGroupId: number; moduleRef: string; languageTag: number; registerId: number; serviceId: number; eventId: number; peripheralRef: string; object: BMLObjectElement | null; segmentId: string | null; } // 同期割り込み事象キュー export type SyncFocusEvent = { type: "focus"; target: HTMLElement; }; export type SyncBlurEvent = { type: "blur"; target: HTMLElement; }; export type SyncClickEvent = { type: "click"; target: HTMLElement; }; export type SyncChangeEvent = { type: "change"; target: HTMLElement; }; export type SyncEvent = SyncFocusEvent | SyncBlurEvent | SyncClickEvent | SyncChangeEvent; export class EventDispatcher { private readonly eventQueue: EventQueue; private readonly bmlDocument: BML.BMLDocument; private readonly resources: Resources; public constructor(eventQueue: EventQueue, bmlDocument: BML.BMLDocument, resources: Resources) { this.eventQueue = eventQueue; this.bmlDocument = bmlDocument; this.resources = resources; } public setCurrentEvent(a: BMLEvent) { const { target: _, ...b } = a; const c = { target: BML.htmlElementToBMLHTMLElement(a.target, this.bmlDocument), ...b } this.bmlDocument._currentEvent = new BML.BMLEvent(c); } public setCurrentIntrinsicEvent(a: BMLIntrinsicEvent) { const { target: _, ...b } = a; const c = { target: BML.htmlElementToBMLHTMLElement(a.target, this.bmlDocument), ...b } this.bmlDocument._currentEvent = new BML.BMLIntrinsicEvent(c); } public setCurrentBeventEvent(ev: Partial<BMLBeventEvent> & BMLEvent) { const a: BMLBeventEvent = { ...{ target: null, status: 0, privateData: "", esRef: "", messageId: 0, messageVersion: 0, messageGroupId: 0, moduleRef: "", languageTag: 0, registerId: 0, serviceId: 0, eventId: 0, peripheralRef: "", object: null, segmentId: null, }, ...ev }; const { target: _1, object: _2, ...b } = a; const c = { target: BML.htmlElementToBMLHTMLElement(a.target, this.bmlDocument), object: BML.htmlElementToBMLHTMLElement(a.object, this.bmlDocument) as (BML.BMLObjectElement | null), ...b } this.bmlDocument._currentEvent = new BML.BMLBeventEvent(c); } public resetCurrentEvent() { this.bmlDocument._currentEvent = null; } public dispatchModuleLockedEvent(module: string, isEx: boolean, status: number) { console.log("ModuleLocked", module); const moduleLocked = (BML.bmlNodeToNode(this.bmlDocument.documentElement) as HTMLElement).querySelectorAll("beitem[type=\"ModuleLocked\"]"); const { componentId, moduleId } = this.resources.parseURLEx(module); for (const beitem of Array.from(moduleLocked)) { if (beitem.getAttribute("subscribe") !== "subscribe") { continue; } const moduleRef = beitem.getAttribute("module_ref"); const { componentId: refComponentId, moduleId: refModuleId } = this.resources.parseURLEx(moduleRef); if (componentId === refComponentId && moduleId == refModuleId) { const onoccur = beitem.getAttribute("onoccur"); if (onoccur) { this.eventQueue.queueAsyncEvent(async () => { this.setCurrentBeventEvent({ type: "ModuleLocked", target: beitem as HTMLElement, status, moduleRef: module, } as BMLBeventEvent); if (await this.eventQueue.executeEventHandler(onoccur)) { return true; } this.resetCurrentEvent(); return false; }); this.eventQueue.processEventQueue(); } } } } public dispatchTimerFiredEvent(status: number, beitem: Element) { console.log("TimerFired", status); if (beitem.getAttribute("subscribe") !== "subscribe") { return; } const onoccur = beitem.getAttribute("onoccur"); if (onoccur) { this.eventQueue.queueAsyncEvent(async () => { this.setCurrentBeventEvent({ type: "TimerFired", target: beitem as HTMLElement, status, }); if (await this.eventQueue.executeEventHandler(onoccur)) { return true; } this.resetCurrentEvent(); return false; }); this.eventQueue.processEventQueue(); } } public dispatchDataButtonPressedEvent() { console.log("DataButtonPressed"); const moduleLocked = (BML.bmlNodeToNode(this.bmlDocument.documentElement) as HTMLElement).querySelectorAll("beitem[type=\"DataButtonPressed\"]"); for (const beitem of Array.from(moduleLocked)) { if (beitem.getAttribute("subscribe") !== "subscribe") { continue; } const onoccur = beitem.getAttribute("onoccur"); if (onoccur) { this.eventQueue.queueAsyncEvent(async () => { this.setCurrentBeventEvent({ type: "DataButtonPressed", target: beitem as HTMLElement, status: 0, }); if (await this.eventQueue.executeEventHandler(onoccur)) { return true; } this.resetCurrentEvent(); return false; }); this.eventQueue.processEventQueue(); } } } async dispatchFocus(event: SyncFocusEvent): Promise<boolean> { this.setCurrentEvent({ type: "focus", target: event.target, } as BMLEvent); const handler = event.target.getAttribute("onfocus"); if (handler) { if (await this.eventQueue.executeEventHandler(handler)) { return true; } } this.resetCurrentEvent(); if (event.target instanceof HTMLInputElement) { // TR-B14 第二分冊 1.6.1 focus割り込み事象の発生の後、直ちに文字入力アプリを起動 if (event.target.getAttribute("inputmode") === "direct") { BML.nodeToBMLNode(event.target, this.bmlDocument).internalLaunchInputApplication(); } } return false; } async dispatchBlur(event: SyncBlurEvent): Promise<boolean> { this.setCurrentEvent({ type: "blur", target: event.target, } as BMLEvent); const handler = event.target.getAttribute("onblur"); if (handler) { if (await this.eventQueue.executeEventHandler(handler)) { return true; } } this.resetCurrentEvent(); return false; } async dispatchClick(event: SyncClickEvent): Promise<boolean> { this.setCurrentEvent({ type: "click", target: event.target, } as BMLEvent); const handler = event.target.getAttribute("onclick"); if (handler) { if (await this.eventQueue.executeEventHandler(handler)) { return true; } } this.resetCurrentEvent(); return false; } async dispatchChange(event: SyncChangeEvent): Promise<boolean> { this.setCurrentEvent({ type: "change", target: event.target, } as BMLEvent); const handler = event.target.getAttribute("onchange"); if (handler) { if (await this.eventQueue.executeEventHandler(handler)) { return true; } } this.resetCurrentEvent(); return false; } } type Timer = { handle: number | null, handler: TimerHandler, timeout: number, }; type BMLTimerID = number; export class EventQueue { private readonly interpreter: Interpreter; public dispatchFocus = (_event: SyncFocusEvent): Promise<boolean> => Promise.resolve(false); public dispatchBlur = (_event: SyncBlurEvent): Promise<boolean> => Promise.resolve(false); public dispatchClick = (_event: SyncClickEvent): Promise<boolean> => Promise.resolve(false); public dispatchChange = (_event: SyncChangeEvent): Promise<boolean> => Promise.resolve(false); public constructor(interpreter: Interpreter) { this.interpreter = interpreter; } public async executeEventHandler(handler: string): Promise<boolean> { if (/^\s*$/.exec(handler)) { return false; } const groups = /^\s*(?<funcName>[a-zA-Z_][0-9a-zA-Z_]*)\s*\(\s*\)\s*;?\s*$/.exec(handler)?.groups; if (!groups) { throw new Error("invalid event handler attribute " + handler); } console.debug("EXECUTE", handler); const result = await this.interpreter.runEventHandler(groups.funcName); console.debug("END", handler); return result; } private readonly timerHandles = new Map<BMLTimerID, Timer>(); public setInterval(handler: TimerHandler, timeout: number, ...args: any[]): BMLTimerID { const handle = window.setInterval(handler, timeout, ...args); this.timerHandles.set(handle, { handle, handler, timeout, }); return handle; } public pauseTimer(timerID: BMLTimerID): boolean { const timer = this.timerHandles.get(timerID); if (timer == null) { return false; } if (timer.handle != null) { window.clearInterval(timer.handle); timer.handle = null; } return true; } public resumeTimer(timerID: BMLTimerID): boolean { const timer = this.timerHandles.get(timerID); if (timer == null) { return false; } if (timer.handle == null) { timer.handle = window.setInterval(timer.handler, timer.timeout); } return true; } public clearInterval(timerID: BMLTimerID): boolean { const timer = this.timerHandles.get(timerID); if (timer == null) { return false; } if (timer.handle != null) { window.clearInterval(timer.handle); } this.timerHandles.delete(timerID); return true; } private asyncEventQueue: { callback: () => Promise<boolean>, local: boolean }[] = []; private syncEventQueue: SyncEvent[] = []; private syncEventQueueLockCount = 0; public async processEventQueue(): Promise<boolean> { if (this.discarded) { return false; } while (this.syncEventQueue.length || this.asyncEventQueue.length) { if (this.syncEventQueueLockCount) { return false; } if (this.syncEventQueue.length) { let exit = false; try { this.lockSyncEventQueue(); const event = this.syncEventQueue.shift(); if (event?.type === "focus") { if (exit = await this.dispatchFocus(event)) { return true; } } else if (event?.type === "blur") { if (exit = await this.dispatchBlur(event)) { return true; } } else if (event?.type === "click") { if (exit = await this.dispatchClick(event)) { return true; } } else if (event?.type === "change") { if (exit = await this.dispatchChange(event)) { return true; } } else { const _: never | undefined = event; } } finally { if (!exit) { this.unlockSyncEventQueue(); } } continue; } if (this.asyncEventQueue.length) { let exit = false; try { this.lockSyncEventQueue(); const event = this.asyncEventQueue.shift(); if (event != null) { exit = await event.callback(); if (exit) { return true; } } } finally { if (!exit) { this.unlockSyncEventQueue(); } } } } return false; } public queueSyncEvent(event: SyncEvent) { if (!this.discarded) { this.syncEventQueue.push(event); } } // タイマーイベントなど文書が変わったら無効になる非同期イベント public queueAsyncEvent(callback: () => Promise<boolean>) { if (!this.discarded) { this.asyncEventQueue.push({ callback, local: true }); } } public queueGlobalAsyncEvent(callback: () => Promise<boolean>) { this.asyncEventQueue.push({ callback, local: false }); } public lockSyncEventQueue() { this.syncEventQueueLockCount++; } public unlockSyncEventQueue() { this.syncEventQueueLockCount--; if (this.syncEventQueueLockCount < 0) { throw new Error("syncEventQueueLockCount < 0"); } } private discarded = false; // launchDocumentが呼び出されて読み込まれるまでの間イベントキューは無効になる public discard() { this.discarded = true; this.clear(); } private clear() { this.asyncEventQueue = this.asyncEventQueue.filter(x => !x.local); this.syncEventQueue.splice(0, this.syncEventQueue.length); for (const i of this.timerHandles.keys()) { this.clearInterval(i); } } public reset() { this.discarded = false; this.clear(); this.syncEventQueueLockCount = 0; } }
the_stack
import {ascending, extent, histogram as d3Histogram, ticks} from 'd3-array'; import keyMirror from 'keymirror'; import {console as Console} from 'global/console'; import get from 'lodash.get'; import isEqual from 'lodash.isequal'; import booleanWithin from '@turf/boolean-within'; import {point as turfPoint} from '@turf/helpers'; import {Decimal} from 'decimal.js'; import {ALL_FIELD_TYPES, FILTER_TYPES, ANIMATION_WINDOW} from 'constants/default-settings'; import {notNullorUndefined, unique, timeToUnixMilli} from './data-utils'; import * as ScaleUtils from './data-scale-utils'; import {LAYER_TYPES} from 'layers/types'; import {generateHashId, set, toArray} from './utils'; import {getCentroid, h3IsValid} from 'layers/h3-hexagon-layer/h3-utils'; import { Filter, FilterBase, PolygonFilter, Datasets, FieldDomain, TimeRangeFieldDomain, HistogramBin, Feature, FeatureValue, VisState, LineChart, TimeRangeFilter, RangeFieldDomain } from '../reducers/vis-state-updaters'; import KeplerTable, {Field, FilterRecord, FilterDatasetOpt} from './table-utils/kepler-table'; import {Layer} from 'layers'; import {ParsedFilter} from 'schemas'; import {DataContainerInterface} from './table-utils/data-container-interface'; import {Millisecond} from 'cloud-providers'; import {Entries} from 'reducers'; export type FilterResult = { filteredIndexForDomain?: number[]; filteredIndex?: number[]; }; export type FilterChanged = { [key in keyof FilterRecord]: { [key: string]: 'added' | 'deleted' | 'name_changed' | 'value_changed' | 'dataId_changed'; } | null; }; export type dataValueAccessor = (data: {index: number}) => number | null; export const TimestampStepMap = [ {max: 1, step: 0.05}, {max: 10, step: 0.1}, {max: 100, step: 1}, {max: 500, step: 5}, {max: 1000, step: 10}, {max: 5000, step: 50}, {max: Number.POSITIVE_INFINITY, step: 1000} ]; export const histogramBins = 30; export const enlargedHistogramBins = 100; const durationSecond = 1000; const durationMinute = durationSecond * 60; const durationHour = durationMinute * 60; const durationDay = durationHour * 24; const durationWeek = durationDay * 7; const durationYear = durationDay * 365; export const PLOT_TYPES = keyMirror({ histogram: null, lineChart: null }); export const FILTER_UPDATER_PROPS = keyMirror({ dataId: null, name: null, layerId: null }); export const LIMITED_FILTER_EFFECT_PROPS = keyMirror({ [FILTER_UPDATER_PROPS.name]: null }); /** * Max number of filter value buffers that deck.gl provides */ const SupportedPlotType = { [FILTER_TYPES.timeRange]: { default: 'histogram', [ALL_FIELD_TYPES.integer]: 'lineChart', [ALL_FIELD_TYPES.real]: 'lineChart' }, [FILTER_TYPES.range]: { default: 'histogram', [ALL_FIELD_TYPES.integer]: 'lineChart', [ALL_FIELD_TYPES.real]: 'lineChart' } }; export const FILTER_COMPONENTS = { [FILTER_TYPES.select]: 'SingleSelectFilter', [FILTER_TYPES.multiSelect]: 'MultiSelectFilter', [FILTER_TYPES.timeRange]: 'TimeRangeFilter', [FILTER_TYPES.range]: 'RangeFilter', [FILTER_TYPES.polygon]: 'PolygonFilter' }; export const DEFAULT_FILTER_STRUCTURE = { dataId: [], // [string] freeze: false, id: null, // time range filter specific fixedDomain: false, enlarged: false, isAnimating: false, animationWindow: ANIMATION_WINDOW.free, speed: 1, // field specific name: [], // string type: null, fieldIdx: [], // [integer] domain: null, value: null, // plot plotType: PLOT_TYPES.histogram, yAxis: null, interval: null, // mode gpu: false }; export const FILTER_ID_LENGTH = 4; export const LAYER_FILTERS = [FILTER_TYPES.polygon]; /** * Generates a filter with a dataset id as dataId */ export function getDefaultFilter(dataId: string | null | string[]): FilterBase { return { ...DEFAULT_FILTER_STRUCTURE, // store it as dataId and it could be one or many dataId: toArray(dataId), id: generateHashId(FILTER_ID_LENGTH) }; } /** * Check if a filter is valid based on the given dataId * @param filter to validate * @param datasetId id to validate filter against * @return true if a filter is valid, false otherwise */ export function shouldApplyFilter(filter: Filter, datasetId: string): boolean { const dataIds = toArray(filter.dataId); return dataIds.includes(datasetId) && filter.value !== null; } /** * Validates and modifies polygon filter structure * @param dataset * @param filter * @param layers * @return - {filter, dataset} */ export function validatePolygonFilter( dataset: KeplerTable, filter: PolygonFilter, layers: Layer[] ): {filter: PolygonFilter | null; dataset: KeplerTable} { const failed = {dataset, filter: null}; const {value, layerId, type, dataId} = filter; if (!layerId || !isValidFilterValue(type, value)) { return failed; } const isValidDataset = dataId.includes(dataset.id); if (!isValidDataset) { return failed; } const layer = layers.find(l => layerId.includes(l.id)); if (!layer) { return failed; } return { filter: { ...filter, freeze: true, fieldIdx: [] }, dataset }; } /** * Custom filter validators */ const filterValidators = { [FILTER_TYPES.polygon]: validatePolygonFilter }; /** * Default validate filter function * @param dataset * @param filter * @return - {filter, dataset} */ export function validateFilter( dataset: KeplerTable, filter: ParsedFilter ): {filter: Filter | null; dataset: KeplerTable} { // match filter.dataId const failed = {dataset, filter: null}; const filterDataId = toArray(filter.dataId); const filterDatasetIndex = filterDataId.indexOf(dataset.id); if (filterDatasetIndex < 0) { // the current filter is not mapped against the current dataset return failed; } // @ts-expect-error const initializeFilter: Filter = { // @ts-expect-error ...getDefaultFilter(filter.dataId), ...filter, dataId: filterDataId, name: toArray(filter.name) }; const fieldName = initializeFilter.name[filterDatasetIndex]; const {filter: updatedFilter, dataset: updatedDataset} = applyFilterFieldName( initializeFilter, dataset, fieldName, filterDatasetIndex, {mergeDomain: true} ); if (!updatedFilter) { return failed; } updatedFilter.value = adjustValueToFilterDomain(filter.value, updatedFilter); updatedFilter.enlarged = typeof filter.enlarged === 'boolean' ? filter.enlarged : updatedFilter.enlarged; if (updatedFilter.value === null) { // cannot adjust saved value to filter return failed; } return { filter: validateFilterYAxis(updatedFilter, updatedDataset), dataset: updatedDataset }; } /** * Validate saved filter config with new data, * calculate domain and fieldIdx based new fields and data * * @param dataset * @param filter - filter to be validate * @param layers - layers * @return validated filter */ export function validateFilterWithData( dataset: KeplerTable, filter: ParsedFilter, layers: Layer[] ): {filter: Filter; dataset: KeplerTable} { return filter.type && filterValidators.hasOwnProperty(filter.type) ? filterValidators[filter.type](dataset, filter, layers) : validateFilter(dataset, filter); } /** * Validate YAxis * @param filter * @param dataset * @return {*} */ function validateFilterYAxis(filter, dataset) { // TODO: validate yAxis against other datasets const {fields} = dataset; const {yAxis} = filter; // TODO: validate yAxis against other datasets if (yAxis) { const matchedAxis = fields.find(({name, type}) => name === yAxis.name && type === yAxis.type); filter = matchedAxis ? { ...filter, yAxis: matchedAxis, ...getFilterPlot({...filter, yAxis: matchedAxis}, dataset) } : filter; } return filter; } /** * Get default filter prop based on field type * * @param field * @param fieldDomain * @returns default filter */ export function getFilterProps( field: Field, fieldDomain: FieldDomain ): Partial<Filter> & {fieldType: string} { const filterProps = { ...fieldDomain, fieldType: field.type }; switch (field.type) { case ALL_FIELD_TYPES.real: case ALL_FIELD_TYPES.integer: return { ...filterProps, value: fieldDomain.domain, type: FILTER_TYPES.range, // @ts-expect-error typeOptions: [FILTER_TYPES.range], gpu: true }; case ALL_FIELD_TYPES.boolean: // @ts-expect-error return { ...filterProps, type: FILTER_TYPES.select, value: true, gpu: false }; case ALL_FIELD_TYPES.string: case ALL_FIELD_TYPES.date: // @ts-expect-error return { ...filterProps, type: FILTER_TYPES.multiSelect, value: [], gpu: false }; case ALL_FIELD_TYPES.timestamp: // @ts-expect-error return { ...filterProps, type: FILTER_TYPES.timeRange, enlarged: true, fixedDomain: true, value: filterProps.domain, gpu: true }; default: // @ts-expect-error return {}; } } export const getPolygonFilterFunctor = (layer, filter, dataContainer) => { const getPosition = layer.getPositionAccessor(dataContainer); switch (layer.type) { case LAYER_TYPES.point: case LAYER_TYPES.icon: return data => { const pos = getPosition(data); return pos.every(Number.isFinite) && isInPolygon(pos, filter.value); }; case LAYER_TYPES.arc: case LAYER_TYPES.line: return data => { const pos = getPosition(data); return ( pos.every(Number.isFinite) && [ [pos[0], pos[1]], [pos[3], pos[4]] ].every(point => isInPolygon(point, filter.value)) ); }; case LAYER_TYPES.hexagonId: if (layer.dataToFeature && layer.dataToFeature.centroids) { return data => { // null or getCentroid({id}) const centroid = layer.dataToFeature.centroids[data.index]; return centroid && isInPolygon(centroid, filter.value); }; } return data => { const id = getPosition(data); if (!h3IsValid(id)) { return false; } const pos = getCentroid({id}); return pos.every(Number.isFinite) && isInPolygon(pos, filter.value); }; default: return () => true; } }; /** * @param param An object that represents a row record. * @param param.index Index of the row in data container. * @returns Returns true to keep the element, or false otherwise. */ type filterFunction = (data: {index: number}) => boolean; /** * @param field dataset Field * @param dataId Dataset id * @param filter Filter object * @param layers list of layers to filter upon * @param dataContainer Data container * @return filterFunction */ export function getFilterFunction( field: Field | null, dataId: string, filter: Filter, layers: Layer[], dataContainer: DataContainerInterface ): filterFunction { // field could be null in polygon filter const valueAccessor = field ? field.valueAccessor : data => null; const defaultFunc = d => true; switch (filter.type) { case FILTER_TYPES.range: return data => isInRange(valueAccessor(data), filter.value); case FILTER_TYPES.multiSelect: return data => filter.value.includes(valueAccessor(data)); case FILTER_TYPES.select: return data => valueAccessor(data) === filter.value; case FILTER_TYPES.timeRange: if (!field) { return defaultFunc; } const mappedValue = get(field, ['filterProps', 'mappedValue']); const accessor = Array.isArray(mappedValue) ? data => mappedValue[data.index] : data => timeToUnixMilli(valueAccessor(data), field.format); return data => isInRange(accessor(data), filter.value); case FILTER_TYPES.polygon: if (!layers || !layers.length || !filter.layerId) { return defaultFunc; } const layerFilterFunctions = filter.layerId .map(id => layers.find(l => l.id === id)) .filter(l => l && l.config.dataId === dataId) .map(layer => getPolygonFilterFunctor(layer, filter, dataContainer)); return data => layerFilterFunctions.every(filterFunc => filterFunc(data)); default: return defaultFunc; } } export function updateFilterDataId(dataId: string): FilterBase { return getDefaultFilter(dataId); } export function filterDataByFilterTypes( { dynamicDomainFilters, cpuFilters, filterFuncs }: { dynamicDomainFilters: Filter[] | null; cpuFilters: Filter[] | null; filterFuncs: { [key: string]: filterFunction; }; }, dataContainer: DataContainerInterface ): FilterResult { const filteredIndexForDomain: number[] = []; const filteredIndex: number[] = []; const filterContext = {index: -1, dataContainer}; const filterFuncCaller = (filter: Filter) => filterFuncs[filter.id](filterContext); const numRows = dataContainer.numRows(); for (let i = 0; i < numRows; ++i) { filterContext.index = i; const matchForDomain = dynamicDomainFilters && dynamicDomainFilters.every(filterFuncCaller); if (matchForDomain) { filteredIndexForDomain.push(filterContext.index); } const matchForRender = cpuFilters && cpuFilters.every(filterFuncCaller); if (matchForRender) { filteredIndex.push(filterContext.index); } } return { ...(dynamicDomainFilters ? {filteredIndexForDomain} : {}), ...(cpuFilters ? {filteredIndex} : {}) }; } /** * Get a record of filters based on domain type and gpu / cpu */ export function getFilterRecord( dataId: string, filters: Filter[], opt: FilterDatasetOpt = {} ): FilterRecord { const filterRecord: FilterRecord = { dynamicDomain: [], fixedDomain: [], cpu: [], gpu: [] }; filters.forEach(f => { if (isValidFilterValue(f.type, f.value) && toArray(f.dataId).includes(dataId)) { (f.fixedDomain || opt.ignoreDomain ? filterRecord.fixedDomain : filterRecord.dynamicDomain ).push(f); (f.gpu && !opt.cpuOnly ? filterRecord.gpu : filterRecord.cpu).push(f); } }); return filterRecord; } /** * Compare filter records to get what has changed */ export function diffFilters( filterRecord: FilterRecord, oldFilterRecord: FilterRecord | {} = {} ): FilterChanged { let filterChanged: Partial<FilterChanged> = {}; (Object.entries(filterRecord) as Entries<FilterRecord>).forEach(([record, items]) => { items.forEach(filter => { const oldFilter: Filter = (oldFilterRecord[record] || []).find( (f: Filter) => f.id === filter.id ); if (!oldFilter) { // added filterChanged = set([record, filter.id], 'added', filterChanged); } else { // check what has changed ['name', 'value', 'dataId'].forEach(prop => { if (filter[prop] !== oldFilter[prop]) { filterChanged = set([record, filter.id], `${prop}_changed`, filterChanged); } }); } }); (oldFilterRecord[record] || []).forEach((oldFilter: Filter) => { // deleted if (!items.find(f => f.id === oldFilter.id)) { filterChanged = set([record, oldFilter.id], 'deleted', filterChanged); } }); }); return {...{dynamicDomain: null, fixedDomain: null, cpu: null, gpu: null}, ...filterChanged}; } /** * Call by parsing filters from URL * Check if value of filter within filter domain, if not adjust it to match * filter domain * * @returns value - adjusted value to match filter or null to remove filter */ /* eslint-disable complexity */ export function adjustValueToFilterDomain(value: Filter['value'], {domain, type}) { if (!domain || !type) { return false; } switch (type) { case FILTER_TYPES.range: case FILTER_TYPES.timeRange: if (!Array.isArray(value) || value.length !== 2) { return domain.map(d => d); } return value.map((d, i) => (notNullorUndefined(d) && isInRange(d, domain) ? d : domain[i])); case FILTER_TYPES.multiSelect: if (!Array.isArray(value)) { return []; } const filteredValue = value.filter(d => domain.includes(d)); return filteredValue.length ? filteredValue : []; case FILTER_TYPES.select: return domain.includes(value) ? value : true; default: return null; } } /* eslint-enable complexity */ /** * Calculate numeric domain and suitable step */ export function getNumericFieldDomain( dataContainer: DataContainerInterface, valueAccessor: dataValueAccessor ): RangeFieldDomain { let domain: [number, number] = [0, 1]; let step = 0.1; const mappedValue = dataContainer.mapIndex(valueAccessor); if (dataContainer.numRows() > 1) { domain = ScaleUtils.getLinearDomain(mappedValue); const diff = domain[1] - domain[0]; // in case equal domain, [96, 96], which will break quantize scale if (!diff) { domain[1] = domain[0] + 1; } step = getNumericStepSize(diff) || step; domain[0] = formatNumberByStep(domain[0], step, 'floor'); domain[1] = formatNumberByStep(domain[1], step, 'ceil'); } const {histogram, enlargedHistogram} = getHistogram(domain, mappedValue); return {domain, step, histogram, enlargedHistogram}; } /** * Calculate step size for range and timerange filter */ export function getNumericStepSize(diff: number): number { diff = Math.abs(diff); if (diff > 100) { return 1; } else if (diff > 3) { return 0.01; } else if (diff > 1) { return 0.001; } // Try to get at least 1000 steps - and keep the step size below that of // the (diff > 1) case. const x = diff / 1000; // Find the exponent and truncate to 10 to the power of that exponent const exponentialForm = x.toExponential(); const exponent = parseFloat(exponentialForm.split('e')[1]); // Getting ready for node 12 // this is why we need decimal.js // Math.pow(10, -5) = 0.000009999999999999999 // the above result shows in browser and node 10 // node 12 behaves correctly return new Decimal(10).pow(exponent).toNumber(); } /** * Calculate timestamp domain and suitable step */ export function getTimestampFieldDomain( dataContainer: DataContainerInterface, valueAccessor: dataValueAccessor ): TimeRangeFieldDomain { // to avoid converting string format time to epoch // every time we compare we store a value mapped to int in filter domain const mappedValue = dataContainer.mapIndex(valueAccessor); const domain = ScaleUtils.getLinearDomain(mappedValue); const defaultTimeFormat = getTimeWidgetTitleFormatter(domain); let step = 0.01; const diff = domain[1] - domain[0]; const entry = TimestampStepMap.find(f => f.max >= diff); if (entry) { step = entry.step; } const {histogram, enlargedHistogram} = getHistogram(domain, mappedValue); return { domain, step, mappedValue, histogram, enlargedHistogram, defaultTimeFormat }; } export function histogramConstruct( domain: [number, number], mappedValue: (Millisecond | number)[], bins: number ): HistogramBin[] { return d3Histogram() .thresholds(ticks(domain[0], domain[1], bins)) .domain(domain)(mappedValue) .map(bin => ({ count: bin.length, x0: bin.x0, x1: bin.x1 })); } /** * Calculate histogram from domain and array of values */ export function getHistogram( domain: [number, number], mappedValue: (Millisecond | number)[] ): {histogram: HistogramBin[]; enlargedHistogram: HistogramBin[]} { const histogram = histogramConstruct(domain, mappedValue, histogramBins); const enlargedHistogram = histogramConstruct(domain, mappedValue, enlargedHistogramBins); return {histogram, enlargedHistogram}; } /** * round number based on step * * @param {Number} val * @param {Number} step * @param {string} bound * @returns {Number} rounded number */ export function formatNumberByStep(val: number, step: number, bound: 'floor' | 'ceil'): number { if (bound === 'floor') { return Math.floor(val * (1 / step)) / (1 / step); } return Math.ceil(val * (1 / step)) / (1 / step); } export function isInRange(val: any, domain: number[]): boolean { if (!Array.isArray(domain)) { return false; } return val >= domain[0] && val <= domain[1]; } /** * Determines whether a point is within the provided polygon * * @param point as input search [lat, lng] * @param polygon Points must be within these (Multi)Polygon(s) * @return {boolean} */ export function isInPolygon(point: number[], polygon: any): boolean { return booleanWithin(turfPoint(point), polygon); } export function isValidTimeDomain(domain) { return Array.isArray(domain) && domain.every(Number.isFinite); } export function getTimeWidgetTitleFormatter(domain: [number, number]): string | null { if (!isValidTimeDomain(domain)) { return null; } const diff = domain[1] - domain[0]; // Local aware formats // https://momentjs.com/docs/#/parsing/string-format return diff > durationYear ? 'L' : diff > durationDay ? 'L LT' : 'L LTS'; } export function getTimeWidgetHintFormatter(domain: [number, number]): string | undefined { if (!isValidTimeDomain(domain)) { return undefined; } const diff = domain[1] - domain[0]; return diff > durationWeek ? 'L' : diff > durationDay ? 'L LT' : diff > durationHour ? 'LT' : 'LTS'; } /** * Sanity check on filters to prepare for save */ /* eslint-disable complexity */ export function isValidFilterValue(type: string | null, value: any): boolean { if (!type) { return false; } switch (type) { case FILTER_TYPES.select: return value === true || value === false; case FILTER_TYPES.range: case FILTER_TYPES.timeRange: return Array.isArray(value) && value.every(v => v !== null && !isNaN(v)); case FILTER_TYPES.multiSelect: return Array.isArray(value) && Boolean(value.length); case FILTER_TYPES.input: return Boolean(value.length); case FILTER_TYPES.polygon: const coordinates = get(value, ['geometry', 'coordinates']); return Boolean(value && value.id && coordinates); default: return true; } } export function getFilterPlot( filter: Filter, dataset: KeplerTable ): {lineChart: LineChart; yAxs: Field} | {} { if (filter.plotType === PLOT_TYPES.histogram || !filter.yAxis) { // histogram should be calculated when create filter return {}; } const {mappedValue = []} = filter; const {yAxis} = filter; const fieldIdx = dataset.getColumnFieldIdx(yAxis.name); if (fieldIdx < 0) { Console.warn(`yAxis ${yAxis.name} does not exist in dataset`); return {lineChart: {}, yAxis}; } // return lineChart const series = dataset.dataContainer .map( (row, rowIndex) => ({ x: mappedValue[rowIndex], y: row.valueAt(fieldIdx) }), true ) .filter(({x, y}) => Number.isFinite(x) && Number.isFinite(y)) .sort((a, b) => ascending(a.x, b.x)); const yDomain = extent(series, d => d.y); const xDomain = [series[0].x, series[series.length - 1].x]; return {lineChart: {series, yDomain, xDomain}, yAxis}; } export function getDefaultFilterPlotType(filter: Filter): string | null { const filterPlotTypes: typeof SupportedPlotType[keyof typeof SupportedPlotType] | null = filter.type && SupportedPlotType[filter.type]; if (!filterPlotTypes) { return null; } if (!filter.yAxis) { return filterPlotTypes.default; } return filterPlotTypes[filter.yAxis.type] || null; } /** * * @param datasetIds list of dataset ids to be filtered * @param datasets all datasets * @param filters all filters to be applied to datasets * @return datasets - new updated datasets */ export function applyFiltersToDatasets( datasetIds: string[], datasets: Datasets, filters: Filter[], layers?: Layer[] ): Datasets { const dataIds = toArray(datasetIds); return dataIds.reduce((acc, dataId) => { const layersToFilter = (layers || []).filter(l => l.config.dataId === dataId); const appliedFilters = filters.filter(d => shouldApplyFilter(d, dataId)); const table = datasets[dataId]; return { ...acc, [dataId]: table.filterTable(appliedFilters, layersToFilter, {}) }; }, datasets); } /** * Applies a new field name value to fielter and update both filter and dataset * @param filter - to be applied the new field name on * @param dataset - dataset the field belongs to * @param fieldName - field.name * @param filterDatasetIndex - field.name * @param option * @return - {filter, datasets} */ export function applyFilterFieldName( filter: Filter, dataset: KeplerTable, fieldName: string, filterDatasetIndex = 0, option?: {mergeDomain: boolean} ): { filter: Filter | null; dataset: KeplerTable; } { // using filterDatasetIndex we can filter only the specified dataset const mergeDomain = option && option.hasOwnProperty('mergeDomain') ? option.mergeDomain : false; const fieldIndex = dataset.getColumnFieldIdx(fieldName); // if no field with same name is found, move to the next datasets if (fieldIndex === -1) { // throw new Error(`fieldIndex not found. Dataset must contain a property with name: ${fieldName}`); return {filter: null, dataset}; } // TODO: validate field type const filterProps = dataset.getColumnFilterProps(fieldName); const newFilter = { ...(mergeDomain ? mergeFilterDomainStep(filter, filterProps) : {...filter, ...filterProps}), name: Object.assign([...toArray(filter.name)], {[filterDatasetIndex]: fieldName}), fieldIdx: Object.assign([...toArray(filter.fieldIdx)], { [filterDatasetIndex]: fieldIndex }), // TODO, since we allow to add multiple fields to a filter we can no longer freeze the filter freeze: true }; return { filter: newFilter, dataset }; } /** * Merge one filter with other filter prop domain */ /* eslint-disable complexity */ export function mergeFilterDomainStep(filter: Filter, filterProps?: any): Filter | null { if (!filter) { return null; } if (!filterProps) { return filter; } if ((filter.fieldType && filter.fieldType !== filterProps.fieldType) || !filterProps.domain) { return filter; } const combinedDomain = !filter.domain ? filterProps.domain : [...(filter.domain || []), ...(filterProps.domain || [])].sort((a, b) => a - b); const newFilter = { ...filter, ...filterProps, domain: [combinedDomain[0], combinedDomain[combinedDomain.length - 1]] }; switch (filterProps.fieldType) { case ALL_FIELD_TYPES.string: case ALL_FIELD_TYPES.date: return { ...newFilter, domain: unique(combinedDomain).sort() }; case ALL_FIELD_TYPES.timestamp: const step = (filter as TimeRangeFilter).step < filterProps.step ? (filter as TimeRangeFilter).step : filterProps.step; return { ...newFilter, step }; case ALL_FIELD_TYPES.real: case ALL_FIELD_TYPES.integer: default: return newFilter; } } /* eslint-enable complexity */ /** * Generates polygon filter */ export const featureToFilterValue = ( feature: Feature, filterId: string, properties?: {} ): FeatureValue => ({ ...feature, id: feature.id, properties: { ...feature.properties, ...properties, filterId } }); export const getFilterIdInFeature = (f: FeatureValue): string => get(f, ['properties', 'filterId']); /** * Generates polygon filter */ export function generatePolygonFilter(layers: Layer[], feature: Feature): PolygonFilter { const dataId = layers.map(l => l.config.dataId).filter(notNullorUndefined); const layerId = layers.map(l => l.id); const name = layers.map(l => l.config.label); const filter = getDefaultFilter(dataId); return { ...filter, fixedDomain: true, type: FILTER_TYPES.polygon, name, layerId, value: featureToFilterValue(feature, filter.id, {isVisible: true}) }; } /** * Run filter entirely on CPU */ export function filterDatasetCPU(state: VisState, dataId: string): VisState { const datasetFilters = state.filters.filter(f => f.dataId.includes(dataId)); const dataset = state.datasets[dataId]; if (!dataset) { return state; } const cpuFilteredDataset = dataset.filterTableCPU(datasetFilters, state.layers); return set(['datasets', dataId], cpuFilteredDataset, state); } /** * Validate parsed filters with datasets and add filterProps to field */ export function validateFiltersUpdateDatasets( state: VisState, filtersToValidate: ParsedFilter[] = [] ): { validated: Filter[]; failed: Filter[]; updatedDatasets: Datasets; } { // TODO Better Typings here const validated: any[] = []; const failed: any[] = []; const {datasets} = state; let updatedDatasets = datasets; // merge filters filtersToValidate.forEach(filter => { // we can only look for datasets define in the filter dataId const datasetIds = toArray(filter.dataId); // we can merge a filter only if all datasets in filter.dataId are loaded if (datasetIds.every(d => datasets[d])) { // all datasetIds in filter must be present the state datasets const {filter: validatedFilter, applyToDatasets, augmentedDatasets} = datasetIds.reduce( (acc, datasetId) => { const dataset = updatedDatasets[datasetId]; const layers = state.layers.filter(l => l.config.dataId === dataset.id); const {filter: updatedFilter, dataset: updatedDataset} = validateFilterWithData( acc.augmentedDatasets[datasetId] || dataset, filter, layers ); if (updatedFilter) { return { ...acc, // merge filter props filter: acc.filter ? { ...acc.filter, ...mergeFilterDomainStep(acc, updatedFilter) } : updatedFilter, applyToDatasets: [...acc.applyToDatasets, datasetId], augmentedDatasets: { ...acc.augmentedDatasets, [datasetId]: updatedDataset } }; } return acc; }, { filter: null, applyToDatasets: [], augmentedDatasets: {} } ); if (validatedFilter && isEqual(datasetIds, applyToDatasets)) { validated.push(validatedFilter); updatedDatasets = { ...updatedDatasets, ...augmentedDatasets }; } } else { failed.push(filter); } }); return {validated, failed, updatedDatasets}; } /** * Retrieve interval bins for time filter */ export function getIntervalBins(filter: TimeRangeFilter) { const {bins} = filter; const interval = filter.plotType?.interval; if (!interval || !bins || Object.keys(bins).length === 0) { return null; } const values = Object.values(bins); return values[0] ? values[0][interval] : null; }
the_stack
import moment, {unitOfTime} from 'moment' import {IAugmentedJQuery} from 'angular' import {GanttCalendar, TimeFrame, TimeFramesDisplayMode} from '../calendar/calendar.factory' /** * Used to display the Gantt grid and header. * The columns are generated by the column generator. */ export class GanttColumn { date: moment.Moment endDate: moment.Moment left: number width: number duration: number originalSize: { left: number; width: number } $element: IAugmentedJQuery calendar: GanttCalendar timeFramesWorkingMode: TimeFramesDisplayMode timeFramesNonWorkingMode: TimeFramesDisplayMode timeFrames: TimeFrame[] = [] visibleTimeFrames: TimeFrame[] = [] daysTimeFrames: { [dateKey: string]: TimeFrame[] } = {} currentDate = false cropped = false constructor (date: moment.Moment, endDate: moment.Moment, left: number, width: number, calendar?: GanttCalendar, timeFramesWorkingMode?: TimeFramesDisplayMode, timeFramesNonWorkingMode?: TimeFramesDisplayMode) { this.date = date this.endDate = endDate this.left = left this.width = width this.calendar = calendar this.duration = this.endDate.diff(this.date, 'milliseconds') this.timeFramesWorkingMode = timeFramesWorkingMode this.timeFramesNonWorkingMode = timeFramesNonWorkingMode this.timeFrames = [] this.visibleTimeFrames = [] this.daysTimeFrames = {} this.originalSize = {left: this.left, width: this.width} this.updateTimeFrames() } private getDateKey (date: moment.Moment) { return date.year() + '-' + date.month() + '-' + date.date() } updateView () { if (this.$element) { if (this.currentDate) { this.$element.addClass('gantt-foreground-col-current-date') } else { this.$element.removeClass('gantt-foreground-col-current-date') } this.$element.css({'left': this.left + 'px', 'width': this.width + 'px'}) this.timeFrames.forEach((timeFrame) => timeFrame.updateView()) } } updateTimeFrames () { if (this.calendar !== undefined && (this.timeFramesNonWorkingMode !== 'hidden' || this.timeFramesWorkingMode !== 'hidden')) { let cDate = this.date let cDateStartOfDay = moment(cDate).startOf('day') let cDateNextDay = cDateStartOfDay.add(1, 'day') let i while (cDate < this.endDate) { let timeFrames = this.calendar.getTimeFrames(cDate) let nextCDate = moment.min(cDateNextDay, this.endDate) timeFrames = this.calendar.solve(timeFrames, cDate, nextCDate) let cTimeFrames = [] for (i = 0; i < timeFrames.length; i++) { let cTimeFrame = timeFrames[i] let start = cTimeFrame.start if (start === undefined) { start = cDate } let end = cTimeFrame.end if (end === undefined) { end = nextCDate } if (start < this.date) { start = this.date } if (end > this.endDate) { end = this.endDate } cTimeFrame = cTimeFrame.clone() cTimeFrame.start = moment(start) cTimeFrame.end = moment(end) cTimeFrames.push(cTimeFrame) } this.timeFrames = this.timeFrames.concat(cTimeFrames) let cDateKey = this.getDateKey(cDate) this.daysTimeFrames[cDateKey] = cTimeFrames cDate = nextCDate cDateStartOfDay = moment(cDate).startOf('day') cDateNextDay = cDateStartOfDay.add(1, 'day') } for (i = 0; i < this.timeFrames.length; i++) { let timeFrame = this.timeFrames[i] let positionDuration = timeFrame.start.diff(this.date, 'milliseconds') let position = positionDuration / this.duration * this.width let timeFrameDuration = timeFrame.end.diff(timeFrame.start, 'milliseconds') let timeFramePosition = timeFrameDuration / this.duration * this.width let hidden = false if (timeFrame.working && this.timeFramesWorkingMode !== 'visible') { hidden = true } else if (!timeFrame.working && this.timeFramesNonWorkingMode !== 'visible') { hidden = true } if (!hidden) { this.visibleTimeFrames.push(timeFrame) } timeFrame.hidden = hidden timeFrame.left = position timeFrame.width = timeFramePosition timeFrame.originalSize = {left: timeFrame.left, width: timeFrame.width} } if (this.timeFramesNonWorkingMode === 'cropped' || this.timeFramesWorkingMode === 'cropped') { let timeFramesWidth = 0 for (let aTimeFrame of this.timeFrames) { if (!aTimeFrame.working && this.timeFramesNonWorkingMode !== 'cropped' || aTimeFrame.working && this.timeFramesWorkingMode !== 'cropped') { timeFramesWidth += aTimeFrame.width } } if (timeFramesWidth !== this.width) { let croppedRatio = this.width / timeFramesWidth let croppedWidth = 0 let originalCroppedWidth = 0 let allCropped = true for (let bTimeFrame of this.timeFrames) { if (!bTimeFrame.working && this.timeFramesNonWorkingMode !== 'cropped' || bTimeFrame.working && this.timeFramesWorkingMode !== 'cropped') { bTimeFrame.left = (bTimeFrame.left - croppedWidth) * croppedRatio bTimeFrame.width = bTimeFrame.width * croppedRatio bTimeFrame.originalSize.left = (bTimeFrame.originalSize.left - originalCroppedWidth) * croppedRatio bTimeFrame.originalSize.width = bTimeFrame.originalSize.width * croppedRatio bTimeFrame.cropped = false allCropped = false } else { croppedWidth += bTimeFrame.width originalCroppedWidth += bTimeFrame.originalSize.width bTimeFrame.left = undefined bTimeFrame.width = 0 bTimeFrame.originalSize = {left: undefined, width: 0} bTimeFrame.cropped = true } } this.cropped = allCropped } else { this.cropped = false } } } } clone () { return new GanttColumn(moment(this.date), moment(this.endDate), this.left, this.width, this.calendar) } containsDate (date: moment.Moment) { return date > this.date && date <= this.endDate } equals (other: GanttColumn) { return this.date === other.date } roundTo (date: moment.Moment, unit: unitOfTime.All, offset: number, midpoint?: 'up' | 'down') { // Waiting merge of https://github.com/moment/moment/pull/1794 if (unit === 'day') { // Inconsistency in units in momentJS. unit = 'date' } offset = offset || 1 let value = date.get(unit) switch (midpoint) { case 'up': value = Math.ceil(value / offset) break case 'down': value = Math.floor(value / offset) break default: value = Math.round(value / offset) break } let units = ['millisecond', 'second', 'minute', 'hour', 'date', 'month', 'year'] as unitOfTime.All[] date.set(unit, value * offset) let indexOf = units.indexOf(unit) for (let i = 0; i < indexOf; i++) { date.set(units[i], 0) } return date } getMagnetDate (date: moment.Moment, magnetValue?: number, magnetUnit?: unitOfTime.All, timeFramesMagnet?: boolean) { if (magnetValue > 0 && magnetUnit !== undefined) { let initialDate = date date = moment(date) if (magnetUnit as string === 'column') { // Snap to column borders only. let position = this.getPositionByDate(date) if (position < this.width / 2) { date = moment(this.date) } else { date = moment(this.endDate) } } else { // Round the value date = this.roundTo(date, magnetUnit, magnetValue) // Snap to column borders if date overflows. if (date < this.date) { date = moment(this.date) } else if (date > this.endDate) { date = moment(this.endDate) } } if (timeFramesMagnet) { let maxTimeFrameDiff = Math.abs(initialDate.diff(date, 'milliseconds')) let currentTimeFrameDiff for (let i = 0; i < this.timeFrames.length; i++) { let timeFrame = this.timeFrames[i] if (timeFrame.magnet) { let previousTimeFrame = this.timeFrames[i - 1] let nextTimeFrame = this.timeFrames[i + 1] let timeFrameDiff if (previousTimeFrame === undefined || previousTimeFrame.working !== timeFrame.working) { timeFrameDiff = Math.abs(initialDate.diff(timeFrame.start, 'milliseconds')) if (timeFrameDiff < maxTimeFrameDiff && (currentTimeFrameDiff === undefined || timeFrameDiff < currentTimeFrameDiff)) { currentTimeFrameDiff = timeFrameDiff date = timeFrame.start } } if (nextTimeFrame === undefined || nextTimeFrame.working !== timeFrame.working) { timeFrameDiff = Math.abs(initialDate.diff(timeFrame.end, 'milliseconds')) if (timeFrameDiff < maxTimeFrameDiff && (currentTimeFrameDiff === undefined || timeFrameDiff < currentTimeFrameDiff)) { currentTimeFrameDiff = timeFrameDiff date = timeFrame.end } } } } } } return date } getDateByPositionUsingTimeFrames (position: number) { for (let timeFrame of this.timeFrames) { if (!timeFrame.cropped && position >= timeFrame.left && position <= timeFrame.left + timeFrame.width) { let positionDuration = timeFrame.getDuration() / timeFrame.width * (position - timeFrame.left) let date = moment(timeFrame.start).add(positionDuration, 'milliseconds') return date } } } getDateByPosition (position: number, magnetValue?: number, magnetUnit?: unitOfTime.All, timeFramesMagnet?: boolean) { let date if (position < 0) { position = 0 } if (position > this.width) { position = this.width } if (this.timeFramesNonWorkingMode === 'cropped' || this.timeFramesWorkingMode === 'cropped') { date = this.getDateByPositionUsingTimeFrames(position) } if (date === undefined) { let positionDuration = this.duration / this.width * position date = moment(this.date).add(positionDuration, 'milliseconds') } date = this.getMagnetDate(date, magnetValue, magnetUnit, timeFramesMagnet) return date } getDayTimeFrame (date: moment.Moment) { let dtf = this.daysTimeFrames[this.getDateKey(date)] if (dtf === undefined) { return [] } return dtf } getPositionByDate (date: moment.Moment) { let croppedDate = date if (this.timeFramesNonWorkingMode === 'cropped' || this.timeFramesWorkingMode === 'cropped') { let timeFrames = this.getDayTimeFrame(croppedDate) for (let i = 0; i < timeFrames.length; i++) { let timeFrame = timeFrames[i] if (croppedDate >= timeFrame.start && croppedDate <= timeFrame.end) { if (timeFrame.cropped) { if (timeFrames.length > i + 1) { croppedDate = timeFrames[i + 1].start } else { croppedDate = timeFrame.end } } else { let positionDuration = croppedDate.diff(timeFrame.start, 'milliseconds') let position = positionDuration / timeFrame.getDuration() * timeFrame.width return this.left + timeFrame.left + position } } } } let positionDuration = croppedDate.diff(this.date, 'milliseconds') let position = positionDuration / this.duration * this.width if (position < 0) { position = 0 } if (position > this.width) { position = this.width } return this.left + position } } export default function () { 'ngInject' return GanttColumn }
the_stack
'use strict'; /*global*/ import { bar, bb, bubble, Chart, ChartOptions, ChartTypes, DataItem, zoom } from 'billboard.js'; // import BubbleCompare from 'billboard.js/dist/plugin/billboardjs-plugin-bubblecompare'; // import { scaleSqrt } from 'd3-scale'; import { Commit, State } from '../../../../plus/webviews/timeline/protocol'; import { formatDate, fromNow } from '../../shared/date'; import { Emitter, Event } from '../../shared/events'; import { throttle } from '../../shared/utils'; export interface DataPointClickEvent { data: { id: string; selected: boolean; }; } export class TimelineChart { private _onDidClickDataPoint = new Emitter<DataPointClickEvent>(); get onDidClickDataPoint(): Event<DataPointClickEvent> { return this._onDidClickDataPoint.event; } private readonly $container: HTMLElement; private _chart: Chart | undefined; private _chartDimensions: { height: number; width: number }; private readonly _resizeObserver: ResizeObserver; private readonly _selector: string; private readonly _commitsByTimestamp = new Map<string, Commit>(); private readonly _authorsByIndex = new Map<number, string>(); private readonly _indexByAuthors = new Map<string, number>(); private _dateFormat: string = undefined!; private _shortDateFormat: string = undefined!; constructor(selector: string) { this._selector = selector; const fn = throttle(() => { const dimensions = this._chartDimensions; this._chart?.resize({ width: dimensions.width, height: dimensions.height - 10, }); }, 100); this._resizeObserver = new ResizeObserver(entries => { const size = entries[0].borderBoxSize[0]; const dimensions = { width: Math.floor(size.inlineSize), height: Math.floor(size.blockSize), }; if ( this._chartDimensions.height === dimensions.height && this._chartDimensions.width === dimensions.width ) { return; } this._chartDimensions = dimensions; fn(); }); this.$container = document.querySelector(selector)!.parentElement!; const rect = this.$container.getBoundingClientRect(); this._chartDimensions = { height: Math.floor(rect.height), width: Math.floor(rect.width) }; this._resizeObserver.observe(this.$container); } reset() { this._chart?.unselect(); this._chart?.unzoom(); } updateChart(state: State) { this._dateFormat = state.dateFormat; this._shortDateFormat = state.shortDateFormat; this._commitsByTimestamp.clear(); this._authorsByIndex.clear(); this._indexByAuthors.clear(); if (state?.dataset == null || state.dataset.length === 0) { this._chart?.destroy(); this._chart = undefined; const $overlay = document.getElementById('chart-empty-overlay') as HTMLDivElement; $overlay?.classList.toggle('hidden', false); const $emptyMessage = $overlay.querySelector('[data-bind="empty"]') as HTMLHeadingElement; $emptyMessage.textContent = state.title; return; } const $overlay = document.getElementById('chart-empty-overlay') as HTMLDivElement; $overlay?.classList.toggle('hidden', true); const xs: { [key: string]: string } = {}; const colors: { [key: string]: string } = {}; const names: { [key: string]: string } = {}; const axes: { [key: string]: string } = {}; const types: { [key: string]: ChartTypes } = {}; const groups: string[][] = []; const series: { [key: string]: any } = {}; const group = []; let index = 0; let commit: Commit; let author: string; let date: string; let additions: number | undefined; let deletions: number | undefined; // // Get the min and max additions and deletions from the dataset // let minChanges = Infinity; // let maxChanges = -Infinity; // for (const commit of state.dataset) { // const changes = commit.additions + commit.deletions; // if (changes < minChanges) { // minChanges = changes; // } // if (changes > maxChanges) { // maxChanges = changes; // } // } // const bubbleScale = scaleSqrt([minChanges, maxChanges], [6, 100]); for (commit of state.dataset) { ({ author, date, additions, deletions } = commit); if (!this._indexByAuthors.has(author)) { this._indexByAuthors.set(author, index); this._authorsByIndex.set(index, author); index--; } const x = 'time'; if (series[x] == null) { series[x] = []; series['additions'] = []; series['deletions'] = []; xs['additions'] = x; xs['deletions'] = x; axes['additions'] = 'y2'; axes['deletions'] = 'y2'; names['additions'] = 'Additions'; names['deletions'] = 'Deletions'; colors['additions'] = 'rgba(73, 190, 71, 1)'; colors['deletions'] = 'rgba(195, 32, 45, 1)'; types['additions'] = bar(); types['deletions'] = bar(); group.push(x); groups.push(['additions', 'deletions']); } const authorX = `${x}.${author}`; if (series[authorX] == null) { series[authorX] = []; series[author] = []; xs[author] = authorX; axes[author] = 'y'; names[author] = author; types[author] = bubble(); group.push(authorX); } series[x].push(date); series['additions'].push(additions ?? 0); series['deletions'].push(deletions ?? 0); series[authorX].push(date); const z = additions == null && deletions == null ? 6 : (additions ?? 0) + (deletions ?? 0); //bubbleScale(additions + deletions); series[author].push({ y: this._indexByAuthors.get(author), z: z, }); this._commitsByTimestamp.set(date, commit); } groups.push(group); const columns = Object.entries(series).map(([key, value]) => [key, ...value]); if (this._chart == null) { const options = this.getChartOptions(); if (options.axis == null) { options.axis = { y: { tick: {} } }; } if (options.axis.y == null) { options.axis.y = { tick: {} }; } if (options.axis.y.tick == null) { options.axis.y.tick = {}; } options.axis.y.min = index - 2; options.axis.y.tick.values = [...this._authorsByIndex.keys()]; options.data = { ...options.data, axes: axes, colors: colors, columns: columns, groups: groups, names: names, types: types, xs: xs, }; this._chart = bb.generate(options); } else { this._chart.config('axis.y.tick.values', [...this._authorsByIndex.keys()], false); this._chart.config('axis.y.min', index - 2, false); this._chart.groups(groups); this._chart.load({ axes: axes, colors: colors, columns: columns, names: names, types: types, xs: xs, unload: true, }); } } private getChartOptions() { const config: ChartOptions = { bindto: this._selector, data: { xFormat: '%Y-%m-%dT%H:%M:%S.%LZ', xLocaltime: false, // selection: { // enabled: selection(), // draggable: false, // grouped: false, // multiple: false, // }, onclick: this.onDataPointClicked.bind(this), }, axis: { x: { type: 'timeseries', clipPath: false, localtime: true, tick: { // autorotate: true, centered: true, culling: false, fit: false, format: (x: number | Date) => typeof x === 'number' ? x : formatDate(x, this._shortDateFormat ?? 'short'), multiline: false, // rotate: 15, show: false, }, }, y: { max: 0, padding: { top: 75, bottom: 100, }, show: true, tick: { format: (y: number) => this._authorsByIndex.get(y) ?? '', outer: false, }, }, y2: { label: { text: 'Lines changed', position: 'outer-middle', }, // min: 0, show: true, // tick: { // outer: true, // // culling: true, // // stepSize: 1, // }, }, }, bar: { width: 2, sensitivity: 4, padding: 2, }, bubble: { maxR: 100, zerobased: true, }, grid: { focus: { edge: true, show: true, y: true, }, front: false, lines: { front: false, }, x: { show: false, }, y: { show: true, }, }, legend: { show: true, padding: 10, }, resize: { auto: false, }, size: { height: this._chartDimensions.height - 10, width: this._chartDimensions.width, }, tooltip: { grouped: true, format: { title: this.getTooltipTitle.bind(this), name: this.getTooltipName.bind(this), value: this.getTooltipValue.bind(this), }, // linked: true, //{ name: 'time' }, show: true, order: 'desc', }, zoom: { enabled: zoom(), type: 'drag', rescale: true, resetButton: true, extent: [1, 0.01], x: { min: 100, }, // onzoomstart: function(...args: any[]) { // console.log('onzoomstart', args); // }, // onzoom: function(...args: any[]) { // console.log('onzoom', args); // }, // onzoomend: function(...args: any[]) { // console.log('onzoomend', args); // } }, // plugins: [ // new BubbleCompare({ // minR: 6, // maxR: 100, // expandScale: 1.2, // }), // ], }; return config; } private getTooltipName(name: string, ratio: number, id: string, index: number) { if (id === 'additions' || /*id === 'changes' ||*/ id === 'deletions') return name; const date = new Date(this._chart!.data(id)[0].values[index].x); const commit = this._commitsByTimestamp.get(date.toISOString()); return commit?.commit.slice(0, 8) ?? '00000000'; } private getTooltipTitle(x: string) { const date = new Date(x); const formattedDate = `${capitalize(fromNow(date))} (${formatDate(date, this._dateFormat)})`; const commit = this._commitsByTimestamp.get(date.toISOString()); if (commit == null) return formattedDate; return `${commit.author}, ${formattedDate}`; } private getTooltipValue(value: any, ratio: number, id: string, index: number) { if (id === 'additions' || /*id === 'changes' ||*/ id === 'deletions') { return value === 0 ? undefined! : value; } const date = new Date(this._chart!.data(id)[0].values[index].x); const commit = this._commitsByTimestamp.get(date.toISOString()); return commit?.message ?? '???'; } private onDataPointClicked(d: DataItem, _element: SVGElement) { const commit = this._commitsByTimestamp.get(new Date(d.x).toISOString()); if (commit == null) return; // const selected = this._chart!.selected(d.id) as unknown as DataItem[]; this._onDidClickDataPoint.fire({ data: { id: commit.commit, selected: true, //selected?.[0]?.id === d.id, }, }); } } function capitalize(s: string): string { return s.charAt(0).toUpperCase() + s.slice(1); }
the_stack
import * as fs from "node:fs"; import getPort from "get-port"; import patchConsole from "patch-console"; import dedent from "ts-dedent"; import Dev from "../dev/dev"; import { mockAccountId, mockApiToken } from "./helpers/mock-account-id"; import { setMockResponse, unsetAllMocks } from "./helpers/mock-cfetch"; import { mockConsoleMethods } from "./helpers/mock-console"; import { runInTempDir } from "./helpers/run-in-tmp"; import { runWrangler } from "./helpers/run-wrangler"; import writeWranglerToml from "./helpers/write-wrangler-toml"; describe("wrangler dev", () => { mockAccountId(); mockApiToken(); runInTempDir(); const std = mockConsoleMethods(); afterEach(() => { (Dev as jest.Mock).mockClear(); patchConsole(() => {}); unsetAllMocks(); }); describe("compatibility-date", () => { it("should not warn if there is no wrangler.toml and no compatibility-date specified", async () => { fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev index.js"); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(`""`); expect(std.err).toMatchInlineSnapshot(`""`); }); it("should warn if there is a wrangler.toml but no compatibility-date", async () => { writeWranglerToml({ main: "index.js", compatibility_date: undefined, }); fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev"); const currentDate = new Date().toISOString().substring(0, 10); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn.replaceAll(currentDate, "<current-date>")) .toMatchInlineSnapshot(` "▲ [WARNING] No compatibility_date was specified. Using today's date: <current-date>. Add one to your wrangler.toml file: \`\`\` compatibility_date = \\"<current-date>\\" \`\`\` or pass it in your terminal: \`\`\` --compatibility-date=<current-date> \`\`\` See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information. " `); expect(std.err).toMatchInlineSnapshot(`""`); }); it("should not warn if there is a wrangler.toml but compatibility-date is specified at the command line", async () => { writeWranglerToml({ main: "index.js", compatibility_date: undefined, }); fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev --compatibility-date=2020-01-01"); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(`""`); expect(std.err).toMatchInlineSnapshot(`""`); }); }); describe("entry-points", () => { it("should error if there is no entry-point specified", async () => { writeWranglerToml(); await expect( runWrangler("dev") ).rejects.toThrowErrorMatchingInlineSnapshot( `"Missing entry-point: The entry-point should be specified via the command line (e.g. \`wrangler dev path/to/script\`) or the \`main\` config field."` ); expect(std.out).toMatchInlineSnapshot(` " If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new." `); expect(std.err).toMatchInlineSnapshot(` "X [ERROR] Missing entry-point: The entry-point should be specified via the command line (e.g. \`wrangler dev path/to/script\`) or the \`main\` config field. " `); }); it("should use `main` from the top-level environment", async () => { writeWranglerToml({ main: "index.js", }); fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev"); expect((Dev as jest.Mock).mock.calls[0][0].entry.file).toMatch( /index\.js$/ ); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(`""`); expect(std.err).toMatchInlineSnapshot(`""`); }); it("should use `main` from a named environment", async () => { writeWranglerToml({ env: { ENV1: { main: "index.js", }, }, }); fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev --env=ENV1"); expect((Dev as jest.Mock).mock.calls[0][0].entry.file).toMatch( /index\.js$/ ); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(`""`); expect(std.err).toMatchInlineSnapshot(`""`); }); it("should use `main` from a named environment, rather than the top-level", async () => { writeWranglerToml({ main: "other.js", env: { ENV1: { main: "index.js", }, }, }); fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev --env=ENV1"); expect((Dev as jest.Mock).mock.calls[0][0].entry.file).toMatch( /index\.js$/ ); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(`""`); expect(std.err).toMatchInlineSnapshot(`""`); }); }); describe("host", () => { it("should resolve a host to its zone", async () => { writeWranglerToml({ main: "index.js", }); fs.writeFileSync("index.js", `export default {};`); mockGetZones("some-host.com", [{ id: "some-zone-id" }]); await runWrangler("dev --host some-host.com"); expect((Dev as jest.Mock).mock.calls[0][0].zone).toEqual({ host: "some-host.com", id: "some-zone-id", }); }); it("should read wrangler.toml's dev.host", async () => { writeWranglerToml({ main: "index.js", dev: { host: "some-host.com", }, }); fs.writeFileSync("index.js", `export default {};`); mockGetZones("some-host.com", [{ id: "some-zone-id" }]); await runWrangler("dev"); expect((Dev as jest.Mock).mock.calls[0][0].zone.host).toEqual( "some-host.com" ); }); it("should read --route", async () => { writeWranglerToml({ main: "index.js", }); fs.writeFileSync("index.js", `export default {};`); mockGetZones("some-host.com", [{ id: "some-zone-id" }]); await runWrangler("dev --route http://some-host.com/some/path/*"); expect((Dev as jest.Mock).mock.calls[0][0].zone.host).toEqual( "some-host.com" ); }); it("should read wrangler.toml's routes", async () => { writeWranglerToml({ main: "index.js", routes: [ "http://some-host.com/some/path/*", "http://some-other-host.com/path/*", ], }); fs.writeFileSync("index.js", `export default {};`); mockGetZones("some-host.com", [{ id: "some-zone-id" }]); await runWrangler("dev"); expect((Dev as jest.Mock).mock.calls[0][0].zone.host).toEqual( "some-host.com" ); }); it("should read wrangler.toml's environment specific routes", async () => { writeWranglerToml({ main: "index.js", routes: [ "http://a-host.com/some/path/*", "http://another-host.com/path/*", ], env: { staging: { routes: [ "http://some-host.com/some/path/*", "http://some-other-host.com/path/*", ], }, }, }); fs.writeFileSync("index.js", `export default {};`); mockGetZones("some-host.com", [{ id: "some-zone-id" }]); await runWrangler("dev --env staging"); expect((Dev as jest.Mock).mock.calls[0][0].zone.host).toEqual( "some-host.com" ); }); it("should, when provided, use a configured zone_id", async () => { writeWranglerToml({ main: "index.js", routes: [ { pattern: "https://some-domain.com/*", zone_id: "some-zone-id" }, ], }); fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev"); expect((Dev as jest.Mock).mock.calls[0][0].zone).toEqual({ host: "some-domain.com", id: "some-zone-id", }); }); it("should, when provided, use a zone_name to get a zone_id", async () => { writeWranglerToml({ main: "index.js", routes: [ { pattern: "https://some-domain.com/*", zone_name: "some-zone.com" }, ], }); fs.writeFileSync("index.js", `export default {};`); mockGetZones("some-zone.com", [{ id: "a-zone-id" }]); await runWrangler("dev"); expect((Dev as jest.Mock).mock.calls[0][0].zone).toEqual({ // note that it uses the provided zone_name as a host too host: "some-zone.com", id: "a-zone-id", }); }); it("given a long host, it should use the longest subdomain that resolves to a zone", async () => { writeWranglerToml({ main: "index.js", }); fs.writeFileSync("index.js", `export default {};`); mockGetZones("111.222.333.some-host.com", []); mockGetZones("222.333.some-host.com", []); mockGetZones("333.some-host.com", [{ id: "some-zone-id" }]); await runWrangler("dev --host 111.222.333.some-host.com"); expect((Dev as jest.Mock).mock.calls[0][0].zone).toEqual({ host: "111.222.333.some-host.com", id: "some-zone-id", }); }); it("should, in order, use args.host/config.dev.host/args.routes/(config.route|config.routes)", async () => { // This test might seem like it's testing implementation details, but let's be specific and consider it a spec fs.writeFileSync("index.js", `export default {};`); // config.routes mockGetZones("5.some-host.com", [{ id: "some-zone-id-5" }]); writeWranglerToml({ main: "index.js", routes: ["http://5.some-host.com/some/path/*"], }); await runWrangler("dev"); expect((Dev as jest.Mock).mock.calls[0][0].zone).toEqual({ host: "5.some-host.com", id: "some-zone-id-5", }); (Dev as jest.Mock).mockClear(); // config.route mockGetZones("4.some-host.com", [{ id: "some-zone-id-4" }]); writeWranglerToml({ main: "index.js", route: "https://4.some-host.com/some/path/*", }); await runWrangler("dev"); expect((Dev as jest.Mock).mock.calls[0][0].zone).toEqual({ host: "4.some-host.com", id: "some-zone-id-4", }); (Dev as jest.Mock).mockClear(); // --routes mockGetZones("3.some-host.com", [{ id: "some-zone-id-3" }]); writeWranglerToml({ main: "index.js", route: "https://4.some-host.com/some/path/*", }); await runWrangler("dev --routes http://3.some-host.com/some/path/*"); expect((Dev as jest.Mock).mock.calls[0][0].zone).toEqual({ host: "3.some-host.com", id: "some-zone-id-3", }); (Dev as jest.Mock).mockClear(); // config.dev.host mockGetZones("2.some-host.com", [{ id: "some-zone-id-2" }]); writeWranglerToml({ main: "index.js", dev: { host: `2.some-host.com`, }, route: "4.some-host.com/some/path/*", }); await runWrangler("dev --routes http://3.some-host.com/some/path/*"); expect((Dev as jest.Mock).mock.calls[0][0].zone).toEqual({ host: "2.some-host.com", id: "some-zone-id-2", }); (Dev as jest.Mock).mockClear(); // --host mockGetZones("1.some-host.com", [{ id: "some-zone-id-1" }]); writeWranglerToml({ main: "index.js", dev: { host: `2.some-host.com`, }, route: "4.some-host.com/some/path/*", }); await runWrangler( "dev --routes http://3.some-host.com/some/path/* --host 1.some-host.com" ); expect((Dev as jest.Mock).mock.calls[0][0].zone).toEqual({ host: "1.some-host.com", id: "some-zone-id-1", }); (Dev as jest.Mock).mockClear(); }); it("should error if a host can't resolve to a zone", async () => { writeWranglerToml({ main: "index.js", }); fs.writeFileSync("index.js", `export default {};`); mockGetZones("some-host.com", []); await expect( runWrangler("dev --host some-host.com") ).rejects.toThrowErrorMatchingInlineSnapshot( `"Could not find zone for some-host.com"` ); }); it("should not try to resolve a zone when starting in local mode", async () => { writeWranglerToml({ main: "index.js", }); fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev --host some-host.com --local"); expect((Dev as jest.Mock).mock.calls[0][0].zone).toEqual(undefined); }); }); describe("custom builds", () => { it("should run a custom build before starting `dev`", async () => { writeWranglerToml({ build: { command: `node -e "console.log('custom build'); require('fs').writeFileSync('index.js', 'export default { fetch(){ return new Response(123) } }')"`, }, }); await runWrangler("dev index.js"); expect(fs.readFileSync("index.js", "utf-8")).toMatchInlineSnapshot( `"export default { fetch(){ return new Response(123) } }"` ); // and the command would pass through expect((Dev as jest.Mock).mock.calls[0][0].build).toEqual({ command: "node -e \"console.log('custom build'); require('fs').writeFileSync('index.js', 'export default { fetch(){ return new Response(123) } }')\"", cwd: undefined, watch_dir: "src", }); expect(std.out).toMatchInlineSnapshot( `"Running custom build: node -e \\"console.log('custom build'); require('fs').writeFileSync('index.js', 'export default { fetch(){ return new Response(123) } }')\\""` ); expect(std.err).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(`""`); }); if (process.platform !== "win32") { it("should run a custom build of multiple steps combined by && before starting `dev`", async () => { writeWranglerToml({ build: { command: `echo "custom build" && echo "export default { fetch(){ return new Response(123) } }" > index.js`, }, }); await runWrangler("dev index.js"); expect(fs.readFileSync("index.js", "utf-8")).toMatchInlineSnapshot(` "export default { fetch(){ return new Response(123) } } " `); expect(std.out).toMatchInlineSnapshot( `"Running custom build: echo \\"custom build\\" && echo \\"export default { fetch(){ return new Response(123) } }\\" > index.js"` ); expect(std.err).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(`""`); }); } it("should throw an error if the entry doesn't exist after the build finishes", async () => { writeWranglerToml({ main: "index.js", build: { command: `node -e "console.log('custom build');"`, }, }); await expect(runWrangler("dev")).rejects .toThrowErrorMatchingInlineSnapshot(` "The expected output file at \\"index.js\\" was not found after running custom build: node -e \\"console.log('custom build');\\". The \`main\` property in wrangler.toml should point to the file generated by the custom build." `); expect(std.out).toMatchInlineSnapshot(` "Running custom build: node -e \\"console.log('custom build');\\" If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new." `); expect(std.err).toMatchInlineSnapshot(` "X [ERROR] The expected output file at \\"index.js\\" was not found after running custom build: node -e \\"console.log('custom build');\\". The \`main\` property in wrangler.toml should point to the file generated by the custom build. " `); expect(std.warn).toMatchInlineSnapshot(`""`); }); }); describe("upstream-protocol", () => { it("should default upstream-protocol to `https`", async () => { writeWranglerToml({ main: "index.js", }); fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev"); expect((Dev as jest.Mock).mock.calls[0][0].upstreamProtocol).toEqual( "https" ); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(`""`); expect(std.err).toMatchInlineSnapshot(`""`); }); it("should warn if `--upstream-protocol=http` is used", async () => { writeWranglerToml({ main: "index.js", }); fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev --upstream-protocol=http"); expect((Dev as jest.Mock).mock.calls[0][0].upstreamProtocol).toEqual( "http" ); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(` "▲ [WARNING] Setting upstream-protocol to http is not currently implemented. If this is required in your project, please add your use case to the following issue: https://github.com/cloudflare/wrangler2/issues/583. " `); expect(std.err).toMatchInlineSnapshot(`""`); }); }); describe("local-protocol", () => { it("should default local-protocol to `http`", async () => { writeWranglerToml({ main: "index.js", }); fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev"); expect((Dev as jest.Mock).mock.calls[0][0].localProtocol).toEqual("http"); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(`""`); expect(std.err).toMatchInlineSnapshot(`""`); }); it("should use `local_protocol` from `wrangler.toml`, if available", async () => { writeWranglerToml({ main: "index.js", dev: { local_protocol: "https", }, }); fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev"); expect((Dev as jest.Mock).mock.calls[0][0].localProtocol).toEqual( "https" ); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(`""`); expect(std.err).toMatchInlineSnapshot(`""`); }); it("should use --local-protocol command line arg, if provided", async () => { // Here we show that the command line overrides the wrangler.toml by // setting the config to https, and then setting it back to http on the command line. writeWranglerToml({ main: "index.js", dev: { local_protocol: "https", }, }); fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev --local-protocol=http"); expect((Dev as jest.Mock).mock.calls[0][0].localProtocol).toEqual("http"); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(`""`); expect(std.err).toMatchInlineSnapshot(`""`); }); }); describe("ip", () => { it("should default ip to localhost", async () => { writeWranglerToml({ main: "index.js", }); fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev"); expect((Dev as jest.Mock).mock.calls[0][0].ip).toEqual("localhost"); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(`""`); expect(std.err).toMatchInlineSnapshot(`""`); }); it("should use to `ip` from `wrangler.toml`, if available", async () => { writeWranglerToml({ main: "index.js", dev: { ip: "0.0.0.0", }, }); fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev"); expect((Dev as jest.Mock).mock.calls[0][0].ip).toEqual("0.0.0.0"); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(`""`); expect(std.err).toMatchInlineSnapshot(`""`); }); it("should use --ip command line arg, if provided", async () => { writeWranglerToml({ main: "index.js", dev: { ip: "1.1.1.1", }, }); fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev --ip=0.0.0.0"); expect((Dev as jest.Mock).mock.calls[0][0].ip).toEqual("0.0.0.0"); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(`""`); expect(std.err).toMatchInlineSnapshot(`""`); }); }); describe("port", () => { it("should default port to 8787 if it is not in use", async () => { writeWranglerToml({ main: "index.js", }); fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev"); expect((Dev as jest.Mock).mock.calls[0][0].port).toEqual(8787); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(`""`); expect(std.err).toMatchInlineSnapshot(`""`); }); it("should use to `port` from `wrangler.toml`, if available", async () => { writeWranglerToml({ main: "index.js", dev: { port: 8888, }, }); fs.writeFileSync("index.js", `export default {};`); // Mock `getPort()` to resolve to a completely different port. (getPort as jest.Mock).mockResolvedValue(98765); await runWrangler("dev"); expect((Dev as jest.Mock).mock.calls[0][0].port).toEqual(8888); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(`""`); expect(std.err).toMatchInlineSnapshot(`""`); }); it("should use --port command line arg, if provided", async () => { writeWranglerToml({ main: "index.js", dev: { port: 8888, }, }); fs.writeFileSync("index.js", `export default {};`); // Mock `getPort()` to resolve to a completely different port. (getPort as jest.Mock).mockResolvedValue(98765); await runWrangler("dev --port=9999"); expect((Dev as jest.Mock).mock.calls[0][0].port).toEqual(9999); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(`""`); expect(std.err).toMatchInlineSnapshot(`""`); }); it("should use a different port to the default if it is in use", async () => { writeWranglerToml({ main: "index.js", }); fs.writeFileSync("index.js", `export default {};`); // Mock `getPort()` to resolve to a completely different port. (getPort as jest.Mock).mockResolvedValue(98765); await runWrangler("dev"); expect((Dev as jest.Mock).mock.calls[0][0].port).toEqual(98765); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(`""`); expect(std.err).toMatchInlineSnapshot(`""`); }); }); describe("durable_objects", () => { it("should warn if there is one or more remote Durable Object", async () => { writeWranglerToml({ main: "index.js", durable_objects: { bindings: [ { name: "NAME_1", class_name: "CLASS_1" }, { name: "NAME_2", class_name: "CLASS_2", script_name: "SCRIPT_A", }, { name: "NAME_3", class_name: "CLASS_3" }, { name: "NAME_4", class_name: "CLASS_4", script_name: "SCRIPT_B", }, ], }, }); fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev"); expect((Dev as jest.Mock).mock.calls[0][0].ip).toEqual("localhost"); expect(std.out).toMatchInlineSnapshot(`""`); expect(std.warn).toMatchInlineSnapshot(` "▲ [WARNING] WARNING: You have Durable Object bindings that are not defined locally in the worker being developed. Be aware that changes to the data stored in these Durable Objects will be permanent and affect the live instances. Remote Durable Objects that are affected: - {\\"name\\":\\"NAME_2\\",\\"class_name\\":\\"CLASS_2\\",\\"script_name\\":\\"SCRIPT_A\\"} - {\\"name\\":\\"NAME_4\\",\\"class_name\\":\\"CLASS_4\\",\\"script_name\\":\\"SCRIPT_B\\"} " `); expect(std.err).toMatchInlineSnapshot(`""`); }); }); describe(".dev.vars", () => { it("should override `vars` bindings from `wrangler.toml` with values in `.dev.vars`", async () => { fs.writeFileSync("index.js", `export default {};`); const localVarsEnvContent = dedent` # Preceding comment VAR_1="var #1 value" # End of line comment VAR_3="var #3 value" VAR_MULTI_LINE_1="A: line 1 line 2" VAR_MULTI_LINE_2="B: line 1\\nline 2" EMPTY= UNQUOTED= unquoted value `; fs.writeFileSync(".dev.vars", localVarsEnvContent, "utf8"); writeWranglerToml({ main: "index.js", vars: { VAR_1: "original value 1", VAR_2: "original value 2", // should not get overridden VAR_3: "original value 3", VAR_MULTI_LINE_1: "original multi-line 1", VAR_MULTI_LINE_2: "original multi-line 2", EMPTY: "original empty", UNQUOTED: "original unquoted", }, }); await runWrangler("dev"); const varBindings: Record<string, unknown> = (Dev as jest.Mock).mock .calls[0][0].bindings.vars; expect(varBindings).toEqual({ VAR_1: "var #1 value", VAR_2: "original value 2", VAR_3: "var #3 value", VAR_MULTI_LINE_1: "A: line 1\nline 2", VAR_MULTI_LINE_2: "B: line 1\nline 2", EMPTY: "", UNQUOTED: "unquoted value", // Note that whitespace is trimmed }); expect(std.out).toMatchInlineSnapshot( `"Using vars defined in .dev.vars"` ); expect(std.warn).toMatchInlineSnapshot(`""`); expect(std.err).toMatchInlineSnapshot(`""`); }); }); describe("site", () => { it("should error if --site is used with no value", async () => { await expect( runWrangler("dev --site") ).rejects.toThrowErrorMatchingInlineSnapshot( `"Not enough arguments following: site"` ); expect(std).toMatchInlineSnapshot(` Object { "debug": "", "err": "wrangler dev [script] 👂 Start a local server for developing your worker Positionals: script The path to an entry point for your worker [string] Flags: -c, --config Path to .toml configuration file [string] -h, --help Show help [boolean] -v, --version Show version number [boolean] Options: --name Name of the worker [string] --format Choose an entry type [deprecated] [choices: \\"modules\\", \\"service-worker\\"] -e, --env Perform on a specific environment [string] --compatibility-date Date to use for compatibility checks [string] --compatibility-flags, --compatibility-flag Flags to use for compatibility checks [array] --latest Use the latest version of the worker runtime [boolean] [default: true] --ip IP address to listen on, defaults to \`localhost\` [string] --port Port to listen on [number] --inspector-port Port for devtools to connect to [number] --routes, --route Routes to upload [array] --host Host to forward requests to, defaults to the zone of project [string] --local-protocol Protocol to listen to requests on, defaults to http. [choices: \\"http\\", \\"https\\"] --experimental-public Static assets to be served [string] --site Root folder of static assets for Workers Sites [string] --site-include Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded. [array] --site-exclude Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded. [array] --upstream-protocol Protocol to forward requests to host on, defaults to https. [choices: \\"http\\", \\"https\\"] --jsx-factory The function that is called for each JSX element [string] --jsx-fragment The function that is called for each JSX fragment [string] --tsconfig Path to a custom tsconfig.json file [string] -l, --local Run on my machine [boolean] [default: false] --minify Minify the script [boolean] --node-compat Enable node.js compatibility [boolean] --experimental-enable-local-persistence Enable persistence for this session (only for local mode) [boolean] --inspect Enable dev tools [deprecated] [boolean] X [ERROR] Not enough arguments following: site ", "out": " ", "warn": "", } `); }); }); describe("--inspect", () => { it("should warn if --inspect is used", async () => { fs.writeFileSync("index.js", `export default {};`); await runWrangler("dev index.js --inspect"); expect(std).toMatchInlineSnapshot(` Object { "debug": "", "err": "", "out": "", "warn": "▲ [WARNING] Passing --inspect is unnecessary, now you can always connect to devtools. ", } `); }); }); }); function mockGetZones(domain: string, zones: { id: string }[] = []) { const removeMock = setMockResponse( "/zones", "GET", (_urlPieces, _init, queryParams) => { expect([...queryParams.entries()]).toEqual([["name", domain]]); // Because the API URL `/zones` is the same for each request, we can get into a situation where earlier mocks get triggered for later requests. So, we simply clear the mock on every trigger. removeMock(); return zones; } ); }
the_stack
import * as parser from "jsonc-parser"; import * as vscode from "vscode"; import { Constants } from "../common/constants"; import { DiagnosticMessage, DigitalTwinConstants } from "./digitalTwinConstants"; import { ClassNode, PropertyNode, ValueSchema } from "./digitalTwinGraph"; import { IntelliSenseUtility, JsonNodeType, PropertyPair, ModelContent } from "./intelliSenseUtility"; import { LANGUAGE_CODE } from "./languageCode"; /** * Diagnostic problem */ interface Problem { offset: number; length: number; message: string; } /** * Diagnostic provider for DigitalTwin IntelliSense */ export class DigitalTwinDiagnosticProvider { /** * find class node by type * @param propertyNode DigitalTwin property node * @param type class type */ private static findClassNode(propertyNode: PropertyNode, type: string): ClassNode | undefined { if (propertyNode.range) { return propertyNode.range.find(classNode => IntelliSenseUtility.getClassType(classNode) === type); } return undefined; } /** * get property pair of name property * @param jsonNode json node */ private static getNamePropertyPair(jsonNode: parser.Node): PropertyPair | undefined { if (jsonNode.type !== JsonNodeType.Object || !jsonNode.children) { return undefined; } let propertyPair: PropertyPair | undefined; for (const child of jsonNode.children) { propertyPair = IntelliSenseUtility.parseProperty(child); if (!propertyPair) { continue; } if (propertyPair.name.value === DigitalTwinConstants.NAME) { return propertyPair; } } return undefined; } /** * add problem of invalid type * @param jsonNode json node * @param digitalTwinNode DigitalTwin property node * @param problems problem collection */ private static addProblemOfInvalidType( jsonNode: parser.Node, digitalTwinNode: PropertyNode, problems: Problem[] ): void { const validTypes: string[] = IntelliSenseUtility.getValidTypes(digitalTwinNode); const message: string = [DiagnosticMessage.InvalidType, ...validTypes].join(Constants.LINE_FEED); DigitalTwinDiagnosticProvider.addProblem(jsonNode, problems, message); } /** * add problem of unexpected property * @param jsonNode json node * @param problems problem collection */ private static addProblemOfUnexpectedProperty(jsonNode: parser.Node, problems: Problem[]): void { const message = `${jsonNode.value as string} ${DiagnosticMessage.UnexpectedProperty}`; DigitalTwinDiagnosticProvider.addProblem(jsonNode, problems, message); } /** * add problem * @param jsonNode json node * @param problems problem collection * @param message diagnostic message * @param isContainer identify if json node is a container (e.g. object or array) */ private static addProblem(jsonNode: parser.Node, problems: Problem[], message: string, isContainer?: boolean): void { const length: number = isContainer ? 0 : jsonNode.length; problems.push({ offset: jsonNode.offset, length, message }); } /** * validate json node by DigitalTwin graph, add problem in problem collection * @param version target version * @param jsonNode json node * @param digitalTwinNode DigitalTwin property node * @param problems problem collection */ private static validateNode( version: number, jsonNode: parser.Node, digitalTwinNode: PropertyNode, problems: Problem[] ): void { switch (jsonNode.type) { case JsonNodeType.Object: DigitalTwinDiagnosticProvider.validateObjectNode(version, jsonNode, digitalTwinNode, problems); break; case JsonNodeType.Array: DigitalTwinDiagnosticProvider.validateArrayNode(version, jsonNode, digitalTwinNode, problems); break; case JsonNodeType.String: DigitalTwinDiagnosticProvider.validateStringNode(version, jsonNode, digitalTwinNode, problems); break; case JsonNodeType.Number: DigitalTwinDiagnosticProvider.validateNumberNode(jsonNode, digitalTwinNode, problems); break; case JsonNodeType.Boolean: DigitalTwinDiagnosticProvider.validateBooleanNode(jsonNode, digitalTwinNode, problems); break; default: } } /** * validate Object json node * @param version target version * @param jsonNode json node * @param digitalTwinNode DigitalTwin property node * @param problems problem collection */ private static validateObjectNode( version: number, jsonNode: parser.Node, digitalTwinNode: PropertyNode, problems: Problem[] ): void { const classes: ClassNode[] = IntelliSenseUtility.getObjectClasses(digitalTwinNode, version); if (!classes.length) { DigitalTwinDiagnosticProvider.addProblem(jsonNode, problems, DiagnosticMessage.NotObjectType); return; } if (!jsonNode.children || !jsonNode.children.length) { DigitalTwinDiagnosticProvider.addProblem(jsonNode, problems, DiagnosticMessage.EmptyObject, true); return; } const typePath: parser.JSONPath = [DigitalTwinConstants.TYPE]; const typeNode: parser.Node | undefined = parser.findNodeAtLocation(jsonNode, typePath); // @type is required when there are multiple choice if (!typeNode && classes.length !== 1) { DigitalTwinDiagnosticProvider.addProblem(jsonNode, problems, DiagnosticMessage.MissingType, true); return; } // validate @type property let classNode: ClassNode | undefined; if (typeNode) { classNode = DigitalTwinDiagnosticProvider.getValidObjectType(typeNode, digitalTwinNode, classes, problems); } else { classNode = classes[0]; } if (!classNode) { return; } // validate language node if (IntelliSenseUtility.isLanguageNode(classNode)) { DigitalTwinDiagnosticProvider.validateLanguageNode(version, jsonNode, digitalTwinNode, problems); return; } // validate other properties const expect = new Set<string>(); const exist = new Set<string>(); DigitalTwinDiagnosticProvider.validateProperties(version, jsonNode, classNode, problems, expect, exist); // validate required property if (classNode.constraint && classNode.constraint.required) { const requiredProperties: string[] = classNode.constraint.required.filter(property => { // property is not available in version if (!IntelliSenseUtility.isReservedName(property) && !expect.has(property)) { return false; } // @context is not required for inline Interface if (property === DigitalTwinConstants.CONTEXT && digitalTwinNode.label === DigitalTwinConstants.SCHEMA) { return false; } return !exist.has(property); }); if (requiredProperties.length) { const message: string = [DiagnosticMessage.MissingRequiredProperties, ...requiredProperties].join( Constants.LINE_FEED ); DigitalTwinDiagnosticProvider.addProblem(jsonNode, problems, message, true); } requiredProperties.length = 0; } expect.clear(); exist.clear(); } /** * get valid object type from classes * @param jsonNode json node * @param digitalTwinNode DigitalTwin property node * @param classes class node collection * @param problems problem collection */ private static getValidObjectType( jsonNode: parser.Node, digitalTwinNode: PropertyNode, classes: ClassNode[], problems: Problem[] ): ClassNode | undefined { let classNode: ClassNode | undefined; const dummyNode: PropertyNode = { id: DigitalTwinConstants.DUMMY_NODE, range: classes }; if (jsonNode.type === JsonNodeType.String) { classNode = DigitalTwinDiagnosticProvider.findClassNode(dummyNode, jsonNode.value as string); } else if ( jsonNode.type === JsonNodeType.Array && jsonNode.children && digitalTwinNode.label === DigitalTwinConstants.CONTENTS ) { // support semantic types let currentNode: ClassNode | undefined; for (const child of jsonNode.children) { if (child.type !== JsonNodeType.String) { classNode = undefined; break; } // validate conflict type currentNode = DigitalTwinDiagnosticProvider.findClassNode(dummyNode, child.value as string); if (currentNode) { if (classNode) { const message = `${DiagnosticMessage.ConflictType} ${classNode.label} and ${currentNode.label}`; DigitalTwinDiagnosticProvider.addProblem(jsonNode, problems, message); return undefined; } else { classNode = currentNode; } } } } if (!classNode) { DigitalTwinDiagnosticProvider.addProblemOfInvalidType(jsonNode, dummyNode, problems); } return classNode; } /** * validate properties of Object json node * @param version target version * @param jsonNode json node * @param classNode class node * @param problems problem colletion * @param expect expected properties * @param exist existing properties */ private static validateProperties( version: number, jsonNode: parser.Node, classNode: ClassNode, problems: Problem[], expect: Set<string>, exist: Set<string> ): void { if (!jsonNode.children) { return; } const expectedProperties = new Map<string, PropertyNode>(); for (const property of IntelliSenseUtility.getPropertiesOfClassByVersion(classNode, version)) { if (property.label) { expect.add(property.label); expectedProperties.set(property.label, property); } } let propertyName: string; let propertyPair: PropertyPair | undefined; let propertyNode: PropertyNode | undefined; for (const child of jsonNode.children) { propertyPair = IntelliSenseUtility.parseProperty(child); if (!propertyPair) { continue; } propertyName = propertyPair.name.value as string; // duplicate property name is handled by json validator exist.add(propertyName); switch (propertyName) { case DigitalTwinConstants.ID: // @id is available for each class propertyNode = IntelliSenseUtility.getPropertyNode(DigitalTwinConstants.ID); if (propertyNode) { DigitalTwinDiagnosticProvider.validateNode(version, propertyPair.value, propertyNode, problems); } break; case DigitalTwinConstants.CONTEXT: // @context is available when it is required if ( classNode.constraint && classNode.constraint.required && classNode.constraint.required.includes(DigitalTwinConstants.CONTEXT) ) { if (IntelliSenseUtility.getDigitalTwinVersion(propertyPair.value) !== version) { DigitalTwinDiagnosticProvider.addProblem(propertyPair.value, problems, DiagnosticMessage.InvalidContext); } } else { DigitalTwinDiagnosticProvider.addProblemOfUnexpectedProperty(propertyPair.name, problems); } break; case DigitalTwinConstants.TYPE: // skip since @type is already validated break; default: // validate expected property propertyNode = expectedProperties.get(propertyName); if (!propertyNode) { DigitalTwinDiagnosticProvider.addProblemOfUnexpectedProperty(propertyPair.name, problems); } else { DigitalTwinDiagnosticProvider.validateNode(version, propertyPair.value, propertyNode, problems); } } } expectedProperties.clear(); } /** * validate Array json node * @param version target version * @param jsonNode json node * @param digitalTwinNode DigitalTwin property node * @param problems problem collection */ private static validateArrayNode( version: number, jsonNode: parser.Node, digitalTwinNode: PropertyNode, problems: Problem[] ): void { if (!digitalTwinNode.isArray) { DigitalTwinDiagnosticProvider.addProblemOfInvalidType(jsonNode, digitalTwinNode, problems); return; } if (!jsonNode.children || !jsonNode.children.length) { DigitalTwinDiagnosticProvider.addProblem(jsonNode, problems, DiagnosticMessage.EmptyArray, true); return; } // validate item constraint let message: string; if (digitalTwinNode.constraint) { if (digitalTwinNode.constraint.minItems && jsonNode.children.length < digitalTwinNode.constraint.minItems) { message = `${DiagnosticMessage.TooFewItems} ${digitalTwinNode.constraint.minItems}.`; DigitalTwinDiagnosticProvider.addProblem(jsonNode, problems, message, true); } else if ( digitalTwinNode.constraint.maxItems && jsonNode.children.length > digitalTwinNode.constraint.maxItems ) { message = `${DiagnosticMessage.TooManyItems} ${digitalTwinNode.constraint.maxItems}.`; DigitalTwinDiagnosticProvider.addProblem(jsonNode, problems, message, true); } } // validate item uniqueness by name let propertyPair: PropertyPair | undefined; let objectName: string; const exist = new Set<string>(); for (const child of jsonNode.children) { propertyPair = DigitalTwinDiagnosticProvider.getNamePropertyPair(child); if (propertyPair) { objectName = propertyPair.value.value as string; if (exist.has(objectName)) { message = `${objectName} ${DiagnosticMessage.DuplicateItem}`; DigitalTwinDiagnosticProvider.addProblem(propertyPair.value, problems, message); } else { exist.add(objectName); } } // validate each item DigitalTwinDiagnosticProvider.validateNode(version, child, digitalTwinNode, problems); } exist.clear(); } /** * validate String json node * @param version target version * @param jsonNode json node * @param digitalTwinNode DigitalTwin property node * @param problems problem collection */ private static validateStringNode( version: number, jsonNode: parser.Node, digitalTwinNode: PropertyNode, problems: Problem[] ): void { const classNode: ClassNode | undefined = DigitalTwinDiagnosticProvider.findClassNode( digitalTwinNode, ValueSchema.String ); // validate enum node if (!classNode) { DigitalTwinDiagnosticProvider.validateEnumNode(version, jsonNode, digitalTwinNode, problems); return; } const value: string = jsonNode.value as string; if (!value) { DigitalTwinDiagnosticProvider.addProblem(jsonNode, problems, DiagnosticMessage.EmptyString); return; } // validate string constraint let message: string; if (digitalTwinNode.constraint) { if (digitalTwinNode.constraint.minLength && value.length < digitalTwinNode.constraint.minLength) { message = `${DiagnosticMessage.ShorterThanMinLength} ${digitalTwinNode.constraint.minLength}.`; DigitalTwinDiagnosticProvider.addProblem(jsonNode, problems, message); return; } else if (digitalTwinNode.constraint.maxLength && value.length > digitalTwinNode.constraint.maxLength) { message = `${DiagnosticMessage.LongerThanMaxLength} ${digitalTwinNode.constraint.maxLength}.`; DigitalTwinDiagnosticProvider.addProblem(jsonNode, problems, message); return; } else if (digitalTwinNode.constraint.pattern) { const regex = new RegExp(digitalTwinNode.constraint.pattern); if (!regex.test(value)) { message = `${DiagnosticMessage.NotMatchPattern} ${digitalTwinNode.constraint.pattern}.`; DigitalTwinDiagnosticProvider.addProblem(jsonNode, problems, message); return; } } } } /** * validate enum node * @param version target version * @param jsonNode json node * @param digitalTwinNode DigitalTwin property node * @param problems problem collection */ private static validateEnumNode( version: number, jsonNode: parser.Node, digitalTwinNode: PropertyNode, problems: Problem[] ): void { const enums: string[] = IntelliSenseUtility.getEnums(digitalTwinNode, version); if (!enums.length) { DigitalTwinDiagnosticProvider.addProblemOfInvalidType(jsonNode, digitalTwinNode, problems); } else if (!enums.includes(jsonNode.value as string)) { const message: string = [DiagnosticMessage.InvalidEnum, ...enums].join(Constants.LINE_FEED); DigitalTwinDiagnosticProvider.addProblem(jsonNode, problems, message); } enums.length = 0; } /** * validate json number node * @param jsonNode json node * @param digitalTwinNode DigitalTwin property node * @param problems problem collection */ private static validateNumberNode(jsonNode: parser.Node, digitalTwinNode: PropertyNode, problems: Problem[]): void { const classNode: ClassNode | undefined = DigitalTwinDiagnosticProvider.findClassNode( digitalTwinNode, ValueSchema.Int ); // validate number is integer if (!classNode || !Number.isInteger(jsonNode.value as number)) { DigitalTwinDiagnosticProvider.addProblemOfInvalidType(jsonNode, digitalTwinNode, problems); return; } } /** * validate boolean node * @param jsonNode json node * @param digitalTwinNode DigitalTwin property node * @param problems problem collection */ private static validateBooleanNode(jsonNode: parser.Node, digitalTwinNode: PropertyNode, problems: Problem[]): void { const classNode: ClassNode | undefined = DigitalTwinDiagnosticProvider.findClassNode( digitalTwinNode, ValueSchema.Boolean ); if (!classNode) { DigitalTwinDiagnosticProvider.addProblemOfInvalidType(jsonNode, digitalTwinNode, problems); return; } } /** * validate language node * @param version target version * @param jsonNode json node * @param digitalTwinNode DigitalTwin property node * @param problems problem collection */ private static validateLanguageNode( version: number, jsonNode: parser.Node, digitalTwinNode: PropertyNode, problems: Problem[] ): void { if (!jsonNode.children) { return; } let propertyName: string; let propertyPair: PropertyPair | undefined; for (const child of jsonNode.children) { propertyPair = IntelliSenseUtility.parseProperty(child); if (!propertyPair) { continue; } propertyName = propertyPair.name.value as string; if (!LANGUAGE_CODE.has(propertyName)) { DigitalTwinDiagnosticProvider.addProblemOfUnexpectedProperty(propertyPair.name, problems); } else if (propertyPair.value.type !== JsonNodeType.String) { DigitalTwinDiagnosticProvider.addProblem(propertyPair.value, problems, DiagnosticMessage.ValueNotString); } else { DigitalTwinDiagnosticProvider.validateStringNode(version, propertyPair.value, digitalTwinNode, problems); } } } /** * update diagnostics * @param document text document * @param collection diagnostic collection */ updateDiagnostics(document: vscode.TextDocument, collection: vscode.DiagnosticCollection): void { if (!IntelliSenseUtility.enabled()) { return; } const modelContent: ModelContent | undefined = IntelliSenseUtility.parseDigitalTwinModel(document.getText()); if (!modelContent) { // clean diagnostic cache collection.delete(document.uri); return; } const diagnostics: vscode.Diagnostic[] = this.provideDiagnostics(document, modelContent); collection.set(document.uri, diagnostics); } /** * provide diagnostics * @param document text document * @param modelContent model content */ private provideDiagnostics(document: vscode.TextDocument, modelContent: ModelContent): vscode.Diagnostic[] { let diagnostics: vscode.Diagnostic[] = []; const digitalTwinNode: PropertyNode | undefined = IntelliSenseUtility.getEntryNode(); if (!digitalTwinNode) { return diagnostics; } const problems: Problem[] = []; DigitalTwinDiagnosticProvider.validateNode(modelContent.version, modelContent.jsonNode, digitalTwinNode, problems); diagnostics = problems.map( p => new vscode.Diagnostic( new vscode.Range(document.positionAt(p.offset), document.positionAt(p.offset + p.length)), p.message, vscode.DiagnosticSeverity.Error ) ); // clear problem collection problems.length = 0; return diagnostics; } }
the_stack
import { TransactionFactory, Transaction, TxStatus } from '../src'; // tslint:disable-next-line: no-implicit-dependencies import { Wallet } from '@harmony-js/account'; import { HttpProvider, Messenger } from '@harmony-js/network'; import { ChainType, ChainID } from '@harmony-js/utils'; import { toChecksumAddress, randomBytes } from '@harmony-js/crypto'; // tslint:disable-next-line: no-implicit-dependencies import fetch from 'jest-fetch-mock'; const http = new HttpProvider('http://mock.com'); // const ws = new WSProvider('ws://mock.com'); const addr = toChecksumAddress('0x' + randomBytes(20)); const msgHttp = new Messenger(http, ChainType.Harmony, ChainID.HmyLocal); // const msgWs = new Messenger(ws, ChainType.Harmony, ChainID.HmyLocal); const walletHttp = new Wallet(msgHttp); // const walletWs = new Wallet(msgWs); describe('test send transaction', () => { beforeEach(() => { // jest.useFakeTimers(); }); afterEach(() => { fetch.resetMocks(); // jest.clearAllTimers(); }); it('should test wallet sign and send', async () => { const responses = [ { jsonrpc: '2.0', id: 1, result: 1, }, { jsonrpc: '2.0', id: 1, result: '0x7e1ef610f700805b93cf85b1e55bce84fcbd04373252a968755366a8d2215424', }, ].map((res) => [JSON.stringify(res)] as [string]); fetch.mockResponses(...responses); const factory = new TransactionFactory(msgHttp); const tx: Transaction = factory.newTx( { to: addr, value: '1', gasLimit: '21000', gasPrice: '1', }, false, ); expect(tx.txStatus).toEqual(TxStatus.INTIALIZED); const account: any | Account = await walletHttp.createAccount(); const signed: Transaction = await account.signTransaction(tx, true, 'rlp', 'latest'); expect(signed.txStatus).toEqual(TxStatus.SIGNED); expect(signed.txParams.nonce).toEqual(1); expect(signed.txPayload.nonce).toEqual('0x1'); expect(signed.txParams.signature.r).toBeTruthy(); expect(signed.txParams.signature.s).toBeTruthy(); expect(signed.txParams.signature.v).toBeTruthy(); expect(signed.txParams.rawTransaction).toEqual(signed.getRawTransaction()); const [sent, hash] = await signed.sendTransaction(); expect(sent.txParams.id).toEqual(hash); expect(sent.txStatus).toEqual(TxStatus.PENDING); }); it('should test wallet sign and send shardingTransaction', async () => { const factory = new TransactionFactory(msgHttp); const tx: Transaction = factory.newTx( { to: addr + '-1', value: '1', gasLimit: '21000', gasPrice: '1', }, true, ); expect(tx.cxStatus).toEqual(TxStatus.INTIALIZED); }); it('should reject and confirm tx', async () => { const responses = [ { jsonrpc: '2.0', id: 1, result: [ { current: true, http: 'http://localhost', shardID: 0, ws: 'ws://localhost', }, { current: false, http: 'http://localhost', shardID: 1, ws: 'ws://localhost', }, ], }, { jsonrpc: '2.0', id: 5, result: '0x0', }, { jsonrpc: '2.0', id: 5, result: '0x1', }, { jsonrpc: '2.0', id: 5, result: null, }, { jsonrpc: '2.0', id: 5, result: '0x1', }, // attemp 1 { jsonrpc: '2.0', id: 5, result: '0x2', }, { jsonrpc: '2.0', id: 5, result: null, }, { jsonrpc: '2.0', id: 5, result: '0x2', }, // attemp 2 { jsonrpc: '2.0', id: 5, result: '0x3', }, { jsonrpc: '2.0', id: 5, result: null, }, { jsonrpc: '2.0', id: 5, result: '0x3', }, // attemp 3 { jsonrpc: '2.0', id: 5, result: '0x4', }, { jsonrpc: '2.0', id: 5, result: '0x5', }, { jsonrpc: '2.0', id: 3, result: { blockHash: '0x7ef01c8532dbe8ae9930ebf3d38cf5f3937193c3c90680d4e9d5206552e4f6a6', blockNumber: '0x1d3c0', contractAddress: null, cumulativeGasUsed: '0x5208', from: 'one1z05g55zamqzfw9qs432n33gycdmyvs38xjemyl', gasUsed: '0x5208', logs: [], logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', shardID: 0, status: '0x1', to: 'one1z05g55zamqzfw9qs432n33gycdmyvs38xjemyl', transactionHash: '0x1bb3cadb2031e5ce987b0c557abe134986b9834963dd0d54f75a9c7d966606ce', transactionIndex: '0x0', }, }, { jsonrpc: '2.0', id: 5, result: '0x5', }, ].map((res) => [JSON.stringify(res)] as [string]); fetch.mockResponses(...responses); const hash = '0x7e1ef610f700805b93cf85b1e55bce84fcbd04373252a968755366a8d2215424'; const factory = new TransactionFactory(msgHttp); const shardID = 0; const toShardID = 1; const tx: Transaction = factory.newTx({ shardID, toShardID }, false); expect(tx.cxStatus).toEqual(TxStatus.INTIALIZED); await tx.messenger.setShardingProviders(); await expect(tx.txConfirm(hash, 3, 100, shardID)).rejects.toThrow( 'The transaction is still not confirmed after 3 attempts.', ); const confirmed = await tx.txConfirm(hash, 4, 100, shardID); expect(confirmed.txStatus).toEqual(TxStatus.CONFIRMED); }); it('should reject and confirm cx', async () => { const responses = [ { jsonrpc: '2.0', id: 1, result: [ { current: true, http: 'http://localhost', shardID: 0, ws: 'ws://localhost', }, { current: false, http: 'http://localhost', shardID: 1, ws: 'ws://localhost', }, ], }, { jsonrpc: '2.0', id: 5, result: '0x0', }, { jsonrpc: '2.0', id: 5, result: '0x1', }, { jsonrpc: '2.0', id: 5, result: null, }, { jsonrpc: '2.0', id: 5, result: '0x1', }, // attemp 1 { jsonrpc: '2.0', id: 5, result: '0x2', }, { jsonrpc: '2.0', id: 5, result: null, }, { jsonrpc: '2.0', id: 5, result: '0x2', }, // attemp 2 { jsonrpc: '2.0', id: 5, result: '0x3', }, { jsonrpc: '2.0', id: 5, result: null, }, { jsonrpc: '2.0', id: 5, result: '0x3', }, // attemp 3 { jsonrpc: '2.0', id: 5, result: '0x4', }, { jsonrpc: '2.0', id: 5, result: '0x5', }, { jsonrpc: '2.0', id: 6, result: { blockHash: '0xd92f3610d52bde907ab42e064d73c2314c058015a7162ee8a4500bc581903cc2', blockNumber: '0x18465', hash: '0xcff4a3a6fd4eb34b9a7e48e3eca0c8c899de71a1ea21a126cc1048e65b332a72', from: 'one1v5fevthrnfeqjwcl5p0sfq3u34c2gmtqq095at', to: 'one18spwh74s5hkg2nva40scx7hwdjpup28dw4dfsg', shardID: 0, toShardID: 1, value: '0xde0b6b3a7640000', }, }, { jsonrpc: '2.0', id: 5, result: '0x5', }, ].map((res) => [JSON.stringify(res)] as [string]); fetch.mockResponses(...responses); const hash = '0x7e1ef610f700805b93cf85b1e55bce84fcbd04373252a968755366a8d2215424'; const factory = new TransactionFactory(msgHttp); const shardID = 0; const toShardID = 1; const tx: Transaction = factory.newTx({ shardID, toShardID }, false); expect(tx.cxStatus).toEqual(TxStatus.INTIALIZED); await tx.messenger.setShardingProviders(); await expect(tx.cxConfirm(hash, 3, 100, toShardID)).rejects.toThrow( 'The transaction is still not confirmed after 3 attempts.', ); const confirmed = await tx.cxConfirm(hash, 4, 100, toShardID); expect(confirmed.cxStatus).toEqual(TxStatus.CONFIRMED); }); it('should confirm and confirm cx', async () => { const responses = [ { jsonrpc: '2.0', id: 1, result: [ { current: true, http: 'http://localhost', shardID: 0, ws: 'ws://localhost', }, { current: false, http: 'http://localhost', shardID: 1, ws: 'ws://localhost', }, ], }, { jsonrpc: '2.0', id: 5, result: '0x0', }, { jsonrpc: '2.0', id: 5, result: '0x1', }, { jsonrpc: '2.0', id: 3, result: { blockHash: '0x7ef01c8532dbe8ae9930ebf3d38cf5f3937193c3c90680d4e9d5206552e4f6a6', blockNumber: '0x1d3c0', contractAddress: null, cumulativeGasUsed: '0x5208', from: 'one1z05g55zamqzfw9qs432n33gycdmyvs38xjemyl', gasUsed: '0x5208', logs: [], logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', shardID: 0, status: '0x1', to: 'one1z05g55zamqzfw9qs432n33gycdmyvs38xjemyl', transactionHash: '0x1bb3cadb2031e5ce987b0c557abe134986b9834963dd0d54f75a9c7d966606ce', transactionIndex: '0x0', }, }, { jsonrpc: '2.0', id: 5, result: '0x1', }, { jsonrpc: '2.0', id: 5, result: '0x4', }, { jsonrpc: '2.0', id: 5, result: '0x5', }, { jsonrpc: '2.0', id: 6, result: { blockHash: '0xd92f3610d52bde907ab42e064d73c2314c058015a7162ee8a4500bc581903cc2', blockNumber: '0x18465', hash: '0xcff4a3a6fd4eb34b9a7e48e3eca0c8c899de71a1ea21a126cc1048e65b332a72', from: 'one1v5fevthrnfeqjwcl5p0sfq3u34c2gmtqq095at', to: 'one18spwh74s5hkg2nva40scx7hwdjpup28dw4dfsg', shardID: 0, toShardID: 1, value: '0xde0b6b3a7640000', }, }, { jsonrpc: '2.0', id: 5, result: '0x5', }, ].map((res) => [JSON.stringify(res)] as [string]); fetch.mockResponses(...responses); const hash = '0x7e1ef610f700805b93cf85b1e55bce84fcbd04373252a968755366a8d2215424'; const factory = new TransactionFactory(msgHttp); const shardID = 0; const toShardID = 1; const tx: Transaction = factory.newTx({ shardID, toShardID }, false); expect(tx.txStatus).toEqual(TxStatus.INTIALIZED); expect(tx.cxStatus).toEqual(TxStatus.INTIALIZED); await tx.messenger.setShardingProviders(); tx.observed() .on('track', (track) => { expect(track).toBeTruthy(); }) .on('confirmation', (confirmation) => { expect(confirmation).toBeTruthy(); }); const confirmed = await tx.confirm(hash); expect(confirmed.isSigned()).toEqual(false); expect(confirmed.isPending()).toEqual(false); expect(confirmed.isRejected()).toEqual(false); expect(confirmed.isInitialized()).toEqual(false); expect(confirmed.isConfirmed()).toEqual(true); expect(confirmed.isCxPending()).toEqual(false); expect(confirmed.isCxRejected()).toEqual(false); expect(confirmed.isCxConfirmed()).toEqual(true); confirmed.setCxStatus(confirmed.cxStatus); confirmed.setTxStatus(confirmed.txStatus); expect(confirmed.getTxStatus()).toEqual(TxStatus.CONFIRMED); expect(confirmed.getCxStatus()).toEqual(TxStatus.CONFIRMED); }); });
the_stack
import type { Compiler, Compilation, Module, ModuleGraph, NormalModule, ChunkGraph, sources, RuntimeModule, Dependency, dependencies, } from 'webpack'; import type { BuildData, DependencyTemplates, RuntimeTemplate, StringSortableSet, StylableBuildMeta, } from './types'; import { stylesheet } from '@stylable/runtime/dist/runtime'; import { injectStyles } from '@stylable/runtime/dist/inject-styles'; import { getStylableBuildData, replaceMappedCSSAssetPlaceholders } from './plugin-utils'; import { getReplacementToken } from './loader-utils'; const entitiesCache = new WeakMap<Compiler['webpack'], StylableWebpackEntities>(); export interface DependencyTemplateContext { module: Module; moduleGraph: ModuleGraph; runtimeRequirements: Set<string>; runtimeTemplate: RuntimeTemplate; runtime?: string | StringSortableSet; chunkGraph: ChunkGraph; dependencyTemplates: DependencyTemplates; } type DependencyTemplate = InstanceType<typeof dependencies.ModuleDependency['Template']>; interface InjectDependencyTemplate { new ( staticPublicPath: string, stylableModules: Map<Module, BuildData | null>, assetsModules: Map<string, NormalModule>, runtimeStylesheetId: 'namespace' | 'module', runtimeId: string, cssInjection: 'js' | 'css' | 'mini-css' | 'none' ): DependencyTemplate; } interface StylableRuntimeDependency { new (stylableBuildMeta: StylableBuildMeta): Dependency; } export interface StylableWebpackEntities { injectRuntimeModules: (name: string, compilation: Compilation) => void; StylableRuntimeInject: typeof RuntimeModule; InjectDependencyTemplate: InjectDependencyTemplate; StylableRuntimeDependency: StylableRuntimeDependency; StylableRuntimeStylesheet: typeof RuntimeModule; CSSURLDependency: typeof dependencies.ModuleDependency; NoopTemplate: typeof dependencies.ModuleDependency.Template; UnusedDependency: typeof dependencies.ModuleDependency; } export function getWebpackEntities(webpack: Compiler['webpack']): StylableWebpackEntities { const { dependencies: { ModuleDependency }, Dependency, NormalModule, RuntimeModule, RuntimeGlobals, } = webpack; let entities = entitiesCache.get(webpack); if (entities) { return entities; } class CSSURLDependency extends ModuleDependency { // @ts-expect-error webpack types are wrong consider this as property get type() { return 'url()'; } // @ts-expect-error webpack types are wrong consider this as property get category() { return 'url'; } } class UnusedDependency extends ModuleDependency { weak = true; // @ts-expect-error webpack types are wrong consider this as property get type() { return '@st-unused-import'; } } class NoopTemplate { apply() { /** noop */ } } class StylableRuntimeStylesheet extends RuntimeModule { constructor() { super('stylable stylesheet', RuntimeModule.STAGE_NORMAL); } generate() { return `(${stylesheet})(__webpack_require__)`; } } class StylableRuntimeDependency extends Dependency { constructor(private stylableBuildMeta: StylableBuildMeta) { super(); } updateHash(hash: any) { hash.update(JSON.stringify(this.stylableBuildMeta)); } serialize(context: any) { context.write(this.stylableBuildMeta); super.serialize(context); } } class InjectDependencyTemplate { constructor( private staticPublicPath: string, private stylableModules: Map<Module, BuildData | null>, private assetsModules: Map<string, NormalModule>, private runtimeStylesheetId: 'namespace' | 'module', private runtimeId: string, private cssInjection: 'js' | 'css' | 'mini-css' | 'none' ) {} apply( _dependency: StylableRuntimeDependency, source: sources.ReplaceSource, { module, runtimeRequirements, runtimeTemplate, moduleGraph, runtime, chunkGraph, dependencyTemplates, }: DependencyTemplateContext ) { const stylableBuildData = getStylableBuildData(this.stylableModules, module); if (!stylableBuildData.isUsed) { return; } if (this.cssInjection === 'js') { const css = replaceMappedCSSAssetPlaceholders({ assetsModules: this.assetsModules, staticPublicPath: this.staticPublicPath, chunkGraph, moduleGraph, dependencyTemplates, runtime, runtimeTemplate, stylableBuildData, }); if (!(module instanceof NormalModule)) { throw new Error( `InjectDependencyTemplate should only be used on stylable modules was found on ${module.identifier()}` ); } const id = this.runtimeStylesheetId === 'module' ? JSON.stringify( runtimeTemplate.requestShortener.contextify(module.resource) ) : 'namespace'; replacePlaceholder( source, '/* JS_INJECT */', `__webpack_require__.sti(${id}, ${JSON.stringify(css)}, ${ stylableBuildData.depth }, ${JSON.stringify(this.runtimeId)});` ); runtimeRequirements.add(StylableRuntimeInject.name); } const usedExports = moduleGraph.getUsedExports(module, runtime); if (typeof usedExports === 'boolean') { if (usedExports) { runtimeRequirements.add(StylableRuntimeStylesheet.name); } } else if (!usedExports) { runtimeRequirements.add(StylableRuntimeStylesheet.name); } else if ( usedExports.has('st') || usedExports.has('style') || usedExports.has('cssStates') ) { runtimeRequirements.add(StylableRuntimeStylesheet.name); } if (runtimeRequirements.has(StylableRuntimeStylesheet.name)) { /* st */ replacePlaceholder(source, getReplacementToken('st'), `/*#__PURE__*/ style`); /* style */ replacePlaceholder( source, getReplacementToken('sts'), `/*#__PURE__*/ __webpack_require__.sts.bind(null, namespace)` ); /* cssStates */ replacePlaceholder( source, getReplacementToken('stc'), `/*#__PURE__*/ __webpack_require__.stc.bind(null, namespace)` ); } replacePlaceholder( source, getReplacementToken('vars'), JSON.stringify(stylableBuildData.exports.vars) ); replacePlaceholder( source, getReplacementToken('stVars'), JSON.stringify(stylableBuildData.exports.stVars) ); replacePlaceholder( source, getReplacementToken('keyframes'), JSON.stringify(stylableBuildData.exports.keyframes) ); replacePlaceholder( source, getReplacementToken('classes'), JSON.stringify(stylableBuildData.exports.classes) ); replacePlaceholder( source, getReplacementToken('namespace'), JSON.stringify(stylableBuildData.namespace) ); } } class StylableRuntimeInject extends RuntimeModule { constructor() { super('stylable inject', RuntimeModule.STAGE_NORMAL); } generate() { return `(${injectStyles})(__webpack_require__)`; } } function injectRuntimeModules(name: string, compilation: Compilation) { compilation.hooks.runtimeRequirementInModule .for(StylableRuntimeInject.name) .tap(name, (_module, set) => { set.add(RuntimeGlobals.require); }); compilation.hooks.runtimeRequirementInModule .for(StylableRuntimeStylesheet.name) .tap(name, (_module, set) => { set.add(RuntimeGlobals.require); }); compilation.hooks.runtimeRequirementInTree .for(StylableRuntimeInject.name) .tap(name, (chunk, _set) => { compilation.addRuntimeModule(chunk, new StylableRuntimeInject()); }); compilation.hooks.runtimeRequirementInTree .for(StylableRuntimeStylesheet.name) .tap(name, (chunk, _set) => { compilation.addRuntimeModule(chunk, new StylableRuntimeStylesheet()); }); } registerSerialization( webpack, StylableRuntimeDependency, (ctx) => [ctx.read()] as [StylableBuildMeta] ); /* The request is empty for both dependencies and it will be overridden by the de-serialization process */ registerSerialization(webpack, UnusedDependency, () => [''] as [string]); registerSerialization(webpack, CSSURLDependency, () => [''] as [string]); entities = { injectRuntimeModules, StylableRuntimeInject, InjectDependencyTemplate, StylableRuntimeDependency, StylableRuntimeStylesheet, CSSURLDependency, NoopTemplate, UnusedDependency, }; entitiesCache.set(webpack, entities); return entities; } function replacePlaceholder( source: sources.ReplaceSource, replacementPoint: string, value: string ) { const i = source.source().indexOf(replacementPoint); if (!i) { throw new Error(`missing ${replacementPoint} from stylable loader source`); } source.replace(i, i + replacementPoint.length - 1, value, `${replacementPoint}`); } type SerializationContext = any; type Serializable = { new (...args: any[]): { serialize: (ctx: SerializationContext) => void; deserialize: (ctx: SerializationContext) => void; }; }; function registerSerialization<T extends Serializable>( webpack: Compiler['webpack'], Type: T, getArgs: (context: SerializationContext) => ConstructorParameters<T> ) { webpack.util.serialization.register(Type, __filename, Type.name, { serialize(instance: InstanceType<T>, context: SerializationContext) { instance.serialize(context); }, deserialize(context: SerializationContext) { const instance = new Type(...getArgs(context)); instance.deserialize(context); return instance; }, }); }
the_stack
import { ChartInternal } from './core' import { isValue, isDefined, diffDomain, notEmpty } from './util' ChartInternal.prototype.getYDomainMin = function(targets) { var $$ = this, config = $$.config, ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets), j, k, baseId, idsInGroup, id, hasNegativeValue if (config.data_groups.length > 0) { hasNegativeValue = $$.hasNegativeValueInTargets(targets) for (j = 0; j < config.data_groups.length; j++) { // Determine baseId idsInGroup = config.data_groups[j].filter(function(id) { return ids.indexOf(id) >= 0 }) if (idsInGroup.length === 0) { continue } baseId = idsInGroup[0] // Consider negative values if (hasNegativeValue && ys[baseId]) { ys[baseId].forEach(function(v, i) { ys[baseId][i] = v < 0 ? v : 0 }) } // Compute min for (k = 1; k < idsInGroup.length; k++) { id = idsInGroup[k] if (!ys[id]) { continue } ys[id].forEach(function(v, i) { if ( $$.axis.getId(id) === $$.axis.getId(baseId) && ys[baseId] && !(hasNegativeValue && +v > 0) ) { ys[baseId][i] += +v } }) } } } return $$.d3.min( Object.keys(ys).map(function(key) { return $$.d3.min(ys[key]) }) ) } ChartInternal.prototype.getYDomainMax = function(targets) { var $$ = this, config = $$.config, ids = $$.mapToIds(targets), ys = $$.getValuesAsIdKeyed(targets), j, k, baseId, idsInGroup, id, hasPositiveValue if (config.data_groups.length > 0) { hasPositiveValue = $$.hasPositiveValueInTargets(targets) for (j = 0; j < config.data_groups.length; j++) { // Determine baseId idsInGroup = config.data_groups[j].filter(function(id) { return ids.indexOf(id) >= 0 }) if (idsInGroup.length === 0) { continue } baseId = idsInGroup[0] // Consider positive values if (hasPositiveValue && ys[baseId]) { ys[baseId].forEach(function(v, i) { ys[baseId][i] = v > 0 ? v : 0 }) } // Compute max for (k = 1; k < idsInGroup.length; k++) { id = idsInGroup[k] if (!ys[id]) { continue } ys[id].forEach(function(v, i) { if ( $$.axis.getId(id) === $$.axis.getId(baseId) && ys[baseId] && !(hasPositiveValue && +v < 0) ) { ys[baseId][i] += +v } }) } } } return $$.d3.max( Object.keys(ys).map(function(key) { return $$.d3.max(ys[key]) }) ) } ChartInternal.prototype.getYDomain = function(targets, axisId, xDomain) { var $$ = this, config = $$.config if ($$.isAxisNormalized(axisId)) { return [0, 100] } var targetsByAxisId = targets.filter(function(t) { return $$.axis.getId(t.id) === axisId }), yTargets = xDomain ? $$.filterByXDomain(targetsByAxisId, xDomain) : targetsByAxisId, yMin = axisId === 'y2' ? config.axis_y2_min : config.axis_y_min, yMax = axisId === 'y2' ? config.axis_y2_max : config.axis_y_max, yDomainMin = $$.getYDomainMin(yTargets), yDomainMax = $$.getYDomainMax(yTargets), domain, domainLength, padding_top, padding_bottom, center = axisId === 'y2' ? config.axis_y2_center : config.axis_y_center, yDomainAbs, lengths, diff, ratio, isAllPositive, isAllNegative, isZeroBased = ($$.hasType('bar', yTargets) && config.bar_zerobased) || ($$.hasType('area', yTargets) && config.area_zerobased), isInverted = axisId === 'y2' ? config.axis_y2_inverted : config.axis_y_inverted, showHorizontalDataLabel = $$.hasDataLabel() && config.axis_rotated, showVerticalDataLabel = $$.hasDataLabel() && !config.axis_rotated // MEMO: avoid inverting domain unexpectedly yDomainMin = isValue(yMin) ? yMin : isValue(yMax) ? yDomainMin < yMax ? yDomainMin : yMax - 10 : yDomainMin yDomainMax = isValue(yMax) ? yMax : isValue(yMin) ? yMin < yDomainMax ? yDomainMax : yMin + 10 : yDomainMax if (yTargets.length === 0) { // use current domain if target of axisId is none return axisId === 'y2' ? $$.y2.domain() : $$.y.domain() } if (isNaN(yDomainMin)) { // set minimum to zero when not number yDomainMin = 0 } if (isNaN(yDomainMax)) { // set maximum to have same value as yDomainMin yDomainMax = yDomainMin } if (yDomainMin === yDomainMax) { yDomainMin < 0 ? (yDomainMax = 0) : (yDomainMin = 0) } isAllPositive = yDomainMin >= 0 && yDomainMax >= 0 isAllNegative = yDomainMin <= 0 && yDomainMax <= 0 // Cancel zerobased if axis_*_min / axis_*_max specified if ((isValue(yMin) && isAllPositive) || (isValue(yMax) && isAllNegative)) { isZeroBased = false } // Bar/Area chart should be 0-based if all positive|negative if (isZeroBased) { if (isAllPositive) { yDomainMin = 0 } if (isAllNegative) { yDomainMax = 0 } } domainLength = Math.abs(yDomainMax - yDomainMin) padding_top = padding_bottom = domainLength * 0.1 if (typeof center !== 'undefined') { yDomainAbs = Math.max(Math.abs(yDomainMin), Math.abs(yDomainMax)) yDomainMax = center + yDomainAbs yDomainMin = center - yDomainAbs } // add padding for data label if (showHorizontalDataLabel) { lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, 'width') diff = diffDomain($$.y.range()) ratio = [lengths[0] / diff, lengths[1] / diff] padding_top += domainLength * (ratio[1] / (1 - ratio[0] - ratio[1])) padding_bottom += domainLength * (ratio[0] / (1 - ratio[0] - ratio[1])) } else if (showVerticalDataLabel) { lengths = $$.getDataLabelLength(yDomainMin, yDomainMax, 'height') const pixelsToAxisPadding = $$.getY( config[`axis_${axisId}_type`], // input domain as pixels [0, config.axis_rotated ? $$.width : $$.height], // output range as axis padding [0, domainLength] ) padding_top += pixelsToAxisPadding(lengths[1]) padding_bottom += pixelsToAxisPadding(lengths[0]) } if (axisId === 'y' && notEmpty(config.axis_y_padding)) { padding_top = $$.axis.getPadding( config.axis_y_padding, 'top', padding_top, domainLength ) padding_bottom = $$.axis.getPadding( config.axis_y_padding, 'bottom', padding_bottom, domainLength ) } if (axisId === 'y2' && notEmpty(config.axis_y2_padding)) { padding_top = $$.axis.getPadding( config.axis_y2_padding, 'top', padding_top, domainLength ) padding_bottom = $$.axis.getPadding( config.axis_y2_padding, 'bottom', padding_bottom, domainLength ) } // Bar/Area chart should be 0-based if all positive|negative if (isZeroBased) { if (isAllPositive) { padding_bottom = yDomainMin } if (isAllNegative) { padding_top = -yDomainMax } } domain = [yDomainMin - padding_bottom, yDomainMax + padding_top] return isInverted ? domain.reverse() : domain } ChartInternal.prototype.getXDomainMin = function(targets) { var $$ = this, config = $$.config return isDefined(config.axis_x_min) ? $$.isTimeSeries() ? this.parseDate(config.axis_x_min) : config.axis_x_min : $$.d3.min(targets, function(t) { return $$.d3.min(t.values, function(v) { return v.x }) }) } ChartInternal.prototype.getXDomainMax = function(targets) { var $$ = this, config = $$.config return isDefined(config.axis_x_max) ? $$.isTimeSeries() ? this.parseDate(config.axis_x_max) : config.axis_x_max : $$.d3.max(targets, function(t) { return $$.d3.max(t.values, function(v) { return v.x }) }) } ChartInternal.prototype.getXDomainPadding = function(domain) { var $$ = this, config = $$.config, diff = domain[1] - domain[0], maxDataCount, padding, paddingLeft, paddingRight if ($$.isCategorized()) { padding = 0 } else if ($$.hasType('bar')) { maxDataCount = $$.getMaxDataCount() padding = maxDataCount > 1 ? diff / (maxDataCount - 1) / 2 : 0.5 } else { padding = diff * 0.01 } if ( typeof config.axis_x_padding === 'object' && notEmpty(config.axis_x_padding) ) { paddingLeft = isValue(config.axis_x_padding.left) ? config.axis_x_padding.left : padding paddingRight = isValue(config.axis_x_padding.right) ? config.axis_x_padding.right : padding } else if (typeof config.axis_x_padding === 'number') { paddingLeft = paddingRight = config.axis_x_padding } else { paddingLeft = paddingRight = padding } return { left: paddingLeft, right: paddingRight } } ChartInternal.prototype.getXDomain = function(targets) { var $$ = this, xDomain = [$$.getXDomainMin(targets), $$.getXDomainMax(targets)], firstX = xDomain[0], lastX = xDomain[1], padding = $$.getXDomainPadding(xDomain), min: Date | number = 0, max: Date | number = 0 // show center of x domain if min and max are the same if (firstX - lastX === 0 && !$$.isCategorized()) { if ($$.isTimeSeries()) { firstX = new Date(firstX.getTime() * 0.5) lastX = new Date(lastX.getTime() * 1.5) } else { firstX = firstX === 0 ? 1 : firstX * 0.5 lastX = lastX === 0 ? -1 : lastX * 1.5 } } if (firstX || firstX === 0) { min = $$.isTimeSeries() ? new Date(firstX.getTime() - padding.left) : firstX - padding.left } if (lastX || lastX === 0) { max = $$.isTimeSeries() ? new Date(lastX.getTime() + padding.right) : lastX + padding.right } return [min, max] } ChartInternal.prototype.updateXDomain = function( targets, withUpdateXDomain, withUpdateOrgXDomain, withTrim, domain ) { var $$ = this, config = $$.config if (withUpdateOrgXDomain) { $$.x.domain(domain ? domain : $$.d3.extent($$.getXDomain(targets))) $$.orgXDomain = $$.x.domain() if (config.zoom_enabled) { $$.zoom.update() } $$.subX.domain($$.x.domain()) if ($$.brush) { $$.brush.updateScale($$.subX) } } if (withUpdateXDomain) { $$.x.domain( domain ? domain : !$$.brush || $$.brush.empty() ? $$.orgXDomain : $$.brush.selectionAsValue() ) } // Trim domain when too big by zoom mousemove event if (withTrim) { $$.x.domain($$.trimXDomain($$.x.orgDomain())) } return $$.x.domain() } ChartInternal.prototype.trimXDomain = function(domain) { var zoomDomain = this.getZoomDomain(), min = zoomDomain[0], max = zoomDomain[1] if (domain[0] <= min) { domain[1] = +domain[1] + (min - domain[0]) domain[0] = min } if (max <= domain[1]) { domain[0] = +domain[0] - (domain[1] - max) domain[1] = max } return domain }
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * Associates a Spring Cloud Application with a CosmosDB Account. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleSpringCloudService = new azure.appplatform.SpringCloudService("exampleSpringCloudService", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * }); * const exampleSpringCloudApp = new azure.appplatform.SpringCloudApp("exampleSpringCloudApp", { * resourceGroupName: exampleResourceGroup.name, * serviceName: exampleSpringCloudService.name, * }); * const exampleAccount = new azure.cosmosdb.Account("exampleAccount", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * offerType: "Standard", * kind: "GlobalDocumentDB", * consistencyPolicy: { * consistencyLevel: "Strong", * }, * geoLocations: [{ * location: exampleResourceGroup.location, * failoverPriority: 0, * }], * }); * const exampleSpringCloudAppCosmosDBAssociation = new azure.appplatform.SpringCloudAppCosmosDBAssociation("exampleSpringCloudAppCosmosDBAssociation", { * springCloudAppId: exampleSpringCloudApp.id, * cosmosdbAccountId: exampleAccount.id, * apiType: "table", * cosmosdbAccessKey: exampleAccount.primaryKey, * }); * ``` * * ## Import * * Spring Cloud Application CosmosDB Association can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:appplatform/springCloudAppCosmosDBAssociation:SpringCloudAppCosmosDBAssociation example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/resourcegroup1/providers/Microsoft.AppPlatform/Spring/service1/apps/app1/bindings/bind1 * ``` */ export class SpringCloudAppCosmosDBAssociation extends pulumi.CustomResource { /** * Get an existing SpringCloudAppCosmosDBAssociation resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: SpringCloudAppCosmosDBAssociationState, opts?: pulumi.CustomResourceOptions): SpringCloudAppCosmosDBAssociation { return new SpringCloudAppCosmosDBAssociation(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:appplatform/springCloudAppCosmosDBAssociation:SpringCloudAppCosmosDBAssociation'; /** * Returns true if the given object is an instance of SpringCloudAppCosmosDBAssociation. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is SpringCloudAppCosmosDBAssociation { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === SpringCloudAppCosmosDBAssociation.__pulumiType; } /** * Specifies the api type which should be used when connecting to the CosmosDB Account. Possible values are `cassandra`, `gremlin`, `mongo`, `sql` or `table`. Changing this forces a new resource to be created. */ public readonly apiType!: pulumi.Output<string>; /** * Specifies the CosmosDB Account access key. */ public readonly cosmosdbAccessKey!: pulumi.Output<string>; /** * Specifies the ID of the CosmosDB Account. Changing this forces a new resource to be created. */ public readonly cosmosdbAccountId!: pulumi.Output<string>; /** * Specifies the name of the Cassandra Keyspace which the Spring Cloud App should be associated with. Should only be set when `apiType` is `cassandra`. */ public readonly cosmosdbCassandraKeyspaceName!: pulumi.Output<string | undefined>; /** * Specifies the name of the Gremlin Database which the Spring Cloud App should be associated with. Should only be set when `apiType` is `gremlin`. */ public readonly cosmosdbGremlinDatabaseName!: pulumi.Output<string | undefined>; /** * Specifies the name of the Gremlin Graph which the Spring Cloud App should be associated with. Should only be set when `apiType` is `gremlin`. */ public readonly cosmosdbGremlinGraphName!: pulumi.Output<string | undefined>; /** * Specifies the name of the Mongo Database which the Spring Cloud App should be associated with. Should only be set when `apiType` is `mongo`. */ public readonly cosmosdbMongoDatabaseName!: pulumi.Output<string | undefined>; /** * Specifies the name of the Sql Database which the Spring Cloud App should be associated with. Should only be set when `apiType` is `sql`. */ public readonly cosmosdbSqlDatabaseName!: pulumi.Output<string | undefined>; /** * Specifies the name of the Spring Cloud Application Association. Changing this forces a new resource to be created. */ public readonly name!: pulumi.Output<string>; /** * Specifies the ID of the Spring Cloud Application where this Association is created. Changing this forces a new resource to be created. */ public readonly springCloudAppId!: pulumi.Output<string>; /** * Create a SpringCloudAppCosmosDBAssociation resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: SpringCloudAppCosmosDBAssociationArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: SpringCloudAppCosmosDBAssociationArgs | SpringCloudAppCosmosDBAssociationState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as SpringCloudAppCosmosDBAssociationState | undefined; inputs["apiType"] = state ? state.apiType : undefined; inputs["cosmosdbAccessKey"] = state ? state.cosmosdbAccessKey : undefined; inputs["cosmosdbAccountId"] = state ? state.cosmosdbAccountId : undefined; inputs["cosmosdbCassandraKeyspaceName"] = state ? state.cosmosdbCassandraKeyspaceName : undefined; inputs["cosmosdbGremlinDatabaseName"] = state ? state.cosmosdbGremlinDatabaseName : undefined; inputs["cosmosdbGremlinGraphName"] = state ? state.cosmosdbGremlinGraphName : undefined; inputs["cosmosdbMongoDatabaseName"] = state ? state.cosmosdbMongoDatabaseName : undefined; inputs["cosmosdbSqlDatabaseName"] = state ? state.cosmosdbSqlDatabaseName : undefined; inputs["name"] = state ? state.name : undefined; inputs["springCloudAppId"] = state ? state.springCloudAppId : undefined; } else { const args = argsOrState as SpringCloudAppCosmosDBAssociationArgs | undefined; if ((!args || args.apiType === undefined) && !opts.urn) { throw new Error("Missing required property 'apiType'"); } if ((!args || args.cosmosdbAccessKey === undefined) && !opts.urn) { throw new Error("Missing required property 'cosmosdbAccessKey'"); } if ((!args || args.cosmosdbAccountId === undefined) && !opts.urn) { throw new Error("Missing required property 'cosmosdbAccountId'"); } if ((!args || args.springCloudAppId === undefined) && !opts.urn) { throw new Error("Missing required property 'springCloudAppId'"); } inputs["apiType"] = args ? args.apiType : undefined; inputs["cosmosdbAccessKey"] = args ? args.cosmosdbAccessKey : undefined; inputs["cosmosdbAccountId"] = args ? args.cosmosdbAccountId : undefined; inputs["cosmosdbCassandraKeyspaceName"] = args ? args.cosmosdbCassandraKeyspaceName : undefined; inputs["cosmosdbGremlinDatabaseName"] = args ? args.cosmosdbGremlinDatabaseName : undefined; inputs["cosmosdbGremlinGraphName"] = args ? args.cosmosdbGremlinGraphName : undefined; inputs["cosmosdbMongoDatabaseName"] = args ? args.cosmosdbMongoDatabaseName : undefined; inputs["cosmosdbSqlDatabaseName"] = args ? args.cosmosdbSqlDatabaseName : undefined; inputs["name"] = args ? args.name : undefined; inputs["springCloudAppId"] = args ? args.springCloudAppId : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(SpringCloudAppCosmosDBAssociation.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering SpringCloudAppCosmosDBAssociation resources. */ export interface SpringCloudAppCosmosDBAssociationState { /** * Specifies the api type which should be used when connecting to the CosmosDB Account. Possible values are `cassandra`, `gremlin`, `mongo`, `sql` or `table`. Changing this forces a new resource to be created. */ apiType?: pulumi.Input<string>; /** * Specifies the CosmosDB Account access key. */ cosmosdbAccessKey?: pulumi.Input<string>; /** * Specifies the ID of the CosmosDB Account. Changing this forces a new resource to be created. */ cosmosdbAccountId?: pulumi.Input<string>; /** * Specifies the name of the Cassandra Keyspace which the Spring Cloud App should be associated with. Should only be set when `apiType` is `cassandra`. */ cosmosdbCassandraKeyspaceName?: pulumi.Input<string>; /** * Specifies the name of the Gremlin Database which the Spring Cloud App should be associated with. Should only be set when `apiType` is `gremlin`. */ cosmosdbGremlinDatabaseName?: pulumi.Input<string>; /** * Specifies the name of the Gremlin Graph which the Spring Cloud App should be associated with. Should only be set when `apiType` is `gremlin`. */ cosmosdbGremlinGraphName?: pulumi.Input<string>; /** * Specifies the name of the Mongo Database which the Spring Cloud App should be associated with. Should only be set when `apiType` is `mongo`. */ cosmosdbMongoDatabaseName?: pulumi.Input<string>; /** * Specifies the name of the Sql Database which the Spring Cloud App should be associated with. Should only be set when `apiType` is `sql`. */ cosmosdbSqlDatabaseName?: pulumi.Input<string>; /** * Specifies the name of the Spring Cloud Application Association. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * Specifies the ID of the Spring Cloud Application where this Association is created. Changing this forces a new resource to be created. */ springCloudAppId?: pulumi.Input<string>; } /** * The set of arguments for constructing a SpringCloudAppCosmosDBAssociation resource. */ export interface SpringCloudAppCosmosDBAssociationArgs { /** * Specifies the api type which should be used when connecting to the CosmosDB Account. Possible values are `cassandra`, `gremlin`, `mongo`, `sql` or `table`. Changing this forces a new resource to be created. */ apiType: pulumi.Input<string>; /** * Specifies the CosmosDB Account access key. */ cosmosdbAccessKey: pulumi.Input<string>; /** * Specifies the ID of the CosmosDB Account. Changing this forces a new resource to be created. */ cosmosdbAccountId: pulumi.Input<string>; /** * Specifies the name of the Cassandra Keyspace which the Spring Cloud App should be associated with. Should only be set when `apiType` is `cassandra`. */ cosmosdbCassandraKeyspaceName?: pulumi.Input<string>; /** * Specifies the name of the Gremlin Database which the Spring Cloud App should be associated with. Should only be set when `apiType` is `gremlin`. */ cosmosdbGremlinDatabaseName?: pulumi.Input<string>; /** * Specifies the name of the Gremlin Graph which the Spring Cloud App should be associated with. Should only be set when `apiType` is `gremlin`. */ cosmosdbGremlinGraphName?: pulumi.Input<string>; /** * Specifies the name of the Mongo Database which the Spring Cloud App should be associated with. Should only be set when `apiType` is `mongo`. */ cosmosdbMongoDatabaseName?: pulumi.Input<string>; /** * Specifies the name of the Sql Database which the Spring Cloud App should be associated with. Should only be set when `apiType` is `sql`. */ cosmosdbSqlDatabaseName?: pulumi.Input<string>; /** * Specifies the name of the Spring Cloud Application Association. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * Specifies the ID of the Spring Cloud Application where this Association is created. Changing this forces a new resource to be created. */ springCloudAppId: pulumi.Input<string>; }
the_stack
import {asyncReplace} from '../../directives/async-replace.js'; import {render, html, nothing} from '../../lit-html.js'; import {TestAsyncIterable} from './test-async-iterable.js'; import {stripExpressionMarkers} from '../test-utils/strip-markers.js'; import {assert} from '@esm-bundle/chai'; import {memorySuite} from '../test-utils/memory.js'; /* eslint-disable @typescript-eslint/no-explicit-any */ // Set Symbol.asyncIterator on browsers without it if (typeof Symbol !== undefined && Symbol.asyncIterator === undefined) { Object.defineProperty(Symbol, 'Symbol.asyncIterator', {value: Symbol()}); } const nextFrame = () => new Promise<void>((r) => requestAnimationFrame(() => r())); suite('asyncReplace', () => { let container: HTMLDivElement; let iterable: TestAsyncIterable<unknown>; setup(() => { container = document.createElement('div'); iterable = new TestAsyncIterable<unknown>(); }); test('replaces content as the async iterable yields new values (ChildPart)', async () => { render(html`<div>${asyncReplace(iterable)}</div>`, container); assert.equal(stripExpressionMarkers(container.innerHTML), '<div></div>'); await iterable.push('foo'); assert.equal(stripExpressionMarkers(container.innerHTML), '<div>foo</div>'); await iterable.push('bar'); assert.equal(stripExpressionMarkers(container.innerHTML), '<div>bar</div>'); }); test('replaces content as the async iterable yields new values (AttributePart)', async () => { render(html`<div class="${asyncReplace(iterable)}"></div>`, container); assert.equal(stripExpressionMarkers(container.innerHTML), '<div></div>'); await iterable.push('foo'); assert.equal( stripExpressionMarkers(container.innerHTML), '<div class="foo"></div>' ); await iterable.push('bar'); assert.equal( stripExpressionMarkers(container.innerHTML), '<div class="bar"></div>' ); }); test('replaces content as the async iterable yields new values (PropertyPart)', async () => { render(html`<div .className=${asyncReplace(iterable)}></div>`, container); assert.equal(stripExpressionMarkers(container.innerHTML), '<div></div>'); await iterable.push('foo'); assert.equal( stripExpressionMarkers(container.innerHTML), '<div class="foo"></div>' ); await iterable.push('bar'); assert.equal( stripExpressionMarkers(container.innerHTML), '<div class="bar"></div>' ); }); test('replaces content as the async iterable yields new values (BooleanAttributePart)', async () => { render(html`<div ?hidden=${asyncReplace(iterable)}></div>`, container); assert.equal(stripExpressionMarkers(container.innerHTML), '<div></div>'); await iterable.push(true); assert.equal( stripExpressionMarkers(container.innerHTML), '<div hidden=""></div>' ); await iterable.push(false); assert.equal(stripExpressionMarkers(container.innerHTML), '<div></div>'); }); test('replaces content as the async iterable yields new values (EventPart)', async () => { render(html`<div @click=${asyncReplace(iterable)}></div>`, container); assert.equal(stripExpressionMarkers(container.innerHTML), '<div></div>'); let value; await iterable.push(() => (value = 1)); (container.firstElementChild as HTMLDivElement)!.click(); assert.equal(stripExpressionMarkers(container.innerHTML), '<div></div>'); assert.equal(value, 1); await iterable.push(() => (value = 2)); (container.firstElementChild as HTMLDivElement)!.click(); assert.equal(stripExpressionMarkers(container.innerHTML), '<div></div>'); assert.equal(value, 2); }); test('clears the Part when a value is undefined', async () => { render(html`<div>${asyncReplace(iterable)}</div>`, container); assert.equal(stripExpressionMarkers(container.innerHTML), '<div></div>'); await iterable.push('foo'); assert.equal(stripExpressionMarkers(container.innerHTML), '<div>foo</div>'); await iterable.push(undefined as unknown as string); assert.equal(stripExpressionMarkers(container.innerHTML), '<div></div>'); }); test('uses the mapper function', async () => { render( html`<div>${asyncReplace(iterable, (v, i) => html`${i}: ${v} `)}</div>`, container ); assert.equal(stripExpressionMarkers(container.innerHTML), '<div></div>'); await iterable.push('foo'); assert.equal( stripExpressionMarkers(container.innerHTML), '<div>0: foo </div>' ); await iterable.push('bar'); assert.equal( stripExpressionMarkers(container.innerHTML), '<div>1: bar </div>' ); }); test('renders new iterable over a pending iterable', async () => { const t = (iterable: any) => html`<div>${asyncReplace(iterable)}</div>`; render(t(iterable), container); assert.equal(stripExpressionMarkers(container.innerHTML), '<div></div>'); await iterable.push('foo'); assert.equal(stripExpressionMarkers(container.innerHTML), '<div>foo</div>'); const iterable2 = new TestAsyncIterable<string>(); render(t(iterable2), container); // The last value is preserved until we receive the first // value from the new iterable assert.equal(stripExpressionMarkers(container.innerHTML), '<div>foo</div>'); await iterable2.push('hello'); assert.equal( stripExpressionMarkers(container.innerHTML), '<div>hello</div>' ); await iterable.push('bar'); assert.equal( stripExpressionMarkers(container.innerHTML), '<div>hello</div>' ); }); test('renders the same iterable even when the iterable new value is emitted at the same time as a re-render', async () => { const t = (iterable: any) => html`<div>${asyncReplace(iterable)}</div>`; let wait: Promise<void>; render(t(iterable), container); assert.equal(stripExpressionMarkers(container.innerHTML), '<div></div>'); wait = iterable.push('hello'); render(t(iterable), container); await wait; assert.equal( stripExpressionMarkers(container.innerHTML), '<div>hello</div>' ); wait = iterable.push('bar'); render(t(iterable), container); await wait; assert.equal(stripExpressionMarkers(container.innerHTML), '<div>bar</div>'); }); test('renders new value over a pending iterable', async () => { const t = (v: any) => html`<div>${v}</div>`; // This is a little bit of an odd usage of directives as values, but it // is possible, and we check here that asyncReplace plays nice in this case render(t(asyncReplace(iterable)), container); assert.equal(stripExpressionMarkers(container.innerHTML), '<div></div>'); await iterable.push('foo'); assert.equal(stripExpressionMarkers(container.innerHTML), '<div>foo</div>'); render(t('hello'), container); assert.equal( stripExpressionMarkers(container.innerHTML), '<div>hello</div>' ); await iterable.push('bar'); assert.equal( stripExpressionMarkers(container.innerHTML), '<div>hello</div>' ); }); test('does not render the first value if it is replaced first', async () => { async function* generator(delay: Promise<any>, value: any) { await delay; yield value; } const component = (value: any) => html`<p>${asyncReplace(value)}</p>`; const delay = (delay: number) => new Promise((res) => setTimeout(res, delay)); const slowDelay = delay(20); const fastDelay = delay(10); render(component(generator(slowDelay, 'slow')), container); render(component(generator(fastDelay, 'fast')), container); await slowDelay; await delay(10); assert.equal(stripExpressionMarkers(container.innerHTML), '<p>fast</p>'); }); suite('disconnection', () => { test('does not render when iterable resolves while while disconnected', async () => { const component = (value: any) => html`<p>${asyncReplace(value)}</p>`; const part = render(component(iterable), container); await iterable.push('1'); assert.equal(stripExpressionMarkers(container.innerHTML), '<p>1</p>'); part.setConnected(false); await iterable.push('2'); assert.equal(stripExpressionMarkers(container.innerHTML), '<p>1</p>'); part.setConnected(true); await nextFrame(); assert.equal(stripExpressionMarkers(container.innerHTML), '<p>2</p>'); await iterable.push('3'); assert.equal(stripExpressionMarkers(container.innerHTML), '<p>3</p>'); }); test('disconnection thrashing', async () => { const component = (value: any) => html`<p>${asyncReplace(value)}</p>`; const part = render(component(iterable), container); await iterable.push('1'); assert.equal(stripExpressionMarkers(container.innerHTML), '<p>1</p>'); part.setConnected(false); await iterable.push('2'); part.setConnected(true); part.setConnected(false); await nextFrame(); assert.equal(stripExpressionMarkers(container.innerHTML), '<p>1</p>'); part.setConnected(true); await nextFrame(); assert.equal(stripExpressionMarkers(container.innerHTML), '<p>2</p>'); await iterable.push('3'); assert.equal(stripExpressionMarkers(container.innerHTML), '<p>3</p>'); }); test('does not render when newly rendered while disconnected', async () => { const component = (value: any) => html`<p>${value}</p>`; const part = render(component('static'), container); assert.equal( stripExpressionMarkers(container.innerHTML), '<p>static</p>' ); part.setConnected(false); render(component(asyncReplace(iterable)), container); await iterable.push('1'); assert.equal( stripExpressionMarkers(container.innerHTML), '<p>static</p>' ); part.setConnected(true); await nextFrame(); assert.equal(stripExpressionMarkers(container.innerHTML), '<p>1</p>'); await iterable.push('2'); assert.equal(stripExpressionMarkers(container.innerHTML), '<p>2</p>'); }); test('does not render when resolved and changed while disconnected', async () => { const component = (value: any) => html`<p>${value}</p>`; const part = render(component('staticA'), container); assert.equal( stripExpressionMarkers(container.innerHTML), '<p>staticA</p>' ); part.setConnected(false); render(component(asyncReplace(iterable)), container); await iterable.push('1'); assert.equal( stripExpressionMarkers(container.innerHTML), '<p>staticA</p>' ); render(component('staticB'), container); assert.equal( stripExpressionMarkers(container.innerHTML), '<p>staticB</p>' ); part.setConnected(true); await nextFrame(); assert.equal( stripExpressionMarkers(container.innerHTML), '<p>staticB</p>' ); await iterable.push('2'); assert.equal( stripExpressionMarkers(container.innerHTML), '<p>staticB</p>' ); }); test('the same promise can be rendered into two asyncReplace instances', async () => { const component = (iterable: AsyncIterable<unknown>) => html`<p>${asyncReplace(iterable)}</p><p>${asyncReplace(iterable)}</p>`; render(component(iterable), container); assert.equal( stripExpressionMarkers(container.innerHTML), '<p></p><p></p>' ); await iterable.push('1'); assert.equal( stripExpressionMarkers(container.innerHTML), '<p>1</p><p>1</p>' ); await iterable.push('2'); assert.equal( stripExpressionMarkers(container.innerHTML), '<p>2</p><p>2</p>' ); }); }); memorySuite('memory leak tests', () => { test('tree with asyncReplace cleared while iterables are pending', async () => { const template = (v: unknown) => html`<div>${v}</div>`; // Make a big array set on an expando to exaggerate any leaked DOM const big = () => new Array(10000).fill(0); // Hold onto the iterables to prevent them from being gc'ed const iterables: Array<TestAsyncIterable<string>> = []; window.gc(); const heap = performance.memory.usedJSHeapSize; for (let i = 0; i < 1000; i++) { // Iterable passed to asyncReplace that will never yield const iterable = new TestAsyncIterable<string>(); iterables.push(iterable); // Render the directive into a `<span>` with a 10kb expando, to exaggerate // when DOM is not being gc'ed render( template(html`<span .p=${big()}>${asyncReplace(iterable)}</span>`), container ); // Clear the `<span>` + directive render(template(nothing), container); } window.gc(); // Allow a 50% margin of heap growth; due to the 10kb expando, an actual // DOM leak will be orders of magnitude larger assert.isAtMost( performance.memory.usedJSHeapSize, heap * 1.5, 'memory leak detected' ); }); }); });
the_stack
import { camelCaseToPascalCase, collectInterfaceFiles } from '../generator/util' import { renameSync, writeFileSync } from 'fs' import stringReplaceAll from 'string-replace-all' import { getLogger } from '../generator/logger' export const typescriptsPaths = [ `bin/core/engine/interface`, `bin/core/engine/type` ] export const generatorDataPath = `${process.cwd()}/bin/core/generator/generatorData.json` export const reformerDataPath = `${process.cwd()}/bin/core/generator/reformerData.json` /** * A function of an automated maintenance script * that automatically renames an overwatch workshop * if the function name is changed * or the interface name is incorrect. * * 오버워치 워크샵의 함수 이름이 변경되었거나, * 인터페이스 이름이 잘못된 경우 이름을 변경가능한, * 자동화 유지보수 스크립트의 함수입니다. */ export const RenameUpdater = async (targetName: string, fixName: string, debugMode: boolean= true) =>{ const targetMap = NameMapGenerator(targetName) const fixMap = NameMapGenerator(fixName) const fixFilter = NameMapFilter(targetMap, fixMap) let Logger = getLogger() Logger.debug('------------------------LOG START----------------------------') // File Name Replace for(let typescriptsPath of typescriptsPaths){ await collectInterfaceFiles( typescriptsPath, async (collectedDatas) => { // Find Replace Target for(let { fileName, staticPath, subPath, filePath } of collectedDatas){ let filters = fixFilter(fileName) let newFileName = fileName for(let filter of filters) newFileName = stringReplaceAll(newFileName, filter.target, filter.fix) if(filters.length != 0){ let newPath = `${staticPath}/${newFileName}` Logger.debug(`File Name has been changed\t[${subPath}${fileName}] -> [${subPath}${newFileName}]`) if(!debugMode) renameSync(filePath, newPath) } } } ) } // File Data Replace for(let typescriptsPath of typescriptsPaths){ collectInterfaceFiles( typescriptsPath, async (collectedDatas) => { // Find Replace Target for(let { fileName, fileData, subPath, filePath } of collectedDatas){ let filters = fixFilter(fileData) let newFileData = fileData for(let filter of filters) newFileData = stringReplaceAll(newFileData, filter.target, filter.fix) // REPORT STATUS & WRITE if(filters.length != 0){ console.log('') Logger.debug(`File [${subPath}${fileName}] has been changed.`) let fileLines = fileData.split(`\n`) let newFileLines = newFileData.split(`\n`) for(let fileLineIndex in fileLines){ let fileLine = fileLines[fileLineIndex] if(fixFilter(fileLine).length == 0) continue console.log('') Logger.debug(`File [${subPath}${fileName}] Line:${fileLineIndex}`) Logger.debug(`[Before: ${fileLine}]`) Logger.debug(`[After : ${newFileLines[fileLineIndex]}]`) console.log('') } // fs.write if(!debugMode) writeFileSync(filePath, newFileData) } } }, // `false` will be include index.ts false ) } // JSON File Data Replace let generatorData = require(generatorDataPath) let isJSON1_Changed = false for(let type1Name of Object.keys(generatorData)){ for(let type2Name of Object.keys(generatorData[type1Name])){ for(let type3Name of Object.keys(generatorData[type1Name][type2Name])){ // console.log(`${type1Name}.${type2Name}.${type3Name}`) // Value backup let value = generatorData[type1Name][type2Name][type3Name] let newValue = JSON.parse(JSON.stringify(value)) // Value has benn changed let valueFilters = fixFilter(value) if(valueFilters.length != 0){ for(let filter of valueFilters) newValue = stringReplaceAll(newValue, filter.target, filter.fix) } let keyFilters = fixFilter(type3Name) if(keyFilters.length == 0){ if(valueFilters.length != 0){ // It must need to rewrite if(!isJSON1_Changed) isJSON1_Changed = true console.log('') Logger.debug(`GeneratorData Value Changed [${type1Name}.${type2Name}.${type3Name}]`) Logger.debug(`Before: [${value}]`) Logger.debug(`After : [${newValue}]`) console.log('') generatorData[type1Name][type2Name][type3Name] = newValue } }else{ // It must need to rewrite if(!isJSON1_Changed) isJSON1_Changed = true let newKey = String(type3Name) for(let filter of keyFilters) newKey = stringReplaceAll(newKey, filter.target, filter.fix) // REPORT STATUS if(valueFilters.length != 0){ // CHANGED VALUE console.log('') Logger.debug(`GeneratorData Key Changed [${type1Name}.${type2Name}.${type3Name}] -> [${type1Name}.${type2Name}.${newKey}]`) Logger.debug(`GeneratorData Value Changed [${type1Name}.${type2Name}.${newKey}]`) Logger.debug(`Before: [${value}]`) Logger.debug(`After : [${newValue}]`) console.log('') }else{ // NON CHANGED VALUE console.log('') Logger.debug(`GeneratorData Key Changed [${type1Name}.${type2Name}.${type3Name}] -> [${type1Name}.${type2Name}.${newKey}]`) console.log('') } generatorData[type1Name][type2Name][newKey] = newValue delete generatorData[type1Name][type2Name][type3Name] } } } } if(!debugMode && isJSON1_Changed) writeFileSync(generatorDataPath, JSON.stringify(generatorData, null, 2)) // JSON File Data Replace let reformerData = require(reformerDataPath) let isJSON2_Changed = false for(let type1Name of Object.keys(reformerData)){ for(let type2Name of Object.keys(reformerData[type1Name])){ let valueArray: string[] = reformerData[type1Name][type2Name] let newValueArray: string[] = [] if(Array.isArray(valueArray)){ for(let valueItem of valueArray){ let filters = fixFilter(valueItem) if(filters.length == 0){ newValueArray.push(valueItem) }else{ // It must need to rewrite if(!isJSON2_Changed) isJSON2_Changed = true let newValueItem = valueItem for(let filter of filters) newValueItem = stringReplaceAll(newValueItem, filter.target, filter.fix) Logger.debug(`* ReformerData Class function has been changed [${type1Name}.${type2Name}] ${valueItem} -> ${newValueItem}`) newValueArray.push(newValueItem) } } reformerData[type1Name][type2Name] = newValueArray } } } if(!debugMode && isJSON2_Changed) writeFileSync(reformerDataPath, JSON.stringify(reformerData, null, 2)) Logger.debug('------------------------LOG ENDED----------------------------') if(!debugMode){ Logger.debug(`The changes were applied to the file.`) Logger.debug(`If anything has been changed, Please re-run <npm run update>.`) }else{ Logger.debug(`The changes were not applied to the file.`) Logger.debug(`If you want to save your changes, enter the third parameter as fix`) console.log('') Logger.debug(`Ex: npm run update:rename ${targetName} ${fixName} fix`) } } export interface INameMap { camelCase: string pascalCase: string upperCase: string interfaceName: string } export const NameMapGenerator = (camelCase: string) => { let pascalCase = camelCaseToPascalCase(camelCase) let upperCase = pascalCase.toUpperCase() let interfaceName = `I${pascalCase.split(' ').join('')}` let namepMap: INameMap = { camelCase, pascalCase, upperCase, interfaceName } return namepMap } export interface NameMapResult { target: string fix : string } export const NameMapFilter = (targetMap: INameMap, fixMap: INameMap) => { return (source: string): NameMapResult[] => { let replaceTarget: NameMapResult[] = [] for(let targetMapIndex of Object.keys(targetMap)){ if(source.indexOf(targetMap[targetMapIndex]) != -1){ replaceTarget.push({ target: targetMap[targetMapIndex], fix: fixMap[targetMapIndex] }) } } return replaceTarget } } try{ if(`${process.argv[1]}` == __filename){ if(typeof process.argv[2] != 'undefined'){ RenameUpdater( process.argv[2], process.argv[3], process.argv[4] != 'fix' ) }else{ // INFO MESSAGE let Logger = getLogger() Logger.debug(`If you enter the function name (in the form of a camel case)`) Logger.debug(`to find and replace in all project files, it will automatically replace it.`) console.log('') Logger.debug(`npm run update:rename <before> <after> <fix||(empty)>`) Logger.debug(`(Ex: npm run update:rename applyImpulse applyImpluse)`) } } }catch(e){}
the_stack
import { TestBed } from '@angular/core/testing'; import { SearchFacetFiltersService } from './search-facet-filters.service'; import { ContentTestingModule } from '../../testing/content.testing.module'; import { SearchQueryBuilderService } from './search-query-builder.service'; describe('SearchFacetFiltersService', () => { let searchFacetFiltersService: SearchFacetFiltersService; let queryBuilder: SearchQueryBuilderService; beforeEach(() => { TestBed.configureTestingModule({ imports: [ContentTestingModule] }); searchFacetFiltersService = TestBed.inject(SearchFacetFiltersService); queryBuilder = TestBed.inject(SearchQueryBuilderService); }); it('should subscribe to query builder executed event', () => { spyOn(searchFacetFiltersService, 'onDataLoaded').and.stub(); const data = { list: {} }; queryBuilder.executed.next(data); expect(searchFacetFiltersService.onDataLoaded).toHaveBeenCalledWith(data); }); it('should fetch facet queries from response payload', () => { searchFacetFiltersService.responseFacets = null; queryBuilder.config = { categories: [], facetQueries: { label: 'label1', queries: [ { label: 'q1', query: 'query1' }, { label: 'q2', query: 'query2' } ] } }; const queries = [ { label: 'q1', filterQuery: 'query1', metrics: [{value: {count: 1}}] }, { label: 'q2', filterQuery: 'query2', metrics: [{value: {count: 1}}] } ]; const data = { list: { context: { facets: [{ type: 'query', label: 'label1', buckets: queries }] } } }; searchFacetFiltersService.onDataLoaded(data); expect(searchFacetFiltersService.responseFacets.length).toBe(1); expect(searchFacetFiltersService.responseFacets[0].buckets.length).toEqual(2); }); it('should preserve order after response processing', () => { searchFacetFiltersService.responseFacets = null; queryBuilder.config = { categories: [], facetQueries: { label: 'label1', queries: [ { label: 'q1', query: 'query1' }, { label: 'q2', query: 'query2' }, { label: 'q3', query: 'query3' } ] } }; const queries = [ { label: 'q2', filterQuery: 'query2', metrics: [{value: {count: 1}}] }, { label: 'q1', filterQuery: 'query1', metrics: [{value: {count: 1}}] }, { label: 'q3', filterQuery: 'query3', metrics: [{value: {count: 1}}] } ]; const data = { list: { context: { facets: [{ type: 'query', label: 'label1', buckets: queries }] } } }; searchFacetFiltersService.onDataLoaded(data); expect(searchFacetFiltersService.responseFacets.length).toBe(1); expect(searchFacetFiltersService.responseFacets[0].buckets.length).toBe(3); expect(searchFacetFiltersService.responseFacets[0].buckets.items[0].label).toBe('q1'); expect(searchFacetFiltersService.responseFacets[0].buckets.items[1].label).toBe('q2'); expect(searchFacetFiltersService.responseFacets[0].buckets.items[2].label).toBe('q3'); }); it('should not fetch facet queries from response payload', () => { searchFacetFiltersService.responseFacets = null; queryBuilder.config = { categories: [], facetQueries: { queries: [] } }; const data = { list: { context: { facets: null } } }; searchFacetFiltersService.onDataLoaded(data); expect(searchFacetFiltersService.responseFacets).toBeNull(); }); it('should fetch facet fields from response payload', () => { searchFacetFiltersService.responseFacets = null; queryBuilder.config = { categories: [], facetFields: { fields: [ { label: 'f1', field: 'f1', mincount: 0 }, { label: 'f2', field: 'f2', mincount: 0 } ]}, facetQueries: { queries: [] } }; const fields: any = [ { type: 'field', label: 'f1', buckets: [{ label: 'a1' }, { label: 'a2' }] }, { type: 'field', label: 'f2', buckets: [{ label: 'b1' }, { label: 'b2' }] } ]; const data = { list: { context: { facets: fields } } }; searchFacetFiltersService.onDataLoaded(data); expect(searchFacetFiltersService.responseFacets.length).toEqual(2); expect(searchFacetFiltersService.responseFacets[0].buckets.length).toEqual(2); expect(searchFacetFiltersService.responseFacets[1].buckets.length).toEqual(2); }); it('should filter response facet fields based on search filter config method', () => { queryBuilder.config = { categories: [], facetFields: { fields: [ { label: 'f1', field: 'f1' } ]}, facetQueries: { queries: [] }, filterWithContains: false }; const initialFields: any = [ { type: 'field', label: 'f1', buckets: [ { label: 'firstLabel', display: 'firstLabel', metrics: [{value: {count: 5}}] }, { label: 'secondLabel', display: 'secondLabel', metrics: [{value: {count: 5}}] }, { label: 'thirdLabel', display: 'thirdLabel', metrics: [{value: {count: 5}}] } ] } ]; const data = { list: { context: { facets: initialFields } } }; searchFacetFiltersService.onDataLoaded(data); expect(searchFacetFiltersService.responseFacets.length).toBe(1); expect(searchFacetFiltersService.responseFacets[0].buckets.visibleItems.length).toBe(3); searchFacetFiltersService.responseFacets[0].buckets.filterText = 'f'; expect(searchFacetFiltersService.responseFacets[0].buckets.visibleItems.length).toBe(1); expect(searchFacetFiltersService.responseFacets[0].buckets.visibleItems[0].label).toEqual('firstLabel'); searchFacetFiltersService.responseFacets[0].buckets.filterText = 'label'; expect(searchFacetFiltersService.responseFacets[0].buckets.visibleItems.length).toBe(0); // Set filter method to use contains and test again queryBuilder.config.filterWithContains = true; searchFacetFiltersService.responseFacets[0].buckets.filterText = 'f'; expect(searchFacetFiltersService.responseFacets[0].buckets.visibleItems.length).toBe(1); searchFacetFiltersService.responseFacets[0].buckets.filterText = 'label'; expect(searchFacetFiltersService.responseFacets[0].buckets.visibleItems.length).toBe(3); }); it('should fetch facet fields from response payload and show the bucket values', () => { searchFacetFiltersService.responseFacets = null; queryBuilder.config = { categories: [], facetFields: { fields: [ { label: 'f1', field: 'f1' }, { label: 'f2', field: 'f2' } ]}, facetQueries: { queries: [] } }; const serverResponseFields: any = [ { type: 'field', label: 'f1', buckets: [ { label: 'b1', metrics: [{value: {count: 10}}] }, { label: 'b2', metrics: [{value: {count: 1}}] } ] }, { type: 'field', label: 'f2', buckets: [] } ]; const data = { list: { context: { facets: serverResponseFields } } }; searchFacetFiltersService.onDataLoaded(data); expect(searchFacetFiltersService.responseFacets.length).toEqual(1); expect(searchFacetFiltersService.responseFacets[0].buckets.items[0].count).toEqual(10); expect(searchFacetFiltersService.responseFacets[0].buckets.items[1].count).toEqual(1); }); it('should fetch facet fields from response payload and update the existing bucket values', () => { queryBuilder.config = { categories: [], facetFields: { fields: [ { label: 'f1', field: 'f1' }, { label: 'f2', field: 'f2' } ]}, facetQueries: { queries: [] } }; const initialFields: any = [ { type: 'field', label: 'f1', buckets: { items: [{ label: 'b1', count: 10, filterQuery: 'filter' }, { label: 'b2', count: 1 }]} }, { type: 'field', label: 'f2', buckets: [] } ]; searchFacetFiltersService.responseFacets = initialFields; expect(searchFacetFiltersService.responseFacets[0].buckets.items[0].count).toEqual(10); expect(searchFacetFiltersService.responseFacets[0].buckets.items[1].count).toEqual(1); const serverResponseFields: any = [ { type: 'field', label: 'f1', buckets: [{ label: 'b1', metrics: [{value: {count: 6}}], filterQuery: 'filter' }, { label: 'b2', metrics: [{value: {count: 0}}] }] }, { type: 'field', label: 'f2', buckets: [] } ]; const data = { list: { context: { facets: serverResponseFields } } }; searchFacetFiltersService.onDataLoaded(data); expect(searchFacetFiltersService.responseFacets[0].buckets.items[0].count).toEqual(6); expect(searchFacetFiltersService.responseFacets[0].buckets.items[1].count).toEqual(0); }); it('should update correctly the existing facetFields bucket values', () => { searchFacetFiltersService.responseFacets = null; queryBuilder.config = { categories: [], facetFields: { fields: [{ label: 'f1', field: 'f1' }] }, facetQueries: { queries: [] } }; const firstCallFields: any = [{ type: 'field', label: 'f1', buckets: [{ label: 'b1', metrics: [{value: {count: 10}}] }] }]; const firstCallData = { list: { context: { facets: firstCallFields }}}; searchFacetFiltersService.onDataLoaded(firstCallData); expect(searchFacetFiltersService.responseFacets[0].buckets.items[0].count).toEqual(10); const secondCallFields: any = [{ type: 'field', label: 'f1', buckets: [{ label: 'b1', metrics: [{value: {count: 6}}] }] }]; const secondCallData = { list: { context: { facets: secondCallFields}}}; searchFacetFiltersService.onDataLoaded(secondCallData); expect(searchFacetFiltersService.responseFacets[0].buckets.items[0].count).toEqual(6); }); it('should fetch facet intervals from response payload', () => { searchFacetFiltersService.responseFacets = null; queryBuilder.config = { categories: [], facetIntervals: { intervals: [ { label: 'test_intervals1', field: 'f1', sets: [ { label: 'interval1', start: 's1', end: 'e1'}, { label: 'interval2', start: 's2', end: 'e2'} ]}, { label: 'test_intervals2', field: 'f2', sets: [ { label: 'interval3', start: 's3', end: 'e3'}, { label: 'interval4', start: 's4', end: 'e4'} ]} ] } }; const response1 = [ { label: 'interval1', filterQuery: 'query1', metrics: [{ value: { count: 1 }}]}, { label: 'interval2', filterQuery: 'query2', metrics: [{ value: { count: 2 }}]} ]; const response2 = [ { label: 'interval3', filterQuery: 'query3', metrics: [{ value: { count: 3 }}]}, { label: 'interval4', filterQuery: 'query4', metrics: [{ value: { count: 4 }}]} ]; const data = { list: { context: { facets: [ { type: 'interval', label: 'test_intervals1', buckets: response1 }, { type: 'interval', label: 'test_intervals2', buckets: response2 } ] } } }; searchFacetFiltersService.onDataLoaded(data); expect(searchFacetFiltersService.responseFacets.length).toBe(2); expect(searchFacetFiltersService.responseFacets[0].buckets.length).toEqual(2); expect(searchFacetFiltersService.responseFacets[1].buckets.length).toEqual(2); }); it('should filter out the fetched facet intervals that have bucket values less than their set mincount', () => { searchFacetFiltersService.responseFacets = null; queryBuilder.config = { categories: [], facetIntervals: { intervals: [ { label: 'test_intervals1', field: 'f1', mincount: 2, sets: [ { label: 'interval1', start: 's1', end: 'e1'}, { label: 'interval2', start: 's2', end: 'e2'} ]}, { label: 'test_intervals2', field: 'f2', mincount: 5, sets: [ { label: 'interval3', start: 's3', end: 'e3'}, { label: 'interval4', start: 's4', end: 'e4'} ]} ] } }; const response1 = [ { label: 'interval1', filterQuery: 'query1', metrics: [{ value: { count: 1 }}]}, { label: 'interval2', filterQuery: 'query2', metrics: [{ value: { count: 2 }}]} ]; const response2 = [ { label: 'interval3', filterQuery: 'query3', metrics: [{ value: { count: 3 }}]}, { label: 'interval4', filterQuery: 'query4', metrics: [{ value: { count: 4 }}]} ]; const data = { list: { context: { facets: [ { type: 'interval', label: 'test_intervals1', buckets: response1 }, { type: 'interval', label: 'test_intervals2', buckets: response2 } ] } } }; searchFacetFiltersService.onDataLoaded(data); expect(searchFacetFiltersService.responseFacets.length).toBe(1); expect(searchFacetFiltersService.responseFacets[0].buckets.length).toEqual(1); }); });
the_stack
* * Copyright © 2018-present, terrestris GmbH & Co. KG and GeoStyler contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import * as React from 'react'; import { Row, Col, Form } from 'antd'; import AttributeCombo from '../AttributeCombo/AttributeCombo'; import OperatorCombo from '../OperatorCombo/OperatorCombo'; import TextFilterField from '../TextFilterField/TextFilterField'; import NumberFilterField from '../NumberFilterField/NumberFilterField'; import { ComparisonFilter as GsComparisonFilter, ComparisonOperator } from 'geostyler-style'; import './ComparisonFilter.less'; import BoolFilterField from '../BoolFilterField/BoolFilterField'; import { Data as Data } from 'geostyler-data'; import _get from 'lodash/get'; import _cloneDeep from 'lodash/cloneDeep'; import _isEqual from 'lodash/isEqual'; import _isEmpty from 'lodash/isEmpty'; import _isFunction from 'lodash/isFunction'; import _isString from 'lodash/isString'; // default props export interface ComparisonFilterProps { /** Initial comparison filter object */ filter?: GsComparisonFilter; /** Set true to hide the attribute's type in the AttributeCombo select options */ hideAttributeType?: boolean; /** * A custom filter function which is passed each attribute. * Should return true to accept each attribute or false to reject it. */ attributeNameFilter?: (attributeName: string) => boolean; /** Label for the underlying AttributeCombo */ attributeLabel?: string; /** Placeholder text for the underlying AttributeCombo */ attributePlaceholderString?: string; /** Validation help text for the underlying AttributeCombo */ attributeValidationHelpString?: string; /** Mapping function for attribute names of underlying AttributeCombo */ attributeNameMappingFunction?: (originalAttributeName: string) => string; /** Label for the underlying OperatorCombo */ operatorLabel?: string; /** Show title of selected item in underlying OperatorCombo */ showOperatorTitles?: boolean; /** Placeholder for the underlying OperatorCombo */ operatorPlaceholderString?: string; /** Validation help text for the underlying OperatorCombo */ operatorValidationHelpString?: string; /** Mapping function for operator names of underlying OperatorCombo */ operatorNameMappingFunction?: (originalOperatorName: string) => string; /** Mapping function for operator title in underlying OperatorCombo */ operatorTitleMappingFunction?: (originalOperatorName: string) => string; /** Label for the underlying value field */ valueLabel?: string; /** Placeholder for the underlying value field */ valuePlaceholder?: string; /** Object aggregating validation functions for attribute, operator and value */ validators?: Validators; /** Show ui in micro mode. Which disables labels etc. */ microUI?: boolean; /** Reference to internal data object (holding schema and example features) */ internalDataDef?: Data; /** Callback function for onFilterChange */ onFilterChange?: ((compFilter: GsComparisonFilter) => void); } interface ValidationStatus { attribute: 'success' | 'warning' | 'error' | 'validating'; operator: 'success' | 'warning' | 'error' | 'validating'; value: 'success' | 'warning' | 'error' | 'validating'; } interface Validators { attribute: (attrName: string) => boolean; operator: (operator: string) => boolean; value: (value: string | number | boolean | null, internalDataDef?: Data, selectedAttribute?: string) => ValidationResult; } type ValidationResult = { isValid: boolean; errorMsg: string; }; export const ComparisonFilterDefaultValidator = ( newValue: string | number | boolean | null, internalDataDef: Data, selectedAttribute: string ): ValidationResult => { let isValid = true; let errorMsg = ''; // read out attribute type const attrType = _get(internalDataDef, `schema.properties[${selectedAttribute}].type`); switch (attrType) { case 'number': // detect min / max from schema const minVal = _get(internalDataDef, `schema.properties[${selectedAttribute}].minimum`); const maxVal = _get(internalDataDef, `schema.properties[${selectedAttribute}].maximum`); if (!isNaN(minVal) && !isNaN(maxVal)) { if (typeof newValue !== 'number') { isValid = false; errorMsg = 'Please enter a number'; } else if (newValue < minVal) { isValid = false; errorMsg = 'Minimum Value is ' + minVal; } else if (newValue > maxVal) { isValid = false; errorMsg = 'Maximum Value is ' + maxVal; } } break; default: break; } return { isValid: isValid, errorMsg: errorMsg }; }; const operatorsMap = { 'string': ['==', '*=', '!='], 'number': ['==', '!=', '<', '<=', '>', '>='], 'boolean': ['==', '!='] }; /** * UI for a ComparisonFilter consisting of * * - A combo to select the attribute * - A combo to select the operator * - An input field for the value */ // export class ComparisonFilter extends React.Component<ComparisonFilterProps, ComparisonFilterState> { export const ComparisonFilter: React.FC<ComparisonFilterProps> = ({ attributeLabel, attributeNameFilter = () => true, attributeNameMappingFunction = n => n, attributePlaceholderString, attributeValidationHelpString, filter = ['==', '', null], hideAttributeType = false, internalDataDef, microUI = false, onFilterChange, operatorLabel, operatorNameMappingFunction = n => n, operatorPlaceholderString, operatorTitleMappingFunction = t => t, operatorValidationHelpString, showOperatorTitles = true, valueLabel, valuePlaceholder, validators = { attribute: attributeName => !_isEmpty(attributeName), operator: operatorName => !_isEmpty(operatorName), value: ComparisonFilterDefaultValidator } }) => { /** * Handler function, which is executed, when to underlying filter attribute changes. * * Changes the input field for the filter value and stores the appropriate attribute name as member. */ const onAttributeChange = (newAttrName: string) => { let newFilter = _cloneDeep(filter); newFilter[1] = newAttrName; if (onFilterChange) { onFilterChange(newFilter); } }; /** * Handler function, which is executed, when to underlying filter operator changes. * * Stores the appropriate operator as member. */ const onOperatorChange = (newOperator: ComparisonOperator) => { let newFilter = _cloneDeep(filter); newFilter[0] = newOperator; if (onFilterChange) { onFilterChange(newFilter); } }; /** * Handler function, which is executed, when to underlying filter value changes. * * Stores the appropriate filter value as member. */ const onValueChange = (newValue: string | number | boolean) => { let newFilter = _cloneDeep(filter); newFilter[2] = newValue; if (onFilterChange) { onFilterChange(newFilter); } }; let className = 'gs-comparison-filter-ui'; if (microUI) { className += ' micro'; } // TODO: implement strategy to handel FunctionFilter const attribute = _isString(filter[1]) ? filter[1] : undefined; const attributeType = attribute ? internalDataDef?.schema?.properties[attribute]?.type : undefined; const operator = filter[0]; const value = filter[2]; const hasFilter = filter && Array.isArray(filter); const valueValidation = validators.value(value, internalDataDef, attribute); const validateStatus: ValidationStatus = { attribute: hasFilter && validators.attribute(attribute) ? 'success' : 'error', operator: hasFilter && validators.operator(operator) ? 'success' : 'error', value: hasFilter && valueValidation.isValid ? 'success' : 'error' }; const valueValidationHelpString = valueValidation.errorMsg; const allowedOperators = attributeType ? operatorsMap[attributeType] : undefined; const textFieldVisible = attributeType !== 'number' && attributeType !== 'boolean'; const numberFieldVisible = attributeType === 'number'; const boolFieldVisible = attributeType === 'boolean'; return ( <div className={className}> <Form> <Row gutter={16} justify="center"> <Col span={10} className="gs-small-col"> <AttributeCombo size={microUI ? 'small' : undefined} value={filter ? filter[1] as string : undefined} internalDataDef={internalDataDef} onAttributeChange={onAttributeChange} attributeNameFilter={attributeNameFilter} attributeNameMappingFunction={attributeNameMappingFunction} label={attributeLabel} placeholder={attributePlaceholderString} validateStatus={validateStatus.attribute} help={attributeValidationHelpString} hideAttributeType={hideAttributeType} /> </Col> <Col span={4} className="gs-small-col"> <OperatorCombo size={microUI ? 'small' : undefined} value={filter ? filter[0] : undefined} onOperatorChange={onOperatorChange} operators={allowedOperators} operatorNameMappingFunction={operatorNameMappingFunction} placeholder={operatorPlaceholderString} label={operatorLabel} validateStatus={validateStatus.operator} help={operatorValidationHelpString} operatorTitleMappingFunction={operatorTitleMappingFunction} showTitles={showOperatorTitles} /> </Col> { textFieldVisible ? <Col span={10} className="gs-small-col"> <TextFilterField size={microUI ? 'small' : undefined} value={filter ? filter[2] as string : undefined} internalDataDef={internalDataDef} selectedAttribute={attribute} onValueChange={onValueChange} label={valueLabel} placeholder={valuePlaceholder} validateStatus={validateStatus.value} help={valueValidationHelpString} /> </Col> : null } { numberFieldVisible ? <Col span={10} className="gs-small-col"> <NumberFilterField size={microUI ? 'small' : undefined} value={filter ? filter[2] as number : undefined} onValueChange={onValueChange} label={valueLabel} placeholder={valuePlaceholder} validateStatus={validateStatus.value} help={valueValidationHelpString} /> </Col> : null } { boolFieldVisible ? <Col span={10} className="gs-small-col"> <BoolFilterField size={microUI ? 'small' : undefined} value={filter ? filter[2] as boolean : undefined} onValueChange={onValueChange} label={valueLabel} /> </Col> : null } </Row> </Form> </div> ); }; export default ComparisonFilter;
the_stack
(function(){ // @ts-ignore const prevReadAt = _prevReadAt_; const highlightCommentEls: HTMLElement[] = []; exec(); async function exec() { // prepare insertTimeIntoReviewBody(); await openResolvedThread(); await replaceEditedTime(); // highlight comment highlightComments(); // close prepare closeNoHighlightResolvedThread(); // add highlight indicator addHighlightIndicator(); // scroll to latest await scrollToHighlight(); } function getComments() { const comments = Array.from(document.querySelectorAll('.review-comment, .discussion-item-review, .timeline-comment')); comments.pop(); // コメントフォームを削除 return comments } function insertTimeIntoReviewBody() { for (const comment of getComments()) { const timeEl = comment.querySelector('relative-time'); if (timeEl) continue; const parent = getParent(comment, 'js-comment'); if (!parent) continue; const parentTimeEl = parent.querySelector('relative-time'); if (!parentTimeEl) continue; comment.querySelector('.timeline-comment-header-text').appendChild(parentTimeEl.cloneNode()) } } async function replaceEditedTime() { const editHistories = Array.from(document.querySelectorAll('.js-discussion details.dropdown')) .filter(el => el.textContent.includes('edited')); for (const editHistory of editHistories) { editHistory.setAttribute('open', 'true'); // @ts-ignore editHistory.querySelector('details-menu').style.opacity = 0; } // wait for loading for (let i = 0; i < 30; i++) { await sleep(30); let loadedCount = 0; for (const editHistory of editHistories) { if (editHistory.querySelector('relative-time')) loadedCount++; } if (loadedCount === editHistories.length) break; } // close for (const editHistory of editHistories) { editHistory.removeAttribute('open'); // @ts-ignore editHistory.querySelector('details-menu').style.opacity = 1; } // replace for (const comment of getComments()) { // `edited` dropdownを取得して、その中の最新の更新時刻を取り出す const editHistory = Array.from(comment.querySelectorAll('details.dropdown')).find(el => el.textContent.includes('edited')); const editedTimeEl = editHistory?.querySelector('relative-time'); if (!editedTimeEl) continue; const editedTime = new Date(editedTimeEl.getAttribute('datetime')); // コメントの時刻を最新の更新時刻で上書きする // `relative-time`だけだと編集履歴のrelative-timeまでとってしまうので、コメントへのリンクが有るもの(href)を条件に加える // さらに複数存在する場合がある(一部は見えない)ので、querySelectorAllですべてとってくることにした。 const timeEls = comment.querySelectorAll('[href] relative-time'); for (const timeEl of timeEls) timeEl.setAttribute('datetime', dateUTCFormat(editedTime)); } } async function openResolvedThread() { const containers = Array.from( document.querySelectorAll('.js-resolvable-timeline-thread-container[data-resolved="true"]:not(.has-inline-notes)') ); // GHE(2.19.5)ではoutdatedはresolvedされてなくても閉じられてしまうので、resolvedと同じようにopenする { const outdatedContainers = Array.from( document.querySelectorAll('.js-resolvable-timeline-thread-container:not(.has-inline-notes)') ).filter(el => el.querySelector('.js-toggle-outdated-comments')); containers.push(...outdatedContainers); } if (containers.length) { // outdatedしている箇所を一度openして、中身を読み込ませる for (const container of containers) { container.setAttribute('open', 'true'); } // 全てのresolvedの中が読み込まれるまで待機 for (let i = 0; i < 30; i++) { await sleep(30); let loadedCount = 0; for (const container of containers) { if (container.classList.contains('has-inline-notes')) loadedCount++; } if (loadedCount === containers.length) break; } } } function closeNoHighlightResolvedThread() { const containers = Array.from( document.querySelectorAll('.js-resolvable-timeline-thread-container[data-resolved="true"]') ); for (const container of containers) { const comment = container.querySelector('.highlight-comment'); if (!comment) container.removeAttribute('open'); } } function highlightComments() { for (const comment of getComments()) { const rect = comment.getBoundingClientRect(); if (!rect.width || !rect.height) continue; const timeEl = comment.querySelector('relative-time'); if (!timeEl) continue; const time = new Date(timeEl.getAttribute('datetime')).getTime(); if (time > prevReadAt) { comment.classList.add('highlight-comment'); highlightCommentEls.push(comment as HTMLElement); } } } function addHighlightIndicator() { if (!highlightCommentEls.length) return; // create indicator wrap const indicatorWrapEl = document.createElement('div'); indicatorWrapEl.classList.add('highlight-indicator-wrap'); document.querySelector('.js-discussion').appendChild(indicatorWrapEl); // create indicator const indicatorEl = document.createElement('div'); indicatorEl.classList.add('highlight-indicator'); indicatorWrapEl.appendChild(indicatorEl); // create current-pos const currentPosEl = document.createElement('div') ; currentPosEl.classList.add('highlight-indicator-scroll-current-pos'); currentPosEl.style.opacity = '0'; indicatorEl.appendChild(currentPosEl); // calc timeline height function getTimelineHeight() { const lastCommentBottom = getComments().pop().getBoundingClientRect().bottom + window.scrollY; const timelineRect = document.querySelector('.js-discussion').getBoundingClientRect(); const timelineBottom = timelineRect.bottom + window.scrollY; const timelineHeight = timelineRect.height - (timelineBottom - lastCommentBottom); return {timelineHeight, timelineRect}; } const {timelineHeight, timelineRect} = getTimelineHeight(); const timelineOffset = timelineRect.top + window.pageYOffset; //.js-discussionのheightを使うために、commentの絶対位置をオフセットする必要がある // タイムラインの高さが小さいときは、インジケータも小さくする const indicatorHeight = Math.min(timelineHeight / window.innerHeight, 1); indicatorEl.style.height = `${indicatorHeight * 100}%`; // コメントが画面に表示されたときにmarkを非表示にする // https://blog.jxck.io/entries/2016-06-25/intersection-observer.html#intersection-observer const highlightCommentMarkMap: Map<HTMLElement, HTMLElement> = new Map(); const observer = new IntersectionObserver((changes) => { for (let change of changes) { if (change.isIntersecting) { const mark = highlightCommentMarkMap.get(change.target as HTMLElement); if (mark) mark.classList.add('highlight-indicator-mark-done'); } } }, {threshold: [0], rootMargin: '-40px'}); // create mark for (const comment of highlightCommentEls) { // calc mark position const commentRect = comment.getBoundingClientRect(); if (!commentRect.width || !commentRect.height) continue; const absYOnViewPort = commentRect.top + window.pageYOffset; const absYOnTimeline = absYOnViewPort - timelineOffset; const y = absYOnTimeline / timelineHeight * 100; // calc mark size const absHeight = commentRect.height; const height = absHeight / timelineHeight * 100; // create mark // const markOffset = (50 - y) / 50 * 10; // markの位置がindicatorの上下ぴったりに来ないように、「中央(50%)を原点として、そこからの距離で0~10のオフセット」をつける const mark = document.createElement('div'); mark.classList.add('highlight-indicator-mark'); // mark.style.top = `calc(${y}% + ${markOffset}px)`; mark.style.top = `${y}%`; mark.style.height = `${height}%`; indicatorEl.appendChild(mark); // intersection observer.observe(comment); highlightCommentMarkMap.set(comment, mark); // click mark mark.addEventListener('click', async () => { await scrollToComment(comment, false); // const marks = Array.from(indicatorEl.querySelectorAll('.highlight-indicator-mark')) as HTMLElement[]; // recursiveMarkDone(mark, marks); }); } // scroll position if (timelineRect.bottom > window.innerHeight) { window.addEventListener('wheel', async () => { const windowTop = window.scrollY; const windowBottom = window.scrollY + window.innerHeight; const {timelineHeight, timelineRect} = getTimelineHeight(); const timelineTop = timelineRect.top + window.scrollY; const top = Math.min(timelineHeight, Math.max(0, windowTop - timelineTop)); const bottom = Math.max(0, Math.min(timelineHeight, windowBottom - timelineTop)); const height = (bottom - top) / timelineHeight; const currentPosEl = document.querySelector('.highlight-indicator-scroll-current-pos') as HTMLElement; currentPosEl.style.top = `${top/timelineHeight * 100}%`; currentPosEl.style.height = `${height * 100}%`; currentPosEl.style.opacity = null; currentPosEl.style.display = null; currentPosEl.style.transition = null; currentPosEl.ontransitionend = null; const t = Date.now().toString(); currentPosEl.dataset['time'] = t; await sleep(300); if (currentPosEl.dataset['time'] === t) { currentPosEl.style.opacity = '0'; currentPosEl.style.transition = 'opacity 0.2s'; currentPosEl.ontransitionend = () => currentPosEl.style.display = 'none'; } }); } } // function recursiveMarkDone(doneMark: HTMLElement, marks: HTMLElement[]) { // doneMark.classList.add('highlight-indicator-mark-done'); // const rect = doneMark.getBoundingClientRect(); // const doneTop = Math.floor(rect.top); // const doneBottom = Math.ceil(rect.top + rect.height); // // for (const mark of marks) { // if (mark.classList.contains('highlight-indicator-mark-done')) continue; // const rect = mark.getBoundingClientRect(); // const top = Math.floor(rect.top); // const bottom = Math.ceil(rect.top + rect.height); // if (bottom >= doneTop && bottom <= doneBottom) { // mark.classList.add('highlight-indicator-mark-done'); // recursiveMarkDone(mark, marks); // } // if (top >= doneTop && top <= doneBottom) { // mark.classList.add('highlight-indicator-mark-done'); // recursiveMarkDone(mark, marks); // } // } // } async function scrollToHighlight() { const comment = document.querySelector('.highlight-comment'); if (comment) { await scrollToComment(comment, true); } else { const comments = getComments(); if (comments.length) { const lastComment = comments[comments.length - 1]; await scrollToComment(lastComment, true); } } } function sleep(msec) { return new Promise((resolve) => { setTimeout(resolve, msec); }); } function getParent(target, clazz) { let result = target.parentElement; while (result) { if (result.classList.contains(clazz)) return result; result = result.parentElement; } return null; } function dateUTCFormat(date: Date): string { const Y = date.getUTCFullYear(); const M = `${date.getUTCMonth() + 1}`.padStart(2, '0'); const D = `${date.getUTCDate()}`.padStart(2, '0'); const h = `${date.getUTCHours()}`.padStart(2, '0'); const m = `${date.getUTCMinutes()}`.padStart(2, '0'); const s = `${date.getUTCSeconds()}`.padStart(2, '0'); return `${Y}-${M}-${D}T${h}:${m}:${s}Z`; } async function scrollToComment(comment: Element, notScrollIfTop: boolean) { if (!comment) return; if (notScrollIfTop && comment === document.querySelector('.timeline-comment')) return; comment.scrollIntoView({block: 'start'}); await sleep(10); window.scrollBy(0, -80); //ヘッダーの分だけさらに移動する } })();
the_stack
// TODO: reduce code duplication, circular references, // and general badness/unmaintainability. // TODO: combat UI on main bar // TODO: stats/info view in inventory screen // TODO: fix inventory image size // TODO: fix style for inventory image amount // TODO: option for scaling the UI module Ui { // Container that all of the top-level UI elements reside in let $uiContainer: HTMLElement; export function init() { $uiContainer = document.getElementById("game-container")!; initSkilldex(); // initCharacterScreen(); document.getElementById("chrButton")!.onclick = () => { characterWindow && characterWindow.close(); initCharacterScreen(); }; } // Bounding box that accepts strings as well as numbers export interface CSSBoundingBox { x: number|string; y: number|string; w: number|string; h: number|string; } export class WindowFrame { children: Widget[] = []; elem: HTMLElement; showing: boolean = false; constructor(public background: string, public bbox: CSSBoundingBox, children?: Widget[]) { this.elem = document.createElement("div"); Object.assign(this.elem.style, { position: "absolute", left: `${bbox.x}px`, top: `${bbox.y}px`, width: `${bbox.w}px`, height: `${bbox.h}px`, backgroundImage: `url('${background}')`, }); if(children) { for(const child of children) this.add(child); } } add(widget: Widget): this { this.children.push(widget); this.elem.appendChild(widget.elem); return this; } show(): this { if(this.showing) return this; this.showing = true; $uiContainer.appendChild(this.elem); return this; } close(): void { if(!this.showing) return; this.showing = false; this.elem.parentNode!.removeChild(this.elem); } toggle(): this { if(this.showing) this.close(); else this.show(); return this; } } export class Widget { elem: HTMLElement; hoverBackground: string|null = null; mouseDownBackground: string|null = null; constructor(public background: string|null, public bbox: CSSBoundingBox) { this.elem = document.createElement("div"); Object.assign(this.elem.style, { position: "absolute", left: `${bbox.x}px`, top: `${bbox.y}px`, width: `${bbox.w}px`, height: `${bbox.h}px`, backgroundImage: background && `url('${background}')`, }); } onClick(fn: (widget?: Widget) => void): this { this.elem.onclick = () => { fn(this); }; return this; } hoverBG(background: string): this { this.hoverBackground = background; if(!this.elem.onmouseenter) { // Set up events for hovering/not hovering this.elem.onmouseenter = () => { this.elem.style.backgroundImage = `url('${this.hoverBackground}')`; }; this.elem.onmouseleave = () => { this.elem.style.backgroundImage = `url('${this.background}')`; }; } return this; } mouseDownBG(background: string): this { this.mouseDownBackground = background; if(!this.elem.onmousedown) { // Set up events for mouse down/up this.elem.onmousedown = () => { this.elem.style.backgroundImage = `url('${this.mouseDownBackground}')`; }; this.elem.onmouseup = () => { this.elem.style.backgroundImage = `url('${this.background}')`; }; } return this; } css(props: object): this { Object.assign(this.elem.style, props); return this; } } export class SmallButton extends Widget { constructor(x: number, y: number) { super("art/intrface/lilredup.png", { x, y, w: 15, h: 16 }); this.mouseDownBG("art/intrface/lilreddn.png"); } } export class Label extends Widget { constructor(x: number, y: number, text: string, public textColor: string="yellow") { super(null, { x, y, w: "auto", h: "auto" }); this.setText(text); this.elem.style.color = this.textColor; } setText(text: string): void { this.elem.innerHTML = text; } } interface ListItem { id?: any; // identifier userdata uid?: number; // unique identifier (filled in by List) text: string; onSelected?: () => void; } // TODO: disable-selection class export class List extends Widget { items: ListItem[] = []; itemSelected?: (item: ListItem) => void; currentlySelected: ListItem|null = null; currentlySelectedElem: HTMLElement|null = null; _lastUID: number = 0; constructor(bbox: CSSBoundingBox, items?: ListItem[], public textColor: string="#00FF00", public selectedTextColor: string="#FCFC7C") { super(null, bbox); this.elem.style.color = this.textColor; if(items) { for(const item of items) this.addItem(item); } } onItemSelected(fn: (item: ListItem) => void): this { this.itemSelected = fn; return this; } getSelection(): ListItem|null { return this.currentlySelected; } // Select the given item (and optionally, give its element for performance reasons) select(item: ListItem, itemElem?: HTMLElement): boolean { if(!itemElem) // Find element belonging to this item itemElem = this.elem.querySelector(`[data-uid="${item.uid}"]`) as HTMLElement; if(!itemElem) { console.warn(`Can't find item's element for item UID ${item.uid}`); return false; } this.itemSelected && this.itemSelected(item); item.onSelected && item.onSelected(); if(this.currentlySelectedElem) // Reset text color for old selection this.currentlySelectedElem.style.color = this.textColor; // Use selection color for new selection itemElem.style.color = this.selectedTextColor; this.currentlySelected = item; this.currentlySelectedElem = itemElem; return true; } // Select item given by its id selectId(id: any): boolean { const item = this.items.filter(item => item.id === id)[0]; if(!item) return false; this.select(item); return true; } addItem(item: ListItem): ListItem { item.uid = this._lastUID++; this.items.push(item); const itemElem = document.createElement("div"); itemElem.style.cursor = "pointer"; itemElem.textContent = item.text; itemElem.setAttribute("data-uid", item.uid+""); itemElem.onclick = () => { this.select(item, itemElem); }; this.elem.appendChild(itemElem); // Select first item added if(!this.currentlySelected) this.select(item); return item; } clear(): void { this.items.length = 0; const node = this.elem; while(node.firstChild) node.removeChild(node.firstChild); } } export let skilldexWindow: WindowFrame; export let characterWindow: WindowFrame; function initSkilldex() { function useSkill(skill: Skills) { return () => { skilldexWindow.close(); uiMode = UI_MODE_USE_SKILL; skillMode = skill; console.log("[UI] Using skill:", skill); } } skilldexWindow = new WindowFrame("art/intrface/skldxbox.png", { x: Config.ui.screenWidth - 185 - 5, y: Config.ui.screenHeight - 368, w: 185, h: 368 }) .add(new Label(65, 13, "Skilldex")) .add(new Label(25, 85, "Lockpick").onClick(useSkill(Skills.Lockpick))) .add(new Label(25, 300, "Repair").onClick(useSkill(Skills.Repair))); } function initCharacterScreen() { const skillList = new List({ x: 380, y: 27, w: "auto", h: "auto" }); skillList.css({fontSize: "0.75em"}); characterWindow = new WindowFrame("art/intrface/edtredt.png", { x: Config.ui.screenWidth/2 - 640/2, y: Config.ui.screenHeight/2 - 480/2, w: 640, h: 480 }) .add(new SmallButton(455, 454).onClick(() => { })).add(new Label(455+18, 454, "Done")) .add(new SmallButton(552, 454).onClick(() => { characterWindow.close(); })).add(new Label(552+18, 454, "Cancel")) .add(new Label(22, 6, "Name")) .add(new Label(160, 6, "Age")) .add(new Label(242, 6, "Gender")) .add(new Label(33, 280, `Level: ${critterGetStat(player, "Level")}`).css({fontSize: "0.75em", color: "#00FF00"})) .add(new Label(33, 292, `Exp: ${critterGetStat(player, "Experience")}`).css({fontSize: "0.75em", color: "#00FF00"})) .add(new Label(380, 5, "Skill")) .add(new Label(399, 233, "Skill Points")) .add(new Label(194, 45, `Hit Points ${critterGetStat(player, "HP")}/${critterGetStat(player, "Max HP")}`) .css({fontSize: "0.75em", color: "#00FF00"})) .add(skillList) .show(); // TODO: Move these constants to their proper place const skills = [ "Small Guns", "Big Guns", "Energy Weapons", "Unarmed", "Melee Weapons", "Throwing", "First Aid", "Doctor", "Sneak", "Lockpick", "Steal", "Traps", "Science", "Repair", "Speech", "Barter", "Gambling", "Outdoorsman" ]; const stats = [ "STR", "PER", "END", "CHA", "INT", "AGI", "LUK" ]; // TODO: Use a list of widgets or something for stats instead of this hack const statWidgets: Label[] = []; let selectedStat = stats[0]; let n = 0; for(const stat of stats) { const widget = new Label(20, 39 + n, "").css({background: "black", padding: "5px"}); widget.onClick(() => { selectedStat = stat; }); statWidgets.push(widget); characterWindow.add(widget); n += 33; } // TODO: (Re-)run this after window is shown / a level-up is invoked const newStatSet = player.stats.clone(); const newSkillSet = player.skills.clone(); // Skill Points / Tag Skills counter const skillPointCounter = new Label(522, 230, "").css({background: "black", padding: "5px"}); characterWindow.add(skillPointCounter); const redrawStatsSkills = () => { // Draw skills skillList.clear(); // TODO: setItemText or something for(const skill of skills) skillList.addItem({ text: `${skill} ${newSkillSet.get(skill, newStatSet)}%`, id: skill }); // Draw stats for(let i = 0; i < stats.length; i++) { const stat = stats[i]; statWidgets[i].setText(`${stat} - ${newStatSet.get(stat)}`); } // Update skill point counter skillPointCounter.setText(pad(newSkillSet.skillPoints, 2)); }; redrawStatsSkills(); const isLevelUp = true; // TODO const canChangeStats = true; // TODO if(isLevelUp) { const modifySkill = (inc: boolean) => { const skill = skillList.getSelection()!.id; console.log("skill: %s currently: %d", skill, newSkillSet.get(skill, newStatSet)); if(inc) { const changed = newSkillSet.incBase(skill); if(!changed) { console.warn("Not enough skill points!"); } } else { newSkillSet.decBase(skill); } redrawStatsSkills(); }; const toggleTagSkill = () => { const skill = skillList.getSelection()!.id; const tagged = newSkillSet.isTagged(skill); console.log("skill: %s currently: %d tagged: %s", skill, newSkillSet.get(skill, newStatSet), tagged); if(!tagged) newSkillSet.tag(skill); else newSkillSet.untag(skill); redrawStatsSkills(); }; const modifyStat = (change: number) => { console.log("stat: %s currently: %d", selectedStat, newStatSet.get(selectedStat)); newStatSet.modifyBase(selectedStat, change); redrawStatsSkills(); }; // Skill level up buttons characterWindow.add(new Label(580, 236, "-").onClick(() => { console.log("-"); modifySkill(false); })); characterWindow.add(new Label(600, 236, "+").onClick(() => { console.log("+"); modifySkill(true); })); characterWindow.add(new Label(620, 236, "Tag").onClick(() => { console.log("Tag"); toggleTagSkill(); })); // Stat level up buttons if(canChangeStats) { characterWindow.add(new Label(115, 260, "-").onClick(() => { console.log("-"); modifyStat(-1); })); characterWindow.add(new Label(135, 260, "+").onClick(() => { console.log("+"); modifyStat(+1); })); } } } } // TODO: enum this var UI_MODE_NONE = 0, UI_MODE_DIALOGUE = 1, UI_MODE_BARTER = 2, UI_MODE_LOOT = 3, UI_MODE_INVENTORY = 4, UI_MODE_WORLDMAP = 5, UI_MODE_ELEVATOR = 6, UI_MODE_CALLED_SHOT = 7, UI_MODE_SKILLDEX = 8, UI_MODE_USE_SKILL = 9, UI_MODE_CONTEXT_MENU = 10, UI_MODE_SAVELOAD = 11, UI_MODE_CHAR = 12 var uiMode: number = UI_MODE_NONE // XXX: Should this throw if the element doesn't exist? function $id(id: string): HTMLElement { return document.getElementById(id)!; } function $img(id: string): HTMLImageElement { return document.getElementById(id) as HTMLImageElement; } function $q(selector: string): HTMLElement { return document.querySelector(selector) as HTMLElement; } function $qa(selector: string): HTMLElement[] { return Array.from(document.querySelectorAll(selector)); } function clearEl($el: HTMLElement): void { $el.innerHTML = ""; } function show($el: HTMLElement): void { $el.style.display = "block"; } function hide($el: HTMLElement): void { $el.style.display = "none"; } // TODO: Examine if we actually need visibility or we can replace them all with show/hide function showv($el: HTMLElement): void { $el.style.visibility = "visible"; } function hidev($el: HTMLElement): void { $el.style.visibility = "hidden"; } function off($el: HTMLElement, events: string): void { const eventList = events.split(" "); for(const event of eventList) (<any>$el)["on" + event] = null; } function appendHTML($el: HTMLElement, html: string): void { $el.insertAdjacentHTML("beforeend", html); } interface ElementOptions { id?: string; src?: string; classes?: string[]; click?: (e: MouseEvent) => void; style?: { [key in keyof CSSStyleDeclaration]?: string }; children?: HTMLElement[]; attrs?: { [key: string]: string|number }; } function makeEl(tag: string, options: ElementOptions): HTMLElement { const $el = document.createElement(tag); if(options.id !== undefined) $el.id = options.id; if(options.src !== undefined) ($el as HTMLImageElement).src = options.src; if(options.classes !== undefined) $el.className = options.classes.join(" "); if(options.click !== undefined) $el.onclick = options.click; if(options.style !== undefined) Object.assign($el.style, options.style); if(options.children !== undefined) { for(const child of options.children) $el.appendChild(child); } if(options.attrs !== undefined) { for(const prop in options.attrs) $el.setAttribute(prop, options.attrs[prop] + ""); } return $el; } function initUI() { Ui.init(); makeDropTarget($id("inventoryBoxList"), (data: string) => { uiMoveSlot(data, "inventory") }) makeDropTarget($id("inventoryBoxItem1"), (data: string) => { uiMoveSlot(data, "leftHand") }) makeDropTarget($id("inventoryBoxItem2"), (data: string) => { uiMoveSlot(data, "rightHand") }) for(let i = 0; i < 2; i++) { for(const $chance of Array.from(document.querySelectorAll("#calledShotBox .calledShotChance"))) $chance.appendChild(makeEl("div", { classes: ["number"], style: { left: (i*9) + "px" }, id: "digit" + (i+1) })); } $id("calledShotCancelBtn").onclick = () => { uiCloseCalledShot() } /* $id("worldmapViewButton").onclick = () => { var onAreaMap = ($("#areamap").css("visibility") === "visible") if(onAreaMap) uiWorldMapWorldView() else { var currentArea = areaContainingMap(gMap.name) if(currentArea) uiWorldMapShowArea(currentArea) else uiWorldMapAreaView() } } */ $id("inventoryButton").onclick = () => { uiInventoryScreen() } $id("inventoryDoneButton").onclick = () => { uiMode = UI_MODE_NONE $id("inventoryBox").style.visibility = "hidden" uiDrawWeapon() } $id("lootBoxDoneButton").onclick = () => { uiEndLoot(); } $id("attackButtonContainer").onclick = () => { if(!Config.engine.doCombat) return if(inCombat) { // TODO: targeting reticle for attacks } else { // begin combat Combat.start() } }; $id("attackButtonContainer").oncontextmenu = () => { // right mouse button (cycle weapon modes) var wep = critterGetEquippedWeapon(player) if(!wep || !wep.weapon) return false wep.weapon.cycleMode() uiDrawWeapon() return false }; $id("endTurnButton").onclick = () => { if(inCombat && combat!.inPlayerTurn) { if(player.anim !== null && player.anim !== "idle") { console.log("Can't end turn while player is in an animation."); return; } console.log("[TURN]") combat!.nextTurn() } } $id("endCombatButton").onclick = () => { if(inCombat) combat!.end() } $id("endContainer").addEventListener("animationiteration", uiEndCombatAnimationDone); $id("endContainer").addEventListener("webkitAnimationIteration", uiEndCombatAnimationDone); $id("skilldexButton").onclick = () => { Ui.skilldexWindow.toggle() } function makeScrollable($el: HTMLElement, scroll: number=60) { $el.onwheel = (e: WheelEvent) => { const delta = e.deltaY > 0 ? 1 : -1; $el.scrollTop = $el.scrollTop + scroll*delta; e.preventDefault(); }; } makeScrollable($id("inventoryBoxList")) makeScrollable($id("barterBoxInventoryLeft")) makeScrollable($id("barterBoxInventoryRight")) makeScrollable($id("barterBoxLeft")) makeScrollable($id("barterBoxRight")) makeScrollable($id("lootBoxLeft")) makeScrollable($id("lootBoxRight")) makeScrollable($id("worldMapLabels")) makeScrollable($id("displayLog")) makeScrollable($id("dialogueBoxReply"), 30) drawHP(critterGetStat(player, "HP")) uiDrawWeapon() } function uiHideContextMenu() { uiMode = UI_MODE_NONE $id("itemContextMenu").style.visibility = "hidden" } function uiContextMenu(obj: Obj, evt: any) { uiMode = UI_MODE_CONTEXT_MENU function button(obj: Obj, action: string, onclick: () => void) { return makeEl("img", { id: "context_" + action, classes: ["itemContextMenuButton"], click: () => { onclick(); uiHideContextMenu(); } }); } var $menu = $id("itemContextMenu"); clearEl($menu); Object.assign($menu.style, { visibility: "visible", left: `${evt.clientX}px`, top: `${evt.clientY}px` }); var cancelBtn = button(obj, "cancel", () => {}) var lookBtn = button(obj, "look", () => uiLog("You see: " + obj.getDescription())) var useBtn = button(obj, "use", () => playerUse()) // TODO: playerUse should take an object var talkBtn = button(obj, "talk", () => { console.log("talking to " + obj.name) if(!obj._script) { console.warn("obj has no script"); return; } Scripting.talk(obj._script, obj) }) var pickupBtn = button(obj, "pickup", () => pickupObject(obj, player)) $menu.appendChild(cancelBtn) $menu.appendChild(lookBtn) if(obj._script && obj._script.talk_p_proc !== undefined) $menu.appendChild(talkBtn) if(canUseObject(obj)) $menu.appendChild(useBtn) $menu.appendChild(pickupBtn) } function uiStartCombat() { // play end container animation Object.assign($id("endContainer").style, {animationPlayState: "running", webkitAnimationPlayState: "running"}); } function uiEndCombat() { // play end container animation Object.assign($id("endContainer").style, {animationPlayState: "running", webkitAnimationPlayState: "running"}); // disable buttons hidev($id("endTurnButton")); hidev($id("endCombatButton")); } function uiEndCombatAnimationDone(this: HTMLElement) { Object.assign(this.style, {animationPlayState: "paused", webkitAnimationPlayState: "paused"}); if(inCombat) { // enable buttons showv($id("endTurnButton")); showv($id("endCombatButton")); } } function uiDrawWeapon() { // draw the active weapon in the interface bar var weapon = critterGetEquippedWeapon(player) clearEl($id("attackButton")); if(!weapon || !weapon.weapon) return; if(weapon.weapon.type !== "melee") { const $attackButtonWeapon = $id("attackButtonWeapon") as HTMLImageElement; $attackButtonWeapon.onload = null; $attackButtonWeapon.onload = function(this: HTMLImageElement) { if(!this.complete) return; Object.assign(this.style, { position: "absolute", top: "5px", left: ($id("attackButton").offsetWidth / 2 - this.width / 2) + "px", maxHeight: ($id("attackButton").offsetHeight - 10) + "px" }); this.setAttribute("draggable", "false"); }; $attackButtonWeapon.src = weapon.invArt + ".png"; } // draw weapon AP var CHAR_W = 10 var digit = weapon.weapon.getAPCost(1) if(digit === undefined || digit > 9) return // TODO: Weapon AP >9? $id("attackButtonAPDigit").style.backgroundPosition = (0 - CHAR_W*digit) + "px" // draw weapon type (single, burst, called, punch, ...) // TODO: all melee weapons var wepTypes: { [wepType: string]: string } = {"melee": "punch", "gun": "single"}; var type = wepTypes[weapon.weapon.type]; $img("attackButtonType").src = `art/intrface/${type}.png` // hide or show called shot sigil? if(weapon.weapon.mode === "called") show($id("attackButtonCalled")); else hide($id("attackButtonCalled")); } // TODO: Rewrite this sanely (and not directly modify the player object's properties...) function uiMoveSlot(data: string, target: string) { const playerUnsafe = player as any; var obj = null if(data[0] === "i") { if(target === "inventory") return // disallow inventory -> inventory var idx = parseInt(data.slice(1)) console.log("idx: " + idx) obj = player.inventory[idx] player.inventory.splice(idx, 1) // remove object from inventory } else { obj = playerUnsafe[data] playerUnsafe[data] = null // remove object from slot } console.log("obj: " + obj + " (data: " + data + ", target: " + target + ")") if(target === "inventory") player.inventory.push(obj) else { if(playerUnsafe[target] !== undefined && playerUnsafe[target] !== null) { // perform a swap if(data[0] === "i") player.inventory.push(playerUnsafe[target]) // inventory -> slot else playerUnsafe[data] = playerUnsafe[target] // slot -> slot } playerUnsafe[target] = obj // move the object over } uiInventoryScreen() } function makeDropTarget($el: HTMLElement, dropCallback: (data: string, e?: DragEvent) => void) { $el.ondrop = (e: DragEvent) => { var data = e.dataTransfer.getData("text/plain") dropCallback(data, e) return false }; $el.ondragenter = () => false; $el.ondragover = () => false; } function makeDraggable($el: HTMLElement, data: string, endCallback?: () => void) { $el.setAttribute("draggable", "true"); $el.ondragstart = (e: DragEvent) => { e.dataTransfer.setData('text/plain', data) console.log("start drag") }; $el.ondragend = (e: DragEvent) => { if(e.dataTransfer.dropEffect !== "none") { //$(this).remove() endCallback && endCallback() } }; } function uiInventoryScreen() { uiMode = UI_MODE_INVENTORY showv($id("inventoryBox")); drawInventory($id("inventoryBoxList"), player.inventory, (obj: Obj, e: MouseEvent) => { makeItemContextMenu(e, obj, "inventory") }) function drawInventory($el: HTMLElement, objects: Obj[], clickCallback?: (item: Obj, e: MouseEvent) => void) { clearEl($el); clearEl($id("inventoryBoxItem1")); clearEl($id("inventoryBoxItem2")); for(let i = 0; i < objects.length; i++) { const invObj = objects[i]; // 90x60 // 70x40 const img = makeEl("img", { src: invObj.invArt+'.png', attrs: { width: 72, height: 60, title: invObj.name }, click: clickCallback ? (e: MouseEvent) => { clickCallback(invObj, e); } : undefined }); $el.appendChild(img); $el.insertAdjacentHTML("beforeend", "x" + invObj.amount); makeDraggable(img, "i" + i, () => { uiInventoryScreen(); }); } } function itemAction(obj: Obj, slot: keyof Player, action: "cancel"|"use"|"drop") { switch(action) { case "cancel": break case "use": console.log("using object: " + obj.art) useObject(obj, player) break case "drop": //console.log("todo: drop " + obj.art); break console.log("dropping: " + obj.art + " with pid " + obj.pid) if(slot !== "inventory") { // add into inventory to drop console.log("moving into inventory first") player.inventory.push(obj) player[slot] = null } dropObject(player, obj) uiInventoryScreen() break } } function makeContextButton(obj: Obj, slot: keyof Player, action: "cancel"|"use"|"drop") { return makeEl("img", { id: "context_" + action, classes: ["itemContextMenuButton"], click: () => { itemAction(obj, slot, action) hidev($id("itemContextMenu")); } }); } function makeItemContextMenu(e: MouseEvent, obj: Obj, slot: keyof Player) { var $menu = $id("itemContextMenu"); clearEl($menu); Object.assign($menu.style, { visibility: "visible", left: `${e.clientX}px`, top: `${e.clientY}px` }); var cancelBtn = makeContextButton(obj, slot, "cancel") var useBtn = makeContextButton(obj, slot, "use") var dropBtn = makeContextButton(obj, slot, "drop") $menu.appendChild(cancelBtn) if(canUseObject(obj)) $menu.appendChild(useBtn) $menu.appendChild(dropBtn) } function drawSlot(slot: keyof Player, slotID: string) { var art = player[slot].invArt // 90x60 // 70x40 var img = makeEl("img", { src: art+'.png', attrs: { width: 72, height: 60, title: player[slot].name }, click: (e: MouseEvent) => { makeItemContextMenu(e, player[slot], slot); } }); makeDraggable(img, slot) const $slotEl = $id(slotID); clearEl($slotEl); $slotEl.appendChild(img); } if(player.leftHand) drawSlot("leftHand", "inventoryBoxItem1") if(player.rightHand) drawSlot("rightHand", "inventoryBoxItem2") } function drawHP(hp: number) { drawDigits("#hpDigit", hp, 4, true) } function drawDigits(idPrefix: string, amount: number, maxDigits: number, hasSign: boolean) { var CHAR_W = 9, CHAR_NEG = 12 var sign = (amount < 0) ? CHAR_NEG : 0 if(amount < 0) amount = -amount var digits = amount.toString() var firstDigitIdx = (hasSign ? 2 : 1) if(hasSign) $q(idPrefix+"1").style.backgroundPosition = (0 - CHAR_W*sign) + "px"; // sign for(var i = firstDigitIdx; i <= maxDigits-digits.length; i++) // left-fill with zeroes $q(idPrefix + i).style.backgroundPosition = "0px"; for(var i = 0; i < digits.length; i++) { var idx = digits.length - 1 - i if(digits[idx] === '-') var digit = 12 else var digit = parseInt(digits[idx]) $q(idPrefix + (maxDigits-i)).style.backgroundPosition = (0 - CHAR_W*digit) + "px"; } } // Smoothly transition an element's top property from an origin to a target position over a duration function uiAnimateBox($el: HTMLElement, origin: number|null, target: number, callback?: () => void): void { const style = $el.style; // Reset to origin, instantly if(origin !== null) { style.transition = "none"; style.top = `${origin}px`; } // We need to wait for the browser to process the updated CSS position, so we need to wait here setTimeout(() => { // Set up our transition finished callback if necessary if(callback) { let listener = () => { callback(); $el.removeEventListener("transitionend", listener); (listener as any) = null; // Allow listener to be GC'd }; $el.addEventListener("transitionend", listener); } // Ease into the target position over 1 second $el.style.transition = "top 1s ease"; $el.style.top = `${target}px`; }, 1); } function uiStartDialogue(force: boolean, target?: Critter) { if(uiMode === UI_MODE_BARTER && force !== true) return uiMode = UI_MODE_DIALOGUE $id("dialogueContainer").style.visibility = "visible" $id("dialogueBox").style.visibility = "visible"; uiAnimateBox($id("dialogueBox"), 480, 290); // center around the dialogue target if(!target) return var bbox = objectBoundingBox(target) if(bbox !== null) { const dc = $id("dialogueContainer") // alternatively: dc.offset().left - $(heart.canvas).offset().left const dx = (dc.offsetWidth / 2 | 0) + dc.offsetLeft const dy = (dc.offsetHeight / 4 | 0) + dc.offsetTop - (bbox.h / 2 | 0) cameraX = bbox.x - dx cameraY = bbox.y - dy } } function uiEndDialogue() { // TODO: Transition the dialogue box down? uiMode = UI_MODE_NONE; $id("dialogueContainer").style.visibility = "hidden"; $id("dialogueBox").style.visibility = "hidden"; $id("dialogueBoxReply").innerHTML = ""; } function uiSetDialogueReply(reply: string) { const $dialogueBoxReply = $id("dialogueBoxReply"); $dialogueBoxReply.innerHTML = reply; $dialogueBoxReply.scrollTop = 0; $id("dialogueBoxTextArea").innerHTML = ""; } function uiAddDialogueOption(msg: string, optionID: number) { $id("dialogueBoxTextArea").insertAdjacentHTML("beforeend", `<li><a href="javascript:dialogueReply(${optionID})">${msg}</a></li>`); } function uiGetAmount(item: Obj) { while(true) { var amount: any = prompt("How many?") if(amount === null) return 0 else if(amount === "") return item.amount // all of it! else amount = parseInt(amount) if(isNaN(amount) || item.amount < amount) alert("Invalid amount") else return amount } } function _uiAddItem(items: Obj[], item: Obj, count: number) { for(var i = 0; i < items.length; i++) { if(items[i].approxEq(item)) { items[i].amount += count return } } // no existing item, add new inventory object items.push(item.clone().setAmount(count)) } function uiSwapItem(a: Obj[], item: Obj, b: Obj[], amount: number) { // swap item from a -> b if(amount === 0) return var idx = -1 for(var i = 0; i < a.length; i++) { if(a[i].approxEq(item)) { idx = i break } } if(idx === -1) throw "item (" + item + ") does not exist in a" if(amount < item.amount) // deduct amount from a and give amount to b item.amount -= amount else // just swap them a.splice(idx, 1) // add the item to b _uiAddItem(b, item, amount) } function uiEndBarterMode() { const $barterBox = $id("barterBox"); uiAnimateBox($barterBox, null, 480, () => { hidev($id("barterBox")); off($id("barterBoxLeft"), "drop dragenter dragover"); off($id("barterBoxRight"), "drop dragenter dragover"); off($id("barterBoxInventoryLeft"), "drop dragenter dragover"); off($id("barterBoxInventoryRight"), "drop dragenter dragover"); off($id("barterTalkButton"), "click"); off($id("barterOfferButton"), "click"); uiStartDialogue(true) // force dialogue mode }); } function uiBarterMode(merchant: Critter) { uiMode = UI_MODE_BARTER // Hide dialogue screen for now (animate down) const $dialogueBox = $id("dialogueBox"); uiAnimateBox($dialogueBox, null, 480, () => { $dialogueBox.style.visibility = "hidden"; console.log("going to pop up barter box"); // Pop up the bartering screen (animate up) const $barterBox = $id("barterBox"); $barterBox.style.visibility = "visible"; uiAnimateBox($barterBox, 480, 290); }); // logic + UI for bartering // TODO: would it be better if we dropped the "working" copies? // a copy of inventories for both parties let workingPlayerInventory = player.inventory.map(cloneItem) let workingMerchantInventory = merchant.inventory.map(cloneItem) // and our working barter tables let playerBarterTable: Obj[] = [] let merchantBarterTable: Obj[] = [] function totalAmount(objects: Obj[]): number { var total = 0 for(var i = 0; i < objects.length; i++) { total += objects[i].pro.extra.cost * objects[i].amount } return total } // TODO: checkOffer() or some-such function offer() { console.log("[OFFER]") var merchantOffered = totalAmount(merchantBarterTable) var playerOffered = totalAmount(playerBarterTable) var diffOffered = playerOffered - merchantOffered if(diffOffered >= 0) { // OK, player offered equal to more more than the value console.log("[OFFER OK]") // finalize and apply the deal // swap to working inventories merchant.inventory = workingMerchantInventory player.inventory = workingPlayerInventory // add in the table items for(var i = 0; i < merchantBarterTable.length; i++) player.addInventoryItem(merchantBarterTable[i], merchantBarterTable[i].amount) for(var i = 0; i < playerBarterTable.length; i++) merchant.addInventoryItem(playerBarterTable[i], playerBarterTable[i].amount) // re-clone so we can continue bartering if necessary workingPlayerInventory = player.inventory.map(cloneItem) workingMerchantInventory = merchant.inventory.map(cloneItem) playerBarterTable = [] merchantBarterTable = [] redrawBarterInventory() } else { console.log("[OFFER REFUSED]") } } function drawInventory($el: HTMLElement, who: "p"|"m"|"l"|"r", objects: Obj[]) { clearEl($el); for(var i = 0; i < objects.length; i++) { var inventoryImage = objects[i].invArt // 90x60 // 70x40 var img = makeEl("img", { src: inventoryImage+'.png', attrs: { width: 72, height: 60, title: objects[i].name } }); $el.appendChild(img); $el.insertAdjacentHTML("beforeend", "x" + objects[i].amount); makeDraggable(img, who + i) } } function uiBarterMove(data: string, where: "left"|"right"|"leftInv"|"rightInv") { console.log("barter: move " + data + " to " + where) var from = ({"p": workingPlayerInventory, "m": workingMerchantInventory, "l": playerBarterTable, "r": merchantBarterTable} as any)[data[0]] if(from === undefined) throw "uiBarterMove: wrong data: " + data var idx = parseInt(data.slice(1)) var obj = from[idx] if(obj === undefined) throw "uiBarterMove: obj not found in list (" + idx + ")" // player inventory -> left table or player inventory if(data[0] === "p" && where !== "left" && where !== "leftInv") return // merchant inventory -> right table or merchant inventory if(data[0] === "m" && where !== "right" && where !== "rightInv") return var to = {"left": playerBarterTable, "right": merchantBarterTable, "leftInv": workingPlayerInventory, "rightInv": workingMerchantInventory}[where] if(to === undefined) throw "uiBarterMove: invalid location: " + where else if(to === from) // table -> same table return else if(obj.amount > 1) uiSwapItem(from, obj, to, uiGetAmount(obj)) else uiSwapItem(from, obj, to, 1) redrawBarterInventory() } // bartering drop targets makeDropTarget($id("barterBoxLeft"), (data: string) => { uiBarterMove(data, "left") }) makeDropTarget($id("barterBoxRight"), (data: string) => { uiBarterMove(data, "right") }) makeDropTarget($id("barterBoxInventoryLeft"), (data: string) => { uiBarterMove(data, "leftInv") }) makeDropTarget($id("barterBoxInventoryRight"), (data: string) => { uiBarterMove(data, "rightInv") }) $id("barterTalkButton").onclick = uiEndBarterMode; $id("barterOfferButton").onclick = offer; function redrawBarterInventory() { drawInventory($id("barterBoxInventoryLeft"), "p", workingPlayerInventory) drawInventory($id("barterBoxInventoryRight"), "m", workingMerchantInventory) drawInventory($id("barterBoxLeft"), "l", playerBarterTable) drawInventory($id("barterBoxRight"), "r", merchantBarterTable) var moneyLeft = totalAmount(playerBarterTable) var moneyRight = totalAmount(merchantBarterTable) $id("barterBoxLeftAmount").innerHTML = "$" + moneyLeft; $id("barterBoxRightAmount").innerHTML = "$" + moneyRight; } redrawBarterInventory() } function uiEndLoot() { uiMode = UI_MODE_NONE hidev($id("lootBox")); off($id("lootBoxLeft"), "drop dragenter dragover"); off($id("lootBoxRight"), "drop dragenter dragover"); off($id("lootBoxTakeAllButton"), "click"); } function uiLoot(object: Obj) { uiMode = UI_MODE_LOOT function uiLootMove(data: string /* "l"|"r" */, where: "left"|"right") { console.log("loot: move " + data + " to " + where) var from = ({"l": player.inventory, "r": object.inventory} as any)[data[0]] if(from === undefined) throw "uiLootMove: wrong data: " + data var idx = parseInt(data.slice(1)) var obj = from[idx] if(obj === undefined) throw "uiLootMove: obj not found in list (" + idx + ")" var to = {"left": player.inventory, "right": object.inventory}[where] if(to === undefined) throw "uiLootMove: invalid location: " + where else if(to === from) // object -> same location return else if(obj.amount > 1) uiSwapItem(from, obj, to, uiGetAmount(obj)) else uiSwapItem(from, obj, to, 1) drawLoot() } function drawInventory($el: HTMLElement, who: "p"|"m"|"l"|"r", objects: Obj[]) { clearEl($el); for(var i = 0; i < objects.length; i++) { var inventoryImage = objects[i].invArt // 90x60 // 70x40 var img = makeEl("img", { src: inventoryImage+'.png', attrs: { width: 72, height: 60, title: objects[i].name } }); $el.appendChild(img); $el.insertAdjacentHTML("beforeend", "x" + objects[i].amount); makeDraggable(img, who + i); } } console.log("looting...") showv($id("lootBox")); // loot drop targets makeDropTarget($id("lootBoxLeft"), (data: string) => { uiLootMove(data, "left") }) makeDropTarget($id("lootBoxRight"), (data: string) => { uiLootMove(data, "right") }) $id("lootBoxTakeAllButton").onclick = () => { console.log("take all...") var inv = object.inventory.slice(0) // clone inventory for(var i = 0; i < inv.length; i++) uiSwapItem(object.inventory, inv[i], player.inventory, inv[i].amount) drawLoot() }; function drawLoot() { drawInventory($id("lootBoxLeft"), "l", player.inventory) drawInventory($id("lootBoxRight"), "r", object.inventory) } drawLoot() } function uiLog(msg: string) { const $log = $id("displayLog"); $log.insertAdjacentHTML("beforeend", `<li>${msg}</li>`); $log.scrollTop = $log.scrollHeight; } function uiCloseWorldMap() { uiMode = UI_MODE_NONE hide($id("worldMapContainer")); hidev($id("areamap")); hidev($id("worldmap")); Worldmap.stop() } function uiWorldMap(onAreaMap: boolean=false) { uiMode = UI_MODE_WORLDMAP show($id("worldMapContainer")); if(!mapAreas) mapAreas = loadAreas() if(onAreaMap) uiWorldMapAreaView() else uiWorldMapWorldView() uiWorldMapLabels() } function uiWorldMapAreaView() { hidev($id("worldmap")); showv($id("areamap")); Worldmap.stop() } function uiWorldMapWorldView() { showv($id("worldmap")); hidev($id("areamap")); Worldmap.start() } function uiWorldMapShowArea(area: Area) { uiWorldMapAreaView() const $areamap = $id("areamap"); $areamap.style.backgroundImage = `url('${area.mapArt}.png')`; clearEl($areamap); for(const entrance of area.entrances) { console.log("Area entrance: " + entrance.mapLookupName) var $entranceEl = makeEl("div", { classes: ["worldmapEntrance"] }); var $hotspot = makeEl("div", { classes: ["worldmapEntranceHotspot"] }); $hotspot.onclick = () => { // hotspot click -- travel to relevant map const mapName = lookupMapNameFromLookup(entrance.mapLookupName) console.log("hotspot -> " + mapName + " (via " + entrance.mapLookupName + ")") gMap.loadMap(mapName) uiCloseWorldMap() }; $entranceEl.appendChild($hotspot) appendHTML($entranceEl, entrance.mapLookupName); $entranceEl.style.left = entrance.x + "px"; $entranceEl.style.top = entrance.y + "px"; $id("areamap").appendChild($entranceEl); } } function uiWorldMapLabels() { $id("worldMapLabels").innerHTML = "<div id='worldMapLabelsBackground'></div>"; var i = 0 for(const areaID in mapAreas) { var area = mapAreas[areaID] if(!area.labelArt) continue var label = makeEl("img", { classes: ["worldMapLabelImage"], src: area.labelArt + ".png" }); var labelButton = makeEl("div", { classes: ["worldMapLabelButton"], click: () => { uiWorldMapShowArea(mapAreas[areaID]) } }); var areaLabel = makeEl("div", { classes: ["worldMapLabel"], style: {top: (1 + i*27) + "px"}, children: [label, labelButton] }); $id("worldMapLabels").appendChild(areaLabel) i++ } } function uiElevatorDone() { uiMode = UI_MODE_NONE hidev($id("elevatorBox")); // flip all buttons to hidden for(const $elevatorButton of $qa(".elevatorButton")) { hidev($elevatorButton); $elevatorButton.onclick = null; } hidev($id("elevatorLabel")); } function uiElevator(elevator: Elevator) { uiMode = UI_MODE_ELEVATOR var art = lookupInterfaceArt(elevator.type) console.log("elevator art: " + art) console.log("buttons: " + elevator.buttonCount) if(elevator.labels !== -1) { var labelArt = lookupInterfaceArt(elevator.labels) console.log("elevator label art: " + labelArt) const $elevatorLabel = $id("elevatorLabel"); showv($elevatorLabel); $elevatorLabel.style.backgroundImage = `url('${labelArt}.png')`; } const $elevatorBox = $id("elevatorBox"); showv($elevatorBox); $elevatorBox.style.backgroundImage = `url('${art}.png')`; // flip the buttons we need visible for(let i = 1; i <= elevator.buttonCount; i++) { const $elevatorButton = $id("elevatorButton" + i); showv($elevatorButton); $elevatorButton.onclick = () => { // button `i` pushed // todo: animate positioner/spinner (and come up with a better name for that) var mapID = elevator.buttons[i-1].mapID var level = elevator.buttons[i-1].level var position = fromTileNum(elevator.buttons[i-1].tileNum) if(mapID !== gMap.mapID) { // different map console.log("elevator -> map " + mapID + ", level " + level + " @ " + position.x + ", " + position.y) gMap.loadMapByID(mapID, position, level) } else if(level !== currentElevation) { // same map, different elevation console.log("elevator -> level " + level + " @ " + position.x + ", " + position.y) player.move(position) gMap.changeElevation(level, true) } // else, same elevation, do nothing uiElevatorDone() }; } } function uiCloseCalledShot() { uiMode = UI_MODE_NONE hide($id("calledShotBox")); } function uiCalledShot(art: string, target: Critter, callback?: (regionHit: string) => void) { uiMode = UI_MODE_CALLED_SHOT show($id("calledShotBox")); function drawChance(region: string) { var chance: any = Combat.prototype.getHitChance(player, target, region).hit console.log("id: %s | chance: %d", "#calledShot-"+region+"-chance #digit", chance) if(chance <= 0) chance = "--" drawDigits("#calledShot-"+region+"-chance #digit", chance, 2, false) } drawChance("torso") drawChance("head") drawChance("eyes") drawChance("groin") drawChance("leftArm") drawChance("rightArm") drawChance("leftLeg") drawChance("rightLeg") $id("calledShotBackground").style.backgroundImage = `url('${art}.png')`; for(const $label of $qa(".calledShotLabel")) { $label.onclick = (evt: MouseEvent) => { var id = (evt.target as HTMLElement).id var regionHit = id.split("-")[1] console.log("clicked a called location (%s)", regionHit) if(callback) callback(regionHit) }; } } function uiSaveLoad(isSave: boolean): void { uiMode = UI_MODE_SAVELOAD; const saveList = new Ui.List({ x: 55, y: 50, w: "auto", h: "auto" }); const saveInfo = new Ui.Label(404, 262, "", "#00FF00"); // TODO: CSSBoundingBox's width and height should be optional (and default to `auto`), then Label can accept one Object.assign(saveInfo.elem.style, { width: "154px", height: "33px", fontSize: "8pt", overflow: "hidden", }); const saveLoadWindow = new Ui.WindowFrame("art/intrface/lsgame.png", { x: 80, y: 20, w: 640, h: 480 }) .add(new Ui.Widget("art/intrface/lscover.png", { x: 340, y: 40, w: 275, h: 173 })) .add(new Ui.Label(50, 26, isSave ? "Save Game" : "Load Game")) .add(new Ui.SmallButton(391, 349).onClick(selected)).add(new Ui.Label(391+18, 349, "Done")) .add(new Ui.SmallButton(495, 349).onClick(done)).add(new Ui.Label(495+18, 349, "Cancel")) .add(saveInfo) .add(saveList) .show(); if(isSave) { saveList.select(saveList.addItem({ text: "<New Slot>", id: -1, onSelected: () => { saveInfo.setText("New save"); } })); } // List saves, and write them to the UI list SaveLoad.saveList((saves: SaveLoad.SaveGame[]) => { for(const save of saves) { saveList.addItem({ text: save.name, id: save.id, onSelected: () => { saveInfo.setText(SaveLoad.formatSaveDate(save) + "<br>" + save.currentMap); } }); } }); function done() { uiMode = UI_MODE_NONE; saveLoadWindow.close(); } function selected() { // Done was clicked, so save/load the slot const item = saveList.getSelection(); if(!item) return; // No slot selected const saveID = item.id; console.log("[UI] %s save #%d.", isSave ? "Saving" : "Loading", saveID); if(isSave) { const name = prompt("Save Name?"); if(saveID !== -1) { if(!confirm("Are you sure you want to overwrite that save slot?")) return; } SaveLoad.save(name, saveID === -1 ? undefined : saveID, done); } else { SaveLoad.load(saveID); done(); } } }
the_stack
import { wrapped, FunctionBuilder } from "./functions"; import { parseType } from "./parse"; import { lookup, Scope } from "./scope"; import { Type } from "./types"; import { concat, lookupForMap } from "./utils"; import { array, call, conditional, conformance, expr, extractContentOfBox, literal, member, read, reuse, set, stringifyType, stringifyValue, typeFromValue, typeRequiresBox, typeValue, undefinedValue, Value } from "./values"; import { isLiteral, Expression } from "@babel/types"; export enum PossibleRepresentation { None, Undefined = 1 << 0, Boolean = 1 << 1, Number = 1 << 2, String = 1 << 3, Function = 1 << 4, // Not used currently Object = 1 << 5, Symbol = 1 << 6, // Not used currently, possibly ever Null = 1 << 7, // Not referenced by typeof, but modeled in our system Array = 1 << 8, // Supported via Array.isArray All = PossibleRepresentation.Undefined | PossibleRepresentation.Boolean | PossibleRepresentation.Number | PossibleRepresentation.String | PossibleRepresentation.Function | PossibleRepresentation.Object | PossibleRepresentation.Symbol | PossibleRepresentation.Null | PossibleRepresentation.Array, } export interface ReifiedType { functions: (name: string) => FunctionBuilder | undefined; conformances: ProtocolConformanceMap; innerTypes: Readonly<TypeMap>; cases?: ReadonlyArray<EnumCase>; defaultValue?(scope: Scope, consume: (fieldName: string) => Expression | undefined): Value; copy?(value: Value, scope: Scope): Value; store?(target: Value, value: Value, scope: Scope): Value; } export type TypeParameterHost = <T extends Array<unknown>>(...args: T) => { [K in keyof T]: T[K] extends string ? Value : T[K] } & Iterable<Value>; export interface TypeMap { [name: string]: (globalScope: Scope, typeParameters: TypeParameterHost) => ReifiedType; } export interface FunctionMap { [name: string]: FunctionBuilder; } export interface ProtocolConformance { functions: { [functionName: string]: FunctionBuilder }; requirements: string[]; } export interface ProtocolConformanceMap { [protocolName: string]: ProtocolConformance; } export interface EnumCase { name: string; fieldTypes: ReadonlyArray<ReifiedType>; } const emptyConformances: ProtocolConformanceMap = Object.create(null); const noFunctions: Readonly<FunctionMap> = Object.create(null); const noInnerTypes: Readonly<TypeMap> = Object.create(null); export function withPossibleRepresentations(conformances: ProtocolConformanceMap, possibleRepresentations: PossibleRepresentation): ProtocolConformanceMap { return { ...conformances, Object: { functions: { ":rep": wrapped(() => literal(possibleRepresentations), "() -> Int"), }, requirements: [], }, }; } export function primitive(possibleRepresentations: PossibleRepresentation, defaultValue: Value, functions: FunctionMap = noFunctions, conformances: ProtocolConformanceMap = emptyConformances, innerTypes: Readonly<TypeMap> = noInnerTypes): ReifiedType { return { functions: functions !== noFunctions ? lookupForMap(functions) : alwaysUndefined, conformances: withPossibleRepresentations(conformances, possibleRepresentations), defaultValue() { return defaultValue; }, innerTypes, }; } export function protocol(protocolName: string, conformances: ProtocolConformanceMap = emptyConformances): ReifiedType { return { functions(functionName) { return (scope, arg, name, argTypes) => { const typeArg = conformance(arg(0, "Self"), protocolName, scope); const fn = typeFromValue(typeArg, scope).functions(functionName); if (typeof fn !== "function") { throw new TypeError(`Could not find ${functionName} on ${stringifyValue(typeArg)}`); } return fn(scope, arg, name, argTypes); }; }, conformances: withPossibleRepresentations(conformances, PossibleRepresentation.Object), innerTypes: noInnerTypes, }; } export function inheritLayout(type: ReifiedType, functions: FunctionMap = noFunctions, conformances: ProtocolConformanceMap = emptyConformances, innerTypes: Readonly<TypeMap> = noInnerTypes) { return { functions: functions !== noFunctions ? lookupForMap(functions) : alwaysUndefined, conformances: { ...conformances, // TODO: Call through with proper types Object: type.conformances.Object, }, defaultValue: type.defaultValue, copy: type.copy, store: type.store, innerTypes, }; } function cannotDefaultInstantiateClass(): never { throw new TypeError(`Cannot default instantiate a class`); } export function newClass(functions: FunctionMap = noFunctions, conformances: ProtocolConformanceMap = emptyConformances, innerTypes: Readonly<TypeMap> = noInnerTypes, defaultValue: (scope: Scope, consume: (fieldName: string) => Expression | undefined) => Value = cannotDefaultInstantiateClass): ReifiedType { return { functions: lookupForMap(functions), conformances: withPossibleRepresentations(conformances, PossibleRepresentation.Object), defaultValue, innerTypes, }; } export function expressionSkipsCopy(expression: Expression): boolean { switch (expression.type) { case "ObjectExpression": case "ArrayExpression": case "CallExpression": return true; case "ConditionalExpression": return expressionSkipsCopy(expression.consequent) && expressionSkipsCopy(expression.alternate); default: return isLiteral(expression); } } export function store(dest: Value, source: Value, type: Value, scope: Scope): Value { switch (dest.kind) { case "boxed": return conditional( typeRequiresBox(dest.type, scope), store(extractContentOfBox(dest, scope), source, type, scope), store(dest.contents, source, type, scope), scope, ); case "direct": const reified = typeFromValue(type, scope); if (reified.store) { return reified.store(dest, source, scope); } else { return set(dest, source, scope, "="); } case "subscript": return set(dest, source, scope, "="); default: throw new TypeError(`Unable to store to a ${dest.kind} value`); } } export function defaultInstantiateType(type: Value, scope: Scope, consume: (fieldName: string) => Expression | undefined): Value { const reified = typeFromValue(type, scope); if (!reified.defaultValue) { throw new Error(`Cannot default instantiate ${stringifyValue(type)}`); } return reified.defaultValue(scope, consume); } function typeArgumentsForArray(args: ReadonlyArray<Value>): TypeParameterHost { return ((...requested: string[]) => { if (requested.length > args.length) { throw new TypeError(`Requested ${requested.length} type arguments from array that only contains ${args.length} elements`); } return args.slice(0, args.length); }) as TypeParameterHost; } export function reifyType(typeOrTypeName: Type | string, scope: Scope, typeArguments: ReadonlyArray<Value> = [], types?: ReadonlyArray<Readonly<TypeMap>>): ReifiedType { const type = typeof typeOrTypeName === "string" ? parseType(typeOrTypeName) : typeOrTypeName; switch (type.kind) { case "name": if (typeof types !== "undefined") { // Search the provided types only for (const map of types) { if (Object.hasOwnProperty.call(map, type.name)) { return map[type.name](scope, typeArgumentsForArray(typeArguments)); } } } else { // Search up the scope chain let currentScope: Scope | undefined = scope; while (typeof currentScope !== "undefined") { const map = currentScope.types; if (Object.hasOwnProperty.call(map, type.name)) { return map[type.name](scope, typeArgumentsForArray(typeArguments)); } currentScope = currentScope.parent; } } return typeFromValue(lookup(type.name, scope), scope); // throw new TypeError(`Cannot resolve type named ${type.name}`); case "array": return reifyType({ kind: "name", name: "Array" }, scope, [typeValue(type.type)]); case "modified": return reifyType(type.type, scope); case "dictionary": return reifyType({ kind: "name", name: "Dictionary" }, scope, [typeValue(type.keyType), typeValue(type.valueType)]); case "tuple": const reifiedTypes = type.types.map((inner) => reifyType(inner, scope)); switch (type.types.length) { case 0: return primitive(PossibleRepresentation.Undefined, undefinedValue); case 1: return reifiedTypes[0]; default: return { functions: lookupForMap(noFunctions), conformances: withPossibleRepresentations({}, PossibleRepresentation.Array), defaultValue(innerScope) { return array(reifiedTypes.map((inner, i) => { const defaultValue = inner.defaultValue; if (typeof defaultValue === "undefined") { throw new TypeError(`Tuple field ${i} of type ${stringifyType(type.types[i])} is not default instantiable`); } return defaultValue(innerScope, alwaysUndefined); }), innerScope); }, copy(value, innerScope) { if (value.kind === "tuple") { return value; } const expression = read(value, innerScope); if (expressionSkipsCopy(expression)) { return expr(expression); } if (!reifiedTypes.some((elementType) => typeof elementType.copy !== "undefined")) { return call(member(expr(expression), "slice", scope), [], [], scope); } return reuse(expr(expression), innerScope, "copySource", (source) => { return array(reifiedTypes.map((elementType, index) => { const fieldValue = member(source, index, innerScope); return elementType.copy ? elementType.copy(fieldValue, innerScope) : fieldValue; }), scope); }); }, innerTypes: noInnerTypes, }; } case "generic": return reifyType(type.base, scope, concat(typeArguments, type.arguments.map((innerType) => typeValue(innerType)))); case "metatype": const reified = reifyType(type.base, scope, typeArguments); return reified; // if (!Object.hasOwnProperty.call(reified.innerTypes, type.as)) { // throw new TypeError(`${stringifyType(type.base)} does not have a ${type.as} inner type`); // } // return reified.innerTypes[type.as](scope, typeArgumentsForArray([])); case "function": return primitive(PossibleRepresentation.Function, undefinedValue); case "namespaced": return reifyType(type.type, scope, [], [reifyType(type.namespace, scope, typeArguments).innerTypes]); case "optional": return reifyType({ kind: "name", name: "Optional" }, scope, [typeValue(type.type)]); default: throw new TypeError(`Received an unexpected type ${(type as Type).kind}`); } } function alwaysUndefined(): undefined { return undefined; }
the_stack
import { useContentGqlHandler } from "../utils/useContentGqlHandler"; import { defaultIdentity } from "../utils/defaultIdentity"; const identityRoot = { id: "root", displayName: "root", type: "admin" }; const updatedDisplayName = "Robert Downey"; describe("Reviewer crud test", () => { const options = { path: "manage/en-US" }; const { securityIdentity, reviewer, until } = useContentGqlHandler({ ...options, plugins: [defaultIdentity()] }); const { securityIdentity: securityIdentityRoot } = useContentGqlHandler({ ...options, plugins: [defaultIdentity()], identity: identityRoot }); const { securityIdentity: securityIdentityRootUpdated } = useContentGqlHandler({ ...options, plugins: [defaultIdentity()], identity: { ...identityRoot, displayName: updatedDisplayName } }); it("should be able to hook on to after login", async () => { const [response] = await securityIdentity.login(); expect(response).toEqual({ data: { security: { login: { data: { id: "12345678" }, error: null } } } }); await until( () => reviewer.listReviewersQuery({}).then(([data]) => data), (response: any) => { const list = response.data.apw.listReviewers.data; return list.length === 1; }, { name: "Wait for listReviewers query" } ); /** * Should created a reviewer entry after login. */ const [listReviewersResponse] = await reviewer.listReviewersQuery({}); expect(listReviewersResponse).toEqual({ data: { apw: { listReviewers: { data: [ { id: expect.any(String), createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), createdBy: { id: "12345678", displayName: "John Doe", type: "admin" }, identityId: "12345678", displayName: "John Doe", type: "admin" } ], error: null, meta: { hasMoreItems: false, cursor: null, totalCount: 1 } } } } }); /* * Login with another identity. */ await securityIdentityRoot.login(); await until( () => reviewer.listReviewersQuery({}).then(([data]) => data), (response: any) => { const list = response.data.apw.listReviewers.data; return list.length === 2; }, { name: "Wait for listReviewers query" } ); /** * Should now have 2 reviewers. */ const [listReviewersAgainResponse] = await reviewer.listReviewersQuery({}); expect(listReviewersAgainResponse).toEqual({ data: { apw: { listReviewers: { data: [ { id: expect.any(String), createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), createdBy: { id: identityRoot.id, displayName: identityRoot.displayName, type: identityRoot.type }, identityId: identityRoot.id, displayName: identityRoot.displayName, type: "admin" }, { id: expect.any(String), createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), createdBy: { id: "12345678", displayName: "John Doe", type: "admin" }, identityId: "12345678", displayName: "John Doe", type: "admin" } ], error: null, meta: { hasMoreItems: false, cursor: null, totalCount: 2 } } } } }); }); it("should not create more than one entry due to multiple login", async () => { const [response] = await securityIdentity.login(); expect(response).toEqual({ data: { security: { login: { data: { id: "12345678" }, error: null } } } }); await until( () => reviewer.listReviewersQuery({}).then(([data]) => data), (response: any) => { const list = response.data.apw.listReviewers.data; return list.length === 1; }, { name: "Wait for listReviewers query" } ); /** * Should created a reviewer entry after login. */ const [listReviewersResponse] = await reviewer.listReviewersQuery({}); expect(listReviewersResponse).toEqual({ data: { apw: { listReviewers: { data: [ { id: expect.any(String), createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), createdBy: { id: "12345678", displayName: "John Doe", type: "admin" }, identityId: "12345678", displayName: "John Doe", type: "admin" } ], error: null, meta: { hasMoreItems: false, cursor: null, totalCount: 1 } } } } }); /* * Login again with same identity. */ await securityIdentity.login(); await until( () => reviewer.listReviewersQuery({}).then(([data]) => data), (response: any) => { const list = response.data.apw.listReviewers.data; return list.length === 1; }, { name: "Wait for listReviewers query" } ); /* * Should not have 2 reviewers. */ const [listReviewersAgainResponse] = await reviewer.listReviewersQuery({}); expect(listReviewersAgainResponse).toEqual({ data: { apw: { listReviewers: { data: [ { id: expect.any(String), createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), createdBy: { id: "12345678", displayName: "John Doe", type: "admin" }, identityId: "12345678", displayName: "John Doe", type: "admin" } ], error: null, meta: { hasMoreItems: false, cursor: null, totalCount: 1 } } } } }); }); it(`should update "displayName" after login if identity has been updated`, async () => { const [response] = await securityIdentityRoot.login(); expect(response).toEqual({ data: { security: { login: { data: { id: "root" }, error: null } } } }); await until( () => reviewer.listReviewersQuery({}).then(([data]) => data), (response: any) => { const list = response.data.apw.listReviewers.data; return list.length === 1; }, { name: "Wait for listReviewers query" } ); /** * Should created a reviewer entry after login. */ const [listReviewersResponse] = await reviewer.listReviewersQuery({}); expect(listReviewersResponse).toEqual({ data: { apw: { listReviewers: { data: [ { id: expect.any(String), createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), createdBy: { id: "root", displayName: "root", type: "admin" }, identityId: "root", displayName: "root", type: "admin" } ], error: null, meta: { hasMoreItems: false, cursor: null, totalCount: 1 } } } } }); /* * Login again with same identity. */ await securityIdentityRootUpdated.login(); await until( () => reviewer.listReviewersQuery({}).then(([data]) => data), (response: any) => { const list = response.data.apw.listReviewers.data; return list.length === 1; }, { name: "Wait for listReviewers query" } ); /* * Should not have 2 reviewers. */ const [listReviewersAgainResponse] = await reviewer.listReviewersQuery({}); expect(listReviewersAgainResponse).toEqual({ data: { apw: { listReviewers: { data: [ { id: expect.any(String), createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), createdBy: { id: "root", displayName: "root", type: "admin" }, identityId: "root", displayName: updatedDisplayName, type: "admin" } ], error: null, meta: { hasMoreItems: false, cursor: null, totalCount: 1 } } } } }); }); });
the_stack
import { SampleData } from '../../../src/containers/ImportWizardModal/SampleData'; describe('Multiple Selection', () => { const graphinEl = 'Graphin2'; const deleteButtonClick = () => { cy.react('Button2', { props: { 'data-testid': 'filter-selection-header:delete', }, }) .first() .click(); }; before(() => { cy.visit('/'); cy.waitForReact(5000); // switch tabs to sample data cy.switchTab('sample-data'); // import sample data by clicking bank cy.importSampleData(SampleData.BANK); cy.switchPanel('filters'); }); describe('Double Strings filter', () => { beforeEach(() => { // switch to filter panel cy.react('AddFilterButton').click(); }); afterEach(() => { deleteButtonClick(); deleteButtonClick(); }); it('Single - Single combination', () => { // perform first selection cy.selectFilterSelection('icon{enter}', 'first'); cy.filterMultiString('account_box{enter}'); // perform second selection cy.react('AddFilterButton').click(); cy.selectFilterSelection('id{enter}', 'first'); cy.filterMultiString('customer_81{enter}', 'first'); // results cy.getReact(graphinEl).getProps('data.nodes').should('have.length', 1); cy.getReact(graphinEl).getProps('data.edges').should('have.length', 0); }); it('Multiple - Single combination', () => { // perform first selection cy.selectFilterSelection('icon{enter}', 'first'); cy.filterMultiString('account_box{enter}'); // perform second selection cy.react('AddFilterButton').click(); cy.selectFilterSelection('id{enter}', 'first'); cy.filterMultiString('customer_81{enter}customer_55{enter}', 'first'); // results cy.getReact(graphinEl).getProps('data.nodes').should('have.length', 2); cy.getReact(graphinEl).getProps('data.edges').should('have.length', 0); }); it('Multiple - Multiple combination', () => { // perform first selection cy.selectFilterSelection('customer_type{enter}', 'first'); cy.filterMultiString('retail{enter}-{enter}'); // perform second selection cy.react('AddFilterButton').click(); cy.selectFilterSelection('id{enter}', 'first'); cy.filterMultiString('customer_81{enter}customer_55{enter}', 'first'); // results cy.getReact(graphinEl).getProps('data.nodes').should('have.length', 2); cy.getReact(graphinEl).getProps('data.edges').should('have.length', 0); }); }); describe('Triple Strings filter', () => { beforeEach(() => { cy.react('AddFilterButton').click(); }); afterEach(() => { deleteButtonClick(); deleteButtonClick(); deleteButtonClick(); }); it('Double - Double - Double combination', () => { // perform first selection cy.selectFilterSelection('customer_type{enter}', 'first'); cy.filterMultiString('retail{enter}-{enter}'); // perform second selection cy.react('AddFilterButton').click(); cy.selectFilterSelection('id{enter}', 'first'); cy.filterMultiString('customer_81{enter}customer_55{enter}', 'first'); // perform third selection cy.react('AddFilterButton').click(); cy.selectFilterSelection('icon{enter}', 'first'); cy.filterMultiString('account_box{enter}-{enter}', 'first'); // results cy.getReact(graphinEl).getProps('data.nodes').should('have.length', 2); cy.getReact(graphinEl).getProps('data.edges').should('have.length', 0); }); }); describe('Numeric and String filter', () => { beforeEach(() => { cy.react('AddFilterButton').click(); }); afterEach(() => { deleteButtonClick(); deleteButtonClick(); }); it('Numeric - Single String combination', () => { // perform first selection cy.selectFilterSelection('risk_score{enter}', 'first'); // perform second selection cy.react('AddFilterButton').click(); cy.selectFilterSelection('id{enter}', 'first'); cy.filterMultiString('customer_901{enter}', 'first'); // results cy.getReact(graphinEl).getProps('data.nodes').should('have.length', 1); cy.getReact(graphinEl).getProps('data.edges').should('have.length', 0); }); it('Numeric - Double String combination', () => { // perform first selection cy.selectFilterSelection('risk_score{enter}', 'first'); // perform second selection cy.react('AddFilterButton').click(); cy.selectFilterSelection('id{enter}', 'first'); cy.filterMultiString('customer_901{enter}customer_902{enter}', 'first'); // results cy.getReact(graphinEl).getProps('data.nodes').should('have.length', 2); cy.getReact(graphinEl).getProps('data.edges').should('have.length', 0); }); }); describe('Numeric and Numeric filter', () => { beforeEach(() => { cy.react('AddFilterButton').click(); }); it('Double Numeric combination', () => { // perform first selection cy.selectFilterSelection('amount{enter}', 'first'); // perform second selection cy.react('AddFilterButton').click(); cy.selectFilterSelection('is_different_bank{enter}', 'first'); // results cy.getReact(graphinEl).getProps('data.nodes').should('have.length', 9); cy.getReact(graphinEl).getProps('data.edges').should('have.length', 14); deleteButtonClick(); deleteButtonClick(); }); it('Triple Numeric combination', () => { // perform first selection cy.selectFilterSelection('amount{enter}', 'first'); // perform second selection cy.react('AddFilterButton').click(); cy.selectFilterSelection('is_different_bank{enter}', 'first'); // perform third selection cy.react('AddFilterButton').click(); cy.selectFilterSelection('risk_score{enter}', 'first'); // results cy.getReact(graphinEl).getProps('data.nodes').should('have.length', 0); cy.getReact(graphinEl).getProps('data.edges').should('have.length', 0); deleteButtonClick(); deleteButtonClick(); deleteButtonClick(); }); }); describe('Numeric and String filter', () => { beforeEach(() => { cy.react('AddFilterButton').click(); }); afterEach(() => { deleteButtonClick(); deleteButtonClick(); }); it('Numeric - Single String combination', () => { // perform first selection cy.selectFilterSelection('risk_score{enter}', 'first'); // perform second selection cy.react('AddFilterButton').click(); cy.selectFilterSelection('id{enter}', 'first'); cy.filterMultiString('customer_901{enter}', 'first'); // results cy.getReact(graphinEl).getProps('data.nodes').should('have.length', 1); cy.getReact(graphinEl).getProps('data.edges').should('have.length', 0); }); }); describe('String and DateTime filter', () => { beforeEach(() => { cy.react('AddFilterButton').click(); }); afterEach(() => { deleteButtonClick(); deleteButtonClick(); }); it('Single String - DateTime combination', () => { // perform first selection cy.selectFilterSelection('create_date{enter}', 'first'); // perform second selection cy.react('AddFilterButton').click(); cy.selectFilterSelection('icon{enter}', 'first'); cy.filterMultiString('account_balance{enter}', 'first'); // results cy.getReact(graphinEl).getProps('data.nodes').should('have.length', 9); cy.getReact(graphinEl).getProps('data.edges').should('have.length', 14); }); it('Multi String - DateTime combination', () => { // perform first selection cy.selectFilterSelection('create_date{enter}', 'first'); // perform second selection cy.react('AddFilterButton').click(); cy.selectFilterSelection('icon{enter}', 'first'); cy.filterMultiString('account_box{enter}-{enter}', 'first'); // results cy.getReact(graphinEl).getProps('data.nodes').should('have.length', 0); cy.getReact(graphinEl).getProps('data.edges').should('have.length', 0); }); }); describe('String and Time filter', () => { beforeEach(() => { cy.react('AddFilterButton').click(); }); afterEach(() => { deleteButtonClick(); deleteButtonClick(); }); it('Single String - Time combination', () => { // perform first selection cy.selectFilterSelection('time{enter}', 'first'); // perform second selection cy.react('AddFilterButton').click(); cy.selectFilterSelection('icon{enter}', 'first'); cy.filterMultiString('account_balance{enter}', 'first'); // results cy.getReact(graphinEl).getProps('data.nodes').should('have.length', 9); cy.getReact(graphinEl).getProps('data.edges').should('have.length', 14); }); it('Multi String - Time combination', () => { // perform first selection cy.selectFilterSelection('create_date{enter}', 'first'); // perform second selection cy.react('AddFilterButton').click(); cy.selectFilterSelection('icon{enter}', 'first'); cy.filterMultiString('account_balance{enter}-{enter}', 'first'); // results cy.getReact(graphinEl).getProps('data.nodes').should('have.length', 9); cy.getReact(graphinEl).getProps('data.edges').should('have.length', 14); }); }); describe('String and Date filter', () => { beforeEach(() => { cy.react('AddFilterButton').click(); }); afterEach(() => { deleteButtonClick(); deleteButtonClick(); }); it('Single String - Date combination', () => { // perform first selection cy.selectFilterSelection('date{enter}', 'first'); // perform second selection cy.react('AddFilterButton').click(); cy.selectFilterSelection('icon{enter}', 'first'); cy.filterMultiString('account_balance{enter}', 'first'); // results cy.getReact(graphinEl).getProps('data.nodes').should('have.length', 9); cy.getReact(graphinEl).getProps('data.edges').should('have.length', 14); }); it('Multi String - Date combination', () => { // perform first selection cy.selectFilterSelection('date{enter}', 'first'); // perform second selection cy.react('AddFilterButton').click(); cy.selectFilterSelection('icon{enter}', 'first'); cy.filterMultiString('account_balance{enter}-{enter}', 'first'); // results cy.getReact(graphinEl).getProps('data.nodes').should('have.length', 9); cy.getReact(graphinEl).getProps('data.edges').should('have.length', 14); }); }); });
the_stack
export type MapFunction<T, R> = (value: T) => R; /** * A stream of values. * * @template T the type of the stream's values. */ export interface Stream<T> { /** * Function to either send a value onto the stream -- by providing a value, `stream1(value)` -- or * to get the stream's latest value -- by calling the function with no arguments, `stream1()`. * * @param {T} [value] the value to send onto the stream. If not provided, the function instead * returns the stream's latest value. * * @returns {T} the stream's latest value. */ (value?: T): T; /** * Function to create a new stream with values that are the result of calling a mapping function * on the source stream's values. * * @template R the type of the returned stream's values. * * @param fn the mapping function. * * @returns {Stream<R>} a stream resulting from mapping the source stream. */ map<R>(fn: MapFunction<T, R>): Stream<R>; /** * Ends a stream, so that the streams that were created with `map` and/or `scan` no longer receive * values from this stream. * * @param {boolean} [value] the value indicating to end the stream. */ end(value?: boolean): void; /** * Indicates whether or not this stream has been ended. */ ended?: boolean; } /** * Function that creates a stream. * * @template T the type of the stream's values. * * @param {T} [value] the stream's initial value. * * @returns {Stream<T>} the created stream. */ export type StreamConstructor = <T>(value?: T) => Stream<T>; /** * Accumulator function. * * @template R the type of the result value. * @template T the type of the source value. * * @param {R} result the current accumulated result value. * @param {T} next the next source value. * * @returns {R} the accumulated result value. */ export type Accumulator<R, T> = (result: R, next: T) => R; /** * Stream library `scan` function. * * @template T the type of the source stream's values. * @template R the type of the returned stream's values. * * @param {Accumulator<R, T>} acc the accumulator function. * @param {R} init the returned stream's initial value. * @param {Stream<T>} stream the source stream. * * @returns {Stream<R>} a stream resulting from scanning the source stream. */ export type Scan = <T, R>(acc: Accumulator<R, T>, init: R, stream: Stream<T>) => Stream<R>; /** * Defines the stream library's `scan` function. */ interface StreamScan { /** * The stream library's `scan` function. */ scan: Scan; } /** * Stream library that provides a function to create a stream. * * @template T the type of the stream's values. */ export interface StreamLibWithFunction extends StreamScan { /** * The function to create a stream. * * @param {T} [value] the initial value for the stream. * * @returns {Stream<T>} the created stream. */ <T>(value?: T): Stream<T>; } /** * Stream library that provides a `stream` property which is a function to create a stream. * * @template T the type of the stream's values. */ export interface StreamLibWithProperty extends StreamScan { /** * The function to create a stream. * * @param {T} [value] the initial value for the stream. * * @returns {Stream<T>} the created stream. */ stream<T>(value?: T): Stream<T>; } /** * Stream library. This works with `meiosis.simpleStream`, `flyd`, `m.stream`, or anything for which * you provide either a function or an object with a `stream` function to create a stream. The * function or object must also have a `scan` property. The returned stream must have a `map` * method. */ export type StreamLib = StreamLibWithFunction | StreamLibWithProperty; /** * Combines an array of patches into a single patch. * * @template P the Patch type. * * @param {P[]} patches the array of patches. * * @returns {P | P[]} the result of combining the array of patches. */ export type Combine<P> = (patches: P[]) => P | P[]; /** * A service function. Receives the current state and returns a patch to be applied to the state. * * @template S the State type. * @template P the Patch type. * * @param {S} state the current state. * * @returns {P} the patch to be applied to the state. */ export type Service<S, P> = (state: S) => P; /** * An effect function. Receives the current state and optionally performs a side effects, including * but not limited to, calling `update` and/or `actions` which are provided to the effect * constructor. * * @template S the State type. * * @param {S} state the current state. */ export type Effect<S> = (state: S) => void; /** * An effects constructor. Receives the `update` stream and the `actions`, and returns an array of * effect functions to be called when the application state changes. * * @template S the State type. * @template P the Patch type. * @template A the Actions type. * * @param {Stream<P>} update the `update` stream. * @param {A} [actions] the application's `actions`. * * @returns {Effect<S>} the array of effect functions that will get called on state changes. */ export type EffectConstructor<S, P, A> = (update: Stream<P>, actions?: A) => Effect<S>[]; /** * Constructor of application actions. * * @template S the State type. * @template P the Patch type. * @template A the Actions type. * * @param {Stream<P>} update the `update` stream. * @param {Stream<S>} [states] the stream of application states. * * @returns {A} the application's actions. */ export type ActionConstructor<S, P, A> = (update: Stream<P>, states?: Stream<S>) => A; /** * Application object that provides the application's initial state, the service functions, the * application's actions, and the effects, all of which are optional. * * @template S the State type. * @template P the Patch type. * @template A the Actions type. */ export type App<S, P, A> = { /** * An object that represents the initial state. If not specified, the initial state will be `{}`. */ initial?: S; /** * An array of service functions. */ services?: Service<S, P>[]; /** * A function that creates the application's actions. */ Actions?: ActionConstructor<S, P, A>; /** * A function that creates the application's effects. */ Effects?: EffectConstructor<S, P, A>; }; /** * Meiosis configuration. * * @template S the State type. * @template P the Patch type. * @template A the Actions type. */ export type MeiosisConfig<S, P, A> = { /** * The stream library. This works with `meiosis.simpleStream`, `flyd`, `m.stream`, or anything for * which you provide either a function or an object with a `stream` function to create a stream. * The function or object must also have a `scan` property. The returned stream must have a `map` * method. */ stream: StreamLib; /** * The accumulator function. */ accumulator: Accumulator<S, P>; /** * The function that combines an array of patches into one patch. */ combine: Combine<P>; /** * The application object, with optional properties. */ app: App<S, P, A>; }; /** * Returned by Meiosis setup. * * @template S the State type. * @template P the Patch type. * @template A the Actions type. */ export type Meiosis<S, P, A> = { /** * The stream of application states. */ states: Stream<S>; /** * The `update` stream. Patches should be sent onto this stream by calling `update(patch)`. */ update: Stream<P>; /** * The application's actions. */ actions: A; }; /** * Base helper to setup the Meiosis pattern. If you are using Mergerino, Function Patches, or Immer, * use their respective `setup` function instead. * * Patch is merged in to the state by default. Services have access to the state and can return a * patch that further updates the state. State changes by services are available to the next * services in the list. * * After the services have run and the state has been updated, effects are executed and have the * opportunity to trigger more updates. * * @template S the State type. * @template P the Patch type. * @template A the Actions type. * * @param {MeiosisConfig<S, P, A>} config the Meiosis config. * * @returns {Meiosis<S, P, A>} the Meiosis setup. */ export function Setup<S, P, A>(config: MeiosisConfig<S, P, A>): Meiosis<S, P, A>; export default Setup; /** * A local path. */ export interface LocalPath { /** The `path` which is stored on the local object for internal use. */ path: Array<string>; } /** * Function that nests a patch `P2` within a parent patch `P1`. * * @template P1 the type of the parent patch. * @template P2 the type of the patch to be nested. * * @param {P2} patch the nested patch. * * @returns {P1} the parent patch with `P2` nested within. */ type NestPatchFunction<P1, P2> = (patch: P2) => P1; /** * A local object with a `patch` function to create a nested patch. * * @template P1 the type of the parent patch. * @template P2 the type of the patch to be nested. */ export interface LocalPatch<P1, P2> { /** Creates a nested patch. */ patch: NestPatchFunction<P1, P2>; } /** * @template S1 the type of the parent state. * @template P1 the type of the parent patch. * @template S2 the type of the nested state. * @template P2 the type of the patch to be nested. */ export interface Local<S1, P1, S2, P2> extends LocalPath, LocalPatch<P1, P2> { /** Function to get the local state from the global state. */ get: (state: S1) => S2; } /** * Function that creates a local object from the specified nest path and, optionally, another * local object. */ type NestFunction<S1, P1, S2, P2> = ( path: string | Array<string>, local?: LocalPath ) => Local<S1, P1, S2, P2>; /** * Creates a function that nests a patch at a given path. * * @param {Array<String>} path the path at which to nest. * * @returns {NestPatchFunction<P1, P2>} the nest patch function. */ export type CreateNestPatchFunction = <P1, P2>(path: Array<string>) => NestPatchFunction<P1, P2>; /** * Constructor to create a `nest` function. * * @template S1 the type of the parent state. * @template P1 the type of the parent patch. * @template S2 the type of the nested state. * @template P2 the type of the patch to be nested. */ declare function Nest<S1, P1, S2, P2>( createNestPatchFunction: CreateNestPatchFunction ): NestFunction<S1, P1, S2, P2>; export { Nest }; /** * Returned by Meiosis One setup. * * @template S the State type. * @template P the Patch type. * @template A the Actions type. */ export interface MeiosisOne<S, P, A> { states: Stream<S>; getState: () => S; update: Stream<P>; actions: A; root: MeiosisOne<S, P, A>; nest: <K extends keyof S>(prop: K) => MeiosisOne<S[K], P, A>; } /** * Constructor of application actions. * * @template S the State type. * @template P the Patch type. * @template A the Actions type. * * @param {Stream<P>} update the `update` stream. * @param {Stream<S>} [states] the stream of application states. * * @returns {A} the application's actions. */ export type ActionOneConstructor<S, P, A> = (context: MeiosisOne<S, P, A>) => A; /** * Application object that provides the application's initial state, the service functions, the * application's actions, and the effects, all of which are optional. * * @template S the State type. * @template P the Patch type. * @template A the Actions type. */ export type AppOne<S, P, A> = { /** * An object that represents the initial state. If not specified, the initial state will be `{}`. */ initial?: S; /** * An array of service functions. */ services?: Service<S, P>[]; /** * A function that creates the application's actions. */ Actions?: ActionOneConstructor<S, P, A>; /** * A function that creates the application's effects. */ Effects?: EffectConstructor<S, P, A>; }; /** * Meiosis One configuration. * * @template S the State type. * @template P the Patch type. * @template A the Actions type. */ export type MeiosisOneConfig<S, P, A> = { /** * The stream library. This works with `meiosis.simpleStream`, `flyd`, `m.stream`, or anything for * which you provide either a function or an object with a `stream` function to create a stream. * The function or object must also have a `scan` property. The returned stream must have a `map` * method. */ stream: StreamLib; /** * The accumulator function. */ accumulator: Accumulator<S, P>; /** * The function that combines an array of patches into one patch. */ combine: Combine<P>; /** * The application object, with optional properties. */ app: AppOne<S, P, A>; /** * Creates a function that nests a patch at a given path. * * @param {Array<String>} path the path at which to nest. * * @returns {NestPatchFunction<P1, P2>} the nest patch function. */ createNestPatchFunction: CreateNestPatchFunction; }; /** * Base helper to setup Meiosis One. If you are using Mergerino, Function Patches, or Immer, * use their respective `meiosisOne` function instead. * * @template S the State type. * @template P the Patch type. * @template A the Actions type. * * @param {MeiosisOneConfig<S, P, A>} config the Meiosis One config. * * @returns {MeiosisOne<S, P, A>} the Meiosis One setup. */ export function meiosisOne<S, P, A>(config: MeiosisOneConfig<S, P, A>): MeiosisOne<S, P, A>;
the_stack
import * as Typing from "../../../../main/js/joynr/util/Typing"; import TypeRegistrySingleton from "../../../../main/js/joynr/types/TypeRegistrySingleton"; import DiscoveryEntry from "../../../../main/js/generated/joynr/types/DiscoveryEntry"; import ProviderQos from "../../../../main/js/generated/joynr/types/ProviderQos"; import ProviderScope from "../../../../main/js/generated/joynr/types/ProviderScope"; import Version from "../../../../main/js/generated/joynr/types/Version"; import RadioStation from "../../../generated/joynr/vehicle/radiotypes/RadioStation"; import ComplexRadioStation from "../../../generated/joynr/datatypes/exampleTypes/ComplexRadioStation"; import ComplexStruct from "../../../generated/joynr/datatypes/exampleTypes/ComplexStruct"; import Country from "../../../generated/joynr/datatypes/exampleTypes/Country"; import TestEnum from "../../../generated/joynr/tests/testTypes/TestEnum"; class MyCustomObj {} // eslint-disable-next-line @typescript-eslint/class-name-casing class _TestConstructor123_ {} class MyType { public a: any; public b: any; public c: any; public d: any; public e: any; public constructor({ a, b, c, d, e }: any = {}) { this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; } public _typeName = "MyTypeName"; public static _typeName = "MyTypeName"; public static getMemberType() {} } class MySecondType { public a: any; public b: any; public c: any; public d: any; public e: any; public constructor({ a, b, c, d, e }: any = {}) { this.a = a; this.b = b; this.c = c; this.d = d; this.e = e; } public _typeName = "MySecondTypeName"; public static _typeName = "MySecondTypeName"; public static getMemberType() {} } const createSettings = (a: any, b?: any, c?: any, d?: any, e?: any) => ({ a, b, c, d, e }); describe(`libjoynr-js.joynr.Typing`, () => { beforeEach(() => { TypeRegistrySingleton.getInstance() .addType(RadioStation) .addType(ComplexRadioStation) .addType(ComplexStruct) .addType(TestEnum) .addType(Country) .addType(ProviderQos) .addType(ProviderScope) .addType(Version); }); it("is defined and of correct type", () => { expect(Typing).toBeDefined(); expect(Typing).not.toBeNull(); expect(typeof Typing === "object").toBeTruthy(); }); describe("libjoynr-js.joynr.Typing.getObjectType", () => { it("returns the correct type strings", () => { expect(Typing.getObjectType(true)).toEqual("Boolean"); expect(Typing.getObjectType(false)).toEqual("Boolean"); expect(Typing.getObjectType(-123)).toEqual("Number"); expect(Typing.getObjectType(0)).toEqual("Number"); expect(Typing.getObjectType(123)).toEqual("Number"); expect(Typing.getObjectType(1.2345678)).toEqual("Number"); expect(Typing.getObjectType("a string")).toEqual("String"); expect(Typing.getObjectType(() => {})).toEqual("Function"); expect(Typing.getObjectType(new MyCustomObj())).toEqual("MyCustomObj"); expect(Typing.getObjectType(new _TestConstructor123_())).toEqual("_TestConstructor123_"); expect(Typing.getObjectType("a String")).toEqual("String"); expect(Typing.getObjectType([])).toEqual("Array"); expect(Typing.getObjectType({})).toEqual("Object"); }); it("throws if no object is provided", () => { expect(() => { Typing.getObjectType(null); }).toThrow(); expect(() => { Typing.getObjectType(undefined); }).toThrow(); }); }); describe("libjoynr-js.joynr.Typing.augmentType", () => { const tests = [ { untyped: null, typed: null }, { untyped: undefined, typed: undefined }, { untyped: true, typed: true }, { untyped: false, typed: false }, { untyped: 12345, typed: 12345 }, { untyped: 0, typed: 0 }, { untyped: -12345, typed: -12345 }, { untyped: 1.23456789, typed: 1.23456789 }, { untyped: "123456", typed: "123456" }, { untyped: "-123456", typed: "-123456" }, { untyped: "1.23456789", typed: "1.23456789" }, { untyped: "myString", typed: "myString" }, { untyped: { a: 1, b: 2, c: 3, d: 4, e: 5, _typeName: "MyTypeName" }, typed: new MyType(createSettings(1, 2, 3, 4, 5)) }, { untyped: { a: 1, b: 2, c: 3, d: 4, e: 5, _typeName: "MySecondTypeName" }, typed: new MySecondType(createSettings(1, 2, 3, 4, 5)) }, { untyped: { a: 1, b: [1, 2, 3], c: "3", d: "asdf", _typeName: "MyTypeName" }, typed: new MyType(createSettings(1, [1, 2, 3], "3", "asdf")) }, { untyped: { a: 1, b: [1, 2, 3], c: "3", d: "asdf", _typeName: "MySecondTypeName" }, typed: new MySecondType(createSettings(1, [1, 2, 3], "3", "asdf")) }, { untyped: { a: 1, b: { a: 1, b: { a: 1, b: 2, c: 3, d: 4, e: 5, _typeName: "MyTypeName" }, c: 3, d: { a: 1, b: 2, c: 3, d: 4, e: 5, _typeName: "MyTypeName" }, e: 5, _typeName: "MySecondTypeName" }, c: 3, d: { a: 1, b: { a: 1, b: 2, c: 3, d: 4, e: 5, _typeName: "MyTypeName" }, c: 3, d: { a: 1, b: 2, c: 3, d: 4, e: 5, _typeName: "MyTypeName" }, e: 5, _typeName: "MySecondTypeName" }, e: 5, _typeName: "MyTypeName" }, typed: new MyType( createSettings( 1, new MySecondType( createSettings( 1, new MyType(createSettings(1, 2, 3, 4, 5)), 3, new MyType(createSettings(1, 2, 3, 4, 5)), 5 ) ), 3, new MySecondType( createSettings( 1, new MyType(createSettings(1, 2, 3, 4, 5)), 3, new MyType(createSettings(1, 2, 3, 4, 5)), 5 ) ), 5 ) ) } ]; it("types all objects correctly", () => { const typeRegistry = TypeRegistrySingleton.getInstance(); typeRegistry.addType(MyType); typeRegistry.addType(MySecondType); let i: any, typed: any; for (i = 0; i < tests.length; ++i) { typed = Typing.augmentTypes(tests[i].untyped); expect(typed).toEqual(tests[i].typed); if (tests[i].untyped) { // filter out undefined and null expect(Typing.getObjectType(typed)).toEqual(Typing.getObjectType(tests[i].typed)); } } }); it("throws when giving a function or an object with a custom type", () => { expect(() => { Typing.augmentTypes(() => {}); }).toThrow(); expect(() => { Typing.augmentTypes(new MyType()); }).toThrow(); expect(() => { Typing.augmentTypes(new MySecondType()); }).toThrow(); }); it("augmentTypes is able to deal with enums as input", () => { const fixture = "ZERO"; const expected = TestEnum.ZERO; expect(Typing.augmentTypes(fixture)).toBe(fixture); expect(Typing.augmentTypes(fixture, "joynr.tests.testTypes.TestEnum")).toBe(expected); }); it("augmentTypes is able to deal with error enums as input", () => { const fixture = { _typeName: "joynr.tests.testTypes.TestEnum", name: "ZERO" }; const expected = TestEnum.ZERO; const result = Typing.augmentTypes(fixture); expect(result.name).toBeDefined(); expect(result.name).toBe(expected.name); expect(result.value).toBeDefined(); expect(result.value).toBe(expected.value); expect(result).toBe(expected); }); it("augmentTypes is able to deal with structs containing enum members", () => { const fixture = { _typeName: "joynr.datatypes.exampleTypes.ComplexRadioStation", name: "name", station: "station", source: "AUSTRIA" }; const expected = new ComplexRadioStation({ name: fixture.name, station: fixture.station, source: Country.AUSTRIA }); expect(Typing.augmentTypes(fixture)).toEqual(expected); }); it("augmentTypes is able to deal with cached structs containing enum members", () => { const fixture = { _typeName: "joynr.datatypes.exampleTypes.ComplexRadioStation", name: "name", station: "station", source: "AUSTRIA" }; const expected = new ComplexRadioStation({ name: fixture.name, station: fixture.station, source: Country.AUSTRIA }); const cachedFixture = JSON.parse(JSON.stringify(Typing.augmentTypes(fixture))); expect(Typing.augmentTypes(cachedFixture)).toEqual(expected); }); it("augmentTypes is able to deal with complex structs containing enum array and other structs as members", () => { const providerQos = { _typeName: "joynr.types.ProviderQos", customParameters: [], priority: 234, scope: "GLOBAL", supportsOnChangeSubscriptions: false }; const providerVersion = { _typeName: "joynr.types.Version", majorVersion: 1, minorVersion: 2 }; const fixture = { _typeName: "joynr.types.DiscoveryEntry", domain: "domain", interfaceName: "interfaceName", participantId: "participantId", qos: providerQos, providerVersion, lastSeenDateMs: 123, publicKeyId: "publicKeyId", expiryDateMs: 1234 }; const expected = new DiscoveryEntry({ domain: fixture.domain, interfaceName: fixture.interfaceName, participantId: fixture.participantId, lastSeenDateMs: 123, qos: new ProviderQos({ customParameters: providerQos.customParameters, priority: providerQos.priority, scope: ProviderScope.GLOBAL, supportsOnChangeSubscriptions: providerQos.supportsOnChangeSubscriptions }), providerVersion: new Version({ majorVersion: 1, minorVersion: 2 }), expiryDateMs: 1234, publicKeyId: "publicKeyId" }); TypeRegistrySingleton.getInstance().addType(DiscoveryEntry); expect(Typing.augmentTypes(fixture)).toEqual(expected); }); }); function augmentTypeName(obj: any, expectedType: any, customMember?: string) { const objWithTypeName = Typing.augmentTypeName(obj, "joynr", customMember); expect(objWithTypeName[customMember || "_typeName"]).toEqual(`joynr.${expectedType}`); } describe("libjoynr-js.joynr.Typing.augmentTypeName", () => { it("augments type into _typeName member", () => { augmentTypeName(new MyCustomObj(), "MyCustomObj"); augmentTypeName(new _TestConstructor123_(), "_TestConstructor123_"); augmentTypeName(new MyType(), "MyType"); augmentTypeName(new MySecondType(), "MySecondType"); }); it("augments type into custom member", () => { augmentTypeName(new MyCustomObj(), "MyCustomObj", "myCustomMember"); augmentTypeName(new _TestConstructor123_(), "_TestConstructor123_", "myCustomMember"); augmentTypeName(new MyType(), "MyType", "myCustomMember"); augmentTypeName(new MySecondType(), "MySecondType", "myCustomMember"); }); it("throws if no object is provided", () => { expect(() => { Typing.augmentTypeName(null); }).toThrow(); expect(() => { Typing.augmentTypeName(undefined); }).toThrow(); }); it("isEnumType accepts enum types", () => { const fixture = TestEnum.ZERO; const radioStation = new RadioStation({ name: "name", byteBuffer: [] }); expect(Typing.isEnumType(fixture)).toBe(true); expect(Typing.isEnumType("TestString")).toBe(false); expect(Typing.isEnumType(123)).toBe(false); expect(Typing.isEnumType(radioStation)).toBe(false); }); }); function testTypingCheckProperty(functionName: "checkProperty" | "checkPropertyIfDefined") { class CustomObj {} class AnotherCustomObj {} const objects = [true, 1, "a string", [], {}, function() {}, new CustomObj(), new AnotherCustomObj()]; const types = ["Boolean", "Number", "String", "Array", "Object", "Function", CustomObj, AnotherCustomObj]; it("provides the correct type information", () => { function functionBuilder(object: any, type: any) { return function() { Typing[functionName](object, type, "some description"); }; } for (let i = 0; i < objects.length; ++i) { for (let j = 0; j < types.length; ++j) { const test = expect(functionBuilder(objects[i], types[j])); if (i === j) { test.not.toThrow(); } else { test.toThrow(); } } } }); it("supports type alternatives", () => { const type = ["Object", "CustomObj"]; expect(() => { Typing[functionName]({}, type, "some description"); }).not.toThrow(); expect(() => { Typing[functionName](new CustomObj(), type, "some description"); }).not.toThrow(); expect(() => { Typing[functionName](new AnotherCustomObj(), type, "some description"); }).toThrow(); }); } describe("libjoynr-js.joynr.Typing.checkProperty", () => { testTypingCheckProperty("checkProperty"); it("throws on null and undefined", () => { expect(() => { Typing.checkProperty(undefined, "undefined", "some description"); }).toThrow(); expect(() => { Typing.checkProperty(null, "null", "some description"); }).toThrow(); }); }); describe("libjoynr-js.joynr.Typing.checkPropertyIfDefined", () => { testTypingCheckProperty("checkPropertyIfDefined"); it("does not throw on null or undefined", () => { expect(() => { Typing.checkPropertyIfDefined(undefined, "undefined", "some description"); }).not.toThrow(); expect(() => { Typing.checkPropertyIfDefined(null, "null", "some description"); }).not.toThrow(); }); }); });
the_stack
import chunk from 'lodash/chunk' import flatMap from 'lodash/flatMap' import last from 'lodash/last' import { getWellDepth } from '@opentrons/shared-data' import { AIR_GAP_OFFSET_FROM_TOP } from '../../constants' import * as errorCreators from '../../errorCreators' import { getPipetteWithTipMaxVol } from '../../robotStateSelectors' import { airGap, aspirate, delay, dispense, dispenseAirGap, dropTip, moveToWell, replaceTip, touchTip, } from '../atomic' import { mixUtil } from './mix' import { curryCommandCreator, reduceCommandCreators, blowoutUtil, getDispenseAirGapLocation, } from '../../utils' import type { DistributeArgs, CommandCreator, CurriedCommandCreator, CommandCreatorError, } from '../../types' export const distribute: CommandCreator<DistributeArgs> = ( args, invariantContext, prevRobotState ) => { /** Distribute will aspirate from a single source well into multiple destination wells. If the volume to aspirate from the source well exceeds the max volume of the pipette, then distribute will be broken up into multiple asp-disp-disp, asp-disp-disp cycles. A single uniform volume will be aspirated to every destination well. ===== For distribute, changeTip means: * 'always': before the first aspirate in a single asp-disp-disp cycle, get a fresh tip * 'once': get a new tip at the beginning of the distribute step, and use it throughout * 'never': reuse the tip from the last step */ // TODO Ian 2018-05-03 next ~20 lines match consolidate.js const actionName = 'distribute' const errors: CommandCreatorError[] = [] // TODO: Ian 2019-04-19 revisit these pipetteDoesNotExist errors, how to do it DRY? if ( !prevRobotState.pipettes[args.pipette] || !invariantContext.pipetteEntities[args.pipette] ) { errors.push( errorCreators.pipetteDoesNotExist({ actionName, pipette: args.pipette, }) ) } if (!args.sourceLabware || !prevRobotState.labware[args.sourceLabware]) { errors.push( errorCreators.labwareDoesNotExist({ actionName, labware: args.sourceLabware, }) ) } if (errors.length > 0) return { errors, } // TODO: BC 2019-07-08 these argument names are a bit misleading, instead of being values bound // to the action of aspiration of dispensing in a given command, they are actually values bound // to a given labware associated with a command (e.g. Source, Destination). For this reason we // currently remapping the inner mix values. Those calls to mixUtil should become easier to read // when we decide to rename these fields/args... probably all the way up to the UI level. const { aspirateDelay, aspirateFlowRateUlSec, aspirateOffsetFromBottomMm, dispenseDelay, dispenseFlowRateUlSec, dispenseOffsetFromBottomMm, blowoutLocation, } = args const aspirateAirGapVolume = args.aspirateAirGapVolume || 0 const dispenseAirGapVolume = args.dispenseAirGapVolume || 0 // TODO error on negative args.disposalVolume? const disposalVolume = args.disposalVolume && args.disposalVolume > 0 ? args.disposalVolume : 0 const maxVolume = getPipetteWithTipMaxVol(args.pipette, invariantContext) - aspirateAirGapVolume const maxWellsPerChunk = Math.floor( (maxVolume - disposalVolume) / args.volume ) const { pipette } = args if (maxWellsPerChunk === 0) { // distribute vol exceeds pipette vol return { errors: [ errorCreators.pipetteVolumeExceeded({ actionName, volume: args.volume, maxVolume, disposalVolume, }), ], } } const destWellChunks = chunk(args.destWells, maxWellsPerChunk) const commandCreators = flatMap( destWellChunks, (destWellChunk: string[], chunkIndex: number): CurriedCommandCreator[] => { const firstDestWell = destWellChunk[0] const sourceLabwareDef = invariantContext.labwareEntities[args.sourceLabware].def const destLabwareDef = invariantContext.labwareEntities[args.destLabware].def const airGapOffsetSourceWell = getWellDepth(sourceLabwareDef, args.sourceWell) + AIR_GAP_OFFSET_FROM_TOP const airGapOffsetDestWell = getWellDepth(destLabwareDef, firstDestWell) + AIR_GAP_OFFSET_FROM_TOP const airGapAfterAspirateCommands = aspirateAirGapVolume ? [ curryCommandCreator(airGap, { pipette: args.pipette, volume: aspirateAirGapVolume, labware: args.sourceLabware, well: args.sourceWell, flowRate: aspirateFlowRateUlSec, offsetFromBottomMm: airGapOffsetSourceWell, }), ...(aspirateDelay != null ? [ curryCommandCreator(delay, { commandCreatorFnName: 'delay', description: null, name: null, meta: null, wait: aspirateDelay.seconds, }), ] : []), curryCommandCreator(dispenseAirGap, { pipette: args.pipette, volume: aspirateAirGapVolume, labware: args.destLabware, well: firstDestWell, flowRate: dispenseFlowRateUlSec, offsetFromBottomMm: airGapOffsetDestWell, }), ...(dispenseDelay != null ? [ curryCommandCreator(delay, { commandCreatorFnName: 'delay', description: null, name: null, meta: null, wait: dispenseDelay.seconds, }), ] : []), ] : [] const dispenseCommands = flatMap( destWellChunk, (destWell: string, wellIndex: number): CurriedCommandCreator[] => { const delayAfterDispenseCommands = dispenseDelay != null ? [ curryCommandCreator(moveToWell, { pipette: args.pipette, labware: args.destLabware, well: destWell, offset: { x: 0, y: 0, z: dispenseDelay.mmFromBottom, }, }), curryCommandCreator(delay, { commandCreatorFnName: 'delay', description: null, name: null, meta: null, wait: dispenseDelay.seconds, }), ] : [] const touchTipAfterDispenseCommand = args.touchTipAfterDispense ? [ curryCommandCreator(touchTip, { pipette, labware: args.destLabware, well: destWell, offsetFromBottomMm: args.touchTipAfterDispenseOffsetMmFromBottom, }), ] : [] return [ curryCommandCreator(dispense, { pipette, volume: args.volume, labware: args.destLabware, well: destWell, flowRate: dispenseFlowRateUlSec, offsetFromBottomMm: dispenseOffsetFromBottomMm, }), ...delayAfterDispenseCommands, ...touchTipAfterDispenseCommand, ] } ) // NOTE: identical to consolidate let tipCommands: CurriedCommandCreator[] = [] if ( args.changeTip === 'always' || (args.changeTip === 'once' && chunkIndex === 0) ) { tipCommands = [ curryCommandCreator(replaceTip, { pipette: args.pipette, }), ] } const { dispenseAirGapLabware, dispenseAirGapWell, } = getDispenseAirGapLocation({ blowoutLocation, sourceLabware: args.sourceLabware, destLabware: args.destLabware, sourceWell: args.sourceWell, // @ts-expect-error(SA, 2021-05-05): last can return undefined destWell: last(destWellChunk), }) const isLastChunk = chunkIndex + 1 === destWellChunks.length const willReuseTip = args.changeTip !== 'always' && !isLastChunk const airGapAfterDispenseCommands = dispenseAirGapVolume && !willReuseTip ? [ curryCommandCreator(airGap, { pipette: args.pipette, volume: dispenseAirGapVolume, labware: dispenseAirGapLabware, well: dispenseAirGapWell, flowRate: aspirateFlowRateUlSec, offsetFromBottomMm: airGapOffsetDestWell, }), ...(aspirateDelay != null ? [ curryCommandCreator(delay, { commandCreatorFnName: 'delay', description: null, name: null, meta: null, wait: aspirateDelay.seconds, }), ] : []), ] : [] // if using dispense > air gap, drop or change the tip at the end const dropTipAfterDispenseAirGap = airGapAfterDispenseCommands.length > 0 ? [ curryCommandCreator(dropTip, { pipette: args.pipette, }), ] : [] const blowoutCommands = disposalVolume ? blowoutUtil({ pipette: pipette, sourceLabwareId: args.sourceLabware, sourceWell: args.sourceWell, destLabwareId: args.destLabware, // @ts-expect-error(SA, 2021-05-05): last can return undefined destWell: last(destWellChunk), blowoutLocation, flowRate: args.blowoutFlowRateUlSec, offsetFromTopMm: args.blowoutOffsetFromTopMm, invariantContext, }) : [] const delayAfterAspirateCommands = aspirateDelay != null ? [ curryCommandCreator(moveToWell, { pipette: args.pipette, labware: args.sourceLabware, well: args.sourceWell, offset: { x: 0, y: 0, z: aspirateDelay.mmFromBottom, }, }), curryCommandCreator(delay, { commandCreatorFnName: 'delay', description: null, name: null, meta: null, wait: aspirateDelay.seconds, }), ] : [] const touchTipAfterAspirateCommand = args.touchTipAfterAspirate ? [ curryCommandCreator(touchTip, { pipette: args.pipette, labware: args.sourceLabware, well: args.sourceWell, offsetFromBottomMm: args.touchTipAfterAspirateOffsetMmFromBottom, }), ] : [] const mixBeforeAspirateCommands = args.mixBeforeAspirate != null ? mixUtil({ pipette: args.pipette, labware: args.sourceLabware, well: args.sourceWell, volume: args.mixBeforeAspirate.volume, times: args.mixBeforeAspirate.times, aspirateOffsetFromBottomMm, dispenseOffsetFromBottomMm: aspirateOffsetFromBottomMm, aspirateFlowRateUlSec, dispenseFlowRateUlSec, aspirateDelaySeconds: aspirateDelay?.seconds, dispenseDelaySeconds: dispenseDelay?.seconds, }) : [] return [ ...tipCommands, ...mixBeforeAspirateCommands, curryCommandCreator(aspirate, { pipette, volume: args.volume * destWellChunk.length + disposalVolume, labware: args.sourceLabware, well: args.sourceWell, flowRate: aspirateFlowRateUlSec, offsetFromBottomMm: aspirateOffsetFromBottomMm, }), ...delayAfterAspirateCommands, ...touchTipAfterAspirateCommand, ...airGapAfterAspirateCommands, ...dispenseCommands, ...blowoutCommands, ...airGapAfterDispenseCommands, ...dropTipAfterDispenseAirGap, ] } ) return reduceCommandCreators( commandCreators, invariantContext, prevRobotState ) }
the_stack
import { readCoord } from './readCoord' import { readDelta } from './readDelta' import { BitStream } from '../BitReader' import { DeltaDecoderTable } from './DeltaDecoder' import { Reader, ReaderDataType } from '../Reader' type FrameDataHandler = (r: Reader, deltaDecoder: DeltaDecoderTable) => any export class FrameDataReader { static bad() { throw new Error('Invalid message type') } static nop(): null { return null } static disconnect(r: Reader) { return { reason: r.str() } } static event(r: Reader, deltaDecoders: DeltaDecoderTable) { let bs = new BitStream(r.data.buffer) bs.index = r.tell() * 8 type Event = { index: number packetIndex?: number fireTime?: number delta?: { [name: string]: any } } let events: Event[] = [] let eventCount = bs.readBits(5) for (let i = 0; i < eventCount; ++i) { let event: Event = { index: bs.readBits(10) } let packetIndexBit = bs.readBits(1) if (packetIndexBit) { event.packetIndex = bs.readBits(11) let deltaBit = bs.readBits(1) if (deltaBit) { event.delta = readDelta(bs, deltaDecoders['event_t']) } } let fireTimeBit = bs.readBits(1) if (fireTimeBit) { event.fireTime = bs.readBits(16) } events.push(event) } if (bs.index % 8 > 0) { r.seek(Math.floor(bs.index / 8) + 1) } else { r.seek(bs.index / 8) } return { events } } static version(r: Reader) { return { version: r.ui() } } static setView(r: Reader) { return { entityIndex: r.s() } } static sound(r: Reader) { let bs = new BitStream(r.data.buffer) bs.index = r.tell() * 8 let flags = bs.readBits(9) let volume = 1 if ((flags & 1) !== 0) { volume = bs.readBits(8) / 255 } let attenuation = 1 if ((flags & 2) !== 0) { attenuation = bs.readBits(8) / 64 } let channel = bs.readBits(3) let entityIndex = bs.readBits(11) let soundIndex if ((flags & 4) !== 0) { soundIndex = bs.readBits(16) } else { soundIndex = bs.readBits(8) } let xFlag = bs.readBits(1) let yFlag = bs.readBits(1) let zFlag = bs.readBits(1) let xPosition let yPosition let zPosition if (xFlag) { xPosition = readCoord(bs) } if (yFlag) { yPosition = readCoord(bs) } if (zFlag) { zPosition = readCoord(bs) } let pitch = 1 if ((flags & 8) !== 0) { pitch = bs.readBits(8) } if (bs.index % 8 > 0) { r.seek(Math.floor(bs.index / 8) + 1) } else { r.seek(bs.index / 8) } return { flags, volume, attenuation, channel, entityIndex, soundIndex, xPosition, yPosition, zPosition, pitch } } static time(r: Reader) { return { time: r.f() } } static print(r: Reader) { return { message: r.str() } } static stuffText(r: Reader) { let message = r.str() let commands = message.split(';').map(command => { let args = command .split(/\s*("[^"]+"|[^\s"]+)/) .map(arg => arg.replace(/^"(.*)"$/, '$1').trim()) .filter(arg => arg) let func = args[0] let params = args.slice(1) return { func, params } }) return { commands } } static setAngle(r: Reader) { return { pitch: r.s(), yaw: r.s(), roll: r.s() } } static serverInfo(r: Reader) { let info = { protocol: r.i(), spawnCount: r.i(), // map change count mapCrc: r.i(), clientDllHash: r.arrx(16, ReaderDataType.UByte), maxPlayers: r.ub(), playerIndex: r.ub(), isDeathmatch: r.ub(), gameDir: r.str(), hostName: r.str(), mapFileName: r.str(), // path to map relative in mod directory mapCycle: r.str() } r.skip(1) // skip padding return info } static lightStyle(r: Reader) { return { index: r.ub(), lightInfo: r.str() } } static updateUserInfo(r: Reader) { return { clientIndex: r.ub(), clientUserId: r.ui(), clientUserInfo: r.str(), clientCdKeyHash: r.arrx(16, ReaderDataType.UByte) } } static deltaDescription(r: Reader, deltaDecoders: DeltaDecoderTable) { let data: { name: string fields: { [name: string]: any }[] } = { name: r.str(), fields: [] } let bs = new BitStream(r.data.buffer) let fieldCount = r.us() bs.index = r.tell() * 8 for (let i = 0; i < fieldCount; ++i) { data.fields.push(readDelta(bs, deltaDecoders['delta_description_t'])) } deltaDecoders[data.name] = data.fields as any if (bs.index % 8 > 0) { r.seek(Math.floor(bs.index / 8) + 1) } else { r.seek(bs.index / 8) } return data } static clientData(r: Reader, deltaDecoders: DeltaDecoderTable) { let bs = new BitStream(r.data.buffer) bs.index = r.tell() * 8 let deltaSequence = bs.readBits(1) if (deltaSequence) { // delta update mask bs.index += 8 } let clientDataDecoder = deltaDecoders['clientdata_t'] let clientData = readDelta(bs, clientDataDecoder) // TODO: weapon data let weaponDataDecoder = deltaDecoders['weapon_data_t'] while (bs.readBits(1)) { bs.index += 6 // weapon index readDelta(bs, weaponDataDecoder) // weapon data } if (bs.index % 8 > 0) { r.seek(Math.floor(bs.index / 8) + 1) } else { r.seek(bs.index / 8) } return { clientData } } static stopSound(r: Reader) { return { entityIndex: r.s() } } static pings(r: Reader) { let bs = new BitStream(r.data.buffer) bs.index = r.tell() * 8 let pings = [] while (bs.readBits(1)) { pings.push({ slot: bs.readBits(8), ping: bs.readBits(8), loss: bs.readBits(8) }) } if (bs.index % 8 > 0) { r.seek(Math.floor(bs.index / 8) + 1) } else { r.seek(bs.index / 8) } return pings } static particle(r: Reader) { return { position: [r.s() / 8, r.s() / 8, r.s() / 8], direction: [r.b(), r.b(), r.b()], count: r.ub(), color: r.ub() } } static damage(): null { // unused return null } static spawnStatic(r: Reader) { let data: any = { modelIndex: r.s(), sequence: r.b(), frame: r.b(), colorMap: r.s(), skin: r.b(), position: [], rotation: [] } data.position[0] = r.s() / 8 data.rotation[0] = r.b() * (360 / 256) data.position[1] = r.s() / 8 data.rotation[1] = r.b() * (360 / 256) data.position[2] = r.s() / 8 data.rotation[2] = r.b() * (360 / 256) data.renderMode = r.b() if (data.renderMode) { data.renderAmt = r.b() data.renderColor = [r.ub(), r.ub(), r.ub()] data.renderFx = r.b() } return data } static eventReliable(r: Reader, deltaDecoders: DeltaDecoderTable) { let bs = new BitStream(r.data.buffer) bs.index = r.tell() * 8 let eventIndex = bs.readBits(10) let eventData = readDelta(bs, deltaDecoders['event_t']) let delayBit = bs.readBits(1) let delay if (delayBit) { delay = bs.readBits(16) } if (bs.index % 8 > 0) { r.seek(Math.floor(bs.index / 8) + 1) } else { r.seek(bs.index / 8) } return { eventIndex, eventData, delayBit, delay } } static spawnBaseLine(r: Reader, deltaDecoders: DeltaDecoderTable) { let bs = new BitStream(r.data.buffer) bs.index = r.tell() * 8 let entities = [] while (true) { let entityIdx = bs.readBits(11) if (entityIdx === (1 << 11) - 1) { break } let entityType = bs.readBits(2) let entityTypeString if (entityType & 1) { if (entityIdx > 0 && entityIdx <= 32) { entityTypeString = 'entity_state_player_t' } else { entityTypeString = 'entity_state_t' } } else { entityTypeString = 'custom_entity_state_t' } entities[entityIdx] = readDelta(bs, deltaDecoders[entityTypeString]) } let footer = bs.readBits(5) if (footer !== (1 << 5) - 1) { throw new Error('Bad spawnbaseline') } let nExtraData = bs.readBits(6) let extraData = [] for (let i = 0; i < nExtraData; ++i) { extraData.push(readDelta(bs, deltaDecoders['entity_state_t'])) } if (bs.index % 8 > 0) { r.seek(Math.floor(bs.index / 8) + 1) } else { r.seek(bs.index / 8) } return { entities, extraData } } static tempEntity(r: Reader) { const TE_BEAMPOINTS = 0 // Beam effect between two points const TE_BEAMENTPOINT = 1 // Beam effect between point and entity const TE_GUNSHOT = 2 // Particle effect plus ricochet sound const TE_EXPLOSION = 3 // Additive sprite, 2 dynamic lights, flickering particles, explosion sound, move vertically 8 pps const TE_TAREXPLOSION = 4 // Quake1 "tarbaby" explosion with sound const TE_SMOKE = 5 // Alphablend sprite, move vertically 30 pps const TE_TRACER = 6 // Tracer effect from point to point const TE_LIGHTNING = 7 // TE_BEAMPOINTS with simplified parameters const TE_BEAMENTS = 8 const TE_SPARKS = 9 // 8 random tracers with gravity, ricochet sprite const TE_LAVASPLASH = 10 // Quake1 lava splash const TE_TELEPORT = 11 // Quake1 teleport splash const TE_EXPLOSION2 = 12 // Quake1 colormaped (base palette) particle explosion with sound const TE_BSPDECAL = 13 // Decal from the .BSP file const TE_IMPLOSION = 14 // Tracers moving toward a point const TE_SPRITETRAIL = 15 // Line of moving glow sprites with gravity, fadeout, and collisions const TE_SPRITE = 17 // Additive sprite, plays 1 cycle const TE_BEAMSPRITE = 18 // A beam with a sprite at the end const TE_BEAMTORUS = 19 // Screen aligned beam ring, expands to max radius over lifetime const TE_BEAMDISK = 20 // Disk that expands to max radius over lifetime const TE_BEAMCYLINDER = 21 // Cylinder that expands to max radius over lifetime const TE_BEAMFOLLOW = 22 // Create a line of decaying beam segments until entity stops moving const TE_GLOWSPRITE = 23 const TE_BEAMRING = 24 // Connect a beam ring to two entities const TE_STREAK_SPLASH = 25 // Oriented shower of tracers const TE_DLIGHT = 27 // Dynamic light, effect world, minor entity effect const TE_ELIGHT = 28 // Point entity light, no world effect const TE_TEXTMESSAGE = 29 const TE_LINE = 30 const TE_BOX = 31 const TE_KILLBEAM = 99 // Kill all beams attached to entity const TE_LARGEFUNNEL = 100 const TE_BLOODSTREAM = 101 // Particle spray const TE_SHOWLINE = 102 // Line of particles every 5 units, dies in 30 seconds const TE_BLOOD = 103 // Particle spray const TE_DECAL = 104 // Decal applied to a brush entity (not the world) const TE_FIZZ = 105 // Create alpha sprites inside of entity, float upwards const TE_MODEL = 106 // Create a moving model that bounces and makes a sound when it hits const TE_EXPLODEMODEL = 107 // Spherical shower of models, picks from set const TE_BREAKMODEL = 108 // Box of models or sprites const TE_GUNSHOTDECAL = 109 // Decal and ricochet sound const TE_SPRITE_SPRAY = 110 // Spray of alpha sprites const TE_ARMOR_RICOCHET = 111 // Quick spark sprite, client ricochet sound. const TE_PLAYERDECAL = 112 const TE_BUBBLES = 113 // Create alpha sprites inside of box, float upwards const TE_BUBBLETRAIL = 114 // Create alpha sprites along a line, float upwards const TE_BLOODSPRITE = 115 // Spray of opaque sprite1's that fall, single sprite2 for 1..2 secs (this is a high-priority tent) const TE_WORLDDECAL = 116 // Decal applied to the world brush const TE_WORLDDECALHIGH = 117 // Decal (with texture index > 256) applied to world brush const TE_DECALHIGH = 118 // Same as TE_DECAL, but the texture index was greater than 256 const TE_PROJECTILE = 119 // Makes a projectile (like a nail) (this is a high-priority tent) const TE_SPRAY = 120 // Throws a shower of sprites or models const TE_PLAYERSPRITES = 121 // Sprites emit from a player's bounding box (ONLY use for players!) const TE_PARTICLEBURST = 122 // Very similar to lavasplash const TE_FIREFIELD = 123 // Makes a field of fire const TE_PLAYERATTACHMENT = 124 // Attaches a TENT to a player (this is a high-priority tent) const TE_KILLPLAYERATTACHMENTS = 125 // Will expire all TENTS attached to a player. const TE_MULTIGUNSHOT = 126 // Much more compact shotgun message const TE_USERTRACER = 127 // Larger message than the standard tracer, but allows some customization. let type = r.ub() let data: any = {} switch (type) { case TE_BEAMPOINTS: { r.skip(24) break } case TE_BEAMENTPOINT: { r.skip(20) break } case TE_GUNSHOT: { r.skip(6) break } case TE_EXPLOSION: { r.skip(11) break } case TE_TAREXPLOSION: { r.skip(6) break } case TE_SMOKE: { r.skip(10) break } case TE_TRACER: { r.skip(12) break } case TE_LIGHTNING: { r.skip(17) break } case TE_BEAMENTS: { r.skip(16) break } case TE_SPARKS: { r.skip(6) break } case TE_LAVASPLASH: { r.skip(6) break } case TE_TELEPORT: { r.skip(6) break } case TE_EXPLOSION2: { r.skip(8) break } case TE_BSPDECAL: { r.skip(8) let entityIndex = r.s() if (entityIndex) { r.skip(2) } break } case TE_IMPLOSION: { r.skip(9) break } case TE_SPRITETRAIL: { r.skip(19) break } case TE_SPRITE: { r.skip(10) break } case TE_BEAMSPRITE: { r.skip(16) break } case TE_BEAMTORUS: { r.skip(24) break } case TE_BEAMDISK: { r.skip(24) break } case TE_BEAMCYLINDER: { r.skip(24) break } case TE_BEAMFOLLOW: { r.skip(10) break } case TE_GLOWSPRITE: { r.skip(11) break } case TE_BEAMRING: { r.skip(16) break } case TE_STREAK_SPLASH: { r.skip(19) break } case TE_DLIGHT: { r.skip(12) break } case TE_ELIGHT: { r.skip(16) break } case TE_TEXTMESSAGE: { data.channel = r.b() data.x = r.s() data.y = r.s() data.effect = r.b() data.textColor = [r.ub(), r.ub(), r.ub(), r.ub()] data.effectColor = [r.ub(), r.ub(), r.ub(), r.ub()] data.fadeInTime = r.s() data.fadeOutTime = r.s() data.holdTime = r.s() if (data.effect) { data.effectTime = r.s() } data.message = r.str() break } case TE_LINE: { r.skip(17) break } case TE_BOX: { r.skip(17) break } case TE_KILLBEAM: { r.skip(2) break } case TE_LARGEFUNNEL: { r.skip(10) break } case TE_BLOODSTREAM: { r.skip(14) break } case TE_SHOWLINE: { r.skip(12) break } case TE_BLOOD: { r.skip(14) break } case TE_DECAL: { r.skip(9) break } case TE_FIZZ: { r.skip(5) break } case TE_MODEL: { r.skip(17) break } case TE_EXPLODEMODEL: { r.skip(13) break } case TE_BREAKMODEL: { r.skip(24) break } case TE_GUNSHOTDECAL: { r.skip(9) break } case TE_SPRITE_SPRAY: { r.skip(17) break } case TE_ARMOR_RICOCHET: { r.skip(7) break } case TE_PLAYERDECAL: { r.skip(10) break } case TE_BUBBLES: { r.skip(19) break } case TE_BUBBLETRAIL: { r.skip(19) break } case TE_BLOODSPRITE: { r.skip(12) break } case TE_WORLDDECAL: { r.skip(7) break } case TE_WORLDDECALHIGH: { r.skip(7) break } case TE_DECALHIGH: { r.skip(9) break } case TE_PROJECTILE: { r.skip(16) break } case TE_SPRAY: { r.skip(18) break } case TE_PLAYERSPRITES: { r.skip(5) break } case TE_PARTICLEBURST: { r.skip(10) break } case TE_FIREFIELD: { r.skip(9) break } case TE_PLAYERATTACHMENT: { r.skip(7) break } case TE_KILLPLAYERATTACHMENTS: { r.skip(1) break } case TE_MULTIGUNSHOT: { r.skip(18) break } case TE_USERTRACER: { r.skip(15) break } default: { throw new Error('Unknown temp entity type') } } return data } static setPause(r: Reader) { return { isPaused: r.b() } } static signOnNum(r: Reader) { return { sign: r.b() } } static centerPrint(r: Reader) { return { message: r.str() } } static killedMonster(): null { // unused return null } static foundSecret(): null { // unused return null } static spawnStaticSound(r: Reader) { return { position: [r.s() / 8, r.s() / 8, r.s() / 8], soundIndex: r.us(), volume: r.ub() / 255, attenuation: r.ub() / 64, entityIndex: r.us(), pitch: r.ub(), flags: r.ub() } } static intermission(): null { // has no arguments return null } static finale(r: Reader) { return { text: r.str() } } static cdTrack(r: Reader) { return { track: r.b(), loopTrack: r.b() } } static restore(r: Reader) { let saveName = r.str() let mapCount = r.ub() let maps = [] for (let i = 0; i < mapCount; ++i) { maps.push(r.str()) } return { saveName, maps } } static cutscene(r: Reader) { return { text: r.str() } } static weaponAnim(r: Reader) { return { sequenceNumber: r.b(), weaponModelBodyGroup: r.b() } } static decalName(r: Reader) { return { positionIndex: r.ub(), decalName: r.str() } } static roomType(r: Reader) { return { type: r.us() } } static addAngle(r: Reader) { // NOTE: not sure if (360/65536) or (65536/360) return { angleToAdd: r.s() / (360 / 65536) } } static newUserMsg(r: Reader) { return { index: r.ub(), size: r.b(), name: r.nstr(16) } } static packetEntities(r: Reader, deltaDecoders: DeltaDecoderTable) { let bs = new BitStream(r.data.buffer) bs.index = r.tell() * 8 let entityStates = [] bs.readBits(16) // skip entity count (unreliable) let entityNumber = 0 while (true) { let footer = bs.readBits(16) if (footer === 0) { break } bs.index -= 16 let entityNumberIncrement = bs.readBits(1) if (!entityNumberIncrement) { let absoluteEntityNumber = bs.readBits(1) if (absoluteEntityNumber) { entityNumber = bs.readBits(11) } else { entityNumber += bs.readBits(6) } } else { entityNumber++ } let custom = bs.readBits(1) let useBaseline = bs.readBits(1) if (useBaseline) { bs.index += 6 // baseline index } let entityType = 'entity_state_t' if (entityNumber > 0 && entityNumber <= 32) { entityType = 'entity_state_player_t' } else if (custom) { entityType = 'custom_entity_state_t' } entityStates.push(readDelta(bs, deltaDecoders[entityType])) } if (bs.index % 8 > 0) { r.seek(Math.floor(bs.index / 8) + 1) } else { r.seek(bs.index / 8) } return { entityStates } } static deltaPacketEntities(r: Reader, deltaDecoders: DeltaDecoderTable) { let bs = new BitStream(r.data.buffer) bs.index = r.tell() * 8 bs.readBits(16) // skip entity count (unreliable) bs.index += 8 // either updatemask or delta sequence number let entityStates = [] let entityIdx = 0 while (true) { let footer = bs.readBits(16) if (footer === 0) { break } bs.index -= 16 let removeEntity = bs.readBits(1) let absoluteEntityNumber = bs.readBits(1) if (absoluteEntityNumber) { entityIdx = bs.readBits(11) } else { entityIdx += bs.readBits(6) } if (removeEntity) { continue } let custom = bs.readBits(1) let entityType = 'entity_state_t' if (entityIdx > 0 && entityIdx < 32) { entityType = 'entity_state_player_t' } else if (custom) { entityType = 'custom_entity_state_t' } entityStates[entityIdx] = readDelta(bs, deltaDecoders[entityType]) } if (bs.index % 8 > 0) { r.seek(Math.floor(bs.index / 8) + 1) } else { r.seek(bs.index / 8) } return { entityStates } } static choke(): null { // no arguments return null } static resourceList(r: Reader) { let bs = new BitStream(r.data.buffer) bs.index = r.tell() * 8 // TODO: extract more data??? let entries = [] let entryCount = bs.readBits(12) for (let i = 0; i < entryCount; ++i) { let entry: any = {} entry.type = bs.readBits(4) entry.name = bs.readString() entry.index = bs.readBits(12) entry.size = bs.readBits(24) let flags = bs.readBits(3) if (flags & 4) { // TODO: entry.md5hash = read 128 bits bs.index += 128 } // 1 bit = boolean hasExtraInfo if (bs.readBits(1)) { // 32 bytes extraInfo bs.index += 256 } entries.push(entry) } if (bs.readBits(1)) { while (bs.readBits(1)) { let nBits = bs.readBits(1) ? 5 : 10 bs.index += nBits } } if (bs.index % 8 > 0) { r.seek(Math.floor(bs.index / 8) + 1) } else { r.seek(bs.index / 8) } return entries } static newMoveVars(r: Reader) { return { gravity: r.f(), stopSpeed: r.f(), maxSpeed: r.f(), spectatorMaxSpeed: r.f(), acceleration: r.f(), airAcceleration: r.f(), waterAcceleration: r.f(), friction: r.f(), edgeFriction: r.f(), waterFriction: r.f(), entityGravity: r.f(), bounce: r.f(), stepSize: r.f(), maxVelocity: r.f(), zMax: r.f(), waveHeight: r.f(), footsteps: r.b(), rollAngle: r.f(), rollSpeed: r.f(), skyColor: [r.f(), r.f(), r.f()], skyVec: [r.f(), r.f(), r.f()], skyName: r.str() } } static resourceRequest(r: Reader) { let data = { spawnCount: r.i() } r.skip(4) // unknown (always 0) return data } static customization(r: Reader) { let playerIndex = r.ub() let type = r.ub() let name = r.str() let index = r.us() let downloadSize = r.ui() let flags = r.ub() let md5hash if (flags & 4) { md5hash = [r.i(), r.i(), r.i(), r.i()] } return { playerIndex, type, name, index, downloadSize, flags, md5hash } } static crosshairAngle(r: Reader) { return { pitch: r.b(), yaw: r.b() } } static soundFade(r: Reader) { return { initialPercent: r.ub(), holdTime: r.ub(), fadeOutTime: r.ub(), fadeInTime: r.ub() } } static fileTxferFailed(r: Reader) { return { filename: r.str() } } static hltv(r: Reader) { return { mode: r.ub() } } static director(r: Reader) { let length = r.ub() return { flag: r.ub(), message: r.nstr(length - 1) } } static voiceInit(r: Reader) { return { codecName: r.str(), quality: r.b() } } static voiceData(r: Reader) { let playerIndex = r.ub() let size = r.us() let data = r.arrx(size, ReaderDataType.UByte) return { playerIndex, data } } static sendExtraInfo(r: Reader) { return { fallbackDir: r.str(), canCheat: r.ub() } } static timeScale(r: Reader) { return { timeScale: r.f() } } static resourceLocation(r: Reader) { return { url: r.str() } } static sendCvarValue(r: Reader) { // deprecated return { name: r.str() } } static sendCvarValue2(r: Reader) { return { requestId: r.ui(), name: r.str() } } static read(r: Reader, type: number, deltaDecoders: DeltaDecoderTable) { if (type === 0) { // SVC_BAD shouldn't happen return null } const handler = FrameDataReader.handlers[type] if (handler) { return handler(r, deltaDecoders) } else { return null } } // prettier-ignore static readonly handlers: FrameDataHandler[] = [ FrameDataReader.bad, // SVC_BAD 0 FrameDataReader.nop, // SVC_NOP 1 FrameDataReader.disconnect, // SVC_DISCONNECT 2 FrameDataReader.event, // SVC_EVENT 3 FrameDataReader.version, // SVC_VERSION 4 FrameDataReader.setView, // SVC_SETVIEW 5 FrameDataReader.sound, // SVC_SOUND 6 FrameDataReader.time, // SVC_TIME 7 FrameDataReader.print, // SVC_PRINT 8 FrameDataReader.stuffText, // SVC_STUFFTEXT 9 FrameDataReader.setAngle, // SVC_SETANGLE 10 FrameDataReader.serverInfo, // SVC_SERVERINFO 11 FrameDataReader.lightStyle, // SVC_LIGHTSTYLE 12 FrameDataReader.updateUserInfo, // SVC_UPDATEUSERINFO 13 FrameDataReader.deltaDescription, // SVC_DELTADESCRIPTION 14 FrameDataReader.clientData, // SVC_CLIENTDATA 15 FrameDataReader.stopSound, // SVC_STOPSOUND 16 FrameDataReader.pings, // SVC_PINGS 17 FrameDataReader.particle, // SVC_PARTICLE 18 FrameDataReader.damage, // SVC_DAMAGE 19 FrameDataReader.spawnStatic, // SVC_SPAWNSTATIC 20 FrameDataReader.eventReliable, // SVC_EVENT_RELIABLE 21 FrameDataReader.spawnBaseLine, // SVC_SPAWNBASELINE 22 FrameDataReader.tempEntity, // SVC_TEMPENTITY 23 FrameDataReader.setPause, // SVC_SETPAUSE 24 FrameDataReader.signOnNum, // SVC_SIGNONNUM 25 FrameDataReader.centerPrint, // SVC_CENTERPRINT 26 FrameDataReader.killedMonster, // SVC_KILLEDMONSTER 27 FrameDataReader.foundSecret, // SVC_FOUNDSECRET 28 FrameDataReader.spawnStaticSound, // SVC_SPAWNSTATICSOUND 29 FrameDataReader.intermission, // SVC_INTERMISSION 30 FrameDataReader.finale, // SVC_FINALE 31 FrameDataReader.cdTrack, // SVC_CDTRACK 32 FrameDataReader.restore, // SVC_RESTORE 33 FrameDataReader.cutscene, // SVC_CUTSCENE 34 FrameDataReader.weaponAnim, // SVC_WEAPONANIM 35 FrameDataReader.decalName, // SVC_DECALNAME 36 FrameDataReader.roomType, // SVC_ROOMTYPE 37 FrameDataReader.addAngle, // SVC_ADDANGLE 38 FrameDataReader.newUserMsg, // SVC_NEWUSERMSG 39 FrameDataReader.packetEntities, // SVC_PACKETENTITIES 40 FrameDataReader.deltaPacketEntities, // SVC_DELTAPACKETENTITIES 41 FrameDataReader.choke, // SVC_CHOKE 42 FrameDataReader.resourceList, // SVC_RESOURCELIST 43 FrameDataReader.newMoveVars, // SVC_NEWMOVEVARS 44 FrameDataReader.resourceRequest, // SVC_RESOURCEREQUEST 45 FrameDataReader.customization, // SVC_CUSTOMIZATION 46 FrameDataReader.crosshairAngle, // SVC_CROSSHAIRANGLE 47 FrameDataReader.soundFade, // SVC_SOUNDFADE 48 FrameDataReader.fileTxferFailed, // SVC_FILETXFERFAILED 49 FrameDataReader.hltv, // SVC_HLTV 50 FrameDataReader.director, // SVC_DIRECTOR 51 FrameDataReader.voiceInit, // SVC_VOICEINIT 52 FrameDataReader.voiceData, // SVC_VOICEDATA 53 FrameDataReader.sendExtraInfo, // SVC_SENDEXTRAINFO 54 FrameDataReader.timeScale, // SVC_TIMESCALE 55 FrameDataReader.resourceLocation, // SVC_RESOURCELOCATION 56 FrameDataReader.sendCvarValue, // SVC_SENDCVARVALUE 57 FrameDataReader.sendCvarValue2 // SVC_SENDCVARVALUE2 58 ] } export namespace FrameDataReader { export enum SVC { BAD = 0, NOP = 1, DISCONNECT = 2, EVENT = 3, VERSION = 4, SETVIEW = 5, SOUND = 6, TIME = 7, PRINT = 8, STUFFTEXT = 9, SETANGLE = 10, SERVERINFO = 11, LIGHTSTYLE = 12, UPDATEUSERINFO = 13, DELTADESCRIPTION = 14, CLIENTDATA = 15, STOPSOUND = 16, PINGS = 17, PARTICLE = 18, DAMAGE = 19, SPAWNSTATIC = 20, EVENT_RELIABLE = 21, SPAWNBASELINE = 22, TEMPENTITY = 23, SETPAUSE = 24, SIGNONNUM = 25, CENTERPRINT = 26, KILLEDMONSTER = 27, FOUNDSECRET = 28, SPAWNSTATICSOUND = 29, INTERMISSION = 30, FINALE = 31, CDTRACK = 32, RESTORE = 33, CUTSCENE = 34, WEAPONANIM = 35, DECALNAME = 36, ROOMTYPE = 37, ADDANGLE = 38, NEWUSERMSG = 39, PACKETENTITIES = 40, DELTAPACKETENTITIES = 41, CHOKE = 42, RESOURCELIST = 43, NEWMOVEVARS = 44, RESOURCEREQUEST = 45, CUSTOMIZATION = 46, CROSSHAIRANGLE = 47, SOUNDFADE = 48, FILETXFERFAILED = 49, HLTV = 50, DIRECTOR = 51, VOICEINIT = 52, VOICEDATA = 53, SENDEXTRAINFO = 54, TIMESCALE = 55, RESOURCELOCATION = 56, SENDCVARVALUE = 57, SENDCVARVALUE2 = 58 } }
the_stack
import $ from '../util/domUtil'; import {em} from '../em'; import animationUtil from '../util/animationUtil'; import constant from '../constant'; import {Col} from '../Col' import {Picker} from '../Picker' import {IOptions} from '../API' import { AWheel } from './AWheel'; import { MyJQuery } from 'my-jquery/types/MyJQuery'; declare function require<T>(name: string): T const perspectiveConversion = require<{(y: number, radius: number, wheelHeight: number): number}>("./perspectiveConversionCache") const tick = require<{(): {play()}}>("../tick/tick")(); export class Wheel3D extends AWheel{ ///////////////////滚轮显示属性 //最大转角 private maxAngle = 0; //最小转角,设置可选项列表后需重新计算 private minAngle = 0; //滚轮的实际半径,因为有透视效果,所以滚轮实际半径比容器的高度的一半还小。根据勾股定理,计算得实际半径是容器高度的根号5分之1 private radius = constant.WHEEL_HEIGHT / Math.sqrt(5); //计算标签可显示的角度的绝对值。因为透视关系,所以可见的标签角度小于90度 private visibleAngle = 0; //获取0.01em的实际像素值 private em: () => number = em; //获得控件到body最顶端的距离,计算触摸事件的offsetY时候使用 private offsetTop = 0; ////////////////////滚动属性 //滚轮转动前初始的转角,用于计算滚轮是否转动过 private originalAngle = 0; //一次拖动过程中滚轮被转动的最大角度 private lastIndexAngle = 0; //当前的刻度,计算发声时候会用到。发声要进过一个刻度线或者达到一个新刻度新才会发声。所以需要记录上一次的刻度线。 private changeMaxAngle = 0; //当前滚轮转角 private angle = 0; //记录惯性滑动动画的id private animationId = -1; //速度,供触摸离开时候的惯性滑动动画使用 private speed = 0; //当前时间戳,主要是计算转动速度使用的 private timeStamp = 0; //记录上一次触摸节点的offsetY,主要是是计算转动速度使用的 private lastY = 0; //是否开始触摸,主要给鼠标事件使用 private isDraging = false; constructor(picker: Picker, col: Col, option: IOptions, index: number){ super() ///////////////////主要属性 //picker对象 this.picker = picker; //option对象 this.option = option; //记录当前滚轮是容器中第几个滚轮 this.index = index; //转轮主体 this.dom = $( '<div class="picker-wheel3d">' + '<div class="picker-label"><span class="picker-text"></span></div>' + '<ul></ul>' + '<div class="picker-label"><span class="picker-text"></span></div>' + '</div>').css('height', constant.WHEEL_HEIGHT / 100 + 'em'); //转轮上面标签的容器,同时也是转动的轴 this.contains = this.dom.find('ul'); ///////////////////滚轮显示属性 //计算标签可显示的角度的绝对值。因为透视关系,所以可见的标签角度小于90度 this.visibleAngle = 90 - (Math.acos(this.radius / constant.WHEEL_HEIGHT * 2) / Math.PI * 180); ////////////////////可选项属性 //如果items数组里的值是对象,其中显示的key this.labelKey = col.labelKey; //如果items数组里的值是对象,其中值的key this.itemValueKey = col.valueKey; ////////////////////注册dom事件 var that = this; //注册拖拽开始事件 function startDrag(event) { //计算offsetTop,为计算触摸事件的offset使用 var target = event.currentTarget; that.offsetTop = 0; while (target){ that.offsetTop += target.offsetTop; var target = target.parentElement; } var offsetY = event.touches ? event.touches[0].clientY - that.offsetTop : event.clientY - that.offsetTop; that.startDrag(offsetY); } this.dom[0].addEventListener("touchstart", startDrag); this.dom[0].addEventListener("mousedown", startDrag); //注册拖拽事件 function drag(event){ var offsetY = event.touches ? event.touches[0].clientY - that.offsetTop : event.clientY - that.offsetTop; that.drag(offsetY); } this.dom[0].addEventListener("touchmove", drag); this.dom[0].addEventListener("mousemove", drag); //注册拖拽结束事件 function endDrag(){ that.endDrag(); } this.dom[0].addEventListener("touchend", endDrag); this.dom[0].addEventListener("mouseup", endDrag); this.dom[0].addEventListener("mouseleave", endDrag); // 注册滚轮事件 this.initMouseWheel() //初始化标签 let transformValue = `translateZ(${this.radius / 100}em) scale(0.75)` this.dom.find(".picker-label").css("-webkit-transform", transformValue).css("transform", transformValue); //设置标签 this.setSuffix(col.suffix); this.setPrefix(col.prefix); this.setOptions(col.options, null, true) } /** * 开始拖拽 * @param {number} offsetY 当前用户手指(鼠标)的y坐标 */ protected startDrag(offsetY: number) { //记录触摸相关信息,为下一步计算用.计算时候,要将坐标系移至中心,并将单位转为em this.lastY = (constant.WHEEL_HEIGHT / 2 - offsetY / this.em()) * -1 ; this.timeStamp = Date.now(); this.isDraging = true; this.offsetTop = this.dom[0].offsetTop; this.originalAngle = this.angle; this.changeMaxAngle = 0; this.lastIndexAngle = this.selectedIndex; for(var parent = this.dom[0].parentElement;parent; parent = parent.parentElement){ this.offsetTop += parent.offsetTop; } //终止之前的动画 animationUtil.stopAnimation(this.animationId); } /** * 拖拽 * @param {number} offsetY 当前用户手指(鼠标)的y坐标 */ protected drag(offsetY: number) { if(!this.isDraging){ return; } //根据触摸位移(鼠标移动位移)计算转角变化量 //现将坐标系移植中心,并将单位转为vm var y = (constant.WHEEL_HEIGHT / 2 - offsetY / this.em()) * -1; //计算位移,因为z轴有透视,所以位移量不是真正的曲面的位移量,要做一次透视变换 var changeAngle = (perspectiveConversion(this.lastY, this.radius, constant.WHEEL_HEIGHT) - perspectiveConversion(y, this.radius, constant.WHEEL_HEIGHT)) / Math.PI * 180; var angle = changeAngle + this.angle; //记录滚轮滚动的最大转角 this.changeMaxAngle = Math.max( Math.abs( this.originalAngle - angle ), this.changeMaxAngle); //记录当前角度 this.setAngle(angle); //计算并记录速度 this.lastY = y; if(changeAngle){ this.speed = changeAngle / (Date.now() - this.timeStamp); } else{ this.speed = 0; } this.timeStamp = Date.now(); } /** * 拖拽结束 */ protected endDrag(): void { if(!this.isDraging){ return; } //速度*4,做均减少运动,计算滚动后的angle。之所以乘4是根据偏移效果经验得到的 var changeAngle = this.speed * Math.abs( this.speed) * 8 * constant.WHEEL_TRANSITION_TIME; var angle = changeAngle + this.angle; //根据角度计算最终的被选值 var selectedIndex = this.calcSelectedIndexByAngle(angle); //开启动画,选中被选中 this.selectIndex(selectedIndex, true); //计算完成,清空速度相关变量,并去除之前的动画效果 this.isDraging = false; this.lastY = 0; this.speed = 0; } /////////////////////////////////设置相关 /** * 生成用户可选的标签 * @param {any[]} list 用户可选项数组 * @param {*} selectedValue 默认值 * @param {boolean} [isInti=false] 是否是初始化,初始化不执行设置默认值操作 */ setOptions(list: any[] = [], selectedValue: any, isInti: boolean = false) { var that = this; if(!Array.isArray(list)){ throw new TypeError("list is not a array.") } // 尽量复用已经存在的DOM,如果newlist长度大于原oldlist长度,用DocumentFragment一次性插入DOM。 // newlist长度大于原oldlist长度,删除现有节点中多出的部分 // 最后修改DOM的text属性,尽量减小DOM重绘的成本和次数 let oldLength = this.list && this.list.length || 0 const lis = this.contains.children() if(oldLength > list.length){ lis.each((i, e)=>{ if(i >= list.length){ $(e).remove() } }) } //清空容器 this.list = list; //计算valueHashMap this.valueHashMap = {}; //计算最小转角 this.maxAngle = constant.WHEEL_ITEM_ANGLE * (Math.max(0, this.list.length - 1) ); //生成滚轮的标签 //标签显示值 var label: string, //显示标签的dom的高度,要求根据wheelItemAngle计算,使各个标签dom的边缘刚好挨在一起,确保没有空细 height = this.radius * Math.PI * constant.WHEEL_ITEM_ANGLE / 180 // 如果newlist长度大于原oldlist长度,用DocumentFragment一次性插入DOM // docFragment = document.createDocumentFragment() this.list.forEach(function(item, index){ //如果是对象,取labelKey对应值显示。否则直接显示它本身 if(typeof item === 'object'){ label = item[that.labelKey]; that.valueHashMap[item[that.itemValueKey]] = index; } else { label = item; that.valueHashMap[item] = index; } if(index < oldLength){ let span = lis.eq(index).find('span') if(span.text() != label){ span.text(label) } } else { //创建label的显示dom,并计算他在容器中的位置(角度) var li = $("<li></li>"); li.append($('<span class="picker-text"></span>').text(label)); var angle = constant.WHEEL_ITEM_ANGLE * -index; //为了解决3d放大后,文字模糊的问题,故采用zoom=2的方案,所以li的尺寸方面,统一缩小一半 var transformValue = "rotateX(" + angle + "deg) translateZ(" + that.radius / 100 + "em) scale(0.75)" li.css("-webkit-transform", transformValue).css("transform", transformValue) .css("padding", `${height / 5.9 / 100}em 0`) .css("height", height / 100 + "em") .css("line-height", height / 100 + "em"); //将标签的角度保存到其dom中 li.data("angle", angle); //将标签的index保存到其dom中 li.data("index", index); //增加点击选择功能 var clickHandle = function (event) { if(that.changeMaxAngle < 1) { //计算完成,清空速度相关变量,并去除之前的动画效果 that.isDraging = false; that.lastY = 0; that.speed = 0; that.selectIndex(index, true); event.stopPropagation(); event.preventDefault(); } } li[0].addEventListener('mouseup', clickHandle); li[0].addEventListener('touchend', clickHandle); //将标签的dom放到contains上,contains的事件全部委托于容器,即标签不监听事件 that.contains.append(li[0]) // docFragment.appendChild(li[0]); } }); // this.contains.append(docFragment) //刷新标签 this.flushLabel(); if(isInti){ if(list.length > 0 ){ this.selectedIndex = 0; if(typeof list[0] === 'object'){ this.selectedValue = this.list[0][this.itemValueKey]; } else { this.selectedValue = this.list[0]; } } else { this.selectedIndex = -1; this.selectedValue = undefined; } return; } //设置被选值。如果用户给定被选值,使用给定被选值。如果没有且之前有被选值,并仍在新options里面,保存之前的值。都没有返回0 if(list.length > 0 ){ if(selectedValue != null && this.valueHashMap[selectedValue] != null){ this.selectOption(selectedValue); } else if(this.valueHashMap[this.selectedValue] != null){ this.selectOption(this.selectedValue); } else { this.selectIndex( 0); } } else { this.selectedIndex = -1; this.selectedValue = undefined; } } /** * 给定指定备选标签的index,自动设定标签的各个位置 * @param index 要选择的index * @param showAnimation 是否显示动画,如果显示动画,会用100帧来显示动画 */ protected selectIndex(index: number, showAnimation = false){ var angle = this.calcAngleBySelectedIndex(index); animationUtil.stopAnimation(this.animationId); if(showAnimation){ //用50帧渲染动画,并使用easeOut,使其有匀减速效果 //当前帧数 var start = 0, //总帧数 during = 50, that = this; //动画渲染函数 var _run = function() { start++; var _angle = animationUtil.easeOut(start, that.angle, angle - that.angle, during); if(Math.abs(_angle - angle) < 1){ _angle = angle; } that.setAngle(_angle); if (_angle != angle) { that.animationId = animationUtil.startAnimation(_run); } else { //记录下原有的index,确定选择是否发生了改变 var oldSelectedIndex = that.selectedIndex; that.selectedIndex = index; that.selectedValue = that.list[index]; if(typeof that.selectedValue == 'object'){ that.selectedValue = that.selectedValue[that.itemValueKey]; } if(oldSelectedIndex != that.selectedIndex) that.toggleSelected(that.selectedIndex, that.selectedValue); } }; //启动动画 that.animationId = animationUtil.startAnimation(_run); } else { //记录下原有的index,确定选择是否发生了改变 var oldSelectedIndex = this.selectedIndex; //如果不显示动画,直接赋值 this.setAngle(angle); this.selectedIndex = index; this.selectedValue = this.list[index]; if(typeof this.selectedValue == 'object'){ this.selectedValue = this.selectedValue[this.itemValueKey]; } if(oldSelectedIndex != this.selectedIndex) this.toggleSelected(this.selectedIndex, this.selectedValue); } } /** * 给定指定角度,自动设定标签的各个位置 * @param {number} angle 要转到的角度 * @returns {number} 修正后的角度,即最终的实际角度 */ private setAngle(angle: number): number{ //修正转角,要求转角不能大于maxAngle,不能小于minAngle angle = this.rangeAngle(angle); // 如果角度变化经过刻度,则放声 if(this.option.hasVoice && this.picker.visible){ var lastIndexAngle = this.lastIndexAngle; var index = this.calcSelectedIndexByAngle(angle); if(lastIndexAngle != index){ if(this.option.hasVoice){ tick.play() } } this.lastIndexAngle = index; } this.contains.css("-webkit-transform","rotateX(" + angle + "deg)").css("transform","rotateX(" + angle + "deg)"); this.angle = angle; this.flushLabel(); return angle; } /** * 通过角度计算被选项的id * @param angle {number} 要计算的角度 * @returns {number} 被选项id */ private calcSelectedIndexByAngle(angle: number): number{ angle = this.rangeAngle(angle); return Math.round(Math.abs(angle / constant.WHEEL_ITEM_ANGLE)); } /** * 通过角度计算被选项的id * @param angle {number} 要计算的角度 * @returns {number} 被选项id */ private calcAngleBySelectedIndex(index: number): number { return index * constant.WHEEL_ITEM_ANGLE; } /** * 限制转角超过极限值 * @param angle {number} 要计算的角度 * @returns {number} 被选项id */ private rangeAngle(angle: number): number { //修正转角,要求转角不能大于maxAngle,不能小于minAngle angle = Math.max(this.minAngle, angle); angle = Math.min(this.maxAngle, angle); return angle; } /** * 刷新各个标签的状态,确定应该显示哪些标签 */ private flushLabel(){ var that = this; this.dom.find("li").each(function(index, li){ li = $(li); var angle = li.data("angle") + that.angle; if(angle > that.visibleAngle || angle < (-that.visibleAngle)){ if(li.css("display") != "none"){ li.css("display","none"); } } else { if(li.css("display") != "block"){ li.css("display","block"); } } }) } /////////////////////////////设置前缀后缀 /** * 设置后缀 * @param text 后缀显示的文本 */ private setSuffix(text) { this.dom.find('.picker-label .picker-text').eq(1).text(text); } /** * 设置前缀 * @param text 前缀显示的文本 */ private setPrefix(text) { this.dom.find('.picker-label .picker-text').eq(0).text(text); } }
the_stack
import { ConfigModel, DocumentInitializationModel, } from '../models/config.model'; import { DocumentType, FieldType, InspectionType } from '../contracts/common'; import { DocumentDefinition } from '../models/document-definition.model'; import { DocumentManagementService } from '../services/document-management.service'; import { Field } from '../models/field.model'; import { InitializationService } from './initialization.service'; import { Input } from 'ky'; import { MappingDefinition } from '../models/mapping-definition.model'; import { TestUtils } from '../../test/test-util'; import atlasmapInspectionComplexObjectRootedJson from '../../../../test-resources/inspected/atlasmap-inspection-complex-object-rooted.json'; import atlasmapInspectionPoExampleSchemaJson from '../../../../test-resources/inspected/atlasmap-inspection-po-example-schema.json'; import atlasmapInspectionTargetTestClassJson from '../../../../test-resources/inspected/atlasmap-inspection-io.atlasmap.java.test.TargetTestClass.json'; import atlasmapInspectionTwitter4jStatusJson from '../../../../test-resources/inspected/atlasmap-inspection-twitter4j.Status.json'; import fs from 'fs'; import ky from 'ky/umd'; describe('DocumentManagementService', () => { let cfg: ConfigModel; let service: DocumentManagementService; beforeEach(() => { const initService = new InitializationService(ky); cfg = initService.cfg; service = cfg.documentService; }); test('initialize()/uninitialize()', () => { TestUtils.createMockMappings(cfg); const spyUfm = spyOn<any>( DocumentDefinition.prototype, 'updateFromMappings' ).and.stub(); cfg.sourceDocs[0].initialized = true; service.uninitialize(); const count = spyUfm.calls.count(); cfg.mappingService.mappingUpdatedSource.next(); expect(spyUfm.calls.count()).toBe(count); service.initialize(); cfg.mappingService.mappingUpdatedSource.next(); expect(spyUfm.calls.count()).toBe(count + 1); service.uninitialize(); cfg.mappingService.mappingUpdatedSource.next(); expect(spyUfm.calls.count()).toBe(count + 1); }); test('inspectDocuments() parse Java inspection', (done) => { const docDef = new DocumentInitializationModel(); docDef.type = DocumentType.JAVA; docDef.inspectionResult = JSON.stringify( atlasmapInspectionTwitter4jStatusJson ); cfg.addDocument(docDef); service.inspectDocuments().subscribe({ next: (answer: DocumentDefinition) => { expect(answer.fields.length).toBe(29); const text = answer.getField('/text'); expect(text).toBeTruthy(); expect(text?.name).toBe('text'); expect(text?.type).toBe('STRING'); expect(text?.children.length).toBe(0); const user = answer.getField('/user'); expect(user).toBeTruthy(); expect(user?.name).toBe('user'); expect(user?.type).toBe('COMPLEX'); expect(user?.classIdentifier).toBe('twitter4j.User'); expect(user?.children.length).toBe(57); const screenName = user?.children?.filter( (child: Field) => child?.name === 'screenName' ); if (!screenName) { fail('no screenName'); } expect(screenName?.length).toBe(1); expect(screenName[0]?.name).toBe('screenName'); expect(screenName[0]?.path).toBe('/user/screenName'); expect(screenName[0]?.type).toBe('STRING'); expect(screenName[0]?.children.length).toBe(0); const url = answer.getField('/place/name'); expect(url?.name).toBe('name'); expect(url?.path).toBe('/place/name'); expect(url?.type).toBe('STRING'); const urlParent = url?.parentField; expect(urlParent?.name).toBe('place'); expect(screenName[0]?.children.length).toBe(0); done(); }, error: (error) => { fail(error); }, }); }); test('inspectDocuments() parse Java inspection TargetTestClass', (done) => { const docDef = new DocumentInitializationModel(); docDef.type = DocumentType.JAVA; docDef.inspectionResult = JSON.stringify( atlasmapInspectionTargetTestClassJson ); cfg.addDocument(docDef); service.inspectDocuments().subscribe({ next: (answer: DocumentDefinition) => { const contact = answer.getField('/contact'); expect(contact).toBeTruthy(); expect(contact?.type).toBe('COMPLEX'); expect(contact?.name).toBe('contact'); expect(contact?.path).toBe('/contact'); expect(contact?.isCollection).toBeFalsy(); const contactFirstName = answer.getField('/contact/firstName'); expect(contactFirstName).toBeTruthy(); expect(contactFirstName?.type).toBe('STRING'); expect(contactFirstName?.name).toBe('firstName'); expect(contactFirstName?.path).toBe('/contact/firstName'); const list = answer.getField('/contactList<>'); expect(list).toBeTruthy(); expect(list?.type).toBe('COMPLEX'); expect(list?.name).toBe('contactList'); expect(list?.path).toBe('/contactList<>'); expect(list?.isCollection).toBeTruthy(); const listFirstName = answer.getField('/contactList<>/firstName'); expect(listFirstName).toBeTruthy(); expect(listFirstName?.type).toBe('STRING'); expect(listFirstName?.name).toBe('firstName'); expect(listFirstName?.path).toBe('/contactList<>/firstName'); const array = answer.getField('/contactArray[]'); expect(array).toBeTruthy(); expect(array?.type).toBe('COMPLEX'); expect(array?.name).toBe('contactArray'); expect(array?.path).toBe('/contactArray[]'); expect(array?.isCollection).toBeTruthy(); const arrayFirstName = answer.getField('/contactArray[]/firstName'); expect(arrayFirstName).toBeTruthy(); expect(arrayFirstName?.type).toBe('STRING'); expect(arrayFirstName?.name).toBe('firstName'); expect(arrayFirstName?.path).toBe('/contactArray[]/firstName'); done(); }, error: (error) => { fail(error); }, }); }); test('inspectDocuments() parse JSON inspection', (done) => { const docDef = new DocumentInitializationModel(); docDef.type = DocumentType.JSON; docDef.inspectionType = InspectionType.SCHEMA; docDef.inspectionResult = JSON.stringify( atlasmapInspectionComplexObjectRootedJson ); cfg.addDocument(docDef); service.inspectDocuments().subscribe({ next: (answer: DocumentDefinition) => { expect(answer.fields.length).toBe(1); expect(answer.fields[0].name).toBe('order'); const order = answer.getField('/order'); expect(order?.name).toBe('order'); expect(order?.type).toBe('COMPLEX'); expect(order?.children).toBeTruthy(); expect(order?.children?.length).toBe(3); done(); }, error: (error) => { fail(error); }, }); }); test('inspectDocuments() parse XML inspection', (done) => { const docDef = new DocumentInitializationModel(); docDef.type = DocumentType.XML; docDef.inspectionType = InspectionType.SCHEMA; docDef.inspectionResult = JSON.stringify( atlasmapInspectionPoExampleSchemaJson ); cfg.addDocument(docDef); service.inspectDocuments().subscribe((answer: DocumentDefinition) => { expect(answer.fields.length).toBe(1); expect(answer.fields[0].name).toBe('purchaseOrder'); const purchaseOrder = answer.getField('/tns:purchaseOrder'); expect(purchaseOrder?.name).toBe('purchaseOrder'); expect(purchaseOrder?.type).toBe('COMPLEX'); expect(purchaseOrder?.children).toBeTruthy(); expect(purchaseOrder?.children?.length).toBe(5); done(); }); }); test('inspectDocuments() pick up one XML root element', (done) => { const docDef = new DocumentInitializationModel(); docDef.type = DocumentType.XML; docDef.name = 'purchaseOrder'; docDef.inspectionType = InspectionType.SCHEMA; docDef.inspectionResult = JSON.stringify( atlasmapInspectionPoExampleSchemaJson ); docDef.selectedRoot = 'purchaseOrder'; cfg.addDocument(docDef); const docDef2 = new DocumentInitializationModel(); docDef2.type = DocumentType.XML; docDef2.name = 'comment'; docDef2.inspectionType = InspectionType.SCHEMA; docDef2.inspectionResult = docDef.inspectionResult; docDef2.selectedRoot = 'comment'; cfg.addDocument(docDef2); let count = 0; service.inspectDocuments().subscribe((answer) => { if (answer.name === 'purchaseOrder') { expect(answer.fields.length).toBe(1); expect(answer.fields[0].name).toBe('purchaseOrder'); count++; } else if (answer.name === 'comment') { expect(answer.fields.length).toBe(1); expect(answer.fields[0].name).toBe('comment'); count++; } if (count === 2) { done(); } }); }); test('getLibraryClassNames()', (done) => { cfg.initCfg.baseMappingServiceUrl = 'dummyurl'; spyOn(ky, 'get').and.callFake((_url: Input) => { return new (class { json(): Promise<any> { return Promise.resolve({ ArrayList: ['dummy.class.0', 'dummy.class.1'], }); } })(); }); service .getLibraryClassNames() .then((values) => { expect(values[0]).toBe('dummy.class.0'); expect(values[1]).toBe('dummy.class.1'); done(); }) .catch((error) => { fail(error); }); }); test('importNonJavaDocument()', (done) => { cfg.initCfg.baseJSONInspectionServiceUrl = 'json'; spyOn(ky, 'post').and.callFake((_url: Input) => { return new (class { json(): Promise<any> { return Promise.resolve({ JsonInspectionResponse: { jsonDocument: { fields: { field: [ { name: 'dummyField', path: 'dummyField', }, ], }, }, }, }); } })(); }); const buf = fs.readFileSync( `${__dirname}/../../../../test-resources/json/schema/mock-json-schema.json` ); const file = new File([new Blob([buf])], 'mock-json-schema.json'); expect(cfg.sourceDocs.length).toBe(0); service .importNonJavaDocument(file, true, true, {}) .then((value) => { expect(value).toBeTruthy(); expect(cfg.sourceDocs.length).toBe(1); expect(cfg.sourceDocs[0].type).toBe(DocumentType.JSON); done(); }) .catch((error) => { fail(error); }); }); test('importJavaDocument()', (done) => { cfg.initCfg.baseJavaInspectionServiceUrl = 'java'; spyOn(ky, 'post').and.callFake((_url: Input) => { return new (class { json(): Promise<any> { return Promise.resolve({ ClassInspectionResponse: { javaClass: { javaFields: { javaField: [ { name: 'dummyField', path: 'dummyField', }, ], }, }, }, }); } })(); }); expect(cfg.sourceDocs.length).toBe(0); service .importJavaDocument('io.atlasmap.test.TestDocumentClass', true) .then((value) => { expect(value).toBeTruthy(); expect(cfg.sourceDocs.length).toBe(1); expect(cfg.sourceDocs[0].type).toBe(DocumentType.JAVA); done(); }) .catch((error) => { fail(error); }); }); test('Constant field', () => { cfg.mappings = new MappingDefinition(); expect(cfg.constantDoc.fields.length).toBe(0); service.createConstant('testConst', 'testConstVal', 'STRING', false); expect(cfg.constantDoc.fields.length).toBe(1); const f = cfg.constantDoc.getField('/testConst'); expect(f).toBeTruthy(); expect(f!.name).toBe('testConst'); expect(f!.path).toBe('/testConst'); expect(f!.type).toBe(FieldType.STRING); expect(f!.value).toBe('testConstVal'); expect(service.getConstantType('testConst')).toBe(FieldType.STRING); expect(service.getConstantTypeIndex('testConst')).toBe(0); service.editConstant( 'testConstMod', 'testConstValMod', 'STRING', 'testConst' ); expect(cfg.constantDoc.fields.length).toBe(1); const fm = cfg.constantDoc.getField('/testConstMod'); expect(fm).toBeTruthy(); expect(fm!.name).toBe('testConstMod'); expect(fm!.path).toBe('/testConstMod'); expect(fm!.type).toBe(FieldType.STRING); expect(fm!.value).toBe('testConstValMod'); service.deleteConstant('testConstMod'); expect(cfg.constantDoc.fields.length).toBe(0); }); test('Property field', () => { cfg.mappings = new MappingDefinition(); expect(cfg.sourcePropertyDoc.fields.length).toBe(0); expect(cfg.targetPropertyDoc.fields.length).toBe(0); service.createProperty('testProp', 'STRING', 'current', true, false); expect(cfg.sourcePropertyDoc.fields.length).toBe(1); expect(cfg.targetPropertyDoc.fields.length).toBe(0); const f = cfg.sourcePropertyDoc.getField('/current/testProp'); expect(f).toBeTruthy(); expect(f!.name).toBe('testProp'); expect(f!.scope).toBe('current'); expect(f!.path).toBe('/current/testProp'); expect(f!.type).toBe(FieldType.STRING); expect(service.getPropertyType('testProp', 'current', true)).toBe( FieldType.STRING ); expect(service.getPropertyTypeIndex('testProp', 'current', true)).toBe(0); service.editProperty( 'testProp', 'STRING', 'current', true, 'testPropMod', 'currentMod' ); expect(cfg.sourcePropertyDoc.fields.length).toBe(1); expect(cfg.targetPropertyDoc.fields.length).toBe(0); const fm = cfg.sourcePropertyDoc.getField('/currentMod/testPropMod'); expect(fm).toBeTruthy(); expect(fm!.name).toBe('testPropMod'); expect(fm!.scope).toBe('currentMod'); expect(fm!.path).toBe('/currentMod/testPropMod'); expect(fm!.type).toBe(FieldType.STRING); service.deleteProperty('testPropMod', 'currentMod', true); expect(cfg.sourcePropertyDoc.fields.length).toBe(0); expect(cfg.targetPropertyDoc.fields.length).toBe(0); }); });
the_stack
import {DanmakuManager} from "./danmakuManager"; import {DanmakuItem} from "./DanmakuItem"; export class Renderer { canvas: HTMLCanvasElement; danmakuManager: DanmakuManager; width: number; height: number; //experimental enableVR = false; constructor(danmakuManager: DanmakuManager) { this.danmakuManager = danmakuManager } init(canvas) { this.canvas = canvas; } resize(width: number, height: number) { this.canvas.width = this.width = width * this.danmakuManager.p; this.canvas.height = this.height = height * this.danmakuManager.p; } update(pause = false) { if (!this.danmakuManager.visible || this.danmakuManager.opacity == 0 || pause == true) { return } let layoutManager = this.danmakuManager.layoutManager; this.clearAll(); this.drawList(layoutManager.initialList, layoutManager.initialListRange[0], layoutManager.initialListRange[1]); this.drawList(layoutManager.appendList, layoutManager.appendListRange[0], layoutManager.appendListRange[1]); } drawList(list: Array<DanmakuItem>, start: number, end: number) { } clearAll() { } drawItemBuffer(item: DanmakuItem) { } } export class Canvas2DRender extends Renderer { ctx: CanvasRenderingContext2D; constructor(manager: DanmakuManager) { super(manager); } init(canvas) { super.init(canvas); this.ctx = canvas.getContext('2d'); } clearAll() { this.ctx.clearRect(0, 0, this.width, this.height); } drawList(list: Array<DanmakuItem>, start: number, end: number) { let drawSettings = this.danmakuManager.drawSettings; let rowHeight = drawSettings.fontSize + drawSettings.rowSpace; for (let i = start; i <= end; i++) { let item = list[i]; if (item && item.buffer) { this.ctx.drawImage(item.buffer, item.left, item.row * rowHeight * drawSettings.p); } } } drawItemBuffer(item: DanmakuItem) { let content = item.content, color = item.color, fontSize = item.fontSize, fontFamily = this.danmakuManager.drawSettings.fontFamily, strokeWidth = this.danmakuManager.drawSettings.strokeWidth, p = this.danmakuManager.p; item.buffer = document.createElement('canvas'); let ctx = item.buffer.getContext('2d'); ctx.font = fontSize * p + 'px ' + fontFamily; let measure = ctx.measureText(content); item.width = item.buffer.width = measure.width + 2 * p * strokeWidth * 2; item.height = item.buffer.height = Math.floor((fontSize * 1.3 + 2 * strokeWidth) * p); ctx.lineWidth = strokeWidth * p; ctx.font = fontSize * p + 'px ' + fontFamily; ctx.fillStyle = color; //ctx.strokeText(content, strokeWidth * p, item.height-strokeWidth* p-fontSize*0.3 ); let bright = Number('0x' + color.substr(1, 2)) + Number('0x' + color.substr(3, 2)) + Number('0x' + color.substr(5, 2)); ctx.shadowColor = (bright > 500) ? '#000000' : '#FFFFFF'; ctx.shadowBlur = strokeWidth * p; ctx.fillText(content, strokeWidth * p, item.height - strokeWidth * p - fontSize * 0.3); } } export class WebglRender extends Renderer { gl; texPosStart: number = 0; texPosEnd: number = 0; texture: WebGLTexture; aspect: number = 1; program: WebGLProgram; posVBO: WebGLBuffer; posAL: number; posArray: Float32Array; texposVBO: WebGLBuffer; texposAL; texposArray: Float32Array; mvpMatUL; textureUL; tmpcanvas: HTMLCanvasElement; tmpCtx: CanvasRenderingContext2D; videoEl; videoRender; videoProgram; videoTex; videoTexUL; videoReady; videoPosAL; videoMvpMatUL; videoUvAL; videoWidth; videoHeight; videoPosVBO; videoUvVBO; logoTexture; logoTextureUL; vrProgram; vrPosAL; vrIndexUL; vrTexUL; vrPosVbo; vrFBuffers = []; vrTextures = []; mvpMat = mat4.create(); modelMat = mat4.create(); viewMat = mat4.create(); perspectiveMat = mat4.create(); eyePosition = new Float32Array([0, 0, 2.5]); eyePositionStart = new Float32Array([0, 0]); distance = 0.8; rotate = new Float32Array([0, 0]); center = new Float32Array([0, 0, 0]); updir = new Float32Array([0, 1, 0]); fov = 30; near = 1; far = 100; mouseDown = false; downPosX = 0; downPosY = 0; constructor(manager: DanmakuManager) { super(manager) } init(canvas: HTMLCanvasElement, maxcount = 400, videoRender = true) { super.init(canvas); this.gl = canvas.getContext('webgl'); this.tmpcanvas = document.createElement('canvas'); this.tmpCtx = this.tmpcanvas.getContext('2d'); this.texture = this.gl.createTexture(); this.gl.activeTexture(this.gl.TEXTURE0); this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture); this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR); this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR); this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE); this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE); this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, 4096, 4096, 0, this.gl.RGBA, this.gl.UNSIGNED_BYTE, null); this.gl.blendFunc(this.gl.SRC_ALPHA, this.gl.ONE_MINUS_SRC_ALPHA); let logoImg = document.createElement('img'); this.logoTexture = this.gl.createTexture(); logoImg.onload = function () { this.gl.activeTexture(this.gl.TEXTURE1); this.gl.bindTexture(this.gl.TEXTURE_2D, this.logoTexture); this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR); this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR); this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE); this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE); this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, logoImg) }.bind(this); logoImg.src = 'images/videologo.png'; let vst = ` attribute vec3 pos; attribute float texpos; letying vec2 uvCoord; uniform mat4 mvpMat; void main(){ vec4 position=vec4(pos,1.0); position=mvpMat*position; gl_Position=position; uvCoord=vec2(fract(texpos),floor(mod(texpos,128.0))/128.0); } `; let fst = ` precision mediump float; letying vec2 uvCoord; uniform sampler2D texture; void main(){ vec4 color=texture2D(texture,uvCoord); gl_FragColor=color; } `; this.program = getProgramByShaderSource(this.gl, vst, fst); this.posArray = new Float32Array(maxcount * 6 * 3); this.texposArray = new Float32Array(maxcount * 6 * 2); this.posVBO = getVBO(this.gl, this.posArray); this.texposVBO = getVBO(this.gl, this.texposArray); this.posAL = this.gl.getAttribLocation(this.program, 'pos'); this.texposAL = this.gl.getAttribLocation(this.program, 'texpos'); this.textureUL = this.gl.getUniformLocation(this.program, 'texture'); this.mvpMatUL = this.gl.getUniformLocation(this.program, 'mvpMat'); this.videoRender = videoRender; if (videoRender) { //this.danmakuManager.player.videoEl.style.display='none'; this.canvas.style.background = 'black'; this.videoEl = this.danmakuManager.player.videoEl; let videoVST = ` attribute vec3 pos; attribute vec2 uv; uniform mat4 mvpMat; letying vec2 uvCoord; void main(){ vec4 position=vec4(pos,1.0); position=mvpMat*position; gl_Position=position; uvCoord=uv; } `; let videoFst = ` precision mediump float; letying vec2 uvCoord; uniform sampler2D texture; uniform sampler2D logoTexture; void main(){ if(gl_FrontFacing) { vec4 color=texture2D(logoTexture,uvCoord); gl_FragColor=color; }else{ vec4 color=texture2D(texture,uvCoord); gl_FragColor=color; } } `; this.videoProgram = getProgramByShaderSource(this.gl, videoVST, videoFst); this.videoPosAL = this.gl.getAttribLocation(this.videoProgram, 'pos'); this.videoUvAL = this.gl.getAttribLocation(this.videoProgram, 'uv'); this.videoMvpMatUL = this.gl.getUniformLocation(this.videoProgram, 'mvpMat'); this.videoTexUL = this.gl.getUniformLocation(this.videoProgram, 'texture'); this.logoTextureUL = this.gl.getUniformLocation(this.videoProgram, 'logoTexture'); //vr let initFB = (i) => { this.vrFBuffers[i] = this.gl.createFramebuffer(); this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, this.vrFBuffers[i]); this.vrTextures[i] = this.gl.createTexture(); this.gl.bindTexture(this.gl.TEXTURE_2D, this.vrTextures[i]); this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR); this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR); this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, 1024, 1024, 0, this.gl.RGBA, this.gl.UNSIGNED_BYTE, null); this.gl.framebufferTexture2D(this.gl.FRAMEBUFFER, this.gl.COLOR_ATTACHMENT0, this.gl.TEXTURE_2D, this.vrTextures[i], 0) }; initFB(0); initFB(1); this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null); this.videoEl.addEventListener('loadedmetadata', function () { this.videoTex = this.gl.createTexture(); this.gl.activeTexture(this.gl.TEXTURE0); this.gl.bindTexture(this.gl.TEXTURE_2D, this.videoTex); this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, this.gl.LINEAR); this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MIN_FILTER, this.gl.LINEAR); this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_S, this.gl.CLAMP_TO_EDGE); this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_WRAP_T, this.gl.CLAMP_TO_EDGE); this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.videoEl.videoWidth, this.videoEl.videoHeight, 0, this.gl.RGBA, this.gl.UNSIGNED_BYTE, null); this.videoHeight = this.videoEl.videoHeight; this.videoWidth = this.videoEl.videoWidth; let vasp = this.videoEl.videoHeight / this.videoEl.videoWidth; this.videoPosVBO = getVBO(this.gl, new Float32Array([-1, vasp, 0, 1, vasp, 0, 1, -vasp, 0, -1, vasp, 0, 1, -vasp, 0, -1, -vasp, 0])); this.videoUvVBO = getVBO(this.gl, new Float32Array([0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1])); this.videoReady = true; }.bind(this)); this.danmakuManager.player.containerEl.addEventListener('mousedown', function (e) { e.stopPropagation(); this.mouseDown = true; this.downPosX = e.screenX; this.downPosY = e.screenY; vec2.copy(this.eyePositionStart, this.rotate); }.bind(this), false); window.addEventListener('mousemove', function (e) { if (this.mouseDown) { this.rotate[0] = -0.003 * (e.screenX - this.downPosX) + this.eyePositionStart[0]; this.rotate[1] = -0.003 * (e.screenY - this.downPosY) + this.eyePositionStart[1]; } }.bind(this), true); window.addEventListener('mouseup', function (e) { if (this.mouseDown) { this.mouseDown = false; } }.bind(this), true); this.danmakuManager.player.containerEl.addEventListener('mousewheel', function (e) { e.preventDefault(); if ((e.wheelDelta || e.detail) > 0) { this.fov /= 1 + (0.4 * Math.abs((e.wheelDelta / 120 || e.detail / 3))); } else { this.fov *= 1 + (0.4 * Math.abs((e.wheelDelta / 120 || e.detail / 3))); } this.fov = Math.max(10, Math.min(80, this.fov)) }.bind(this)); } vst = ` attribute vec2 pos; uniform float index; letying vec2 uvCoord; void main(){ vec2 tempPos=pos; uvCoord=(tempPos+vec2(1.0,1.0))*0.5; if(index==1.0){ tempPos.x=tempPos.x*0.5-0.5; }else{ tempPos.x=-tempPos.x; tempPos.x=tempPos.x*0.5+0.5; uvCoord.x=1.0-uvCoord.x; } gl_Position=vec4(tempPos,0.0,1.0); } `; fst = ` precision mediump float; letying vec2 uvCoord; uniform sampler2D texture; void main(){ gl_FragColor=texture2D(texture,uvCoord); } `; this.vrProgram = getProgramByShaderSource(this.gl, vst, fst); this.vrPosAL = this.gl.getAttribLocation(this.vrProgram, 'pos'); this.vrIndexUL = this.gl.getUniformLocation(this.vrProgram, 'index'); this.vrTexUL = this.gl.getUniformLocation(this.vrProgram, 'texture'); } __enableVR = false; get enableVR() { return this.__enableVR } set enableVR(v) { if (v == true) { this.initVR(); } this.__enableVR = v } vrDev; vrEyeParams = []; initVR() { window['test'] = this; if (!this.vrDev) { navigator['getVRDisplays']().then(result => { this.vrDev = result[0]; this.vrEyeParams[0] = this.vrDev.getEyeParameters('left'); this.vrEyeParams[1] = this.vrDev.getEyeParameters('right'); let fov = this.vrEyeParams[0].fieldOfView; let x1 = -fov.rightDegrees / fov.leftDegrees; let x2 = 1; let y1 = fov.downDegrees / fov.upDegrees; let y2 = -1; this.vrPosVbo = getVBO(this.gl, [x1, y1, x2, y1, x2, y2, x1, y1, x2, y2, x1, y2]); this.vrPosVbo = getVBO(this.gl, [-1, 1, 1, 1, 1, -1, -1, 1, 1, -1, -1, -1]); }); } } btnupdown = false; btndowndown = false; btnleftdown = false; btnrightdown = false; updatePos() { let direction = new Float32Array([0, 0, 0.01]); let length = vec3.len(direction); vec3.rotateY(direction, direction, this.center, this.rotate[0]); vec3.rotateX(direction, direction, this.center, this.rotate[1]); if (this.btnupdown) { vec3.sub(this.eyePosition, this.eyePosition, direction) } if (this.btndowndown) { vec3.add(this.eyePosition, this.eyePosition, direction) } if (this.btnleftdown) { vec3.add(this.eyePosition, this.eyePosition, [length * -Math.cos(this.rotate[0]), 0, length * Math.sin(this.rotate[1])]); } if (this.btnrightdown) { vec3.sub(this.eyePosition, this.eyePosition, [length * -Math.cos(this.rotate[0]), 0, length * Math.sin(this.rotate[1])]) } } resize(width: number, height: number) { super.resize(width, height); this.gl.viewport(0, 0, this.width, this.height); this.width = width; this.height = height; this.aspect = this.width / this.height } updateMvp() { //let epos=new Float32Array([this.distance*Math.cos(this.eyePosition[0]),0,this.distance*Math.sin(this.eyePosition[0])]); mat4.lookAt(this.viewMat, this.eyePosition, this.center, this.updir); mat4.perspective(this.perspectiveMat, this.fov * 3.14159 / 180, this.aspect, this.near, this.far); mat4.identity(this.modelMat); mat4.rotateY(this.modelMat, this.modelMat, this.rotate[0]); mat4.rotateX(this.modelMat, this.modelMat, this.rotate[1]); //mat4.translate(this.viewMat, this.viewMat, [-this.eyePosition[0], -this.eyePosition[1], -this.eyePosition[2]]); mat4.multiply(this.mvpMat, this.perspectiveMat, this.viewMat); mat4.multiply(this.mvpMat, this.mvpMat, this.modelMat); } updateVrMVP(index) { let ePos = vec3.create(); vec3.subtract(ePos, ePos, this.vrEyeParams[index].offset); let vmat = mat4.create(); mat4.translate(vmat, vmat, ePos); let rotate = mat4.create(); mat4.fromQuat(rotate, this.vrDev.getPose().orientation); //ma44.rotateY(rotate,rotate,0.5*3.1415926); mat4.mul(vmat, rotate, vmat); mat4.invert(vmat, vmat); let fov = 80; mat4.perspective(this.perspectiveMat, fov * 3.14159 / 180, 1, 0.04, 100); mat4.multiply(this.mvpMat, this.perspectiveMat, vmat); let modelMat = mat4.create(); mat4.translate(modelMat, modelMat, [-1, 0, 0]); mat4.rotateY(modelMat, modelMat, 0.5 * 3.1415926); mat4.scale(modelMat, modelMat, vec3.fromValues(0.7, 0.7, 0.7)); mat4.multiply(this.mvpMat, this.mvpMat, modelMat); } bindVR(index) { this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, this.vrFBuffers[index]); //let width=this.vrEyeParams[0].fieldOfView. this.gl.viewport(0, 0, 1024, 1024); this.updateVrMVP(index); } renderVideo() { //this.gl.useProgram(this.videoProgram); this.gl.uniformMatrix4fv(this.videoMvpMatUL, false, this.mvpMat); this.gl.depthMask(true); this.gl.enable(this.gl.DEPTH_TEST); this.gl.depthFunc(this.gl.LEQUAL); this.gl.drawArrays(this.gl.TRIANGLES, 0, 6); } renderDanmaku() { this.gl.uniformMatrix4fv(this.mvpMatUL, false, this.mvpMat); this.gl.depthMask(false); this.gl.drawArrays(this.gl.TRIANGLES, 0, this.drawCount * 6); } renderVR() { this.gl.useProgram(this.vrProgram); this.gl.viewport(0, 0, this.width * this.danmakuManager.p, this.height * this.danmakuManager.p); this.gl.bindFramebuffer(this.gl.FRAMEBUFFER, null); this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.vrPosVbo); this.gl.enableVertexAttribArray(this.vrPosAL); this.gl.vertexAttribPointer(this.vrPosVbo, 2, this.gl.FLOAT, false, 0, 0); this.gl.uniform1i(this.vrTexUL, 0); this.gl.bindTexture(this.gl.TEXTURE_2D, this.vrTextures[0]); this.gl.uniform1f(this.vrIndexUL, 0.0); this.gl.drawArrays(this.gl.TRIANGLES, 0, 6); this.gl.bindTexture(this.gl.TEXTURE_2D, this.vrTextures[1]); this.gl.uniform1f(this.vrIndexUL, 1.0); this.gl.drawArrays(this.gl.TRIANGLES, 0, 6); } update() { if (!this.enableVR) { this.updateMvp(); } //this.updateMvp(); if (this.videoReady) { this.gl.useProgram(this.videoProgram); this.gl.activeTexture(this.gl.TEXTURE0); this.gl.depthMask(true); this.gl.disable(this.gl.DEPTH_TEST); this.gl.disable(this.gl.BLEND); this.gl.activeTexture(this.gl.TEXTURE0); this.gl.bindTexture(this.gl.TEXTURE_2D, this.videoTex); this.gl.texImage2D(this.gl.TEXTURE_2D, 0, this.gl.RGBA, this.gl.RGBA, this.gl.UNSIGNED_BYTE, this.videoEl); this.gl.activeTexture(this.gl.TEXTURE1); this.gl.bindTexture(this.gl.TEXTURE_2D, this.logoTexture); this.gl.uniform1i(this.logoTextureUL, 1); this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.videoPosVBO); this.gl.enableVertexAttribArray(this.videoPosAL); this.gl.vertexAttribPointer(this.videoPosAL, 3, this.gl.FLOAT, false, 0, 0); this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.videoUvVBO); this.gl.enableVertexAttribArray(this.videoUvAL); this.gl.vertexAttribPointer(this.videoUvAL, 2, this.gl.FLOAT, false, 0, 0); this.gl.uniform1i(this.videoTexUL, 0); //this.gl.uniformMatrix4fv(this.videoMvpMatUL, false, this.mvpMat); //this.gl.depthMask(true); //this.gl.enable(this.gl.DEPTH_TEST); //this.gl.depthFunc(this.gl.LEQUAL); //this.gl.drawArrays(this.gl.TRIANGLES, 0, 6); //this.updateVrMVP(0); //this.updateMvp(); //this.renderVideo(); if (this.enableVR && this.vrDev) { this.bindVR(0); this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT); this.renderVideo(); this.bindVR(1); this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT); this.renderVideo(); } else { this.renderVideo() } } if (!this.danmakuManager.visible || this.danmakuManager.opacity == 0) { return } let layoutManager = this.danmakuManager.layoutManager; this.activeTexture(); this.texPosStart = Number.MAX_VALUE; let list = layoutManager.initialList.slice(layoutManager.initialListRange[0], layoutManager.initialListRange[1]).concat(layoutManager.appendList.slice(layoutManager.appendListRange[0], layoutManager.appendListRange[1])); if (this.videoReady) { list.sort(function (a, b) { return a.zpos - b.zpos }) } //this.drawList(layoutManager.initialList,layoutManager.initialListRange[0],layoutManager.initialListRange[1]); //this.drawList(layoutManager.appendList,layoutManager.appendListRange[0],layoutManager.appendListRange[1]); this.drawList(list); this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.posVBO); this.gl.bufferData(this.gl.ARRAY_BUFFER, this.posArray, this.gl.DYNAMIC_DRAW); this.gl.enableVertexAttribArray(this.posAL); this.gl.vertexAttribPointer(this.posAL, 3, this.gl.FLOAT, false, 0, 0); this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.texposVBO); this.gl.bufferData(this.gl.ARRAY_BUFFER, this.texposArray, this.gl.DYNAMIC_DRAW); this.gl.enableVertexAttribArray(this.texposAL); this.gl.vertexAttribPointer(this.texposAL, 1, this.gl.FLOAT, false, 0, 0); if (this.enableVR && this.vrDev) { this.bindVR(0); this.renderDanmaku(); this.bindVR(1); this.renderDanmaku(); this.renderVR(); } else { this.renderDanmaku() } //this.gl.uniformMatrix4fv(this.mvpMatUL, false, this.mvpMat); //this.gl.depthMask(false); //this.gl.drawArrays(this.gl.TRIANGLES, 0, this.drawCount * 6); this.drawCount = 0; this.textureIsActive = false; } textureIsActive = false; activeTexture() { if (!this.textureIsActive) { this.gl.useProgram(this.program); this.gl.enable(this.gl.BLEND); this.gl.activeTexture(this.gl.TEXTURE0); this.gl.bindTexture(this.gl.TEXTURE_2D, this.texture); this.gl.uniform1i(this.textureUL, 0); } } drawItemBuffer(item: DanmakuItem) { if (this.texPosStart - this.texPosEnd > 127) { return } this.activeTexture(); let content = item.content, color = item.color, fontSize = item.fontSize, fontFamily = this.danmakuManager.drawSettings.fontFamily, strokeWidth = this.danmakuManager.drawSettings.strokeWidth, p = this.danmakuManager.p; let ctx = this.tmpCtx; ctx.font = 25 + 'px ' + fontFamily; let measure = ctx.measureText(content); item.width = this.tmpcanvas.width = measure.width + 2 * strokeWidth * 2 + 10; let relWidth = item.width / 4096; item.width *= p; if (relWidth >= 1) { return } item.height = 32; this.tmpcanvas.height = 32; ctx.lineWidth = strokeWidth; ctx.font = 25 + 'px ' + fontFamily; ctx.fillStyle = color; //ctx.strokeText(content, strokeWidth * p, item.height-strokeWidth* p-fontSize*0.3 ); let bright = Number('0x' + color.substr(1, 2)) + Number('0x' + color.substr(3, 2)) + Number('0x' + color.substr(5, 2)); ctx.shadowColor = (bright > 500) ? '#000000' : '#FFFFFF'; ctx.shadowBlur = strokeWidth; ctx.clearRect(0, 0, this.tmpcanvas.width, this.tmpcanvas.height); ctx.fillText(content, strokeWidth + 3, item.height - strokeWidth - fontSize * 0.3 + 1); let x = this.texPosEnd % 1; let y = Math.floor(this.texPosEnd % 128); if (relWidth + x <= 1) { this.gl.texSubImage2D(this.gl.TEXTURE_2D, 0, Math.floor(x * 4096), y * 32, this.gl.RGBA, this.gl.UNSIGNED_BYTE, this.tmpcanvas); item.texposStart = this.texPosEnd; this.texPosEnd += relWidth; item.texposEnd = this.texPosEnd; } else { y = y + 1; x = 0; this.gl.texSubImage2D(this.gl.TEXTURE_2D, 0, Math.floor(x * 4096), y * 32, this.gl.RGBA, this.gl.UNSIGNED_BYTE, this.tmpcanvas); item.texposStart = Math.ceil(this.texPosEnd); item.texposEnd = this.texPosEnd = item.texposStart + relWidth; //let firstHalf=this.tmpCtx.getImageData(0,0,Math.round((1-x)*4096),32); //let secondHalf=this.tmpCtx.getImageData(Math.round((relWidth-1+x)*4096),0,Math.round(relWidth*4096),32); //this.gl.texSubImage2D(this.gl.TEXTURE_2D,0,x*4096,y*32,this.gl.RGBA,this.gl.UNSIGNED_BYTE,firstHalf); //this.gl.texSubImage2D(this.gl.TEXTURE_2D,0,0,(y+1)*32,this.gl.RGBA,this.gl.UNSIGNED_BYTE,secondHalf) } item.buffer = true; item.zpos = this.__enableVR ? 2 * Math.random() : Math.random() } drawList(list: Array<DanmakuItem>) { let posList = this.posArray; let uvList = this.texposArray; let w = this.width, h = this.height; let drawSettings = this.danmakuManager.drawSettings; let rowHeight = drawSettings.fontSize + drawSettings.rowSpace; let a = this.aspect; let va = this.videoWidth / this.videoHeight; let vh = w / va; let p = drawSettings.p; for (let i = 0; i <= list.length; i++) { let item = list[i]; if (!item) { continue } let index = this.drawCount * 18; posList[index] = (item.left / p / w * 2 - 1); posList[index + 1] = (1 / va - ((item.row + 0.5) * rowHeight / 2) / vh * 2.5); posList[index + 3] = ((item.left / p + item.width / p) / w * 2 - 1); posList[index + 4] = posList[index + 1]; posList[index + 6] = posList[index + 3]; posList[index + 7] = posList[index + 1] + item.height / vh * 1.15; posList[index + 9] = posList[index]; posList[index + 10] = posList[index + 1]; posList[index + 12] = posList[index + 6]; posList[index + 13] = posList[index + 7]; posList[index + 15] = posList[index]; posList[index + 16] = posList[index + 7]; posList[index + 2] = posList[index + 5] = posList[index + 8] = posList[index + 11] = posList[index + 14] = posList[index + 17] = 0.5 * item.zpos; index = this.drawCount * 6; uvList[index] = item.texposStart + 1 + 3 / 4096; uvList[index + 1] = item.texposEnd + 1 - 3 / 4096; uvList[index + 2] = item.texposEnd - 3 / 4096; uvList[index + 3] = uvList[index]; uvList[index + 4] = uvList[index + 2]; uvList[index + 5] = item.texposStart + 3 / 4096; this.drawCount++; this.texPosStart = Math.min(item.texposStart, this.texPosStart); } } drawCount = 0; }
the_stack
import './litdev-icon-button.js'; import {LitElement, html, css, nothing} from 'lit'; import {customElement, property, state} from 'lit/decorators.js'; import {signInToGithub} from '../github/github-signin.js'; import {getAuthenticatedUser} from '../github/github-user.js'; import {createGist, updateGist} from '../github/github-gists.js'; import {githubLogo} from '../icons/github-logo.js'; import {showErrors} from '../errors.js'; import {playgroundToGist} from '../util/gist-conversion.js'; import type {Gist} from '../github/github-gists.js'; import type {SampleFile} from 'playground-elements/shared/worker-api.js'; /** * An in-memory cache of the GitHub authentication tokens associated with each * instance of this component. This allows the user to authenticate only once * per page load, instead of on each save. * * By using a WeakMap instead of a class instance property, we make it much more * difficult for code outside of this module to directly access tokens. * * (It's not expected to usually have more than one instance of this component, * but it could happen e.g. in testing.) */ const tokenCache = new WeakMap<LitDevPlaygroundShareGist, string>(); const GITHUB_USER_LOCALSTORAGE_KEY = 'github-user'; /** * Buttons for sharing a Playground project as a GitHub gist and signing into * GitHub when needed. */ @customElement('litdev-playground-share-gist') export class LitDevPlaygroundShareGist extends LitElement { static styles = css` litdev-icon-button { background: var(--color-blue); color: white; } litdev-icon-button:hover { background: blue; } #signInStatus { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; font-size: 16px; } #signInStatus > span { display: flex; align-items: center; } #avatar { margin-left: 8px; border-radius: 50%; } #signOutButton:visited { color: currentcolor; } #signOutButton:hover { color: blue; } #gistActions { display: flex; justify-content: space-between; } `; /** * GitHub OAuth App client ID. Generated when a GitHub OAuth App is first * created. */ @property() clientId?: string; /** * URL where users will be redirected to authorize with GitHub. */ @property() authorizeUrl?: string; /** * Base URL for the GitHub API. */ @property() githubApiUrl?: string; /** * Base URL for the GitHub avatar service. */ @property() githubAvatarUrl?: string; /** * A function to allow this component to access the project upon save. */ @property({attribute: false}) getProjectFiles?: () => SampleFile[] | undefined; /** * Whether we're actively awaiting something like signing in or writing a * gist. The buttons should be disabled in that case. */ @state() private _pending = false; /** * The gist we are currently viewing, if any. */ @property({attribute: false}) activeGist?: Gist; override render() { if (!this._signedInUser) { return this._signInButton; } return html` ${this._signedInStatus} <div id="gistActions"> ${this.canUpdateGist ? this._updateGistButton : nothing} ${this._newGistButton} </div> `; } private get _signInButton() { return html`<litdev-icon-button id="signInButton" .disabled=${this._pending} @click=${this._signIn} > ${githubLogo} Sign in to GitHub </litdev-icon-button>`; } private get _signedInStatus() { const {id, login} = this._signedInUser!; const avatarSize = 24; const avatarUrl = new URL( `/u/${id}?s=${/* double for high dpi */ avatarSize * 2}`, this.githubAvatarUrl ).href; return html`<div id="signInStatus"> <span> <span>Signed in as <b>${login}</b></span> <img id="avatar" src="${avatarUrl}" width="${avatarSize}" height="${avatarSize}" /></span> <a id="signOutButton" href="#" @click=${this._signOut}>Sign out</a> </div>`; } private get _newGistButton() { return html`<litdev-icon-button id="createNewGistButton" .disabled=${this._pending} @click=${this.createNewGist} > ${githubLogo} Create new gist </litdev-icon-button>`; } private get _updateGistButton() { return html`<litdev-icon-button id="updateGistButton" .disabled=${this._pending} @click=${this.updateGist} > ${githubLogo} Update gist </litdev-icon-button>`; } private get _signedInUser(): {id: number; login: string} | undefined { const value = localStorage.getItem(GITHUB_USER_LOCALSTORAGE_KEY); if (value) { return JSON.parse(value); } return undefined; } get isSignedIn(): boolean { return this._signedInUser !== undefined; } get canUpdateGist(): boolean { if (!this.activeGist) { return false; } const user = this._signedInUser; if (!user) { return false; } return this.activeGist.owner.id === user.id; } @showErrors() private async _signIn() { this._pending = true; try { if (!this.githubApiUrl || !this.clientId || !this.authorizeUrl) { throw new Error('Missing required properties'); } // TODO(aomarks) Show a scrim and some indication about what is happening // while the GitHub sign in popup is open. const token = await signInToGithub({ clientId: this.clientId, authorizeUrl: this.authorizeUrl, }); tokenCache.set(this, token); const {id, login} = await getAuthenticatedUser({ apiBaseUrl: this.githubApiUrl, token, }); localStorage.setItem( GITHUB_USER_LOCALSTORAGE_KEY, JSON.stringify({id, login}) ); // Render share button. this.requestUpdate(); } finally { this._pending = false; } } /** * Note signing out does not deauthorize the lit.dev GitHub app from the * user's GitHub account. */ private _signOut(event: Event) { event.preventDefault(); tokenCache.delete(this); localStorage.removeItem(GITHUB_USER_LOCALSTORAGE_KEY); // Render sign-in button. this.requestUpdate(); } @showErrors() async createNewGist() { this._pending = true; try { if (!this.githubApiUrl) { throw new Error('Missing required properties'); } const projectFiles = this.getProjectFiles?.(); if (!projectFiles || projectFiles.length === 0) { // TODO(aomarks) The button should just be disabled in this case. throw new Error("Can't save an empty project"); } this.dispatchEvent( new CustomEvent('status', { detail: {text: 'Creating gist ...'}, bubbles: true, }) ); let token = tokenCache.get(this); if (token === undefined) { await this._signIn(); } token = tokenCache.get(this); if (token === undefined) { throw new Error('Error token not defined'); } const gistFiles = playgroundToGist(projectFiles); const gist = await createGist(gistFiles, { apiBaseUrl: this.githubApiUrl, token, }); window.location.hash = '#gist=' + gist.id; let statusText = 'Gist created'; try { await navigator.clipboard.writeText(window.location.toString()); statusText += ' and URL copied to clipboard'; } catch { // The browser isn't allowing us to copy. This could happen because it's // disabled in settings, or because we're in a browser like Safari that // only allows copying from a synchronous event handler. statusText += ' and URL bar updated'; } this.dispatchEvent(new Event('created')); this.dispatchEvent( new CustomEvent('status', { detail: {text: statusText}, bubbles: true, }) ); } finally { this._pending = false; } } @showErrors() async updateGist() { this._pending = true; try { if (!this.githubApiUrl || !this.activeGist) { throw new Error('Missing required properties'); } const projectFiles = this.getProjectFiles?.(); if (!projectFiles || projectFiles.length === 0) { // TODO(aomarks) The button should just be disabled in this case. throw new Error("Can't save an empty project"); } this.dispatchEvent( new CustomEvent('status', { detail: {text: 'Updating gist ...'}, bubbles: true, }) ); let token = tokenCache.get(this); if (token === undefined) { await this._signIn(); } token = tokenCache.get(this); if (token === undefined) { throw new Error('Error token not defined'); } const gistFiles = playgroundToGist(projectFiles); // If we have deleted or renamed a file, then the old filename will no // longer be in our project files list. However, when updating a gist, if // you omit a file that existed in the previous revision, it will not be // automatically deleted. Instead, we need to add an explicit entry for the // file where the content is empty. for (const oldFilename of Object.keys(this.activeGist.files)) { if (!gistFiles[oldFilename]) { gistFiles[oldFilename] = {content: ''}; } } const gist = await updateGist(this.activeGist.id, gistFiles, { apiBaseUrl: this.githubApiUrl, token, }); window.location.hash = '#gist=' + gist.id; let statusText = 'Gist updated'; try { await navigator.clipboard.writeText(window.location.toString()); statusText += ' and URL copied to clipboard'; } catch {} this.dispatchEvent(new Event('created')); this.dispatchEvent( new CustomEvent('status', { detail: {text: statusText}, bubbles: true, }) ); } finally { this._pending = false; } } } declare global { interface HTMLElementTagNameMap { 'litdev-playground-share-gist': LitDevPlaygroundShareGist; } }
the_stack
import { ActivatedRoute, Router } from '@angular/router'; import { DefaultApi } from '../../../../../../gen/api/DefaultApi'; import { Comment } from '../../../../../../gen/model/Comment'; import { NgForm } from '@angular/forms'; import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser'; import { AfterViewInit, Component, OnDestroy } from '@angular/core'; import { trigger, style, transition, animate } from '@angular/animations'; import { getErrorMessage } from '../../../../../../shared/errorHandler'; @Component({ selector: 'comments', styleUrls: ['./pdf.scss'], templateUrl: './pdf.html', animations: [ trigger('anim', [ transition(':enter', [ style({transform: 'translateX(-10%)', opacity: 0}), animate('0.2s', style({transform: 'translateX(0%)', opacity: 1})), ]), transition(':leave', [ animate('0.2s', style({transform: 'translateX(-10%)', opacity: 0})), ]), ]), trigger('fadeInOut', [ transition(':enter', [ style({opacity: 0}), animate('0.2s', style({opacity: 1})), ]), transition(':leave', [ animate('0.2s', style({opacity: 0})), ]), ]), ], }) export class PdfViewComponent implements AfterViewInit, OnDestroy { id: string; private subParam: any; comments: Comment[]; newComment: Comment; pdfUrl: string = ''; hasPdf: boolean = false; back: Function; addComment: Function; viewerUrl: SafeResourceUrl; private currentUser: string; httpErrorMsg = null; deleteId: number; pdfViewerScroll: HTMLDivElement; inputElementPage: HTMLInputElement; inputElementPageNumber: HTMLSpanElement; listenerIFrame; listenerWindow; private selectedComment: number; private tempSelectedCommentContent: string; private tempSelectedCommentPublish: boolean; private selectedCommentIndex: number private hiddenModal: boolean = true; searchableList = ['author', 'content']; sort: string = 'pageNumber'; private queryString: string = null; private lastPageNumberLabel: number; private searchInputValue: string; private showAll: boolean = false; private disableShowAll: boolean = false; private triggerShowAll() { // toggle this.showAll = !this.showAll; if (this.showAll) { // show all comments this.queryString = ''; } else { // reset show all this.queryString = null; } } private searchComments() { // check if search input changed if (this.queryString !== this.searchInputValue) { if (this.searchInputValue != null && this.searchInputValue !== '') { // change search string this.queryString = this.searchInputValue; this.showAll = true; this.disableShowAll = true; } else { // reset search this.queryString = null; this.showAll = false; this.disableShowAll = false; } // check if a comment is selected if (this.selectedComment != null) { // deselect comment if (this.commentChanged()) { this.showModalChangedComment(); } else { // not changed -> reset values this.tempSelectedCommentContent = null; this.tempSelectedCommentPublish = null; this.selectedComment = null; } } } } /** * Trigger search pipe again with the same search string. */ private triggerSearchAgain() { // assign new object to trigger pipe again this.searchableList = [].concat(this.searchableList); } private sameAsLastPageNumberLabel(index: number, page: number): boolean { if (index !== 0 && this.lastPageNumberLabel === page) { return true; } this.lastPageNumberLabel = page; return false; } private showModalChangedComment() { if (this.hiddenModal) { this.hiddenModal = false; document.getElementById('openModalCommentChangedButton').click(); } } private editComment(id: number) { if (this.selectedComment == null || (this.selectedComment !== id && !this.commentChanged())) { // save comment for reset this.selectedCommentIndex = this.comments.findIndex(x => x.id === id); this.tempSelectedCommentContent = this.comments[this.selectedCommentIndex].content; this.tempSelectedCommentPublish = this.comments[this.selectedCommentIndex].publish; this.selectedComment = id; } else if (this.selectedComment !== id) { this.showModalChangedComment(); } } private cancelEditing() { // reset comment let id = this.comments.findIndex(x => x.id === this.selectedComment); this.comments[id].content = this.tempSelectedCommentContent; this.comments[id].publish = this.tempSelectedCommentPublish; // reset values this.tempSelectedCommentContent = null; this.tempSelectedCommentPublish = null; this.selectedComment = null; this.hiddenModal = true; } private commentChanged(): boolean { if (this.selectedComment != null) { // find selected comment let id = this.comments.findIndex(x => x.id === this.selectedComment); // check if comment exists if (id >= 0) { // check if comment changed if (this.tempSelectedCommentPublish !== this.comments[id].publish || this.tempSelectedCommentContent !== this.comments[id].content) { return true; } } else { // comment does not exist, delete selection this.tempSelectedCommentContent = null; this.tempSelectedCommentPublish = null; this.selectedComment = null; } } return false; } private loadPdfAndComments() { // get pdf and comments from backend this.api.getPdfFile(this.id).subscribe(response => { if (response != null) { this.hasPdf = true; this.pdfUrl = URL.createObjectURL(response); let tempViewerUrl = 'assets/pdfjs/web/viewer.html?file=' + encodeURIComponent(this.pdfUrl); this.viewerUrl = this.domSanitizer.bypassSecurityTrustResourceUrl(tempViewerUrl); // get comments from backend this.loadComments(false); } }, (err) => { this.errorHandler(err); }, ); } private loadComments(resetSelected: boolean) { this.api.getPdfComments(this.id).subscribe(result => { if (result != null) { if (this.comments == null) { this.comments = result; } else { // update array with comments from backend to prevent animation of all comments for (let i = 0; i < this.comments.length; i++) { // find comment in result let id = result.findIndex(x => x.id === this.comments[i].id); // update comment if (id >= 0) { // update all values of comment separately to prevent animation of comment this.comments[i].content = result[id].content; this.comments[i].publish = result[id].publish; this.comments[i].pageNumber = result[id].pageNumber; this.comments[i].author = result[id].author; this.comments[i].page = result[id].page; this.comments[i].alterationDate = result[id].alterationDate; this.comments[i].date = result[id].date; // delete comment from result array result.splice(id, 1); } else { // comment does not exist at backend -> delete it from the array this.comments.splice(i, 1); i--; } } // add remaining comments from backend to the array Array.prototype.push.apply(this.comments, result); if (resetSelected != null && resetSelected) { // reset selected comment this.selectedComment = null; } // trigger search pipe again because comments may changed if ((this.queryString != null && this.queryString !== '')) { this.triggerSearchAgain(); } } } }, (err) => { this.errorHandler(err); }, ); } constructor(private router: Router, private api: DefaultApi, private route: ActivatedRoute, private domSanitizer: DomSanitizer) { let object = localStorage.getItem('CloudRefUser'); if (object != null) { let userInfo = JSON.parse(object); this.currentUser = userInfo.username; } this.listenerIFrame = (event) => { // send message to window to inform it about scrolling window.postMessage('scrolling', '*'); } this.listenerWindow = (event) => { // get current page numbers this.loadCurrentPdfPage(); } // get bibtexkey from url this.subParam = this.route.params.subscribe(params => { this.id = params['id']; }); // initialize form this.newComment = { id: 100, bibtexkey: this.id, author: this.currentUser, publish: true, content: '', page: '', pageNumber: -1, }; // get pdf and comments from backend this.loadPdfAndComments(); this.back = function () { this.router.navigate(['references', this.id]); }; this.addComment = function (f: NgForm) { // check if form content is valid if (f.valid) { this.api.saveComment(this.newComment, this.id).subscribe( data => { // close modal document.getElementById('closeModal').click(); // reset fields of form this.resetForm(f); this.loadComments(false); }, (err) => { this.errorHandler(err); // check if status does not contain no response from backend if (err.status !== 0) { // reload comments this.loadComments(false); } }, ); } }; } /** * Triggered if popover is opened and closed. * @param idForDelete the comment id on which popover was triggered */ private deleteCommentId(idForDelete: number) { if (this.deleteId == null) { // set new value -> opened popover this.deleteId = idForDelete; } else if (this.deleteId === idForDelete) { // same value -> closed popover this.deleteId = null; } else { // id changed -> close old popover this.closePopover(); // set new id this.deleteId = idForDelete; } } /** * Close popover manually if user opens another one. */ private closePopover() { let buttonDelete = <HTMLButtonElement> document.getElementById(this.deleteId.toString()); buttonDelete.click(); this.deleteId = null; } /** * Delete comment at backend. */ private deleteCommentBackend() { this.api.deleteComment(this.id, this.deleteId).subscribe( (data) => { // successfully deleted comment at backend // load comments this.loadComments(true); // close popover this.closePopover(); }, (err) => { this.errorHandler(err); // check if status does not contain no response from backend if (err.status !== 0) { // reload comments this.loadComments(false); } }, ); } /** * Update a comment. * * @param id the id of the comment shich should be updated */ private updateComment(id: number) { // save changes at backend let index = this.comments.findIndex(x => x.id === id); let updatedComment: Comment = this.comments[index]; this.api.updateComment(updatedComment, this.id, updatedComment.id).subscribe((data) => { // // update comment in array, prevent animation of comment let result: Comment = <Comment> data; this.comments[index].content = result.content; this.comments[index].publish = result.publish; this.comments[index].pageNumber = result.pageNumber; this.comments[index].author = result.author; this.comments[index].page = result.page; this.comments[index].alterationDate = result.alterationDate; this.comments[index].date = result.date; this.selectedComment = null; this.hiddenModal = true; }, (err) => { this.errorHandler(err); // check if status does not contain no response from backend if (err.status !== 0) { // reload comments this.loadComments(false); } }, ); } resetForm(f: NgForm) { f.resetForm({isPublic: true}); } private errorHandler(err: any) { // show error to user this.httpErrorMsg = getErrorMessage(err); } /** * Called if iFrame is loaded. Check if PDF viewer element exists, if yes add listener to scroll event. **/ private loadedIFrame(): void { try { // check if iFrame element is loaded this.pdfViewerScroll = <HTMLDivElement> (<HTMLIFrameElement> document.getElementById('viewerIFrame')) .contentWindow.document.getElementById('viewerContainer'); if (this.pdfViewerScroll != null) { // add listener to scroll event this.pdfViewerScroll.addEventListener('scroll', this.listenerIFrame); // get current page numbers this.loadCurrentPdfPage(); } } catch (e) { // not loaded yet } } currentPageNumber: number = -1; /** * Get current shown real page number and sequential page number of PDF. **/ private loadCurrentPdfPage(): void { try { this.inputElementPage = <HTMLInputElement>(<HTMLIFrameElement> document.getElementById('viewerIFrame')) .contentWindow.document.getElementById('pageNumber'); this.inputElementPageNumber = <HTMLSpanElement>(<HTMLIFrameElement> document.getElementById('viewerIFrame')) .contentWindow.document.getElementById('numPages'); if (this.inputElementPage != null && this.inputElementPageNumber != null) { // get current page from PDF viewer this.newComment.page = this.inputElementPage.value; // get continuous page number let tempNumberString = this.inputElementPageNumber.innerText; let regexp: RegExp = /[0-9]*\svon\s[0-9]*/; if (regexp.test(tempNumberString)) { this.newComment.pageNumber = Number(tempNumberString.substring(1, tempNumberString.indexOf(' '))); } else { this.newComment.pageNumber = Number(this.newComment.page); } let tempValue = this.newComment.pageNumber; // set current page if changed if (this.currentPageNumber === -1 || this.currentPageNumber !== this.newComment.pageNumber) { // remove page number -> fade out comments of page this.currentPageNumber = -1; // show modal if comment was edited and search mode is not activated // if search mode is activated the comment is not hidden on change of PDF page if (!(this.queryString != null && this.queryString !== '') && this.commentChanged()) { this.showModalChangedComment(); } // set new page number after timeout -> fade in comments after comments from other page are invisible setTimeout(() => { // deselect comment if page changes, search is deactivated and comment is not modified if (!(this.queryString != null && this.queryString !== '') && !this.commentChanged()) { this.selectedComment = null; } // filter out fast scrolling if (tempValue === this.newComment.pageNumber) { // set new page number this.currentPageNumber = this.newComment.pageNumber; } }, 300); // 0.3sec } } } catch (e) { // elements not loaded } } ngAfterViewInit() { // add listener to window to get informed about page changes of iframe content window.addEventListener('message', this.listenerWindow); } ngOnDestroy() { // close modals if page is changed document.getElementById('closeModalChanges').click(); document.getElementById('closeModal').click(); // remove event listener try { this.pdfViewerScroll.removeEventListener('scroll', this.listenerIFrame); window.removeEventListener('message', this.listenerWindow); } catch (e) { // listener not defined because no PDF exists for reference } // release object URL of PDF file try { if (this.pdfUrl !== '') { URL.revokeObjectURL(this.pdfUrl); } } catch (e) { console.log(e); } // unsubscribe from url parameter id this.subParam.unsubscribe(); } }
the_stack
import { Authority } from "../../src/authority/Authority"; import { INetworkModule, NetworkRequestOptions } from "../../src/network/INetworkModule"; import { Constants } from "../../src/utils/Constants"; import { TEST_URIS, RANDOM_TEST_GUID, DEFAULT_OPENID_CONFIG_RESPONSE, TEST_CONFIG, DEFAULT_TENANT_DISCOVERY_RESPONSE, B2C_OPENID_CONFIG_RESPONSE } from "../test_kit/StringConstants"; import { ClientConfigurationErrorMessage, ClientConfigurationError } from "../../src/error/ClientConfigurationError"; import { MockStorageClass, mockCrypto } from "../client/ClientTestUtils"; import { ClientAuthErrorMessage, ClientAuthError } from "../../src/error/ClientAuthError"; import { AuthorityOptions } from "../../src/authority/AuthorityOptions"; import { ProtocolMode } from "../../src/authority/ProtocolMode"; import { AuthorityMetadataEntity } from "../../src/cache/entities/AuthorityMetadataEntity"; let mockStorage: MockStorageClass; const authorityOptions: AuthorityOptions = { protocolMode: ProtocolMode.AAD, knownAuthorities: [Constants.DEFAULT_AUTHORITY_HOST], cloudDiscoveryMetadata: "", authorityMetadata: "" } describe("Authority.ts Class Unit Tests", () => { beforeEach(() => { mockStorage = new MockStorageClass(TEST_CONFIG.MSAL_CLIENT_ID, mockCrypto); }); afterEach(() => { jest.restoreAllMocks(); }); describe("Constructor", () => { it("Creates canonical authority uri based on given uri (and normalizes with '/')", () => { const networkInterface: INetworkModule = { sendGetRequestAsync<T>(url: string, options?: NetworkRequestOptions): T { // @ts-ignore return null; }, sendPostRequestAsync<T>(url: string, options?: NetworkRequestOptions): T { // @ts-ignore return null; } }; const authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, authorityOptions); expect(authority.canonicalAuthority).toBe(`${Constants.DEFAULT_AUTHORITY}`); }); it("Throws error if URI is not in valid format", () => { const networkInterface: INetworkModule = { sendGetRequestAsync<T>(url: string, options?: NetworkRequestOptions): T { // @ts-ignore return null; }, sendPostRequestAsync<T>(url: string, options?: NetworkRequestOptions): T { // @ts-ignore return null; } }; expect(() => new Authority("http://login.microsoftonline.com/common", networkInterface, mockStorage, authorityOptions)).toThrowError(ClientConfigurationErrorMessage.authorityUriInsecure.desc); expect(() => new Authority("This is not a URI", networkInterface, mockStorage, authorityOptions)).toThrowError(ClientConfigurationErrorMessage.urlParseError.desc); expect(() => new Authority("", networkInterface, mockStorage, authorityOptions)).toThrowError(ClientConfigurationErrorMessage.urlEmptyError.desc); }); }); describe("Getters and setters", () => { const networkInterface: INetworkModule = { sendGetRequestAsync<T>(url: string, options?: NetworkRequestOptions): T { // @ts-ignore return null; }, sendPostRequestAsync<T>(url: string, options?: NetworkRequestOptions): T { // @ts-ignore return null; } }; let authority: Authority; beforeEach(() => { authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, authorityOptions); }); it("Gets canonical authority that ends in '/'", () => { expect(authority.canonicalAuthority.endsWith("/")).toBe(true); expect(authority.canonicalAuthority).toBe(`${Constants.DEFAULT_AUTHORITY}`); }); it("Set canonical authority performs validation and canonicalization on url", () => { expect(() => authority.canonicalAuthority = "http://login.microsoftonline.com/common").toThrowError(ClientConfigurationErrorMessage.authorityUriInsecure.desc); expect(() => authority.canonicalAuthority = "https://login.microsoftonline.com/").not.toThrowError(); expect(() => authority.canonicalAuthority = "This is not a URI").toThrowError(ClientConfigurationErrorMessage.urlParseError.desc); authority.canonicalAuthority = `${TEST_URIS.ALTERNATE_INSTANCE}/${RANDOM_TEST_GUID}`; expect(authority.canonicalAuthority.endsWith("/")).toBe(true); expect(authority.canonicalAuthority).toBe(`${TEST_URIS.ALTERNATE_INSTANCE}/${RANDOM_TEST_GUID}/`); }); it("Get canonicalAuthorityUrlComponents returns current url components", () => { expect(authority.canonicalAuthorityUrlComponents.Protocol).toBe("https:"); expect(authority.canonicalAuthorityUrlComponents.HostNameAndPort).toBe("login.microsoftonline.com"); expect(authority.canonicalAuthorityUrlComponents.PathSegments).toEqual(["common"]); expect(authority.canonicalAuthorityUrlComponents.AbsolutePath).toBe("/common/"); expect(authority.canonicalAuthorityUrlComponents.Hash).toBeUndefined(); expect(authority.canonicalAuthorityUrlComponents.Search).toBeUndefined(); }); it("tenant is equal to first path segment value", () => { expect(authority.tenant).toBe("common"); expect(authority.tenant).toBe(authority.canonicalAuthorityUrlComponents.PathSegments[0]); }); it("Gets options that were passed into constructor", () => { expect(authority.options).toBe(authorityOptions); }); describe("OAuth Endpoints", () => { beforeEach(async () => { jest.spyOn(Authority.prototype, <any>"getEndpointMetadataFromNetwork").mockResolvedValue(DEFAULT_OPENID_CONFIG_RESPONSE.body); await authority.resolveEndpointsAsync(); }); it("Returns authorization_endpoint of tenantDiscoveryResponse", () => { expect(authority.authorizationEndpoint).toBe( DEFAULT_OPENID_CONFIG_RESPONSE.body.authorization_endpoint.replace("{tenant}", "common") ); }); it("Returns token_endpoint of tenantDiscoveryResponse", () => { expect(authority.tokenEndpoint).toBe( DEFAULT_OPENID_CONFIG_RESPONSE.body.token_endpoint.replace("{tenant}", "common") ); }); it("Returns end_session_endpoint of tenantDiscoveryResponse", () => { expect(authority.endSessionEndpoint).toBe( DEFAULT_OPENID_CONFIG_RESPONSE.body.end_session_endpoint.replace("{tenant}", "common") ); }); it("Returns issuer of tenantDiscoveryResponse for selfSignedJwtAudience", () => { expect(authority.selfSignedJwtAudience).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.issuer.replace("{tenant}", "common")); }); it("Throws error if endpoint discovery is incomplete for authorizationEndpoint, tokenEndpoint, endSessionEndpoint and selfSignedJwtAudience", () => { authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, authorityOptions); expect(() => authority.authorizationEndpoint).toThrowError(ClientAuthErrorMessage.endpointResolutionError.desc); expect(() => authority.tokenEndpoint).toThrowError(ClientAuthErrorMessage.endpointResolutionError.desc); expect(() => authority.endSessionEndpoint).toThrowError(ClientAuthErrorMessage.endpointResolutionError.desc); expect(() => authority.deviceCodeEndpoint).toThrowError(ClientAuthErrorMessage.endpointResolutionError.desc); expect(() => authority.selfSignedJwtAudience).toThrowError(ClientAuthErrorMessage.endpointResolutionError.desc); }); it("Returns endpoints for different b2c policy than what is cached", async () => { jest.clearAllMocks(); const signInPolicy = "b2c_1_sisopolicy"; const resetPolicy = "b2c_1_password_reset"; const baseAuthority = "https://login.microsoftonline.com/tfp/msidlabb2c.onmicrosoft.com/"; jest.spyOn(Authority.prototype, <any>"getEndpointMetadataFromNetwork").mockResolvedValue(B2C_OPENID_CONFIG_RESPONSE.body); authority = new Authority(`${baseAuthority}${signInPolicy}`, networkInterface, mockStorage, authorityOptions); await authority.resolveEndpointsAsync(); const secondAuthority = new Authority(`${baseAuthority}${resetPolicy}`, networkInterface, mockStorage, authorityOptions); await secondAuthority.resolveEndpointsAsync(); expect(authority.authorizationEndpoint).toBe(B2C_OPENID_CONFIG_RESPONSE.body.authorization_endpoint); expect(secondAuthority.authorizationEndpoint).toBe( B2C_OPENID_CONFIG_RESPONSE.body.authorization_endpoint.replace(signInPolicy, resetPolicy) ); expect(authority.tokenEndpoint).toBe(B2C_OPENID_CONFIG_RESPONSE.body.token_endpoint); expect(secondAuthority.tokenEndpoint).toBe( B2C_OPENID_CONFIG_RESPONSE.body.token_endpoint.replace(signInPolicy, resetPolicy) ); expect(authority.endSessionEndpoint).toBe(B2C_OPENID_CONFIG_RESPONSE.body.end_session_endpoint); expect(secondAuthority.endSessionEndpoint).toBe( B2C_OPENID_CONFIG_RESPONSE.body.end_session_endpoint.replace(signInPolicy, resetPolicy) ); }); }); }); describe("Regional authorities", () => { const networkInterface: INetworkModule = { sendGetRequestAsync<T>(url: string, options?: NetworkRequestOptions): T { return {} as T; }, sendPostRequestAsync<T>(url: string, options?: NetworkRequestOptions): T { return {} as T; } }; const authorityOptions = { protocolMode: ProtocolMode.AAD, knownAuthorities: [Constants.DEFAULT_AUTHORITY_HOST], cloudDiscoveryMetadata: "", authorityMetadata: "", azureRegionConfiguration: { azureRegion: "westus2", environmentRegion: undefined } }; it("discovery endpoint metadata is updated with regional information when the region is provided", async () => { const deepCopyOpenIdResponse = JSON.parse(JSON.stringify(DEFAULT_OPENID_CONFIG_RESPONSE)); networkInterface.sendGetRequestAsync = (url: string, options?: NetworkRequestOptions): any => { return JSON.parse(JSON.stringify(DEFAULT_OPENID_CONFIG_RESPONSE)); }; const authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, authorityOptions); await authority.resolveEndpointsAsync(); expect(authority.discoveryComplete()).toBe(true); expect(authority.authorizationEndpoint).toEqual(`${deepCopyOpenIdResponse.body.authorization_endpoint.replace("{tenant}", "common").replace("login.microsoftonline.com", "westus2.login.microsoft.com")}/`); expect(authority.tokenEndpoint).toEqual(`${deepCopyOpenIdResponse.body.token_endpoint.replace("{tenant}", "common").replace("login.microsoftonline.com", "westus2.login.microsoft.com")}/?allowestsrnonmsi=true`); expect(authority.endSessionEndpoint).toEqual(`${deepCopyOpenIdResponse.body.end_session_endpoint.replace("{tenant}", "common").replace("login.microsoftonline.com", "westus2.login.microsoft.com")}/`); }); it("region provided by the user overrides the region auto-discovered", async () => { const deepCopyOpenIdResponse = JSON.parse(JSON.stringify(DEFAULT_OPENID_CONFIG_RESPONSE)); networkInterface.sendGetRequestAsync = (url: string, options?: NetworkRequestOptions): any => { return JSON.parse(JSON.stringify(DEFAULT_OPENID_CONFIG_RESPONSE)); }; const authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, {...authorityOptions, azureRegionConfiguration: { azureRegion: "westus2", environmentRegion: "centralus" }}); await authority.resolveEndpointsAsync(); expect(authority.discoveryComplete()).toBe(true); expect(authority.authorizationEndpoint).toEqual(`${deepCopyOpenIdResponse.body.authorization_endpoint.replace("{tenant}", "common").replace("login.microsoftonline.com", "westus2.login.microsoft.com")}/`); expect(authority.tokenEndpoint).toEqual(`${deepCopyOpenIdResponse.body.token_endpoint.replace("{tenant}", "common").replace("login.microsoftonline.com", "westus2.login.microsoft.com")}/?allowestsrnonmsi=true`); expect(authority.endSessionEndpoint).toEqual(`${deepCopyOpenIdResponse.body.end_session_endpoint.replace("{tenant}", "common").replace("login.microsoftonline.com", "westus2.login.microsoft.com")}/`); }); it("auto discovered region only used when the user provides the AUTO_DISCOVER flag", async () => { const deepCopyOpenIdResponse = JSON.parse(JSON.stringify(DEFAULT_OPENID_CONFIG_RESPONSE)); networkInterface.sendGetRequestAsync = (url: string, options?: NetworkRequestOptions): any => { return JSON.parse(JSON.stringify(DEFAULT_OPENID_CONFIG_RESPONSE)); }; const authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, {...authorityOptions, azureRegionConfiguration: { azureRegion: Constants.AZURE_REGION_AUTO_DISCOVER_FLAG, environmentRegion: "centralus" }}); await authority.resolveEndpointsAsync(); expect(authority.discoveryComplete()).toBe(true); expect(authority.authorizationEndpoint).toEqual(`${deepCopyOpenIdResponse.body.authorization_endpoint.replace("{tenant}", "common").replace("login.microsoftonline.com", "centralus.login.microsoft.com")}/`); expect(authority.tokenEndpoint).toEqual(`${deepCopyOpenIdResponse.body.token_endpoint.replace("{tenant}", "common").replace("login.microsoftonline.com", "centralus.login.microsoft.com")}/?allowestsrnonmsi=true`); expect(authority.endSessionEndpoint).toEqual(`${deepCopyOpenIdResponse.body.end_session_endpoint.replace("{tenant}", "common").replace("login.microsoftonline.com", "centralus.login.microsoft.com")}/`); }); it("fallbacks to the global endpoint when the user provides the AUTO_DISCOVER flag but no region is detected", async () => { const deepCopyOpenIdResponse = JSON.parse(JSON.stringify(DEFAULT_OPENID_CONFIG_RESPONSE)); networkInterface.sendGetRequestAsync = (url: string, options?: NetworkRequestOptions): any => { return JSON.parse(JSON.stringify(DEFAULT_OPENID_CONFIG_RESPONSE)); }; const authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, {...authorityOptions, azureRegionConfiguration: { azureRegion: Constants.AZURE_REGION_AUTO_DISCOVER_FLAG, environmentRegion: undefined }}); await authority.resolveEndpointsAsync(); expect(authority.discoveryComplete()).toBe(true); expect(authority.authorizationEndpoint).toEqual(deepCopyOpenIdResponse.body.authorization_endpoint.replace("{tenant}", "common")); expect(authority.tokenEndpoint).toEqual(deepCopyOpenIdResponse.body.token_endpoint.replace("{tenant}", "common")); expect(authority.endSessionEndpoint).toEqual(deepCopyOpenIdResponse.body.end_session_endpoint.replace("{tenant}", "common")); }) }) describe("Endpoint discovery", () => { const networkInterface: INetworkModule = { sendGetRequestAsync<T>(url: string, options?: NetworkRequestOptions): T { // @ts-ignore return null; }, sendPostRequestAsync<T>(url: string, options?: NetworkRequestOptions): T { // @ts-ignore return null; } }; let authority: Authority; beforeEach(() => { authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, authorityOptions); }); it("discoveryComplete returns false if endpoint discovery has not been completed", () => { expect(authority.discoveryComplete()).toBe(false); }); it("discoveryComplete returns true if resolveEndpointsAsync resolves successfully", async () => { jest.spyOn(Authority.prototype, <any>"getEndpointMetadataFromNetwork").mockResolvedValue(DEFAULT_OPENID_CONFIG_RESPONSE.body); await authority.resolveEndpointsAsync(); expect(authority.discoveryComplete()).toBe(true); }); describe("Endpoint Metadata", () => { it("Gets endpoints from config", async () => { const options = { protocolMode: ProtocolMode.AAD, knownAuthorities: [Constants.DEFAULT_AUTHORITY_HOST], cloudDiscoveryMetadata: "", authorityMetadata: JSON.stringify(DEFAULT_OPENID_CONFIG_RESPONSE.body) }; authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, options); await authority.resolveEndpointsAsync(); expect(authority.discoveryComplete()).toBe(true); expect(authority.authorizationEndpoint).toBe( DEFAULT_OPENID_CONFIG_RESPONSE.body.authorization_endpoint.replace("{tenant}", "common") ); expect(authority.tokenEndpoint).toBe( DEFAULT_OPENID_CONFIG_RESPONSE.body.token_endpoint.replace("{tenant}", "common") ); expect(authority.deviceCodeEndpoint).toBe(authority.tokenEndpoint.replace("/token", "/devicecode")); expect(authority.endSessionEndpoint).toBe( DEFAULT_OPENID_CONFIG_RESPONSE.body.end_session_endpoint.replace("{tenant}", "common") ); expect(authority.selfSignedJwtAudience).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.issuer.replace("{tenant}", "common")); // Test that the metadata is cached const key = `authority-metadata-${TEST_CONFIG.MSAL_CLIENT_ID}-${Constants.DEFAULT_AUTHORITY_HOST}`; const cachedAuthorityMetadata = mockStorage.getAuthorityMetadata(key); if (!cachedAuthorityMetadata) { throw Error("Cached AuthorityMetadata should not be null!"); } else { expect(cachedAuthorityMetadata.authorization_endpoint).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.authorization_endpoint); expect(cachedAuthorityMetadata.token_endpoint).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.token_endpoint); expect(cachedAuthorityMetadata.end_session_endpoint).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.end_session_endpoint); expect(cachedAuthorityMetadata.issuer).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.issuer); expect(cachedAuthorityMetadata.endpointsFromNetwork).toBe(false); } }); it("Throws error if authorityMetadata cannot be parsed to json", (done) => { const options = { protocolMode: ProtocolMode.AAD, knownAuthorities: [Constants.DEFAULT_AUTHORITY_HOST], cloudDiscoveryMetadata: "", authorityMetadata: "invalid-json" }; authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, options); authority.resolveEndpointsAsync().catch(e => { expect(e).toBeInstanceOf(ClientConfigurationError); expect(e.errorMessage).toBe(ClientConfigurationErrorMessage.invalidAuthorityMetadata.desc); done(); }); }); it("Gets endpoints from cache", async () => { const key = `authority-metadata-${TEST_CONFIG.MSAL_CLIENT_ID}-${Constants.DEFAULT_AUTHORITY_HOST}`; const value = new AuthorityMetadataEntity(); value.updateCloudDiscoveryMetadata(DEFAULT_TENANT_DISCOVERY_RESPONSE.body.metadata[0], true); value.updateEndpointMetadata(DEFAULT_OPENID_CONFIG_RESPONSE.body, true); value.updateCanonicalAuthority(Constants.DEFAULT_AUTHORITY); mockStorage.setAuthorityMetadata(key, value); authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, authorityOptions); await authority.resolveEndpointsAsync(); expect(authority.discoveryComplete()).toBe(true); expect(authority.authorizationEndpoint).toBe( DEFAULT_OPENID_CONFIG_RESPONSE.body.authorization_endpoint.replace("{tenant}", "common") ); expect(authority.tokenEndpoint).toBe( DEFAULT_OPENID_CONFIG_RESPONSE.body.token_endpoint.replace("{tenant}", "common") ); expect(authority.deviceCodeEndpoint).toBe(authority.tokenEndpoint.replace("/token", "/devicecode")); expect(authority.endSessionEndpoint).toBe( DEFAULT_OPENID_CONFIG_RESPONSE.body.end_session_endpoint.replace("{tenant}", "common") ); expect(authority.selfSignedJwtAudience).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.issuer.replace("{tenant}", "common")); // Test that the metadata is cached const cachedAuthorityMetadata = mockStorage.getAuthorityMetadata(key); if (!cachedAuthorityMetadata) { throw Error("Cached AuthorityMetadata should not be null!"); } else { expect(cachedAuthorityMetadata.authorization_endpoint).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.authorization_endpoint); expect(cachedAuthorityMetadata.token_endpoint).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.token_endpoint); expect(cachedAuthorityMetadata.end_session_endpoint).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.end_session_endpoint); expect(cachedAuthorityMetadata.issuer).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.issuer); expect(cachedAuthorityMetadata.endpointsFromNetwork).toBe(true); } }); it("Gets endpoints from network if cached metadata is expired", async () => { const key = `authority-metadata-${TEST_CONFIG.MSAL_CLIENT_ID}-${Constants.DEFAULT_AUTHORITY_HOST}`; const value = new AuthorityMetadataEntity(); value.updateCloudDiscoveryMetadata(DEFAULT_TENANT_DISCOVERY_RESPONSE.body.metadata[0], true); value.updateEndpointMetadata(DEFAULT_OPENID_CONFIG_RESPONSE.body, true); value.updateCanonicalAuthority(Constants.DEFAULT_AUTHORITY); mockStorage.setAuthorityMetadata(key, value); jest.spyOn(AuthorityMetadataEntity.prototype, "isExpired").mockReturnValue(true); networkInterface.sendGetRequestAsync = (url: string, options?: NetworkRequestOptions): any => { return DEFAULT_OPENID_CONFIG_RESPONSE; }; authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, authorityOptions); await authority.resolveEndpointsAsync(); expect(authority.discoveryComplete()).toBe(true); expect(authority.authorizationEndpoint).toBe( DEFAULT_OPENID_CONFIG_RESPONSE.body.authorization_endpoint.replace("{tenant}", "common") ); expect(authority.tokenEndpoint).toBe( DEFAULT_OPENID_CONFIG_RESPONSE.body.token_endpoint.replace("{tenant}", "common") ); expect(authority.deviceCodeEndpoint).toBe(authority.tokenEndpoint.replace("/token", "/devicecode")); expect(authority.endSessionEndpoint).toBe( DEFAULT_OPENID_CONFIG_RESPONSE.body.end_session_endpoint.replace("{tenant}", "common") ); expect(authority.selfSignedJwtAudience).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.issuer.replace("{tenant}", "common")); // Test that the metadata is cached const cachedAuthorityMetadata = mockStorage.getAuthorityMetadata(key); if (!cachedAuthorityMetadata) { throw Error("Cached AuthorityMetadata should not be null!"); } else { expect(cachedAuthorityMetadata.authorization_endpoint).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.authorization_endpoint); expect(cachedAuthorityMetadata.token_endpoint).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.token_endpoint); expect(cachedAuthorityMetadata.end_session_endpoint).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.end_session_endpoint); expect(cachedAuthorityMetadata.issuer).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.issuer); expect(cachedAuthorityMetadata.endpointsFromNetwork).toBe(true); } }); it("Gets endpoints from network", async () => { networkInterface.sendGetRequestAsync = (url: string, options?: NetworkRequestOptions): any => { return DEFAULT_OPENID_CONFIG_RESPONSE; }; authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, authorityOptions); await authority.resolveEndpointsAsync(); expect(authority.discoveryComplete()).toBe(true); expect(authority.authorizationEndpoint).toBe( DEFAULT_OPENID_CONFIG_RESPONSE.body.authorization_endpoint.replace("{tenant}", "common") ); expect(authority.tokenEndpoint).toBe( DEFAULT_OPENID_CONFIG_RESPONSE.body.token_endpoint.replace("{tenant}", "common") ); expect(authority.deviceCodeEndpoint).toBe(authority.tokenEndpoint.replace("/token", "/devicecode")); expect(authority.endSessionEndpoint).toBe( DEFAULT_OPENID_CONFIG_RESPONSE.body.end_session_endpoint.replace("{tenant}", "common") ); expect(authority.selfSignedJwtAudience).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.issuer.replace("{tenant}", "common")); // Test that the metadata is cached const key = `authority-metadata-${TEST_CONFIG.MSAL_CLIENT_ID}-${Constants.DEFAULT_AUTHORITY_HOST}`; const cachedAuthorityMetadata = mockStorage.getAuthorityMetadata(key); if (!cachedAuthorityMetadata) { throw Error("Cached AuthorityMetadata should not be null!"); } else { expect(cachedAuthorityMetadata.authorization_endpoint).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.authorization_endpoint); expect(cachedAuthorityMetadata.token_endpoint).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.token_endpoint); expect(cachedAuthorityMetadata.end_session_endpoint).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.end_session_endpoint); expect(cachedAuthorityMetadata.issuer).toBe(DEFAULT_OPENID_CONFIG_RESPONSE.body.issuer); expect(cachedAuthorityMetadata.endpointsFromNetwork).toBe(true); } }); it("Throws error if openid-configuration network call fails", (done) => { networkInterface.sendGetRequestAsync = (url: string, options?: NetworkRequestOptions): any => { throw Error("Unable to reach endpoint"); }; authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, authorityOptions); authority.resolveEndpointsAsync().catch(e => { expect(e).toBeInstanceOf(ClientAuthError); expect(e.errorMessage.includes(ClientAuthErrorMessage.unableToGetOpenidConfigError.desc)).toBe(true); done(); }); }); }); describe("Cloud Discovery Metadata", () => { it("Sets instance metadata from knownAuthorities config", async () => { const authorityOptions: AuthorityOptions = { protocolMode: ProtocolMode.AAD, knownAuthorities: [Constants.DEFAULT_AUTHORITY_HOST], cloudDiscoveryMetadata: "", authorityMetadata: "" }; networkInterface.sendGetRequestAsync = (url: string, options?: NetworkRequestOptions): any => { return DEFAULT_OPENID_CONFIG_RESPONSE; }; authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, authorityOptions); await authority.resolveEndpointsAsync(); expect(authority.isAlias(Constants.DEFAULT_AUTHORITY_HOST)).toBe(true); expect(authority.getPreferredCache()).toBe(Constants.DEFAULT_AUTHORITY_HOST); expect(authority.canonicalAuthority.includes(Constants.DEFAULT_AUTHORITY_HOST)).toBe(true); // Test that the metadata is cached const key = `authority-metadata-${TEST_CONFIG.MSAL_CLIENT_ID}-${Constants.DEFAULT_AUTHORITY_HOST}`; const cachedAuthorityMetadata = mockStorage.getAuthorityMetadata(key); if (!cachedAuthorityMetadata) { throw Error("Cached AuthorityMetadata should not be null!"); } else { expect(cachedAuthorityMetadata.aliases).toContain(Constants.DEFAULT_AUTHORITY_HOST); expect(cachedAuthorityMetadata.preferred_cache).toBe(Constants.DEFAULT_AUTHORITY_HOST); expect(cachedAuthorityMetadata.preferred_network).toBe(Constants.DEFAULT_AUTHORITY_HOST); expect(cachedAuthorityMetadata.aliasesFromNetwork).toBe(false); } }); it("Sets instance metadata from cloudDiscoveryMetadata config & change canonicalAuthority to preferred_network", async () => { const authorityOptions: AuthorityOptions = { protocolMode: ProtocolMode.AAD, knownAuthorities: [], cloudDiscoveryMetadata: JSON.stringify(DEFAULT_TENANT_DISCOVERY_RESPONSE.body), authorityMetadata: "" }; networkInterface.sendGetRequestAsync = (url: string, options?: NetworkRequestOptions): any => { return DEFAULT_OPENID_CONFIG_RESPONSE; }; authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, authorityOptions); await authority.resolveEndpointsAsync(); expect(authority.isAlias("login.microsoftonline.com")).toBe(true); expect(authority.isAlias("login.windows.net")).toBe(true); expect(authority.isAlias("sts.windows.net")).toBe(true); expect(authority.getPreferredCache()).toBe("sts.windows.net"); expect(authority.canonicalAuthority.includes("login.windows.net")).toBe(true); // Test that the metadata is cached const key = `authority-metadata-${TEST_CONFIG.MSAL_CLIENT_ID}-sts.windows.net`; const cachedAuthorityMetadata = mockStorage.getAuthorityMetadata(key); if (!cachedAuthorityMetadata) { throw Error("Cached AuthorityMetadata should not be null!"); } else { expect(cachedAuthorityMetadata.aliases).toContain("login.microsoftonline.com"); expect(cachedAuthorityMetadata.aliases).toContain("login.windows.net"); expect(cachedAuthorityMetadata.aliases).toContain("sts.windows.net"); expect(cachedAuthorityMetadata.preferred_cache).toBe("sts.windows.net"); expect(cachedAuthorityMetadata.preferred_network).toBe("login.windows.net"); expect(cachedAuthorityMetadata.aliasesFromNetwork).toBe(false); } }); it("Sets instance metadata from cache", async () => { const authorityOptions: AuthorityOptions = { protocolMode: ProtocolMode.AAD, knownAuthorities: [], cloudDiscoveryMetadata: "", authorityMetadata: "" }; const key = `authority-metadata-${TEST_CONFIG.MSAL_CLIENT_ID}-sts.windows.net`; const value = new AuthorityMetadataEntity(); value.updateCloudDiscoveryMetadata(DEFAULT_TENANT_DISCOVERY_RESPONSE.body.metadata[0], true); value.updateCanonicalAuthority(Constants.DEFAULT_AUTHORITY); mockStorage.setAuthorityMetadata(key, value); jest.spyOn(Authority.prototype, <any>"updateEndpointMetadata").mockResolvedValue("cache"); authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, authorityOptions); await authority.resolveEndpointsAsync(); expect(authority.isAlias("login.microsoftonline.com")).toBe(true); expect(authority.isAlias("login.windows.net")).toBe(true); expect(authority.isAlias("sts.windows.net")).toBe(true); expect(authority.getPreferredCache()).toBe("sts.windows.net"); expect(authority.canonicalAuthority.includes("login.windows.net")).toBe(true); // Test that the metadata is cached const cachedAuthorityMetadata = mockStorage.getAuthorityMetadata(key); if (!cachedAuthorityMetadata) { throw Error("Cached AuthorityMetadata should not be null!"); } else { expect(cachedAuthorityMetadata.aliases).toContain("login.microsoftonline.com"); expect(cachedAuthorityMetadata.aliases).toContain("login.windows.net"); expect(cachedAuthorityMetadata.aliases).toContain("sts.windows.net"); expect(cachedAuthorityMetadata.preferred_cache).toBe("sts.windows.net"); expect(cachedAuthorityMetadata.preferred_network).toBe("login.windows.net"); expect(cachedAuthorityMetadata.aliasesFromNetwork).toBe(true); } }); it("Sets instance metadata from network if cached metadata is expired", async () => { const authorityOptions: AuthorityOptions = { protocolMode: ProtocolMode.AAD, knownAuthorities: [], cloudDiscoveryMetadata: "", authorityMetadata: "" } const key = `authority-metadata-${TEST_CONFIG.MSAL_CLIENT_ID}-sts.windows.net`; const value = new AuthorityMetadataEntity(); value.updateCloudDiscoveryMetadata(DEFAULT_TENANT_DISCOVERY_RESPONSE.body.metadata[0], true); value.updateCanonicalAuthority(Constants.DEFAULT_AUTHORITY); mockStorage.setAuthorityMetadata(key, value); jest.spyOn(AuthorityMetadataEntity.prototype, "isExpired").mockReturnValue(true); jest.spyOn(Authority.prototype, <any>"updateEndpointMetadata").mockResolvedValue("cache"); networkInterface.sendGetRequestAsync = (url: string, options?: NetworkRequestOptions): any => { return DEFAULT_TENANT_DISCOVERY_RESPONSE; }; authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, authorityOptions); await authority.resolveEndpointsAsync(); expect(authority.isAlias("login.microsoftonline.com")).toBe(true); expect(authority.isAlias("login.windows.net")).toBe(true); expect(authority.isAlias("sts.windows.net")).toBe(true); expect(authority.getPreferredCache()).toBe("sts.windows.net"); expect(authority.canonicalAuthority.includes("login.windows.net")).toBe(true); // Test that the metadata is cached const cachedAuthorityMetadata = mockStorage.getAuthorityMetadata(key); if (!cachedAuthorityMetadata) { throw Error("Cached AuthorityMetadata should not be null!"); } else { expect(cachedAuthorityMetadata.aliases).toContain("login.microsoftonline.com"); expect(cachedAuthorityMetadata.aliases).toContain("login.windows.net"); expect(cachedAuthorityMetadata.aliases).toContain("sts.windows.net"); expect(cachedAuthorityMetadata.preferred_cache).toBe("sts.windows.net"); expect(cachedAuthorityMetadata.preferred_network).toBe("login.windows.net"); expect(cachedAuthorityMetadata.aliasesFromNetwork).toBe(true); } }); it("Sets instance metadata from network", async () => { const authorityOptions: AuthorityOptions = { protocolMode: ProtocolMode.AAD, knownAuthorities: [], cloudDiscoveryMetadata: "", authorityMetadata: "" } networkInterface.sendGetRequestAsync = (url: string, options?: NetworkRequestOptions): any => { return DEFAULT_TENANT_DISCOVERY_RESPONSE; }; jest.spyOn(Authority.prototype, <any>"updateEndpointMetadata").mockResolvedValue("cache"); authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, authorityOptions); await authority.resolveEndpointsAsync(); expect(authority.isAlias("login.microsoftonline.com")).toBe(true); expect(authority.isAlias("login.windows.net")).toBe(true); expect(authority.isAlias("sts.windows.net")).toBe(true); expect(authority.getPreferredCache()).toBe("sts.windows.net"); expect(authority.canonicalAuthority.includes("login.windows.net")).toBe(true); // Test that the metadata is cached const key = `authority-metadata-${TEST_CONFIG.MSAL_CLIENT_ID}-sts.windows.net`; const cachedAuthorityMetadata = mockStorage.getAuthorityMetadata(key); if (!cachedAuthorityMetadata) { throw Error("Cached AuthorityMetadata should not be null!"); } else { expect(cachedAuthorityMetadata.aliases).toContain("login.microsoftonline.com"); expect(cachedAuthorityMetadata.aliases).toContain("login.windows.net"); expect(cachedAuthorityMetadata.aliases).toContain("sts.windows.net"); expect(cachedAuthorityMetadata.preferred_cache).toBe("sts.windows.net"); expect(cachedAuthorityMetadata.preferred_network).toBe("login.windows.net"); expect(cachedAuthorityMetadata.aliasesFromNetwork).toBe(true); } }); it("Sets metadata from host if network call succeeds but does not explicitly include the host", async () => { const authorityOptions: AuthorityOptions = { protocolMode: ProtocolMode.AAD, knownAuthorities: [], cloudDiscoveryMetadata: "", authorityMetadata: "" } networkInterface.sendGetRequestAsync = (url: string, options?: NetworkRequestOptions): any => { return DEFAULT_TENANT_DISCOVERY_RESPONSE; }; jest.spyOn(Authority.prototype, <any>"updateEndpointMetadata").mockResolvedValue("cache"); authority = new Authority("https://custom-domain.microsoft.com", networkInterface, mockStorage, authorityOptions); await authority.resolveEndpointsAsync(); expect(authority.isAlias("custom-domain.microsoft.com")).toBe(true); expect(authority.getPreferredCache()).toBe("custom-domain.microsoft.com"); expect(authority.canonicalAuthority.includes("custom-domain.microsoft.com")); // Test that the metadata is cached const key = `authority-metadata-${TEST_CONFIG.MSAL_CLIENT_ID}-custom-domain.microsoft.com`; const cachedAuthorityMetadata = mockStorage.getAuthorityMetadata(key); if (!cachedAuthorityMetadata) { throw Error("Cached AuthorityMetadata should not be null!"); } else { expect(cachedAuthorityMetadata.aliases).toContain("custom-domain.microsoft.com"); expect(cachedAuthorityMetadata.preferred_cache).toBe("custom-domain.microsoft.com"); expect(cachedAuthorityMetadata.preferred_network).toBe("custom-domain.microsoft.com"); expect(cachedAuthorityMetadata.aliasesFromNetwork).toBe(true); } }); it("Throws if cloudDiscoveryMetadata cannot be parsed into json", (done) => { const authorityOptions: AuthorityOptions = { protocolMode: ProtocolMode.AAD, knownAuthorities: [], cloudDiscoveryMetadata: "this-is-not-valid-json", authorityMetadata: "" } authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, authorityOptions); authority.resolveEndpointsAsync().catch(e => { expect(e).toBeInstanceOf(ClientConfigurationError); expect(e.errorMessage).toBe(ClientConfigurationErrorMessage.invalidCloudDiscoveryMetadata.desc); done(); }); }); it("throws untrustedAuthority error if host is not part of knownAuthorities, cloudDiscoveryMetadata and instance discovery network call fails", (done) => { const authorityOptions: AuthorityOptions = { protocolMode: ProtocolMode.AAD, knownAuthorities: [], cloudDiscoveryMetadata: "", authorityMetadata: "" }; networkInterface.sendGetRequestAsync = (url: string, options?: NetworkRequestOptions): any => { throw Error("Unable to get response"); }; authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, authorityOptions); authority.resolveEndpointsAsync().catch(e => { expect(e).toBeInstanceOf(ClientConfigurationError); expect(e.errorMessage).toBe(ClientConfigurationErrorMessage.untrustedAuthority.desc); expect(e.errorCode).toBe(ClientConfigurationErrorMessage.untrustedAuthority.code); done(); }); }); it("throws untrustedAuthority error if host is not part of knownAuthorities, cloudDiscoveryMetadata and instance discovery network call doesn't return metadata", (done) => { const authorityOptions: AuthorityOptions = { protocolMode: ProtocolMode.AAD, knownAuthorities: [], cloudDiscoveryMetadata: "", authorityMetadata: "" }; networkInterface.sendGetRequestAsync = (url: string, options?: NetworkRequestOptions): any => { return { body: { error: "This endpoint does not exist" } }; }; authority = new Authority(Constants.DEFAULT_AUTHORITY, networkInterface, mockStorage, authorityOptions); authority.resolveEndpointsAsync().catch(e => { expect(e).toBeInstanceOf(ClientConfigurationError); expect(e.errorMessage).toEqual(ClientConfigurationErrorMessage.untrustedAuthority.desc); expect(e.errorCode).toEqual(ClientConfigurationErrorMessage.untrustedAuthority.code); done(); }); }); it("getPreferredCache throws error if discovery is not complete", () => { expect(() => authority.getPreferredCache()).toThrowError(ClientAuthErrorMessage.endpointResolutionError.desc); }); }); it("ADFS authority uses v1 well-known endpoint", async () => { const authorityUrl = "https://login.microsoftonline.com/adfs/" let endpoint = ""; authority = new Authority(authorityUrl, networkInterface, mockStorage, authorityOptions); jest.spyOn(networkInterface, <any>"sendGetRequestAsync").mockImplementation((openIdConfigEndpoint) => { // @ts-ignore endpoint = openIdConfigEndpoint; return DEFAULT_OPENID_CONFIG_RESPONSE; }); await authority.resolveEndpointsAsync(); expect(endpoint).toBe(`${authorityUrl}.well-known/openid-configuration`); }); it("OIDC ProtocolMode does not append v2 to endpoint", async () => { const authorityUrl = "https://login.microsoftonline.com/" let endpoint = ""; const options = { protocolMode: ProtocolMode.OIDC, knownAuthorities: [Constants.DEFAULT_AUTHORITY], cloudDiscoveryMetadata: "", authorityMetadata: "" } authority = new Authority(authorityUrl, networkInterface, mockStorage, options); jest.spyOn(networkInterface, <any>"sendGetRequestAsync").mockImplementation((openIdConfigEndpoint) => { // @ts-ignore endpoint = openIdConfigEndpoint; return DEFAULT_OPENID_CONFIG_RESPONSE; }); await authority.resolveEndpointsAsync(); expect(endpoint).toBe(`${authorityUrl}.well-known/openid-configuration`); }) }); });
the_stack
import { mockAchievements, mockGoals } from 'src/commons/mocks/AchievementMocks'; import { AchievementGoal, AchievementItem, AchievementStatus, GoalType } from 'src/features/achievement/AchievementTypes'; import AchievementInferencer from '../AchievementInferencer'; // NOTE: changed to not raise errors due to id changing to uuid. Some tests likely will not work. // Especially those that depend on the sorting of the achievements. These have been commented out. const testAchievement: AchievementItem = { uuid: '0', title: 'Test Achievement', xp: 100, isVariableXp: false, isTask: false, prerequisiteUuids: [], goalUuids: [], position: 0, cardBackground: 'https://source-academy-assets.s3-ap-southeast-1.amazonaws.com/achievement/card-background/default.png', view: { coverImage: 'https://source-academy-assets.s3-ap-southeast-1.amazonaws.com/achievement/cover-image/default.png', description: 'This is a test achievement', completionText: `Congratulations! You've completed the test achievement!` } }; const testGoal: AchievementGoal = { uuid: '0', text: 'Test Goal', achievementUuids: [], meta: { type: GoalType.MANUAL, targetCount: 1 }, count: 0, targetCount: 1, completed: false }; const testGoalComplete: AchievementGoal = { uuid: '0', text: 'Test Goal', achievementUuids: [], meta: { type: GoalType.MANUAL, targetCount: 1 }, count: 1, targetCount: 1, completed: true }; describe('Achievement Inferencer Constructor', () => { test('Empty achievements and goals', () => { const inferencer = new AchievementInferencer([], []); expect(inferencer.getAllAchievements()).toEqual([]); expect(inferencer.getAllGoals()).toEqual([]); }); test('Non-empty achievements and empty goals', () => { const inferencer = new AchievementInferencer([testAchievement], []); expect(inferencer.getAllAchievements()).toEqual([testAchievement]); expect(inferencer.getAllGoals()).toEqual([]); }); test('Empty achievements and non-empty goals', () => { const inferencer = new AchievementInferencer([], [testGoal]); expect(inferencer.getAllAchievements()).toEqual([]); expect(inferencer.getAllGoals()).toEqual([testGoal]); }); test('Non-empty achievements and non-empty goals', () => { const inferencer = new AchievementInferencer(mockAchievements, mockGoals); expect(inferencer.getAllAchievements()).toEqual(mockAchievements); expect(inferencer.getAllGoals()).toEqual(mockGoals); }); describe('Overlapping IDs', () => { const testAchievement1: AchievementItem = { ...testAchievement, uuid: '1', title: 'testAchievement1' }; const testAchievement2: AchievementItem = { ...testAchievement, uuid: '2', title: 'testAchievement2' }; const testAchievement3: AchievementItem = { ...testAchievement, uuid: '2', title: 'testAchievement3' }; const testGoal1: AchievementGoal = { ...testGoal, uuid: '1', text: 'testGoal1' }; const testGoal2: AchievementGoal = { ...testGoal, uuid: '1', text: 'testGoal2' }; const testGoal3: AchievementGoal = { ...testGoal, uuid: '2', text: 'testGoal3' }; const inferencer = new AchievementInferencer( [testAchievement1, testAchievement2, testAchievement3], [testGoal1, testGoal2, testGoal3] ); test('Overwrites items of same IDs', () => { expect(inferencer.getAllAchievements()).toEqual([testAchievement1, testAchievement3]); expect(inferencer.getAllGoals()).toEqual([testGoal2, testGoal3]); }); test('References the correct achievements and goals', () => { expect(inferencer.getAchievement('1')).toEqual(testAchievement1); expect(inferencer.getAchievement('2')).not.toEqual(testAchievement2); expect(inferencer.getAchievement('2')).toEqual(testAchievement3); expect(inferencer.getGoal('1')).not.toEqual(testGoal1); expect(inferencer.getGoal('1')).toEqual(testGoal2); expect(inferencer.getGoal('2')).toEqual(testGoal3); expect(inferencer.getGoalDefinition('1')).not.toEqual(testGoal1); expect(inferencer.getGoalDefinition('1')).toEqual(testGoal2); expect(inferencer.getGoalDefinition('2')).toEqual(testGoal3); }); }); }); describe('Achievement Setter', () => { const testAchievement1: AchievementItem = { ...testAchievement, uuid: '1', title: 'Test Achievement 1', prerequisiteUuids: ['2', '2', '3', '3', '3', '4'], goalUuids: ['1', '2', '2', '1'] }; const testGoal1: AchievementGoal = { ...testGoal, uuid: '1', text: 'Test Goal 1' }; const inferencer = new AchievementInferencer(mockAchievements, mockGoals); test('Insert new achievement', () => { // Before insertion expect(inferencer.getAllAchievements().length).toBe(mockAchievements.length); expect(inferencer.getUuidByTitle('Test Achievement 1')).toBeUndefined(); const newUuid = inferencer.insertAchievement(testAchievement1); // After insertion expect(inferencer.getAllAchievements().length).toBe(mockAchievements.length + 1); expect(inferencer.getAchievement('1')).toEqual(mockAchievements[1]); expect(inferencer.getAchievement(newUuid)).toEqual(testAchievement1); expect(inferencer.getTitleByUuid(newUuid)).toBe('Test Achievement 1'); expect(inferencer.getUuidByTitle('Test Achievement 1')).toBe(newUuid); expect(inferencer.getAchievement(newUuid).prerequisiteUuids).toEqual(['2', '3', '4']); expect(inferencer.getAchievement(newUuid).goalUuids).toEqual(['1', '2']); }); test('Insert new goal definition', () => { // Before insertion expect(inferencer.getAllGoals().length).toBe(mockGoals.length); expect(inferencer.getUuidByText('Test Goal 1')).toBeUndefined(); const newUuid = inferencer.insertGoalDefinition(testGoal1); // After insertion expect(inferencer.getAllGoals().length).toBe(mockGoals.length + 1); expect(inferencer.getGoalDefinition('1')).toEqual(mockGoals[1]); expect(inferencer.getGoalDefinition(newUuid)).toEqual(testGoal1); expect(inferencer.getTextByUuid(newUuid)).toBe('Test Goal 1'); expect(inferencer.getUuidByText('Test Goal 1')).toBe(newUuid); }); test('Modify achievement', () => { const newUuid = inferencer.insertAchievement(testAchievement1); const testAchievement2: AchievementItem = { ...testAchievement, uuid: newUuid, title: 'Test Achievement 2' }; // Before modification expect(inferencer.getAchievement(newUuid)).toEqual(testAchievement1); expect(inferencer.getTitleByUuid(newUuid)).toBe('Test Achievement 1'); expect(inferencer.getUuidByTitle('Test Achievement 1')).toBe(newUuid); inferencer.modifyAchievement(testAchievement2); // After modification expect(inferencer.getAchievement(newUuid)).toEqual(testAchievement2); expect(inferencer.getTitleByUuid(newUuid)).toBe('Test Achievement 2'); expect(inferencer.getUuidByTitle('Test Achievement 2')).toBe(newUuid); }); test('Modify goal definition', () => { const newUuid = inferencer.insertGoalDefinition(testGoal1); const testGoal2: AchievementGoal = { ...testGoal, uuid: newUuid, text: 'Test Goal 2' }; // Before modification expect(inferencer.getGoalDefinition(newUuid)).toEqual(testGoal1); expect(inferencer.getTextByUuid(newUuid)).toBe('Test Goal 1'); expect(inferencer.getUuidByText('Test Goal 1')).toBe(newUuid); inferencer.modifyGoalDefinition(testGoal2); // After modification expect(inferencer.getGoalDefinition(newUuid)).toEqual(testGoal2); expect(inferencer.getTextByUuid(newUuid)).toBe('Test Goal 2'); expect(inferencer.getUuidByText('Test Goal 2')).toBe(newUuid); }); test('Remove achievement', () => { const { title } = inferencer.getAchievement('2'); // Before removal expect(inferencer.hasAchievement('2')).toBeTruthy(); expect( inferencer .getAllAchievements() .reduce( (hasPrereq, achievement) => achievement.prerequisiteUuids.find(uuid => uuid === '2') !== undefined || hasPrereq, false ) ).toBeTruthy(); expect(inferencer.getTitleByUuid('2')).toBe(title); expect(inferencer.getUuidByTitle(title)).toBe('2'); inferencer.removeAchievement('2'); // After removal expect(inferencer.hasAchievement('2')).toBeFalsy(); expect( inferencer .getAllAchievements() .reduce( (hasPrereq, achievement) => achievement.prerequisiteUuids.find(uuid => uuid === '2') !== undefined || hasPrereq, false ) ).toBeFalsy(); expect(inferencer.getTitleByUuid('2')).toBe('invalid'); expect(inferencer.getUuidByTitle(title)).toBeUndefined(); }); test('Remove goal definition', () => { const { text } = inferencer.getGoalDefinition('2'); // Before removal expect(inferencer.hasGoal('2')).toBeTruthy(); expect( inferencer .getAllAchievements() .reduce( (hasGoal, achievement) => achievement.goalUuids.find(uuid => uuid === '2') !== undefined || hasGoal, false ) ).toBeTruthy(); expect(inferencer.getTextByUuid('2')).toBe(text); expect(inferencer.getUuidByText(text)).toBe('2'); inferencer.removeGoalDefinition('2'); // After removal expect(inferencer.hasGoal('2')).toBeFalsy(); expect( inferencer .getAllAchievements() .reduce( (hasGoal, achievement) => achievement.goalUuids.find(uuid => uuid === '2') !== undefined || hasGoal, false ) ).toBeFalsy(); expect(inferencer.getTextByUuid('2')).toBe('invalid'); expect(inferencer.getUuidByText(text)).toBeUndefined(); }); }); describe('Achievement Inferencer Getter', () => { // sorting based tests do not work with uuid implementation const inferencer = new AchievementInferencer(mockAchievements, mockGoals); test('Get all achievement IDs', () => { const achievementUuids = ['0', '1', '13', '16', '2', '21', '3', '4', '5', '6', '8', '9']; expect(inferencer.getAllAchievementUuids().sort()).toEqual(achievementUuids); }); test('Get all goal IDs', () => { const goalUuids = ['0', '1', '11', '14', '16', '18', '2', '3', '4', '5', '8']; expect(inferencer.getAllGoalUuids().sort()).toEqual(goalUuids); }); test('List task IDs', () => { const taskUuids = ['0', '1', '13', '16', '21', '4', '5', '8']; expect(inferencer.listTaskUuids().sort()).toEqual(taskUuids); }); test('List sorted task IDs', () => { const sortedTaskUuids = ['1', '5', '0', '8', '21', '4', '16', '13']; expect(inferencer.listSortedTaskUuids()).toEqual(sortedTaskUuids); }); test('List goals', () => { const testAchievement1: AchievementItem = { ...testAchievement, uuid: '1', goalUuids: ['2', '1'] }; const testAchievement2: AchievementItem = { ...testAchievement, uuid: '2', goalUuids: [] }; const testGoal1: AchievementGoal = { ...testGoal, uuid: '1' }; const testGoal2: AchievementGoal = { ...testGoal, uuid: '2' }; const inferencer = new AchievementInferencer( [testAchievement1, testAchievement2], [testGoal1, testGoal2] ); expect(inferencer.listGoals('1').length).toBe(2); expect(inferencer.listGoals('1')[0]).toEqual(testGoal2); expect(inferencer.listGoals('1')[1]).toEqual(testGoal1); expect(inferencer.listGoals('2')).toEqual([]); }); test('List prerequisite goals', () => { const testAchievement1: AchievementItem = { ...testAchievement, uuid: '1', prerequisiteUuids: ['2'] }; const testAchievement2: AchievementItem = { ...testAchievement, uuid: '2', goalUuids: ['2', '1'] }; const testGoal1: AchievementGoal = { ...testGoal, uuid: '1' }; const testGoal2: AchievementGoal = { ...testGoal, uuid: '2' }; const inferencer = new AchievementInferencer( [testAchievement1, testAchievement2], [testGoal1, testGoal2] ); expect(inferencer.listPrerequisiteGoals('1').length).toBe(2); expect(inferencer.listPrerequisiteGoals('1')[0]).toEqual(testGoal2); expect(inferencer.listPrerequisiteGoals('1')[1]).toEqual(testGoal1); }); }); describe('Achievement ID to Title', () => { const achievementUuid = '123'; const achievementTitle = 'AcH1Ev3m3Nt t1tL3 h3R3'; const testAchievement1: AchievementItem = { ...testAchievement, uuid: achievementUuid, title: achievementTitle }; const inferencer = new AchievementInferencer([testAchievement1], []); test('Non-existing achievement ID', () => { expect(inferencer.getTitleByUuid('1')).toBe('invalid'); }); test('Existing achievement ID', () => { expect(inferencer.getTitleByUuid(achievementUuid)).toBe(achievementTitle); }); test('Non-existing achievement title', () => { expect(inferencer.getUuidByTitle('IUisL0v3')).toBeUndefined(); }); test('Existing achievement title', () => { expect(inferencer.getUuidByTitle(achievementTitle)).toBe(achievementUuid); }); }); describe('Goal ID to Text', () => { const goalUuid = '123'; const goalText = 'g0@L T3xt h3R3'; const testGoal1: AchievementGoal = { ...testGoal, uuid: goalUuid, text: goalText }; const inferencer = new AchievementInferencer([], [testGoal1]); test('Non-existing goal ID', () => { expect(inferencer.getTextByUuid('1')).toBe('invalid'); }); test('Existing goal ID', () => { expect(inferencer.getTextByUuid(goalUuid)).toBe(goalText); }); test('Non-existing goal text', () => { expect(inferencer.getUuidByText('IUisL0v3')).toBeUndefined(); }); test('Existing goal text', () => { expect(inferencer.getUuidByText(goalText)).toBe(goalUuid); }); }); describe('Achievement Prerequisite System', () => { const testAchievement1: AchievementItem = { ...testAchievement, uuid: '1', prerequisiteUuids: ['2', '3'] }; const testAchievement2: AchievementItem = { ...testAchievement, uuid: '2' }; const testAchievement3: AchievementItem = { ...testAchievement, uuid: '3', prerequisiteUuids: ['4'] }; const testAchievement4: AchievementItem = { ...testAchievement, uuid: '4', prerequisiteUuids: ['5'] }; const testAchievement5: AchievementItem = { ...testAchievement, uuid: '5' }; const inferencer = new AchievementInferencer( [testAchievement1, testAchievement2, testAchievement3, testAchievement4, testAchievement5], [] ); test('Is immediate children', () => { expect(inferencer.isImmediateChild('1', '2')).toBeTruthy(); expect(inferencer.isImmediateChild('1', '3')).toBeTruthy(); expect(inferencer.isImmediateChild('1', '4')).toBeFalsy(); expect(inferencer.isImmediateChild('1', '5')).toBeFalsy(); expect(inferencer.isImmediateChild('1', '101')).toBeFalsy(); expect(inferencer.isImmediateChild('101', '1')).toBeFalsy(); }); test('Get immediate children', () => { expect(inferencer.getImmediateChildren('1')).toEqual(new Set(['2', '3'])); expect(inferencer.getImmediateChildren('2')).toEqual(new Set()); expect(inferencer.getImmediateChildren('3')).toEqual(new Set(['4'])); expect(inferencer.getImmediateChildren('4')).toEqual(new Set(['5'])); expect(inferencer.getImmediateChildren('101')).toEqual(new Set()); }); test('Is descendant', () => { expect(inferencer.isDescendant('1', '2')).toBeTruthy(); expect(inferencer.isDescendant('1', '3')).toBeTruthy(); expect(inferencer.isDescendant('1', '4')).toBeTruthy(); expect(inferencer.isDescendant('1', '5')).toBeTruthy(); expect(inferencer.isDescendant('1', '101')).toBeFalsy(); expect(inferencer.isDescendant('101', '1')).toBeFalsy(); }); test('Get descendants', () => { expect(inferencer.getDescendants('1')).toEqual(new Set(['2', '3', '4', '5'])); expect(inferencer.getDescendants('2')).toEqual(new Set()); expect(inferencer.getDescendants('3')).toEqual(new Set(['4', '5'])); expect(inferencer.getDescendants('4')).toEqual(new Set(['5'])); expect(inferencer.getDescendants('101')).toEqual(new Set()); }); test('List available prerequisite IDs', () => { expect(inferencer.listAvailablePrerequisiteUuids('1')).toEqual([]); expect(inferencer.listAvailablePrerequisiteUuids('2')).toEqual(['3', '4', '5']); expect(inferencer.listAvailablePrerequisiteUuids('3')).toEqual(['2']); expect(inferencer.listAvailablePrerequisiteUuids('4')).toEqual(['2']); expect(inferencer.listAvailablePrerequisiteUuids('5')).toEqual(['2']); expect(inferencer.listAvailablePrerequisiteUuids('101')).toEqual(['1', '2', '3', '4', '5']); }); }); describe('Achievement XP System', () => { const testAchievement1: AchievementItem = { ...testAchievement, uuid: '1', goalUuids: ['1', '3'] }; const testAchievement2: AchievementItem = { ...testAchievement, uuid: '2', goalUuids: [] }; const testAchievement3: AchievementItem = { ...testAchievement, uuid: '3', goalUuids: ['3'] }; const testGoal1: AchievementGoal = { ...testGoal, uuid: '1' }; const testGoal2: AchievementGoal = { ...testGoal, uuid: '2' }; const testGoal3: AchievementGoal = { ...testGoalComplete, uuid: '3' }; const inferencer = new AchievementInferencer( [testAchievement1, testAchievement2, testAchievement3], [testGoal1, testGoal2, testGoal3] ); test('XP earned from an achievement', () => { expect(inferencer.getAchievementXp('1')).toBe(100); expect(inferencer.getAchievementXp('2')).toBe(100); expect(inferencer.getAchievementXp('3')).toBe(100); expect(inferencer.getAchievementXp('101')).toBe(0); }); test('Total XP earned from all achievements', () => { expect(inferencer.getTotalXp()).toBe(100); }); test('Progress frac from an achievement', () => { expect(inferencer.getProgressFrac('1')).toBe(1 / 2); expect(inferencer.getProgressFrac('2')).toBe(0); expect(inferencer.getProgressFrac('3')).toBe(1); expect(inferencer.getProgressFrac('101')).toBe(0); }); }); describe('Achievement Display Deadline', () => { const expiredDeadline = new Date(1920, 1, 1); const closerExpiredDeadline = new Date(2020, 1, 1); const closestUnexpiredDeadline = new Date(2070, 1, 1); const closerUnexpiredDeadline = new Date(2120, 1, 1); const unexpiredDeadline = new Date(2220, 1, 1); const testAchievement1: AchievementItem = { ...testAchievement, uuid: '1', prerequisiteUuids: ['2', '5'] }; const testAchievement2: AchievementItem = { ...testAchievement, uuid: '2', prerequisiteUuids: ['3', '4'] }; const testAchievement3: AchievementItem = { ...testAchievement, uuid: '3' }; const testAchievement4: AchievementItem = { ...testAchievement, uuid: '4' }; const testAchievement5: AchievementItem = { ...testAchievement, uuid: '5' }; test('All deadlines undefined', () => { const inferencer = new AchievementInferencer( [testAchievement1, testAchievement2, testAchievement3, testAchievement4, testAchievement5], [] ); expect(inferencer.getDisplayDeadline('1')).toBeUndefined(); expect(inferencer.getDisplayDeadline('2')).toBeUndefined(); expect(inferencer.getDisplayDeadline('3')).toBeUndefined(); expect(inferencer.getDisplayDeadline('4')).toBeUndefined(); expect(inferencer.getDisplayDeadline('5')).toBeUndefined(); expect(inferencer.getDisplayDeadline('101')).toBeUndefined(); }); test('All deadlines expired', () => { testAchievement1.deadline = expiredDeadline; testAchievement2.deadline = expiredDeadline; testAchievement3.deadline = expiredDeadline; testAchievement4.deadline = expiredDeadline; testAchievement5.deadline = expiredDeadline; const inferencer = new AchievementInferencer( [testAchievement1, testAchievement2, testAchievement3, testAchievement4, testAchievement5], [] ); expect(inferencer.getDisplayDeadline('1')).toEqual(expiredDeadline); expect(inferencer.getDisplayDeadline('2')).toEqual(expiredDeadline); expect(inferencer.getDisplayDeadline('3')).toEqual(expiredDeadline); expect(inferencer.getDisplayDeadline('4')).toEqual(expiredDeadline); expect(inferencer.getDisplayDeadline('5')).toEqual(expiredDeadline); }); test('Display own deadline if no unexpired descendant deadline', () => { testAchievement1.deadline = expiredDeadline; testAchievement2.deadline = undefined; testAchievement3.deadline = expiredDeadline; testAchievement4.deadline = undefined; testAchievement5.deadline = closerExpiredDeadline; const inferencer = new AchievementInferencer( [testAchievement1, testAchievement2, testAchievement3, testAchievement4, testAchievement5], [] ); expect(inferencer.getDisplayDeadline('1')).toEqual(expiredDeadline); expect(inferencer.getDisplayDeadline('2')).toBeUndefined(); expect(inferencer.getDisplayDeadline('3')).toEqual(expiredDeadline); expect(inferencer.getDisplayDeadline('4')).toBeUndefined(); expect(inferencer.getDisplayDeadline('5')).toEqual(closerExpiredDeadline); }); test('Display closest unexpired deadline', () => { testAchievement1.deadline = undefined; testAchievement2.deadline = expiredDeadline; testAchievement3.deadline = closestUnexpiredDeadline; testAchievement4.deadline = unexpiredDeadline; testAchievement5.deadline = closerUnexpiredDeadline; const inferencer = new AchievementInferencer( [testAchievement1, testAchievement2, testAchievement3, testAchievement4, testAchievement5], [] ); expect(inferencer.getDisplayDeadline('1')).toEqual(closestUnexpiredDeadline); expect(inferencer.getDisplayDeadline('2')).toEqual(closestUnexpiredDeadline); expect(inferencer.getDisplayDeadline('3')).toEqual(closestUnexpiredDeadline); expect(inferencer.getDisplayDeadline('4')).toEqual(unexpiredDeadline); expect(inferencer.getDisplayDeadline('5')).toEqual(closerUnexpiredDeadline); }); }); describe('Achievement Status', () => { const fullyCompleted: AchievementItem = { ...testAchievement, uuid: '1', goalUuids: ['1', '2'] }; const partiallyCompleted: AchievementItem = { ...testAchievement, uuid: '2', goalUuids: ['1', '3'] }; const notCompleted: AchievementItem = { ...testAchievement, uuid: '3', goalUuids: ['3'] }; const emptyGoal: AchievementItem = { ...testAchievement, uuid: '4', goalUuids: [] }; const testGoal1: AchievementGoal = { ...testGoal, uuid: '1', completed: true }; const testGoal2: AchievementGoal = { ...testGoal, uuid: '2', completed: true }; const testGoal3: AchievementGoal = { ...testGoal, uuid: '3', completed: false }; test('Completed status', () => { const inferencer = new AchievementInferencer( [fullyCompleted, partiallyCompleted, notCompleted, emptyGoal], [testGoal1, testGoal2, testGoal3] ); expect(inferencer.getStatus('1')).toBe(AchievementStatus.COMPLETED); expect(inferencer.getStatus('2')).not.toBe(AchievementStatus.COMPLETED); expect(inferencer.getStatus('3')).not.toBe(AchievementStatus.COMPLETED); expect(inferencer.getStatus('4')).not.toBe(AchievementStatus.COMPLETED); }); test('Active & Expired status', () => { const expiredDeadline = new Date(1920, 1, 1); const unexpiredDeadline = new Date(2220, 1, 1); const deadlineExpired: AchievementItem = { ...partiallyCompleted, deadline: expiredDeadline }; const deadlineUnexpired: AchievementItem = { ...notCompleted, deadline: unexpiredDeadline }; const noDeadline: AchievementItem = { ...emptyGoal, deadline: undefined }; const inferencer = new AchievementInferencer( [fullyCompleted, deadlineExpired, deadlineUnexpired, noDeadline], [testGoal1, testGoal2, testGoal3] ); expect(inferencer.getStatus('1')).not.toBe(AchievementStatus.ACTIVE); expect(inferencer.getStatus('2')).not.toBe(AchievementStatus.ACTIVE); expect(inferencer.getStatus('3')).toBe(AchievementStatus.ACTIVE); expect(inferencer.getStatus('4')).toBe(AchievementStatus.ACTIVE); expect(inferencer.getStatus('101')).toBe(AchievementStatus.ACTIVE); expect(inferencer.getStatus('2')).toBe(AchievementStatus.EXPIRED); }); test('Unreleased status', () => { const expiredDeadline = new Date(1920, 1, 1); const unexpiredDeadline = new Date(2220, 1, 1); const unreleased: AchievementItem = { ...partiallyCompleted, release: unexpiredDeadline }; const released: AchievementItem = { ...notCompleted, release: expiredDeadline }; const precompleted: AchievementItem = { ...fullyCompleted, release: unexpiredDeadline }; const inferencer = new AchievementInferencer( [unreleased, released, precompleted], [testGoal1, testGoal2, testGoal3] ); expect(inferencer.getStatus('1')).not.toBe(AchievementStatus.UNRELEASED); expect(inferencer.getStatus('2')).toBe(AchievementStatus.UNRELEASED); expect(inferencer.getStatus('3')).not.toBe(AchievementStatus.UNRELEASED); expect(inferencer.getStatus('1')).toBe(AchievementStatus.COMPLETED); expect(inferencer.getStatus('3')).toBe(AchievementStatus.ACTIVE); }); }); describe('Achievement Position', () => { const listPositions = () => inferencer .getAllAchievements() .filter(achievement => achievement.position !== 0) .map(achievement => achievement.position) .sort((a, b) => a - b); const mockPositions = [1, 2, 3, 4, 5, 6]; const inferencer = new AchievementInferencer(mockAchievements, mockGoals); test('Mock achievement positions', () => { expect(listPositions()).toEqual(mockPositions); }); test('Insert non-task', () => { const testAchievement1: AchievementItem = { ...testAchievement, isTask: false }; inferencer.insertAchievement(testAchievement1); expect(listPositions()).toEqual(mockPositions); }); test('Insert task', () => { const testAchievement1: AchievementItem = { ...testAchievement, isTask: true }; const newUuid = inferencer.insertAchievement(testAchievement1); expect(inferencer.getAchievement(newUuid).position).toBe(1); expect(listPositions()).toEqual([...mockPositions, 7]); inferencer.removeAchievement(newUuid); }); test('Insert task with anchor position', () => { const testAchievement1: AchievementItem = { ...testAchievement, isTask: true, position: 3 }; const newUuid = inferencer.insertAchievement(testAchievement1); expect(inferencer.getAchievement(newUuid).position).toBe(3); expect(listPositions()).toEqual([...mockPositions, 7]); inferencer.removeAchievement(newUuid); }); test('Modify task with anchor position', () => { const testAchievement1: AchievementItem = { ...testAchievement, isTask: true, position: 3 }; const newUuid = inferencer.insertAchievement(testAchievement1); inferencer.modifyAchievement({ ...testAchievement1, position: 2 }); expect(inferencer.getAchievement(newUuid).position).toBe(2); inferencer.modifyAchievement({ ...testAchievement1, position: 7 }); expect(inferencer.getAchievement(newUuid).position).toBe(7); inferencer.modifyAchievement({ ...testAchievement1, position: 10 }); expect(inferencer.getAchievement(newUuid).position).toBe(7); expect(listPositions()).toEqual([...mockPositions, 7]); inferencer.modifyAchievement({ ...testAchievement1, isTask: false, position: 0 }); expect(inferencer.getAchievement(newUuid).position).toBe(0); expect(listPositions()).toEqual(mockPositions); inferencer.removeAchievement(newUuid); }); test('Remove task', () => { const testAchievement1: AchievementItem = { ...testAchievement, isTask: true, position: 4 }; const newUuid = inferencer.insertAchievement(testAchievement1); //Before removal expect(inferencer.getAchievement(newUuid).position).toBe(4); expect(listPositions()).toEqual([...mockPositions, 7]); inferencer.removeAchievement(newUuid); //After removal expect(listPositions()).toEqual(mockPositions); }); test('Remove non-task', () => { const testAchievement1: AchievementItem = { ...testAchievement, isTask: true, position: 4 }; const testAchievement2: AchievementItem = { ...testAchievement, uuid: '1' }; const newUuid = inferencer.insertAchievement(testAchievement1); inferencer.modifyAchievement(testAchievement2); //Before removal expect(inferencer.getAchievement(newUuid).position).toBe(4); expect(listPositions()).toEqual([...mockPositions, 7]); inferencer.removeAchievement('1'); //After removal expect(inferencer.getAchievement(newUuid).position).toBe(4); expect(listPositions()).toEqual([...mockPositions, 7]); }); });
the_stack
import Notifications from '../lib/collections/notifications/collection'; import Messages from '../lib/collections/messages/collection'; import { messageGetLink } from '../lib/helpers'; import Subscriptions from '../lib/collections/subscriptions/collection'; import Users from '../lib/collections/users/collection'; import { userGetProfileUrl } from '../lib/collections/users/helpers'; import { Posts } from '../lib/collections/posts'; import { postGetPageUrl } from '../lib/collections/posts/helpers'; import { Comments } from '../lib/collections/comments/collection' import { commentGetPageUrlFromDB } from '../lib/collections/comments/helpers' import { DebouncerTiming } from './debouncer'; import { ensureIndex } from '../lib/collectionUtils'; import { getNotificationTypeByName } from '../lib/notificationTypes'; import { notificationDebouncers } from './notificationBatching'; import { defaultNotificationTypeSettings } from '../lib/collections/users/custom_fields'; import * as _ from 'underscore'; import { createMutator } from './vulcan-lib/mutators'; import keyBy from 'lodash/keyBy'; import TagRels from '../lib/collections/tagRels/collection'; import { getSiteUrl } from '../lib/vulcan-lib/utils'; import Localgroups from '../lib/collections/localgroups/collection'; /** * Return a list of users (as complete user objects) subscribed to a given * document. This is the union of users who have subscribed to it explicitly, * and users who were subscribed to it by default and didn't suppress the * subscription. * * documentId: The document to look for subscriptions to. * collectionName: The collection the document to look for subscriptions to is in. * type: The type of subscription to check for. * potentiallyDefaultSubscribedUserIds: (Optional) An array of user IDs for * users who are potentially subscribed to this document by default, eg * because they wrote the post being replied to or are an organizer of the * group posted in. * userIsDefaultSubscribed: (Optional. User=>bool) If * potentiallyDefaultSubscribedUserIds is given, takes a user and returns * whether they would be default-subscribed to this document. */ export async function getSubscribedUsers({ documentId, collectionName, type, potentiallyDefaultSubscribedUserIds=null, userIsDefaultSubscribed=null }: { documentId: string|null, collectionName: CollectionNameString, type: string, potentiallyDefaultSubscribedUserIds?: null|Array<string>, userIsDefaultSubscribed?: null|((u:DbUser)=>boolean), }) { if (!documentId) { return []; } const subscriptions = await Subscriptions.find({documentId, type, collectionName, deleted: false, state: 'subscribed'}).fetch() const explicitlySubscribedUserIds = _.pluck(subscriptions, 'userId') const explicitlySubscribedUsers = await Users.find({_id: {$in: explicitlySubscribedUserIds}}).fetch() const explicitlySubscribedUsersDict = keyBy(explicitlySubscribedUsers, u=>u._id); // Handle implicitly subscribed users if (potentiallyDefaultSubscribedUserIds && potentiallyDefaultSubscribedUserIds.length>0) { // Filter explicitly-subscribed users out of the potentially-implicitly-subscribed // users list, since their subscription status is already known potentiallyDefaultSubscribedUserIds = _.filter(potentiallyDefaultSubscribedUserIds, id=>!(id in explicitlySubscribedUsersDict)); // Fetch and filter potentially-subscribed users const potentiallyDefaultSubscribedUsers: Array<DbUser> = await Users.find({ _id: {$in: potentiallyDefaultSubscribedUserIds} }).fetch(); // @ts-ignore @types/underscore annotated this wrong; the filter is optional, if it's null then everything passes const defaultSubscribedUsers: Array<DbUser> = _.filter(potentiallyDefaultSubscribedUsers, userIsDefaultSubscribed); // Check for suppression in the subscriptions table const suppressions = await Subscriptions.find({documentId, type, collectionName, deleted: false, state: "suppressed"}).fetch(); const suppressionsByUserId = keyBy(suppressions, s=>s.userId); const defaultSubscribedUsersNotSuppressed = _.filter(defaultSubscribedUsers, u=>!(u._id in suppressionsByUserId)) return _.union(explicitlySubscribedUsers, defaultSubscribedUsersNotSuppressed); } else { return explicitlySubscribedUsers; } } export async function getUsersWhereLocationIsInNotificationRadius(location): Promise<Array<DbUser>> { return await Users.aggregate([ { "$geoNear": { "near": location, "spherical": true, "distanceField": "distance", "distanceMultiplier": 0.001, "maxDistance": 300000, // 300km is maximum distance we allow to set in the UI "key": "nearbyEventsNotificationsMongoLocation" } }, { "$match": { "$expr": { "$gt": ["$nearbyEventsNotificationsRadius", "$distance"] } } } ]).toArray() } ensureIndex(Users, {nearbyEventsNotificationsMongoLocation: "2dsphere"}, {name: "users.nearbyEventsNotifications"}) const getNotificationTiming = (typeSettings): DebouncerTiming => { switch (typeSettings.batchingFrequency) { case "realtime": return { type: "none" }; case "daily": return { type: "daily", timeOfDayGMT: typeSettings.timeOfDayGMT, }; case "weekly": return { type: "weekly", timeOfDayGMT: typeSettings.timeOfDayGMT, dayOfWeekGMT: typeSettings.dayOfWeekGMT, }; default: // eslint-disable-next-line no-console console.error(`Unrecognized batching frequency: ${typeSettings.batchingFrequency}`); return { type: "none" }; } } const notificationMessage = async (notificationType: string, documentType: string|null, documentId: string|null) => { return await getNotificationTypeByName(notificationType) .getMessage({documentType, documentId}); } const getDocument = async (documentType: string|null, documentId: string|null) => { if (!documentId) return null; switch(documentType) { case "post": return await Posts.findOne(documentId); case "comment": return await Comments.findOne(documentId); case "user": return await Users.findOne(documentId); case "message": return await Messages.findOne(documentId); case "localgroup": return await Localgroups.findOne(documentId); case "tagRel": return await TagRels.findOne(documentId) default: //eslint-disable-next-line no-console console.error(`Invalid documentType type: ${documentType}`); } } const getLink = async (notificationType: string, documentType: string|null, documentId: string|null) => { let document = await getDocument(documentType, documentId); switch(notificationType) { case "emailVerificationRequired": return "/resendVerificationEmail"; default: // Fall through to based on document-type break; } switch(documentType) { case "post": return postGetPageUrl(document as DbPost); case "comment": return await commentGetPageUrlFromDB(document as DbComment); case "user": return userGetProfileUrl(document as DbUser); case "message": return messageGetLink(document as DbMessage); case "localgroup": return `/groups/${documentId}` case "tagRel": const post = await Posts.findOne({_id: (document as DbTagRel).postId}) return postGetPageUrl(post as DbPost); default: //eslint-disable-next-line no-console console.error("Invalid notification type"); } } export const createNotification = async ({userId, notificationType, documentType, documentId, noEmail}:{ userId: string, notificationType: string, documentType: string|null, documentId: string|null, noEmail?: boolean|null }) => { let user = await Users.findOne({ _id:userId }); if (!user) throw Error(`Wasn't able to find user to create notification for with id: ${userId}`) const userSettingField = getNotificationTypeByName(notificationType).userSettingField; const notificationTypeSettings = (userSettingField && user[userSettingField]) ? user[userSettingField] : defaultNotificationTypeSettings; let notificationData = { userId: userId, documentId: documentId||undefined, documentType: documentType||undefined, message: await notificationMessage(notificationType, documentType, documentId), type: notificationType, link: await getLink(notificationType, documentType, documentId), } if (notificationTypeSettings.channel === "onsite" || notificationTypeSettings.channel === "both") { const createdNotification = await createMutator({ collection: Notifications, document: { ...notificationData, emailed: false, waitingForBatch: notificationTypeSettings.batchingFrequency !== "realtime", }, currentUser: user, validate: false }); if (notificationTypeSettings.batchingFrequency !== "realtime") { await notificationDebouncers[notificationType]!.recordEvent({ key: {notificationType, userId}, data: createdNotification.data._id, timing: getNotificationTiming(notificationTypeSettings), af: false, //TODO: Handle AF vs non-AF notifications }); } } if ((notificationTypeSettings.channel === "email" || notificationTypeSettings.channel === "both") && !noEmail) { const createdNotification = await createMutator({ collection: Notifications, document: { ...notificationData, emailed: true, waitingForBatch: true, }, currentUser: user, validate: false }); if (!notificationDebouncers[notificationType]) throw new Error("Invalid notification type"); await notificationDebouncers[notificationType]!.recordEvent({ key: {notificationType, userId}, data: createdNotification.data._id, timing: getNotificationTiming(notificationTypeSettings), af: false, //TODO: Handle AF vs non-AF notifications }); } } export const createNotifications = async ({ userIds, notificationType, documentType, documentId, noEmail }:{ userIds: Array<string> notificationType: string, documentType: string|null, documentId: string|null, noEmail?: boolean|null }) => { return Promise.all( userIds.map(async userId => { await createNotification({userId, notificationType, documentType, documentId, noEmail}); }) ); }
the_stack
import { generateUUID } from "../tools/uuid"; import { credentialsAllowsPurpose, getCredentials, setCredentials } from "./channel"; import { getSharedAppEnv } from "../env/appEnv"; /** * The signature of legacy encrypted credentials * @private */ const LEGACY_SIGNING_KEY = "b~>buttercup/acreds.v2."; /** * The signature of encrypted credentials * @private */ const SIGNING_KEY = "bc~3>"; /** * Sign encrypted content * @see SIGNING_KEY * @private * @param content The encrypted text * @returns The signed key */ function signEncryptedContent(content: string): string { return `${SIGNING_KEY}${content}`; } /** * Remove the signature from encrypted content * @private * @param content The encrypted text * @returns The unsigned encrypted key * @throws {Error} Throws if no SIGNING_KEY is detected * @see SIGNING_KEY */ function unsignEncryptedContent(content: string): string { const newIndex = content.indexOf(SIGNING_KEY); const oldIndex = content.indexOf(LEGACY_SIGNING_KEY); if (newIndex === -1 && oldIndex === -1) { throw new Error("Invalid credentials content (unknown signature)"); } return newIndex === 0 ? content.substr(SIGNING_KEY.length) : content.substr(LEGACY_SIGNING_KEY.length); } /** * Secure credentials storage/transfer class * - Allows for the safe transfer of credentials within the * Buttercup application environment. Will not allow * credentials to be shared or transferred outside of the * environment. Credential properties are stored in memory * and are inaccessible to public functions. * @memberof module:Buttercup */ export default class Credentials { static PURPOSE_DECRYPT_VAULT = "vault-decrypt"; static PURPOSE_ENCRYPT_VAULT = "vault-encrypt"; static PURPOSE_SECURE_EXPORT = "secure-export"; /** * Get all available purposes * @memberof Credentials * @static */ static allPurposes() { return [ Credentials.PURPOSE_DECRYPT_VAULT, Credentials.PURPOSE_ENCRYPT_VAULT, Credentials.PURPOSE_SECURE_EXPORT ]; } /** * Create a new Credentials instance using an existing Credentials * instance - This can be used to reset a credentials's purposes. * @param credentials A credentials instance * @param masterPassword The master password used to * encrypt the instance being cloned * @memberof Credentials * @static * @throws {Error} Throws if no master password provided * @throws {Error} Throws if master password does not match * original */ static fromCredentials(credentials: Credentials, masterPassword: string): Credentials { if (!masterPassword) { throw new Error("Master password is required for credentials cloning"); } const credentialsData = getCredentials(credentials.id); if (credentialsData.masterPassword !== masterPassword) { throw new Error("Master password does not match that of the credentials to be cloned"); } const newData = JSON.parse(JSON.stringify(credentialsData.data)); return new Credentials(newData, masterPassword); } /** * Create a new Credentials instance from a Datasource configuration * @param datasourceConfig The configuration for the * datasource - this usually includes the credential data used for * authenticating against the datasource host platform. * @param masterPassword Optional master password to * store alongside the credentials. Used to create secure strings. * @memberof Credentials * @static */ static fromDatasource(datasourceConfig: Object, masterPassword: string = null): Credentials { return new Credentials( { datasource: datasourceConfig }, masterPassword ); } /** * Create a new Credentials instance from a password * - uses the single password value as the master password stored * alongside the original password if no master password is * provided. The master password is used when generating secure * strings. * @param password The password to store * @param masterPassword Optional master password * to store alongside the credentials. Used to create secure * strings. * @memberof Credentials * @static */ static fromPassword(password: string, masterPassword: string = null): Credentials { const masterPass = masterPassword || password; return new Credentials({ password }, masterPass); } /** * Create a new instance from a secure string * @param content Encrypted content * @param masterPassword The password for decryption * @returns A promise that resolves with the new instance * @static * @memberof Credentials */ static fromSecureString(content: string, masterPassword: string): Promise<Credentials> { const decrypt = getSharedAppEnv().getProperty("crypto/v1/decryptText"); return decrypt(unsignEncryptedContent(content), masterPassword) .then((decryptedContent: string) => JSON.parse(decryptedContent)) .then((credentialsData: any) => { // Handle compatibility updates for legacy credentials if (credentialsData.datasource) { if (typeof credentialsData.datasource === "string") { credentialsData.datasource = JSON.parse(credentialsData.datasource); } // Move username and password INTO the datasource config, as // they relate to the remote connection/source if (credentialsData.username) { credentialsData.datasource.username = credentialsData.username; delete credentialsData.username; } if (credentialsData.password) { credentialsData.datasource.password = credentialsData.password; delete credentialsData.password; } } return new Credentials(credentialsData, masterPassword); }); } /** * Check if a value is an instance of Credentials * @param inst The value to check * @statuc * @memberof Credentials */ static isCredentials(inst: Credentials | any): boolean { return !!inst && typeof inst === "object" && typeof inst.toSecureString === "function" && !!inst.id; } id: string; /** * Create a new Credentials instance * @param obj Object data representing some credentials * @param masterPassword Optional master password to store with * the credentials data, which is used for generating secure strings. */ constructor(obj: Object = {}, masterPassword: string = null) { const id = generateUUID(); Object.defineProperty(this, "id", { writable: false, configurable: false, enumerable: true, value: id }); setCredentials(id, { data: obj, masterPassword, purposes: Credentials.allPurposes(), open: false }); } /** * Get raw credentials data (only available in specialised environments) * @memberof Credentials */ getData(): Object | null { const isClosedEnv = getSharedAppEnv().getProperty("env/v1/isClosedEnv")(); const payload = getCredentials(this.id); if (isClosedEnv || payload.open === true) { return payload; } return null; } /** * Restrict the purposes that this set of credentials * can be used for. Once a purpose is removed it can * no longer be added again to the same instance. * @param allowedPurposes An array of * new allowed purposes. If a purpose mentioned is * not currently permitted, it will be ignored. * @returns Returns self * @memberof Credentials * @example * credentials.restrictPurposes( * Credentials.PURPOSE_SECURE_EXPORT * ); * // credentials can only be exported to an * // encrypted string, and not used for things * // like encrypting datasource changes. */ restrictPurposes(allowedPurposes: Array<string>): this { const creds = getCredentials(this.id); const { purposes } = creds; // Filter out purposes which have already been restricted const finalPurposes = allowedPurposes.filter(newPurpose => purposes.includes(newPurpose)); setCredentials( this.id, Object.assign(creds, { purposes: finalPurposes }) ); return this; } /** * Convert the credentials to an encrypted string, for storage * @returns A promise that resolves with the encrypted credentials * @throws {Error} Rejects when masterPassword is not a string * @throws {Error} Rejects if credentials don't permit secure export purposes * @memberof Credentials */ toSecureString(): Promise<string> { if (credentialsAllowsPurpose(this.id, Credentials.PURPOSE_SECURE_EXPORT) !== true) { return Promise.reject(new Error("Credential purposes don't allow for secure exports")); } const encrypt = getSharedAppEnv().getProperty("crypto/v1/encryptText"); const { data, masterPassword } = getCredentials(this.id); if (typeof masterPassword !== "string") { return Promise.reject( new Error("Cannot convert Credentials to string: master password was not set or is invalid") ); } return encrypt(JSON.stringify(data), masterPassword).then(signEncryptedContent); } /** * Get raw credentials data (only available in specialised environments) * @protected * @memberof Credentials * @deprecated */ _getData() { return this.getData(); } }
the_stack
import {clamp, Vec2, AffineTransform, Rect} from './math' import * as jsc from 'jsverify' test('clamp', () => { jsc.assertForall(jsc.number, jsc.number, jsc.number, (a, b, c) => { const result = clamp(a, b, c) if (a < b) return result == b if (a > c) return result == c return result == a }) }) // Change this to jsc.integer to debug failures more easily let numericType = jsc.number const arbitraryVec2 = jsc.record({x: jsc.integer, y: numericType}).smap( v => new Vec2(v.x, v.y), v => v, ) const positiveVec2 = jsc.suchthat(arbitraryVec2, v => v.x > 0 && v.y > 0) const arbitraryTransform = jsc .record({ m00: numericType, m01: numericType, m02: numericType, m10: numericType, m11: numericType, m12: numericType, }) .smap( t => new AffineTransform(t.m00, t.m01, t.m02, t.m10, t.m11, t.m12), t => t, ) const invertibleTransform = jsc.suchthat(arbitraryTransform, t => t.det() != 0) const simpleTransform = jsc.suchthat( jsc.record({scale: arbitraryVec2, translation: arbitraryVec2}).smap( t => AffineTransform.withScale(t.scale).withTranslation(t.translation), t => ({scale: t.getScale(), translation: t.getTranslation()}), ), t => t.det() != 0, ) const arbitraryRect = jsc.record({origin: arbitraryVec2, size: positiveVec2}).smap( r => new Rect(r.origin, r.size), r => r, ) describe('Vec2', () => { test('constructor', () => { jsc.assertForall(jsc.number, jsc.number, (a, b) => { const v = new Vec2(a, b) return v.x == a && v.y == b }) }) test('withX', () => { jsc.assertForall(arbitraryVec2, jsc.number, (v, n) => { return v.withX(n).x === n }) }) test('withY', () => { jsc.assertForall(arbitraryVec2, jsc.number, (v, n) => { return v.withY(n).y === n }) }) test('plus', () => { jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { const sum = v1.plus(v2) return sum.x === v1.x + v2.x && sum.y === v1.y + v2.y }) }) test('minus', () => { jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { const diff = v1.minus(v2) return diff.x === v1.x - v2.x && diff.y === v1.y - v2.y }) }) test('times', () => { jsc.assertForall(arbitraryVec2, jsc.number, (v1, s) => { const prod = v1.times(s) return prod.x === v1.x * s && prod.y === v1.y * s }) }) test('timesPointwise', () => { jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { const prod = v1.timesPointwise(v2) return prod.x === v1.x * v2.x && prod.y === v1.y * v2.y }) }) test('dividedByPointwise', () => { jsc.assertForall( arbitraryVec2, jsc.suchthat(arbitraryVec2, v => v.x !== 0 && v.y !== 0), (v1, v2) => { const div = v1.dividedByPointwise(v2) return div.x === v1.x / v2.x && div.y === v1.y / v2.y }, ) }) test('dot', () => { jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { return v1.dot(v2) === v1.x * v2.x + v1.y * v2.y }) }) test('equals', () => { jsc.assertForall(jsc.number, jsc.number, (a, b) => { return new Vec2(a, b).equals(new Vec2(a, b)) }) jsc.assertForall(arbitraryVec2, arbitraryVec2, (a, b) => { return a.equals(b) === (a.x === b.x && a.y === b.y) }) }) test('length2', () => { jsc.assertForall(arbitraryVec2, v => { return v.length2() === v.x * v.x + v.y * v.y }) }) test('length', () => { jsc.assertForall(arbitraryVec2, v => { return v.length() === Math.sqrt(v.x * v.x + v.y * v.y) }) }) test('abs', () => { jsc.assertForall(arbitraryVec2, v => { const q = v.abs() return q.x === Math.abs(v.x) && q.y === Math.abs(v.y) }) }) test('min', () => { jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { const min = Vec2.min(v1, v2) return min.x === Math.min(v1.x, v2.x) && min.y === Math.min(v1.y, v2.y) }) }) test('max', () => { jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { const max = Vec2.max(v1, v2) return max.x === Math.max(v1.x, v2.x) && max.y === Math.max(v1.y, v2.y) }) }) test('flatten', () => { jsc.assertForall(arbitraryVec2, v1 => { const flat = v1.flatten() return flat[0] == v1.x && flat[1] == v1.y }) }) }) describe('Rect', () => { test('isEmpty', () => { jsc.assertForall(arbitraryVec2, jsc.number, (v, n) => { return new Rect(v, new Vec2(0, n)).isEmpty() }) jsc.assertForall(arbitraryVec2, jsc.number, (v, n) => { return new Rect(v, new Vec2(n, 0)).isEmpty() }) jsc.assertForall(arbitraryVec2, v => { return !new Rect(v, Vec2.unit).isEmpty() }) }) test('width', () => { jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { return new Rect(v1, v2).width() == v2.x }) }) test('height', () => { jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { return new Rect(v1, v2).height() == v2.y }) }) test('left', () => { jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { return new Rect(v1, v2).left() == v1.x }) }) test('top', () => { jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { return new Rect(v1, v2).top() == v1.y }) }) test('right', () => { jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { return new Rect(v1, v2).right() == v1.x + v2.x }) }) test('bottom', () => { jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { return new Rect(v1, v2).bottom() == v1.y + v2.y }) }) test('topLeft', () => { jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { return new Rect(v1, v2).topLeft().equals(v1) }) }) test('topRight', () => { jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { return new Rect(v1, v2).topRight().equals(v1.plus(v2.withY(0))) }) }) test('bottomLeft', () => { jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { return new Rect(v1, v2).bottomLeft().equals(v1.plus(v2.withX(0))) }) }) test('bottomRight', () => { jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { return new Rect(v1, v2).bottomRight().equals(v1.plus(v2)) }) }) test('withOrigin', () => { jsc.assertForall(arbitraryRect, arbitraryVec2, (r, v) => { return r.withOrigin(v).origin.equals(v) }) }) test('withSize', () => { jsc.assertForall(arbitraryRect, arbitraryVec2, (r, v) => { return r.withSize(v).size.equals(v) }) }) test('closestPointTo', () => { jsc.assertForall(arbitraryRect, arbitraryVec2, (r, v) => { const p = r.closestPointTo(v) return p.x >= r.left() && p.x <= r.right() && p.y >= r.top() && p.y <= r.bottom() }) }) test('hasIntersectionWith', () => { jsc.assertForall(arbitraryRect, arbitraryRect, (r1, r2) => { return r1.hasIntersectionWith(r2) === !r1.intersectWith(r2).isEmpty() }) }) test('intersectWith', () => { jsc.assertForall(arbitraryRect, arbitraryRect, (r1, r2) => { const inter = r1.intersectWith(r2) return inter.isEmpty() || (r1.hasIntersectionWith(inter) && r2.hasIntersectionWith(inter)) }) }) }) describe('AffineTransform', () => { test('inverted', () => { expect(new AffineTransform(0, 0, 0, 0, 0, 0).inverted()).toBe(null) jsc.assertForall(invertibleTransform, t => { return t.inverted()!.inverted()!.approxEquals(t) }) }) test('translation', () => { jsc.assertForall(arbitraryTransform, arbitraryVec2, (t, v1) => { return t.withTranslation(v1).getTranslation().equals(v1) }) jsc.assertForall(arbitraryTransform, arbitraryVec2, (t, v1) => { const initialTranslation = t.getTranslation() return t.translatedBy(v1).getTranslation().approxEquals(initialTranslation.plus(v1)) }) }) test('scale', () => { jsc.assertForall(arbitraryTransform, arbitraryVec2, (t, v1) => { return t.withScale(v1).getScale().equals(v1) }) }) test('transformVector', () => { // Vector transformation are translation-invariant jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { return AffineTransform.withTranslation(v1).transformVector(v2).approxEquals(v2) }) jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { return AffineTransform.withScale(v1).transformVector(v2).approxEquals(v2.timesPointwise(v1)) }) }) test('inverseTransformVector', () => { jsc.assertForall(invertibleTransform, arbitraryVec2, (t, v) => { return t.inverseTransformVector(t.transformVector(v))!.approxEquals(v) }) }) test('transformPosition', () => { jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { return AffineTransform.withTranslation(v1).transformPosition(v2).approxEquals(v2.plus(v1)) }) jsc.assertForall(arbitraryVec2, arbitraryVec2, (v1, v2) => { return AffineTransform.withScale(v1).transformPosition(v2).approxEquals(v2.timesPointwise(v1)) }) }) test('inverseTransformPosition', () => { jsc.assertForall(invertibleTransform, arbitraryVec2, (t, v) => { return t.inverseTransformPosition(t.transformPosition(v))!.approxEquals(v) }) }) test('transformRect', () => { jsc.assertForall(arbitraryVec2, arbitraryRect, (v, r) => { return AffineTransform.withTranslation(v) .transformRect(r) .equals(r.withOrigin(r.origin.plus(v))) }) jsc.assertForall(arbitraryVec2, arbitraryRect, (v, r) => { const t = AffineTransform.withScale(v) const rt = t.transformRect(r) return Math.abs(rt.area() - r.area() * Math.abs(t.det())) < 1e-6 }) }) test('inverseTransformRect', () => { jsc.assertForall(simpleTransform, arbitraryRect, (t, r) => { return t.inverseTransformRect(t.transformRect(r))!.approxEquals(r) }) }) test('times', () => { jsc.assertForall(invertibleTransform, invertibleTransform, (t1, t2) => { return t1.times(t2).times(t2.inverted()!).approxEquals(t1) }) }) })
the_stack
import GL from '@luma.gl/constants'; import {hasFeature, FEATURES, Buffer} from '@luma.gl/core'; import ShaderAttribute, {IShaderAttribute} from './shader-attribute'; import {glArrayFromType} from './gl-utils'; import typedArrayManager from '../../utils/typed-array-manager'; import {toDoublePrecisionArray} from '../../utils/math-utils'; import log from '../../utils/log'; import type {Buffer as LumaBuffer} from '@luma.gl/webgl'; import type {TypedArray, NumericArray, TypedArrayConstructor} from '../../types/types'; export type BufferAccessor = { // WebGL attribute pointer parameters type?: number; size?: 1 | 2 | 3 | 4; divisor?: number; offset?: number; stride?: number; normalized?: boolean; integer?: boolean; }; export type ShaderAttributeOptions = Partial<BufferAccessor> & { offset: number; stride: number; vertexOffset?: number; elementOffset?: number; }; function getStride(accessor: DataColumnSettings<any>): number { return accessor.stride || accessor.size * accessor.bytesPerElement; } function resolveShaderAttribute( baseAccessor: DataColumnSettings<any>, shaderAttributeOptions: Partial<ShaderAttributeOptions> ): ShaderAttributeOptions { if (shaderAttributeOptions.offset) { log.removed('shaderAttribute.offset', 'vertexOffset, elementOffset')(); } // All shader attributes share the parent's stride const stride = getStride(baseAccessor); // `vertexOffset` is used to access the neighboring vertex's value // e.g. `nextPositions` in polygon const vertexOffset = shaderAttributeOptions.vertexOffset !== undefined ? shaderAttributeOptions.vertexOffset : baseAccessor.vertexOffset || 0; // `elementOffset` is defined when shader attribute's size is smaller than the parent's // e.g. `translations` in transform matrix const elementOffset = shaderAttributeOptions.elementOffset || 0; const offset = // offsets defined by the attribute vertexOffset * stride + elementOffset * baseAccessor.bytesPerElement + // offsets defined by external buffers if any (baseAccessor.offset || 0); return { ...shaderAttributeOptions, offset, stride }; } function resolveDoublePrecisionShaderAttributes( baseAccessor: DataColumnSettings<any>, shaderAttributeOptions: Partial<ShaderAttributeOptions> ): { high: ShaderAttributeOptions; low: ShaderAttributeOptions; } { const resolvedOptions = resolveShaderAttribute(baseAccessor, shaderAttributeOptions); return { high: resolvedOptions, low: { ...resolvedOptions, offset: resolvedOptions.offset + baseAccessor.size * 4 } }; } export type DataColumnOptions<Options> = Options & BufferAccessor & { id?: string; vertexOffset?: number; fp64?: boolean; logicalType?: number; isIndexed?: boolean; defaultValue?: number | number[]; }; type DataColumnSettings<Options> = DataColumnOptions<Options> & { type: number; size: 1 | 2 | 3 | 4; logicalType?: number; bytesPerElement: number; defaultValue: number[]; defaultType: TypedArrayConstructor; }; type DataColumnInternalState<Options, State> = State & { externalBuffer: LumaBuffer | null; bufferAccessor: DataColumnSettings<Options>; allocatedValue: TypedArray | null; numInstances: number; bounds: [number[], number[]] | null; constant: boolean; }; export default class DataColumn<Options, State> implements IShaderAttribute { gl: WebGLRenderingContext; id: string; size: 1 | 2 | 3 | 4; settings: DataColumnSettings<Options>; value: NumericArray | null; doublePrecision: boolean; protected _buffer: LumaBuffer | null; protected state: DataColumnInternalState<Options, State>; /* eslint-disable max-statements */ constructor(gl: WebGLRenderingContext, opts: DataColumnOptions<Options>, state: State) { this.gl = gl; this.id = opts.id || ''; this.size = opts.size || 1; const logicalType = opts.logicalType || opts.type; const doublePrecision = logicalType === GL.DOUBLE; let {defaultValue} = opts; defaultValue = Number.isFinite(defaultValue) ? [defaultValue] : defaultValue || new Array(this.size).fill(0); let bufferType: number; if (doublePrecision) { bufferType = GL.FLOAT; } else if (!logicalType && opts.isIndexed) { bufferType = gl && hasFeature(gl, FEATURES.ELEMENT_INDEX_UINT32) ? GL.UNSIGNED_INT : GL.UNSIGNED_SHORT; } else { bufferType = logicalType || GL.FLOAT; } // This is the attribute type defined by the layer // If an external buffer is provided, this.type may be overwritten // But we always want to use defaultType for allocation let defaultType = glArrayFromType(logicalType || bufferType || GL.FLOAT); this.doublePrecision = doublePrecision; // `fp64: false` tells a double-precision attribute to allocate Float32Arrays // by default when using auto-packing. This is more efficient in use cases where // high precision is unnecessary, but the `64Low` attribute is still required // by the shader. if (doublePrecision && opts.fp64 === false) { defaultType = Float32Array; } this.value = null; this.settings = { ...opts, defaultType, defaultValue: defaultValue as number[], logicalType, type: bufferType, size: this.size, bytesPerElement: defaultType.BYTES_PER_ELEMENT }; this.state = { ...state, externalBuffer: null, bufferAccessor: this.settings, allocatedValue: null, numInstances: 0, bounds: null, constant: false }; this._buffer = null; } /* eslint-enable max-statements */ get isConstant(): boolean { return this.state.constant; } get buffer(): LumaBuffer { if (!this._buffer) { const {isIndexed, type} = this.settings; this._buffer = new Buffer(this.gl, { id: this.id, target: isIndexed ? GL.ELEMENT_ARRAY_BUFFER : GL.ARRAY_BUFFER, accessor: {type} }) as LumaBuffer; } return this._buffer; } get byteOffset(): number { const accessor = this.getAccessor(); if (accessor.vertexOffset) { return accessor.vertexOffset * getStride(accessor); } return 0; } get numInstances(): number { return this.state.numInstances; } set numInstances(n: number) { this.state.numInstances = n; } delete(): void { if (this._buffer) { this._buffer.delete(); this._buffer = null; } typedArrayManager.release(this.state.allocatedValue); } getShaderAttributes( id: string, options: Partial<ShaderAttributeOptions> | null ): Record<string, IShaderAttribute> { if (this.doublePrecision) { const shaderAttributes = {}; const isBuffer64Bit = this.value instanceof Float64Array; const doubleShaderAttributeDefs = resolveDoublePrecisionShaderAttributes( this.getAccessor(), options || {} ); shaderAttributes[id] = new ShaderAttribute(this, doubleShaderAttributeDefs.high); shaderAttributes[`${id}64Low`] = isBuffer64Bit ? new ShaderAttribute(this, doubleShaderAttributeDefs.low) : new Float32Array(this.size); // use constant for low part if buffer is 32-bit return shaderAttributes; } if (options) { const shaderAttributeDef = resolveShaderAttribute(this.getAccessor(), options); return {[id]: new ShaderAttribute(this, shaderAttributeDef)}; } return {[id]: this}; } getBuffer(): LumaBuffer | null { if (this.state.constant) { return null; } return this.state.externalBuffer || this._buffer; } getValue(): [LumaBuffer, BufferAccessor] | NumericArray | null { if (this.state.constant) { return this.value; } return [this.getBuffer() as LumaBuffer, this.getAccessor()]; } getAccessor(): DataColumnSettings<Options> { return this.state.bufferAccessor; } // Returns [min: Array(size), max: Array(size)] /* eslint-disable max-depth */ getBounds(): [number[], number[]] | null { if (this.state.bounds) { return this.state.bounds; } let result: [number[], number[]] | null = null; if (this.state.constant && this.value) { const min = Array.from(this.value); result = [min, min]; } else { const {value, numInstances, size} = this; const len = numInstances * size; if (value && len && value.length >= len) { const min = new Array(size).fill(Infinity); const max = new Array(size).fill(-Infinity); for (let i = 0; i < len; ) { for (let j = 0; j < size; j++) { const v = value[i++]; if (v < min[j]) min[j] = v; if (v > max[j]) max[j] = v; } } result = [min, max]; } } this.state.bounds = result; return result; } // returns true if success // eslint-disable-next-line max-statements setData( data: | TypedArray | LumaBuffer | ({ constant?: boolean; value?: NumericArray; buffer?: LumaBuffer; } & Partial<BufferAccessor>) ): boolean { const {state} = this; let opts: { constant?: boolean; value?: NumericArray; buffer?: LumaBuffer; } & Partial<BufferAccessor>; if (ArrayBuffer.isView(data)) { opts = {value: data}; } else if (data instanceof Buffer) { opts = {buffer: data as LumaBuffer}; } else { opts = data; } const accessor: DataColumnSettings<Options> = {...this.settings, ...opts}; state.bufferAccessor = accessor; state.bounds = null; // clear cached bounds if (opts.constant) { // set constant let value = opts.value as NumericArray; value = this._normalizeValue(value, [], 0); if (this.settings.normalized) { value = this.normalizeConstant(value); } const hasChanged = !state.constant || !this._areValuesEqual(value, this.value); if (!hasChanged) { return false; } state.externalBuffer = null; state.constant = true; this.value = value; } else if (opts.buffer) { const buffer = opts.buffer; state.externalBuffer = buffer; state.constant = false; this.value = opts.value || null; const isBuffer64Bit = opts.value instanceof Float64Array; // Copy the type of the buffer into the accessor // @ts-ignore accessor.type = opts.type || buffer.accessor.type; // @ts-ignore accessor.bytesPerElement = buffer.accessor.BYTES_PER_ELEMENT * (isBuffer64Bit ? 2 : 1); accessor.stride = getStride(accessor); } else if (opts.value) { this._checkExternalBuffer(opts); let value = opts.value as TypedArray; state.externalBuffer = null; state.constant = false; this.value = value; accessor.bytesPerElement = value.BYTES_PER_ELEMENT; accessor.stride = getStride(accessor); const {buffer, byteOffset} = this; if (this.doublePrecision && value instanceof Float64Array) { value = toDoublePrecisionArray(value, accessor); } // A small over allocation is used as safety margin // Shader attributes may try to access this buffer with bigger offsets const requiredBufferSize = value.byteLength + byteOffset + accessor.stride * 2; if (buffer.byteLength < requiredBufferSize) { buffer.reallocate(requiredBufferSize); } // Hack: force Buffer to infer data type buffer.setAccessor(null); buffer.subData({data: value, offset: byteOffset}); // @ts-ignore accessor.type = opts.type || buffer.accessor.type; } return true; } updateSubBuffer( opts: { startOffset?: number; endOffset?: number; } = {} ): void { this.state.bounds = null; // clear cached bounds const value = this.value as TypedArray; const {startOffset = 0, endOffset} = opts; this.buffer.subData({ data: this.doublePrecision && value instanceof Float64Array ? toDoublePrecisionArray(value, { size: this.size, startIndex: startOffset, endIndex: endOffset }) : value.subarray(startOffset, endOffset), offset: startOffset * value.BYTES_PER_ELEMENT + this.byteOffset }); } allocate(numInstances: number, copy: boolean = false): boolean { const {state} = this; const oldValue = state.allocatedValue; // Allocate at least one element to ensure a valid buffer const value = typedArrayManager.allocate(oldValue, numInstances + 1, { size: this.size, type: this.settings.defaultType, copy }); this.value = value; const {buffer, byteOffset} = this; if (buffer.byteLength < value.byteLength + byteOffset) { buffer.reallocate(value.byteLength + byteOffset); if (copy && oldValue) { // Upload the full existing attribute value to the GPU, so that updateBuffer // can choose to only update a partial range. // TODO - copy old buffer to new buffer on the GPU buffer.subData({ data: oldValue instanceof Float64Array ? toDoublePrecisionArray(oldValue, this) : oldValue, offset: byteOffset }); } } state.allocatedValue = value; state.constant = false; state.externalBuffer = null; state.bufferAccessor = this.settings; return true; } // PRIVATE HELPER METHODS protected _checkExternalBuffer(opts: {value?: NumericArray; normalized?: boolean}): void { const {value} = opts; if (!ArrayBuffer.isView(value)) { throw new Error(`Attribute ${this.id} value is not TypedArray`); } const ArrayType = this.settings.defaultType; let illegalArrayType = false; if (this.doublePrecision) { // not 32bit or 64bit illegalArrayType = value.BYTES_PER_ELEMENT < 4; } if (illegalArrayType) { throw new Error(`Attribute ${this.id} does not support ${value.constructor.name}`); } if (!(value instanceof ArrayType) && this.settings.normalized && !('normalized' in opts)) { log.warn(`Attribute ${this.id} is normalized`)(); } } // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer normalizeConstant(value: NumericArray): NumericArray { switch (this.settings.type) { case GL.BYTE: // normalize [-128, 127] to [-1, 1] return new Float32Array(value).map(x => ((x + 128) / 255) * 2 - 1); case GL.SHORT: // normalize [-32768, 32767] to [-1, 1] return new Float32Array(value).map(x => ((x + 32768) / 65535) * 2 - 1); case GL.UNSIGNED_BYTE: // normalize [0, 255] to [0, 1] return new Float32Array(value).map(x => x / 255); case GL.UNSIGNED_SHORT: // normalize [0, 65535] to [0, 1] return new Float32Array(value).map(x => x / 65535); default: // No normalization for gl.FLOAT and gl.HALF_FLOAT return value; } } /* check user supplied values and apply fallback */ protected _normalizeValue(value: any, out: NumericArray, start: number): NumericArray { const {defaultValue, size} = this.settings; if (Number.isFinite(value)) { out[start] = value; return out; } if (!value) { out[start] = defaultValue[0]; return out; } // Important - switch cases are 5x more performant than a for loop! /* eslint-disable no-fallthrough, default-case */ switch (size) { case 4: out[start + 3] = Number.isFinite(value[3]) ? value[3] : defaultValue[3]; case 3: out[start + 2] = Number.isFinite(value[2]) ? value[2] : defaultValue[2]; case 2: out[start + 1] = Number.isFinite(value[1]) ? value[1] : defaultValue[1]; case 1: out[start + 0] = Number.isFinite(value[0]) ? value[0] : defaultValue[0]; break; default: // In the rare case where the attribute size > 4, do it the slow way // This is used for e.g. transform matrices let i = size; while (--i >= 0) { out[start + i] = Number.isFinite(value[i]) ? value[i] : defaultValue[i]; } } return out; } protected _areValuesEqual(value1: any, value2: any): boolean { if (!value1 || !value2) { return false; } const {size} = this; for (let i = 0; i < size; i++) { if (value1[i] !== value2[i]) { return false; } } return true; } }
the_stack
import { GraphRenderer } from './graph_renderer' import { GraphLegend } from './graph_legend' import './series_overrides_ctrl' import './thresholds_form' import template from './template' import _ from 'lodash' import config from 'grafana/app/core/config' import { MetricsPanelCtrl, alertTab } from 'grafana/app/plugins/sdk' import { DataProcessor } from './data_processor' import { axesEditorComponent } from './axes_editor' import * as timeShiftUtil from './time_shift_util' import $ from 'jquery' class GraphCtrl extends MetricsPanelCtrl { static template = template hiddenSeries: any = {} seriesList: any = [] dataList: any = [] annotations: any = [] alertState: any _panelPath: any annotationsPromise: any dataWarning: any colors: any = [] subTabIndex: number processor: DataProcessor timeShifts_sort: number range_bak: any timeInfo_bak: any queryTimeShifts: any = [] openLog: false snapshot_tmp: any private _graphRenderer: GraphRenderer private _graphLegend: GraphLegend panelDefaults = { // datasource name, null = default datasource datasource: null, // sets client side (flot) or native graphite png renderer (png) renderer: 'flot', yaxes: [ { label: null, show: true, logBase: 1, min: null, max: null, format: 'short' }, { label: null, show: true, logBase: 1, min: null, max: null, format: 'short' } ], xaxis: { show: true, mode: 'time', name: null, values: [], buckets: null, customDateFormatShow: false, customDateFormat: '' }, // show/hide lines lines: true, // fill factor fill: 1, // line width in pixels linewidth: 1, // show/hide dashed line dashes: false, // length of a dash dashLength: 10, // length of space between two dashes spaceLength: 10, // show hide points points: false, // point radius in pixels pointradius: 5, // show hide bars bars: false, // enable/disable stacking stack: false, // stack percentage mode percentage: false, // legend options legend: { show: true, // disable/enable legend values: false, // disable/enable legend values min: false, max: false, current: false, total: false, avg: false }, // how null points should be handled nullPointMode: 'null', // staircase line mode steppedLine: false, // tooltip options tooltip: { value_type: 'individual', shared: true, sort: 0 }, // time overrides timeFrom: null, timeShift: null, // metric queries targets: [{}], // series color overrides aliasColors: {}, // other style overrides seriesOverrides: [], thresholds: [], timeShifts: [], displayBarsSideBySide: false, labelAlign: 'left' } /** @ngInject */ constructor( $scope, $injector, private annotationsSrv, private popoverSrv, private contextSrv ) { super($scope, $injector) _.defaults(this.panel, this.panelDefaults) _.defaults(this.panel.tooltip, this.panelDefaults.tooltip) _.defaults(this.panel.legend, this.panelDefaults.legend) _.defaults(this.panel.xaxis, this.panelDefaults.xaxis) this.processor = new DataProcessor(this.panel) this.events.on('render', this.onRender.bind(this)) this.events.on('data-received', this.onDataReceived.bind(this)) this.events.on('data-error', this.onDataError.bind(this)) this.events.on('data-snapshot-load', this.onDataSnapshotLoad.bind(this)) this.events.on('init-edit-mode', this.onInitEditMode.bind(this)) this.events.on('init-panel-actions', this.onInitPanelActions.bind(this)) } link(scope, elem, attrs, ctrl) { var $graphElem = $(elem[0]).find('#grafana-compare-graph') var $legendElem = $(elem[0]).find('#graph-compare-legend') this._graphRenderer = new GraphRenderer( $graphElem, this.timeSrv, this.contextSrv, this.$scope ) this._graphLegend = new GraphLegend( $legendElem, this.popoverSrv, this.$scope ) } onInitEditMode() { var partialPath = this.panelPath + 'partials' this.addEditorTab('Axes', axesEditorComponent, 2) this.addEditorTab('Legend', `${partialPath}/tab_legend.html`, 3) this.addEditorTab('Display', `${partialPath}/tab_display.html`, 4) this.addEditorTab('CompareTime', `${partialPath}/tab_compare_time.html`, 5) if (config.alertingEnabled) { this.addEditorTab('Alert', alertTab, 6) } this.log( 'editorTabs+++++++++++panel.editorTabs:' + JSON.stringify(this.editorTabs) + '+++' ) let timeRangeIndex = -1 for (let index = 0; index < this.editorTabs.length; index++) { let tab = this.editorTabs[index] if (typeof tab != 'undefined' && tab.title == 'Time range') { timeRangeIndex = index break } } if (timeRangeIndex > -1) { this.editorTabs.splice(timeRangeIndex, 1) } this.subTabIndex = 0 } onInitPanelActions(actions) { actions.push({ text: 'Export CSV', click: 'ctrl.exportCsv()' }) actions.push({ text: 'Toggle legend', click: 'ctrl.toggleLegend()' }) } issueQueries(datasource) { this.annotationsPromise = this.annotationsSrv.getAnnotations({ dashboard: this.dashboard, panel: this.panel, range: this.range }) return super.issueQueries(datasource) } zoomOut(evt) { this.publishAppEvent('zoom-out', 2) } onDataSnapshotLoad(snapshotData) { this.annotationsPromise = this.annotationsSrv.getAnnotations({ dashboard: this.dashboard, panel: this.panel, range: this.range }) this.dataReceived(snapshotData) } onDataError(err) { this.timeShifts_sort = 0 this.seriesList = [] this.annotations = [] this.render([]) } emitTimeShiftRefresh() { let timeShift = this.panel.timeShifts[this.timeShifts_sort - 1] this.log( 'emitRefresh+++++++++++timeShift:' + JSON.stringify(timeShift) + '++timeShifts_sort:' + this.timeShifts_sort + '++++++++timeShift.value:' + timeShift.value ) this.panel.timeShift = this.templateSrv.replace(timeShift.value, this.panel.scopedVars) this.events.emit('refresh') } gennerDataListTimeShift(dataList, timeShift) { if ( dataList.length == 0 || dataList[0].type || dataList[0].type == 'table' || typeof timeShift == 'undefined' || typeof timeShift.value == 'undefined' || timeShift.value == null || timeShift.value == '' ) { return dataList } this.log('gennerDataListTimeShift+from' + JSON.stringify(this.range.from)) //let timeShift_ms = timeShiftUtil.parseShiftToMs(timeShift.value); let timeShiftValue = this.templateSrv.replace(timeShift.value, this.panel.scopedVars) let timeShiftAlias = this.templateSrv.replace(timeShift.alias, this.panel.scopedVars) let timeShift_ms = timeShiftUtil.parseShiftToMs( this.range.from, timeShiftValue ) if (typeof timeShift_ms == 'undefined') { return [] } this.log( 'gennerDataListTimeShift: timeShift=' + JSON.stringify(timeShiftValue) + '======;timeShift_ms=' + timeShift_ms ) for (let line of dataList) { if ( typeof timeShift.alias == 'undefined' || timeShift.alias == null || timeShift.alias == '' ) { line.target = line.target + '_' + timeShiftValue } else { line.target = line.target + '_' + timeShiftAlias } for (let point of line.datapoints) { point[1] = point[1] + timeShift_ms } } return dataList } needEmitTimeShift() { this.log( 'this.timeShifts_sort :' + this.timeShifts_sort + ',this.panel.timeShifts.length:' + this.panel.timeShifts.length ) if (this.panel.timeShifts.length < this.timeShifts_sort) { return false } this.timeShifts_sort++ let timeShift = this.panel.timeShifts[this.timeShifts_sort - 1] if ( typeof timeShift !== 'undefined' && typeof timeShift.value !== 'undefined' && timeShift.value != null && timeShift.value != '' ) { return true } else { return this.needEmitTimeShift() } } onDataReceived(dataList) { this.log( 'this.timeShifts_sort :' + this.timeShifts_sort + ',this.panel.timeShifts.length:' + this.panel.timeShifts.length ) this.log( 'this.panel.snapshotData:' + JSON.stringify(this.panel.snapshotData) ) if (this.dashboard.snapshot) { this.snapshot_tmp = this.dashboard.snapshot this.dashboard.snapshot = undefined this.panel.snapshotData = undefined } if ( this.timeShifts_sort == 0 || typeof this.timeShifts_sort == 'undefined' ) { this.timeShifts_sort = 0 this.dataList = dataList this.range_bak = this.range this.timeInfo_bak = this.timeInfo this.log('+++++++++++++ssssssss+++++++++++++') } else { dataList = this.gennerDataListTimeShift( dataList, this.panel.timeShifts[this.timeShifts_sort - 1] ) this.dataList.push(...dataList) } if (this.needEmitTimeShift()) { this.emitTimeShiftRefresh() return } this.revert() this.log('final:' + JSON.stringify(this.dataList)) dataList = this.dataList this.dataReceived(dataList) } revert() { this.range = this.range_bak this.timeInfo = this.timeInfo_bak this.panel.timeShift = '' this.timeShifts_sort = 0 } dataReceived(dataList) { this.log('this.snapshot_tmp:' + JSON.stringify(this.snapshot_tmp)) if (this.snapshot_tmp) { this.panel.snapshotData = dataList this.dashboard.snapshot = this.snapshot_tmp this.snapshot_tmp = undefined } this.seriesList = this.processor.getSeriesList({ dataList: dataList, range: this.range }) this.dataWarning = null const datapointsCount = this.seriesList.reduce((prev, series) => { return prev + series.datapoints.length }, 0) if (datapointsCount === 0) { this.dataWarning = { title: 'No data points', tip: 'No datapoints returned from data query' } } else { for (let series of this.seriesList) { if (series.isOutsideRange) { this.dataWarning = { title: 'Data points outside time range', tip: 'Can be caused by timezone mismatch or missing time filter in query' } break } } } this.annotationsPromise.then( result => { this.loading = false this.alertState = result.alertState this.annotations = result.annotations this.render(this.seriesList) }, () => { this.loading = false this.render(this.seriesList) } ) this.log('++++++++++++++eeeeeeee++++++++++++') } onRender(data) { if (!this.seriesList) { return } for (let series of this.seriesList) { series.applySeriesOverrides(this.panel.seriesOverrides) if (series.unit) { this.panel.yaxes[series.yaxis - 1].format = series.unit } } this._graphRenderer.render(data) this._graphLegend.render() this._graphRenderer.renderPanel() } changeSeriesColor(series, color) { series.color = color this.panel.aliasColors[series.alias] = series.color this.render() } toggleSeries(serie, event) { if (event.ctrlKey || event.metaKey || event.shiftKey) { if (this.hiddenSeries[serie.alias]) { delete this.hiddenSeries[serie.alias] } else { this.hiddenSeries[serie.alias] = true } } else { this.toggleSeriesExclusiveMode(serie) } this.render() } toggleSeriesExclusiveMode(serie) { var hidden = this.hiddenSeries if (hidden[serie.alias]) { delete hidden[serie.alias] } // check if every other series is hidden var alreadyExclusive = _.every(this.seriesList, value => { if (value.alias === serie.alias) { return true } return hidden[value.alias] }) if (alreadyExclusive) { // remove all hidden series _.each(this.seriesList, value => { delete this.hiddenSeries[value.alias] }) } else { // hide all but this serie _.each(this.seriesList, value => { if (value.alias === serie.alias) { return } this.hiddenSeries[value.alias] = true }) } } toggleAxis(info) { var override = _.find(this.panel.seriesOverrides, { alias: info.alias }) if (!override) { override = { alias: info.alias } this.panel.seriesOverrides.push(override) } info.yaxis = override.yaxis = info.yaxis === 2 ? 1 : 2 this.render() } addSeriesOverride(override) { this.panel.seriesOverrides.push(override || {}) } removeSeriesOverride(override) { this.panel.seriesOverrides = _.without(this.panel.seriesOverrides, override) this.render() } toggleLegend() { this.panel.legend.show = !this.panel.legend.show this.refresh() } legendValuesOptionChanged() { var legend = this.panel.legend legend.values = legend.min || legend.max || legend.avg || legend.current || legend.total this.render() } exportCsv() { var scope = this.$scope.$new(true) scope.seriesList = this.seriesList this.publishAppEvent('show-modal', { templateHtml: '<export-data-modal data="seriesList"></export-data-modal>', scope, modalClass: 'modal--narrow' }) } addTimeShifts() { let id = this.getTimeShiftId() this.log('addTimeShifts++++++++++id:' + id) this.panel.timeShifts.push({ id: id }) } removeTimeShift(timeShift) { this.log('removeTimeShift++++++++++:' + JSON.stringify(timeShift)) var index = _.indexOf(this.panel.timeShifts, timeShift) this.log('removeTimeShift++++++++++index:' + index) this.panel.timeShifts.splice(index, 1) this.refreshTimeShifts() } refreshTimeShifts() { this.log('refreshTimeShifts:' + JSON.stringify(this.panel.timeShifts)) this.refresh() } getTimeShiftId() { let id = 0 while (true) { let notExits = _.every(this.panel.timeShifts, function(timeShift) { return timeShift.id !== id }) if (notExits) { return id } else { id++ } } } get panelPath() { if (this._panelPath === undefined) { this._panelPath = 'public/plugins/' + this.pluginId + '/' } return this._panelPath } log(msg) { if (true) { console.log(msg) } } } export { GraphCtrl, GraphCtrl as PanelCtrl }
the_stack
import React, { useState } from 'react'; import { Components, registerComponent } from '../../../lib/vulcan-lib'; import { userIsAllowedToComment } from '../../../lib/collections/users/helpers'; import { userCanDo } from '../../../lib/vulcan-users/permissions'; import classNames from 'classnames'; import withErrorBoundary from '../../common/withErrorBoundary'; import { useCurrentUser } from '../../common/withUser'; import { Link } from '../../../lib/reactRouterWrapper'; import { tagGetUrl } from "../../../lib/collections/tags/helpers"; import { Comments } from "../../../lib/collections/comments"; import { AnalyticsContext } from "../../../lib/analyticsEvents"; import type { CommentTreeOptions } from '../commentTree'; import { commentGetPageUrlFromIds } from '../../../lib/collections/comments/helpers'; import { forumTypeSetting } from '../../../lib/instanceSettings'; import { REVIEW_NAME_IN_SITU, REVIEW_YEAR, reviewIsActive, eligibleToNominate } from '../../../lib/reviewUtils'; import { useCurrentTime } from '../../../lib/utils/timeUtil'; const isEAForum= forumTypeSetting.get() === "EAForum" // Shared with ParentCommentItem export const styles = (theme: ThemeType): JssStyles => ({ root: { paddingLeft: theme.spacing.unit*1.5, paddingRight: theme.spacing.unit*1.5, "&:hover $menu": { opacity:1 } }, body: { borderStyle: "none", padding: 0, ...theme.typography.commentStyle, }, menu: { opacity:.35, marginRight:-5, float: "right", }, replyLink: { marginRight: 5, display: "inline", color: theme.palette.link.dim, "@media print": { display: "none", }, }, collapse: { marginRight: 5, opacity: 0.8, fontSize: "0.8rem", lineHeight: "1rem", paddingBottom: 4, display: "inline-block", verticalAlign: "middle", "& span": { fontFamily: "monospace", } }, firstParentComment: { marginLeft: -theme.spacing.unit*1.5, marginRight: -theme.spacing.unit*1.5 }, meta: { "& > div": { display: "inline-block", marginRight: 5, }, marginBottom: 8, color: theme.palette.text.dim, paddingTop: ".6em", "& a:hover, & a:active": { textDecoration: "none", color: `${theme.palette.linkHover.dim} !important`, }, }, bottom: { paddingBottom: 5, fontSize: 12, minHeight: 12 }, replyForm: { marginTop: 2, marginBottom: 8, border: theme.palette.border.normal, }, deleted: { backgroundColor: theme.palette.panelBackground.deletedComment, }, moderatorHat: { marginRight: 8, }, username: { marginRight: 10, }, metaNotice: { color: theme.palette.lwTertiary.main, fontStyle: "italic", fontSize: "1rem", marginBottom: theme.spacing.unit, marginLeft: theme.spacing.unit/2 }, postTitle: { paddingTop: theme.spacing.unit, ...theme.typography.commentStyle, display: "block", color: theme.palette.link.dim2, }, reviewVotingButtons: { borderTop: theme.palette.border.normal, display: "flex", justifyContent: "space-between", alignItems: "center", paddingLeft: 6, }, updateVoteMessage: { ...theme.typography.body2, ...theme.typography.smallText, color: theme.palette.grey[600] } }) export const CommentsItem = ({ treeOptions, comment, nestingLevel=1, isChild, collapsed, isParentComment, parentCommentId, scrollIntoView, toggleCollapse, setSingleLine, truncated, parentAnswerId, classes }: { treeOptions: CommentTreeOptions, comment: CommentsList|CommentsListWithParentMetadata, nestingLevel: number, isChild?: boolean, collapsed?: boolean, isParentComment?: boolean, parentCommentId?: string, scrollIntoView?: ()=>void, toggleCollapse?: ()=>void, setSingleLine?: (boolean)=>void, truncated: boolean, parentAnswerId?: string|undefined, classes: ClassesType, }) => { const [showReplyState, setShowReplyState] = useState(false); const [showEditState, setShowEditState] = useState(false); const [showParentState, setShowParentState] = useState(false); const now = useCurrentTime(); const currentUser = useCurrentUser(); const { postPage, tag, post, refetch, hideReply, showPostTitle, singleLineCollapse, hideReviewVoteButtons } = treeOptions; const showReply = (event: React.MouseEvent) => { event.preventDefault(); setShowReplyState(true); } const replyCancelCallback = () => { setShowReplyState(false); } const replySuccessCallback = () => { if (refetch) { refetch() } setShowReplyState(false); } const setShowEdit = () => { setShowEditState(true); } const editCancelCallback = () => { setShowEditState(false); } const editSuccessCallback = () => { if (refetch) { refetch() } setShowEditState(false); } const toggleShowParent = () => { setShowParentState(!showParentState); } const renderMenu = () => { const { CommentsMenu } = Components; return ( <AnalyticsContext pageElementContext="tripleDotMenu"> <CommentsMenu className={classes.menu} comment={comment} post={post} tag={tag} showEdit={setShowEdit} /> </AnalyticsContext> ) } const renderBodyOrEditor = () => { if (showEditState) { return <Components.CommentsEditForm comment={comment} successCallback={editSuccessCallback} cancelCallback={editCancelCallback} /> } else { return <Components.CommentBody truncated={truncated} collapsed={collapsed} comment={comment} postPage={postPage} /> } } const renderCommentBottom = () => { const { CommentBottomCaveats } = Components const blockedReplies = comment.repliesBlockedUntil && new Date(comment.repliesBlockedUntil) > now; const showReplyButton = ( !hideReply && !comment.deleted && (!blockedReplies || userCanDo(currentUser,'comments.replyOnBlocked.all')) && // FIXME userIsAllowedToComment depends on some post metadatadata that we // often don't want to include in fragments, producing a type-check error // here. We should do something more complicated to give client-side feedback // if you're banned. // @ts-ignore (!currentUser || userIsAllowedToComment(currentUser, treeOptions.post)) ) return ( <div className={classes.bottom}> <CommentBottomCaveats comment={comment}/> { showReplyButton && <a className={classNames("comments-item-reply-link", classes.replyLink)} onClick={showReply}> Reply </a> } </div> ) } const renderReply = () => { const levelClass = (nestingLevel + 1) % 2 === 0 ? "comments-node-even" : "comments-node-odd" return ( <div className={classNames(classes.replyForm, levelClass)}> <Components.CommentsNewForm post={treeOptions.post} parentComment={comment} successCallback={replySuccessCallback} cancelCallback={replyCancelCallback} prefilledProps={{ parentAnswerId: parentAnswerId ? parentAnswerId : null }} type="reply" /> </div> ) } const { ShowParentComment, CommentsItemDate, CommentUserName, CommentShortformIcon, SmallSideVote, LWTooltip, PostsPreviewTooltipSingle, ReviewVotingWidget, LWHelpIcon } = Components if (!comment) { return null; } const displayReviewVoting = !hideReviewVoteButtons && reviewIsActive() && comment.reviewingForReview === REVIEW_YEAR+"" && post && currentUser?._id !== post.userId && eligibleToNominate(currentUser) return ( <AnalyticsContext pageElementContext="commentItem" commentId={comment._id}> <div className={classNames( classes.root, "recent-comments-node", { [classes.deleted]: comment.deleted && !comment.deletedPublic, }, )}> { comment.parentCommentId && showParentState && ( <div className={classes.firstParentComment}> <Components.ParentCommentSingle post={post} tag={tag} documentId={comment.parentCommentId} nestingLevel={nestingLevel - 1} truncated={false} key={comment.parentCommentId} /> </div> )} {showPostTitle && !isChild && hasPostField(comment) && comment.post && <LWTooltip tooltip={false} title={<PostsPreviewTooltipSingle postId={comment.postId}/>}> <Link className={classes.postTitle} to={commentGetPageUrlFromIds({postId: comment.postId, commentId: comment._id, postSlug: ""})}> {comment.post.draft && "[Draft] "} {comment.post.title} </Link> </LWTooltip>} {showPostTitle && !isChild && hasTagField(comment) && comment.tag && <Link className={classes.postTitle} to={tagGetUrl(comment.tag)}>{comment.tag.name}</Link>} <div className={classes.body}> <div className={classes.meta}> { !parentCommentId && !comment.parentCommentId && isParentComment && <div className={classes.usernameSpacing}>○</div> } {post && <CommentShortformIcon comment={comment} post={post} />} { parentCommentId!=comment.parentCommentId && parentAnswerId!=comment.parentCommentId && <ShowParentComment comment={comment} active={showParentState} onClick={toggleShowParent} /> } { (postPage || collapsed) && <a className={classes.collapse} onClick={toggleCollapse}> [<span>{collapsed ? "+" : "-"}</span>] </a> } {singleLineCollapse && <a className={classes.collapse} onClick={() => setSingleLine && setSingleLine(true)}> [<span>{collapsed ? "+" : "-"}</span>] </a> } <CommentUserName comment={comment} className={classes.username}/> <CommentsItemDate comment={comment} post={post} tag={tag} scrollIntoView={scrollIntoView} scrollOnClick={postPage && !isParentComment} /> {comment.moderatorHat && <span className={classes.moderatorHat}> Moderator Comment </span>} <SmallSideVote document={comment} collection={Comments} hideKarma={post?.hideCommentKarma} /> {!isParentComment && renderMenu()} {post && <Components.CommentOutdatedWarning comment={comment} post={post}/>} {comment.nominatedForReview && <Link to={`/nominations/${comment.nominatedForReview}`} className={classes.metaNotice}> {`Nomination for ${comment.nominatedForReview} Review`} </Link>} {comment.reviewingForReview && <Link to={`/reviews/${comment.reviewingForReview}`} className={classes.metaNotice}> {`Review for ${isEAForum && comment.reviewingForReview === '2020' ? 'the Decade' : comment.reviewingForReview} Review`} </Link>} </div> { comment.promoted && comment.promotedByUser && <div className={classes.metaNotice}> Promoted by {comment.promotedByUser.displayName} </div>} {renderBodyOrEditor()} {!comment.deleted && !collapsed && renderCommentBottom()} </div> {displayReviewVoting && !collapsed && <div className={classes.reviewVotingButtons}> <div className={classes.updateVoteMessage}> <LWTooltip title={`If this review changed your mind, update your ${REVIEW_NAME_IN_SITU} vote for the original post `}> Update your {REVIEW_NAME_IN_SITU} vote for this post. <LWHelpIcon/> </LWTooltip> </div> {post && <ReviewVotingWidget post={post} showTitle={false}/>} </div>} { showReplyState && !collapsed && renderReply() } </div> </AnalyticsContext> ) } const CommentsItemComponent = registerComponent( 'CommentsItem', CommentsItem, { styles, hocs: [withErrorBoundary], areEqual: { treeOptions: "shallow", }, } ); function hasPostField(comment: CommentsList | CommentsListWithParentMetadata): comment is CommentsListWithParentMetadata { return !!(comment as CommentsListWithParentMetadata).post } function hasTagField(comment: CommentsList | CommentsListWithParentMetadata): comment is CommentsListWithParentMetadata { return !!(comment as CommentsListWithParentMetadata).tag } declare global { interface ComponentTypes { CommentsItem: typeof CommentsItemComponent, } }
the_stack
import * as React from "react" import { contourDensity } from "d3-contour" import { scaleLinear } from "d3-scale" import polylabel from "@mapbox/polylabel" import { hexbin } from "d3-hexbin" import regression from "regression" import { curveCardinal } from "d3-shape" import { ProjectedPoint, GenericObject } from "../types/generalTypes" interface BinArray { [position: number]: number x?: number y?: number } export function contouring({ summaryType, data, finalXExtent, finalYExtent }) { let projectedSummaries = [] if (!summaryType.type) { summaryType = { type: summaryType } } const { resolution = 500, thresholds = 10, bandwidth = 20, neighborhood } = summaryType const xScale = scaleLinear() .domain(finalXExtent) .rangeRound([0, resolution]) .nice() const yScale = scaleLinear() .domain(finalYExtent) .rangeRound([resolution, 0]) .nice() data.forEach(contourData => { let contourProjectedSummaries = contourDensity() .size([resolution, resolution]) .x(d => xScale(d[0])) .y(d => yScale(d[1])) .thresholds(thresholds) .bandwidth(bandwidth)(contourData._xyfCoordinates) if (neighborhood) { contourProjectedSummaries = [contourProjectedSummaries[0]] } const max = Math.max(...contourProjectedSummaries.map(d => d.value)) contourProjectedSummaries.forEach(summary => { summary.parentSummary = contourData summary.bounds = [] summary.percent = summary.value / max summary.coordinates.forEach(poly => { poly.forEach((subpoly, i) => { poly[i] = subpoly.map(coordpair => { coordpair = [ xScale.invert(coordpair[0]), yScale.invert(coordpair[1]) ] return coordpair }) //Only push bounds for the main poly, not its interior rings, otherwise you end up labeling interior cutouts if (i === 0) { summary.bounds.push(shapeBounds(poly[i])) } }) }) }) projectedSummaries = [...projectedSummaries, ...contourProjectedSummaries] }) return projectedSummaries } export function hexbinning({ preprocess = true, processedData = false, summaryType, data: baseData, finalXExtent = [ Math.min(...baseData.coordinates.map(d => d.x)), Math.max(...baseData.coordinates.map(d => d.x)) ], finalYExtent = [ Math.min(...baseData.coordinates.map(d => d.y)), Math.max(...baseData.coordinates.map(d => d.y)) ], size, xScaleType = scaleLinear(), yScaleType = scaleLinear(), margin, baseMarkProps, styleFn, classFn, renderFn, chartSize }) { if (processedData) { return baseData[0].coordinates } let projectedSummaries = [] if (!summaryType.type) { summaryType = { type: summaryType } } const { // binGraphic = "hex", bins = 0.05, cellPx, binValue = d => d.length, binMax, customMark } = summaryType if (baseData.coordinates && !baseData._xyfCoordinates) { baseData._xyfCoordinates = baseData.coordinates.map(d => [d.x, d.y]) } const data = Array.isArray(baseData) ? baseData : [baseData] const hexBinXScale = xScaleType.domain(finalXExtent).range([0, size[0]]) const hexBinYScale = yScaleType.domain(finalYExtent).range([0, size[1]]) const actualResolution = (cellPx && cellPx / 2) || ((bins > 1 ? 1 / bins : bins) * size[0]) / 2 const hexbinner = hexbin() .x(d => hexBinXScale(d._xyfPoint[0])) .y(d => hexBinYScale(d._xyfPoint[1])) .radius(actualResolution) .size(size) let hexMax const allHexes: ProjectedPoint[] = hexbinner.centers() data.forEach(hexbinData => { hexMax = 0 const hexes = hexbinner( hexbinData._xyfCoordinates.map((d, i) => ({ _xyfPoint: d, ...hexbinData.coordinates[i] })) ) const centerHash = {} hexes.forEach(d => { centerHash[`${parseInt(d.x)}-${parseInt(d.y)}`] = true }) allHexes.forEach(hexCenter => { if (!centerHash[`${parseInt(hexCenter[0])}-${parseInt(hexCenter[1])}`]) { const newHex: BinArray = [] newHex.x = hexCenter[0] newHex.y = hexCenter[1] hexes.push(newHex) } }) hexMax = Math.max(...hexes.map(d => binValue(d))) if (binMax) { binMax(hexMax) } //Option for blank hexe const hexBase = [ [0, -1], [0.866, -0.5], [0.866, 0.5], [0, 1], [-0.866, 0.5], [-0.866, -0.5] ] const hexWidth = hexBinXScale.invert(actualResolution) - finalXExtent[0] const hexHeight = hexBinYScale.invert(actualResolution) - finalYExtent[0] const hexacoordinates = hexBase.map(d => [ d[0] * hexWidth, d[1] * hexHeight ]) const hexbinProjectedSummaries = hexes.map((d: GenericObject) => { const hexValue = binValue(d) const gx = d.x const gy = d.y d.x = hexBinXScale.invert(d.x) d.y = hexBinYScale.invert(d.y) const percent = hexValue / hexMax return { customMark: customMark && ( <g transform={`translate(${gx},${size[1] - gy})`}> {customMark({ d: { ...d, binItems: d, percent, value: hexValue, radius: actualResolution, hexCoordinates: hexBase.map(d => [ d[0] * actualResolution, d[1] * actualResolution ]) }, baseMarkProps, margin, styleFn, classFn, renderFn, chartSize, adjustedSize: size })} </g> ), _xyfCoordinates: hexacoordinates.map(p => [p[0] + d.x, p[1] + d.y]), value: hexValue, percent, data: d, parentSummary: hexbinData, centroid: true } }) projectedSummaries = [...projectedSummaries, ...hexbinProjectedSummaries] }) if (preprocess) { projectedSummaries.forEach(d => { d.x = d.data.x d.y = d.data.y }) return { type: "hexbin", processedData: true, coordinates: projectedSummaries, binMax: hexMax } } return projectedSummaries } // ADD PRECALC AND EXPOSE PRECALC FUNCTION export function heatmapping({ preprocess = true, processedData = false, summaryType, data: baseData, finalXExtent = [ Math.min(...baseData.coordinates.map(d => d.x)), Math.max(...baseData.coordinates.map(d => d.x)) ], finalYExtent = [ Math.min(...baseData.coordinates.map(d => d.y)), Math.max(...baseData.coordinates.map(d => d.y)) ], size, xScaleType = scaleLinear(), yScaleType = scaleLinear(), margin, baseMarkProps, styleFn, classFn, renderFn, chartSize }) { if (processedData) { return baseData[0].coordinates } if (baseData.coordinates && !baseData._xyfCoordinates) { baseData._xyfCoordinates = baseData.coordinates.map(d => [d.x, d.y]) } const data = Array.isArray(baseData) ? baseData : [baseData] let projectedSummaries = [] if (!summaryType.type) { summaryType = { type: summaryType } } const { // binGraphic = "square", binValue = d => d.length, xBins = summaryType.yBins || 0.05, yBins = xBins, xCellPx = !summaryType.xBins && summaryType.yCellPx, yCellPx = !summaryType.yBins && xCellPx, customMark, binMax } = summaryType const xBinPercent = xBins < 1 ? xBins : 1 / xBins const yBinPercent = yBins < 1 ? yBins : 1 / yBins const heatmapBinXScale = xScaleType.domain(finalXExtent).range([0, size[0]]) const heatmapBinYScale = yScaleType.domain(finalYExtent).range([size[1], 0]) const actualResolution = [ Math.ceil(((xCellPx && xCellPx / size[0]) || xBinPercent) * size[0] * 10) / 10, Math.ceil(((yCellPx && yCellPx / size[1]) || yBinPercent) * size[1] * 10) / 10 ] let maxValue = -Infinity data.forEach(heatmapData => { const grid = [] const flatGrid = [] let cell let gridColumn for (let i = 0; i < size[0]; i += actualResolution[0]) { const x = heatmapBinXScale.invert(i) const x1 = heatmapBinXScale.invert(i + actualResolution[0]) gridColumn = [] grid.push(gridColumn) for (let j = 0; j < size[1]; j += actualResolution[1]) { const y = heatmapBinYScale.invert(j) const y1 = heatmapBinYScale.invert(j + actualResolution[1]) cell = { gx: i, gy: j, gw: actualResolution[0], gh: actualResolution[1], x: (x + x1) / 2, y: (y + y1) / 2, binItems: [], value: 0, _xyfCoordinates: [[x, y], [x1, y], [x1, y1], [x, y1]], parentSummary: heatmapData } gridColumn.push(cell) flatGrid.push(cell) } gridColumn.push(cell) } grid.push(gridColumn) heatmapData._xyfCoordinates.forEach((d: number[], di: number) => { const xCoordinate = Math.floor( heatmapBinXScale(d[0]) / actualResolution[0] ) const yCoordinate = Math.floor( heatmapBinYScale(d[1]) / actualResolution[1] ) grid[xCoordinate][yCoordinate].binItems.push(heatmapData.coordinates[di]) }) flatGrid.forEach(d => { d.value = binValue(d.binItems) maxValue = Math.max(maxValue, d.value) }) flatGrid.forEach(d => { d.percent = d.value / maxValue d.customMark = customMark && ( <g transform={`translate(${d.gx},${d.gy})`}> {customMark({ d, baseMarkProps, margin, styleFn, classFn, renderFn, chartSize, adjustedSize: size })} </g> ) }) projectedSummaries = [...projectedSummaries, ...flatGrid] }) if (binMax) { binMax(maxValue) } if (preprocess) { return { type: "heatmap", processedData: true, coordinates: projectedSummaries, binMax: maxValue } } return projectedSummaries } export function trendlining({ preprocess = true, processedData = false, summaryType, data: baseData, finalXExtent = [ Math.min(...baseData.coordinates.map(d => d.x)), Math.max(...baseData.coordinates.map(d => d.x)) ], finalYExtent = [ Math.min(...baseData.coordinates.map(d => d.y)), Math.max(...baseData.coordinates.map(d => d.y)) ], size, xScaleType = scaleLinear(), yScaleType = scaleLinear(), margin, baseMarkProps, styleFn, classFn, renderFn, chartSize }) { if (processedData) { return baseData[0].coordinates } let projectedSummaries = [] if (!summaryType.type) { summaryType = { type: summaryType } } const { regressionType: baseRegressionType = "linear", order = 2, precision = 4, controlPoints = 20, curve = curveCardinal } = summaryType let regressionType = baseRegressionType if ( finalXExtent[0] < 0 && (baseRegressionType === "logarithmic" || baseRegressionType === "power" || baseRegressionType === "exponential") ) { console.error( `Cannot use this ${baseRegressionType} regressionType type with value range that goes below 0, defaulting to linear` ) regressionType = "linear" } if (baseData.coordinates && !baseData._xyfCoordinates) { baseData._xyfCoordinates = baseData.coordinates.map(d => [d.x, d.y]) } const data = Array.isArray(baseData) ? baseData : [baseData] const xScale = xScaleType.domain([0, 1]).range(finalXExtent) projectedSummaries = [] data.forEach(bdata => { const regressionLine = regression[regressionType]( bdata._xyfCoordinates.map(d => [ d[0].getTime ? d[0].getTime() : d[0], d[1].getTime ? d[1].getTime() : d[1] ]), { order, precision } ) const controlStep = 1 / controlPoints let steps = [0, 1] if (regressionType !== "linear") { steps = [] for (let step = 0; step < 1 + controlStep; step += controlStep) { steps.push(step) } } const controlPointArray = [] steps.forEach(controlPoint => { controlPointArray.push(regressionLine.predict(xScale(controlPoint))) }) projectedSummaries.push({ centroid: false, customMark: undefined, data: bdata, parentSummary: bdata, value: regressionLine.string, r2: regressionLine.r2, curve, _xyfCoordinates: controlPointArray }) }) return projectedSummaries } export function shapeBounds(coordinates) { let left = [Infinity, 0] let right = [-Infinity, 0] let top = [0, Infinity] let bottom = [0, -Infinity] coordinates.forEach(d => { left = d[0] < left[0] ? d : left right = d[0] > right[0] ? d : right bottom = d[1] > bottom[1] ? d : bottom top = d[1] < top[1] ? d : top }) return { center: polylabel([coordinates]), top, left, right, bottom } }
the_stack
import { clipboard, ipcRenderer } from "electron"; import { join, extname } from "path"; import Zip from "adm-zip"; import { Nullable, Undefinable } from "../../../shared/types"; import { IPCResponses } from "../../../shared/ipc"; import * as React from "react"; import { ButtonGroup, Button, Classes, ContextMenu, Menu, MenuItem, MenuDivider, Divider, Popover, Position, Tag, Intent, Code, } from "@blueprintjs/core"; import { Material, Mesh, ShaderMaterial, PickingInfo, Tools as BabylonTools, NodeMaterial, MultiMaterial, Scene, Node, } from "babylonjs"; import { assetsHelper, OffscreenAssetsHelperMesh } from "../tools/offscreen-assets-helper/offscreen-asset-helper"; import { Tools } from "../tools/tools"; import { undoRedo } from "../tools/undo-redo"; import { IPCTools } from "../tools/ipc"; import { Icon } from "../gui/icon"; import { Alert } from "../gui/alert"; import { Dialog } from "../gui/dialog"; import { Overlay } from "../gui/overlay"; import { Project } from "../project/project"; import { FilesStore } from "../project/files"; import { Assets } from "../components/assets"; import { AbstractAssets, IAssetComponentItem } from "./abstract-assets"; import "./materials/augmentations"; export class MaterialAssets extends AbstractAssets { /** * Defines the type of the data transfer data when drag'n'dropping asset. * @override */ public readonly dragAndDropType: string = "application/material"; private static _NodeMaterialEditors: { id: number; material: NodeMaterial }[] = []; /** * Registers the component. */ public static Register(): void { Assets.addAssetComponent({ title: "Materials", identifier: "materials", ctor: MaterialAssets, }); } /** * Renders the component. */ public render(): React.ReactNode { const node = super.render(); const add = <Menu> <MenuItem key="add-standard-material" text="Standard Material..." onClick={() => this._addMaterial("StandardMaterial")} /> <MenuItem key="add-pbr-material" text="PBR Material..." onClick={() => this._addMaterial("PBRMaterial")} /> <MenuItem key="add-node-material" text="Node Material..." onClick={() => this._addMaterial("NodeMaterial")} /> <MenuDivider /> <MenuItem key="add-node-material-from-snippet" text="Node Material From Snippet..." onClick={() => this._addNodeMaterialFromWeb()} /> <MenuDivider /> <MenuItem key="add-material-from-preset" icon={<Icon src="search.svg" />} text="From Preset..." onClick={() => this._handleLoadFromPreset()} /> <MenuDivider /> <Code>Materials Library</Code> <MenuItem key="add-cell-material" text="Add Cell Material..." onClick={() => this._addMaterial("CellMaterial")} /> <MenuItem key="add-fire-material" text="Add Fire Material..." onClick={() => this._addMaterial("FireMaterial")} /> <MenuItem key="add-lava-material" text="Add Lava Material..." onClick={() => this._addMaterial("LavaMaterial")} /> <MenuItem key="add-water-material" text="Add Water Material..." onClick={() => this._addMaterial("WaterMaterial")} /> <MenuItem key="add-tri-planar-material" text="Add Tri Planar Material..." onClick={() => this._addMaterial("TriPlanarMaterial")} /> </Menu>; return ( <> <div className={Classes.FILL} key="materials-toolbar" style={{ width: "100%", height: "25px", backgroundColor: "#333333", borderRadius: "10px", marginTop: "5px" }}> <ButtonGroup> <Button key="refresh-folder" icon="refresh" small={true} onClick={() => this.refresh()} /> <Divider /> <Popover key="add-popover" content={add} position={Position.BOTTOM_LEFT}> <Button key="add" icon={<Icon src="plus.svg" />} rightIcon="caret-down" small={true} text="Add" /> </Popover> <Divider /> <Button key="clear-unused" icon={<Icon src="recycle.svg" />} small={true} text="Clear Unused" onClick={() => this._clearUnusedMaterials()} /> </ButtonGroup> </div> {node} </> ); } /** * Refreshes the component. * @override */ public async refresh(object?: Material): Promise<void> { await assetsHelper.init(); await assetsHelper.createMesh(OffscreenAssetsHelperMesh.Sphere); for (const material of this.editor.scene!.materials) { if (material === this.editor.scene!.defaultMaterial || material instanceof ShaderMaterial || material.doNotSerialize) { continue; } if (object && object !== material) { continue; } const item = this.items.find((i) => i.key === material.id); if (!object && item) { continue; } const copy = material.serialize(); await assetsHelper.setMaterial(copy, material instanceof NodeMaterial ? undefined : join(Project.DirPath!, "/")); const base64 = await assetsHelper.getScreenshot(); const itemData: IAssetComponentItem = { id: material.name, key: material.id, base64 }; if (material.metadata?.isLocked) { itemData.style = { border: "solid red" }; } if (item) { const index = this.items.indexOf(item); if (index !== -1) { this.items[index] = itemData; } } else { this.items.push(itemData); } this.updateAssetThumbnail(material.id, base64); await assetsHelper.disposeMaterial(); this.updateAssetObservable.notifyObservers(); } await assetsHelper.reset(); return super.refresh(); } /** * Called on the user clicks on an item. * @param item the item being clicked. * @param img the clicked image element. */ public onClick(item: IAssetComponentItem, img: HTMLImageElement): void { super.onClick(item, img); const material = this.editor.scene!.getMaterialByID(item.key); if (material) { this.editor.selectedMaterialObservable.notifyObservers(material); } } /** * Called on the user double clicks an item. * @param item the item being double clicked. * @param img the double-clicked image element. */ public async onDoubleClick(item: IAssetComponentItem, img: HTMLImageElement): Promise<void> { super.onDoubleClick(item, img); const material = this.editor.scene!.getMaterialByID(item.key); if (!material) { return; } this.openMaterial(material); } /** * Called on the user right-clicks on an item. * @param item the item being right-clicked. * @param event the original mouse event. */ public onContextMenu(item: IAssetComponentItem, e: React.MouseEvent<HTMLImageElement, MouseEvent>): void { super.onContextMenu(item, e); const material = this.editor.scene!.getMaterialByID(item.key); if (!material) { return; } material.metadata = material.metadata ?? {}; material.metadata.isLocked = material.metadata.isLocked ?? false; ContextMenu.show( <Menu className={Classes.DARK}> <MenuItem text="Copy Name" icon="clipboard" onClick={() => clipboard.writeText(material.name, "clipboard")} /> <MenuDivider /> <MenuItem text="Refresh..." icon={<Icon src="recycle.svg" />} onClick={() => this.refresh(material)} /> <MenuDivider /> <MenuItem text="Save Material Preset..." icon={<Icon src="save.svg" />} onClick={() => this._handleSaveMaterialPreset(item)} /> <MenuDivider /> <MenuItem text="Clone..." onClick={async () => { const name = await Dialog.Show("Material Name?", "Please provide a name for the cloned material"); const existing = this.editor.scene!.materials.find((m) => m.name === name); if (existing) { return Alert.Show("Can't clone material", `A material named "${name}" already exists.`); } const clone = material.clone(name); if (!clone) { return Alert.Show("Failed to clone", "An error occured while clonig the material. The returned refenrence is equal to null."); } clone.uniqueId = this.editor.scene!.getUniqueId(); clone.id = Tools.RandomId(); this.refresh(); }} /> <MenuItem text="Locked" icon={material.metadata.isLocked ? <Icon src="check.svg" /> : undefined} onClick={() => { material.metadata.isLocked = !material.metadata.isLocked; item.style = item.style ?? {}; item.style.border = material.metadata.isLocked ? "solid red" : ""; super.refresh(); }} /> <MenuDivider /> <MenuItem text="Remove" icon={<Icon src="times.svg" />} onClick={() => this._handleRemoveMaterial(item)} /> </Menu>, { left: e.clientX, top: e.clientY }, ); } /** * Called on the user drops an asset in editor. (typically the preview canvas). * @param item the item being dropped. * @param pickInfo the pick info generated on the drop event. * @override */ public async onDropAsset(item: IAssetComponentItem, pickInfo: PickingInfo): Promise<void> { super.onDropAsset(item, pickInfo); const mesh = pickInfo.pickedMesh; if (!mesh || !(mesh instanceof Mesh)) { return; } const material = this.editor.scene!.getMaterialByID(item.key); if (!material) { return; } const subMeshId = pickInfo.subMeshId ?? null; if (mesh.material && mesh.material instanceof MultiMaterial && subMeshId) { const oldMaterial = mesh.material.subMaterials[subMeshId]; undoRedo.push({ common: () => this.editor.inspector.refresh(), undo: () => { if (mesh.material instanceof MultiMaterial) { mesh.material.subMaterials[subMeshId] = oldMaterial; } mesh.getLODLevels().forEach((lod) => lod.mesh && lod.mesh.material instanceof MultiMaterial && (lod.mesh.material.subMaterials[subMeshId] = oldMaterial)); }, redo: () => { if (mesh.material instanceof MultiMaterial) { mesh.material.subMaterials[subMeshId] = material; } mesh.getLODLevels().forEach((lod) => lod.mesh && lod.mesh.material instanceof MultiMaterial && (lod.mesh.material.subMaterials[subMeshId] = material)); }, }); } else { const oldMaterial = mesh.material; undoRedo.push({ common: () => this.editor.inspector.refresh(), undo: () => { mesh.material = oldMaterial; mesh.getLODLevels().forEach((lod) => lod.mesh && (lod.mesh.material = oldMaterial)); }, redo: () => { mesh.material = material; mesh.getLODLevels().forEach((lod) => lod.mesh && (lod.mesh.material = material)); }, }); } } /** * Called on the user pressed the delete key on the asset. * @param item defines the item being deleted. */ public onDeleteAsset(item: IAssetComponentItem): void { super.onDeleteAsset(item); this._handleRemoveMaterial(item); } /** * Called on an asset item has been drag'n'dropped on graph component. * @param data defines the data of the asset component item being drag'n'dropped. * @param nodes defines the array of nodes having the given item being drag'n'dropped. */ public onGraphDropAsset(data: IAssetComponentItem, nodes: (Scene | Node)[]): boolean { super.onGraphDropAsset(data, nodes); const material = this.editor.scene!.getMaterialByID(data.key); if (!material) { return false; } const meshes = nodes.filter((n) => n instanceof Mesh) as Mesh[]; meshes.forEach((m) => m.material = material); return true; } /** * Returns the content of the item's tooltip on the pointer is over the given item. * @param item defines the reference to the item having the pointer over. */ protected getItemTooltipContent(item: IAssetComponentItem): Undefinable<JSX.Element> { const material = this.editor.scene!.getMaterialByID(item.key); if (!material) { return undefined; } const binded = material.getBindedMeshes().filter((m) => !m._masterMesh); const attachedEllement = binded.length > 0 ? ( <> <Divider /> <b>Attached to:</b><br /> <ul> {binded.map((b) => <li key={`${b.id}-li`}><Tag interactive={true} fill={true} key={`${b.id}-tag`} intent={Intent.PRIMARY} onClick={() => { this.editor.selectedNodeObservable.notifyObservers(b); this.editor.preview.focusSelectedNode(false); }}>{b.name}</Tag></li>)} </ul> </> ) : undefined; return ( <> <Tag key="itemId" fill={true} intent={Intent.PRIMARY}>{item.id}</Tag> <Divider /> <Tag key="itemClassName" fill={true} intent={Intent.PRIMARY}>{material.getClassName()}</Tag> {attachedEllement} <Divider /> <img src={item.base64} style={{ width: `${Math.max(this.size * 2, 256)}px`, height: "256px", objectFit: "contain", backgroundColor: "#222222", left: "50%", }} ></img> </> ); } /** * Saves the given material as zip and returns its zip reference. * @param materialId the id of the material to save as zip. */ public getZippedMaterial(materialId: string): Nullable<Zip> { const material = this.editor.scene!.getMaterialByID(materialId); if (!material) { return null; } const json = material.serialize(); json.editorPreview = this.items.find((i) => i.key === materialId)?.base64; const jsonStr = JSON.stringify(json, null, "\t"); const task = this.editor.addTaskFeedback(0, "Saving Material..."); const textures = material.getActiveTextures(); const zip = new Zip(); zip.addFile("material.json", Buffer.alloc(jsonStr.length, jsonStr), "material configuration"); textures.forEach((texture, index) => { // Take care of embeded textures. if (texture.name.indexOf("data:") === 0) { return; } const path = join(Project.DirPath!, texture.name); zip.addLocalFile(path, "files/"); this.editor.updateTaskFeedback(task, (index / textures.length) * 100); }); this.editor.closeTaskFeedback(task, 500); return zip; } /** * Loads a material preset from the given preset path. * @param path the absolute path of the material preset. */ public loadMaterialFromZip(path: string): Nullable<Material> { const zip = new Zip(path); const entries = zip.getEntries(); const jsonEntry = entries.find((e) => e.entryName === "material.json"); if (!jsonEntry) { return null; } const json = JSON.parse(zip.readAsText(jsonEntry)); entries.forEach((e) => { if (e === jsonEntry) { return; } zip.extractEntryTo(e.entryName, Project.DirPath!, true, true); FilesStore.AddFile(join(Project.DirPath!, e.entryName)); }); const material = Material.Parse(json, this.editor.scene!, Project.DirPath!); if (material instanceof NodeMaterial) { material.build(true); } return material; } /** * Opens the given material in a separated window. * @param material defines the reference to the material to open. */ public async openMaterial(material: Material): Promise<void> { if (material instanceof NodeMaterial) { const index = MaterialAssets._NodeMaterialEditors.findIndex((m) => m.material === material); const existingId = index !== -1 ? MaterialAssets._NodeMaterialEditors[index].id : undefined; const popupId = await this.editor.addWindowedPlugin("node-material-editor", existingId, { json: material.serialize(), lights: material.getScene().lights.map((l) => l.serialize()), editorData: material.editorData, }); if (!popupId) { return; } if (index === -1) { MaterialAssets._NodeMaterialEditors.push({ id: popupId, material }); } else { MaterialAssets._NodeMaterialEditors[index].id = popupId; } let callback: (...args: any[]) => void; ipcRenderer.on(IPCResponses.SendWindowMessage, callback = (_, message) => { if (message.id !== "node-material-json") { return; } if (message.data.json && message.data.json.id !== material.id) { return; } if (message.data.closed) { ipcRenderer.removeListener(IPCResponses.SendWindowMessage, callback); const windowIndex = MaterialAssets._NodeMaterialEditors.findIndex((m) => m.id === popupId); if (windowIndex !== -1) { MaterialAssets._NodeMaterialEditors.splice(windowIndex, 1); } } if (message.data.json) { try { // Clear textures material.getTextureBlocks().forEach((block) => block.texture?.dispose()); material.editorData = message.data.editorData; material.loadFromSerialization(message.data.json); material.build(); material.metadata ??= {}; material.metadata.shouldExportTextures = true; IPCTools.SendWindowMessage(popupId, "node-material-json"); } catch (e) { IPCTools.SendWindowMessage(popupId, "graph-json", { error: true }); } this.refresh(material); } }); } else { await this.editor.addWindowedPlugin("material-viewer", undefined, { rootUrl: join(Project.DirPath!), json: material.serialize(), environmentTexture: this.editor.scene!.environmentTexture?.serialize(), }); } } /** * Returns, if found, the item in assets related to the given material. * @param material defines the reference to the material to retrieve its asset item. */ public getAssetFromMaterial(material: Material): Nullable<IAssetComponentItem> { return this.items.find((i) => i.key === material.id) ?? null; } /** * Called on the user wants to remove a material. */ private _handleRemoveMaterial(item: IAssetComponentItem): void { const material = this.editor.scene!.getMaterialByID(item.key); if (!material || material.metadata?.isLocked) { return; } const bindedMeshes = material.getBindedMeshes(); undoRedo.push({ description: `Removed material "${item.id}" from assets`, common: () => this.refresh(), redo: () => { this.editor.scene!.removeMaterial(material); bindedMeshes.forEach((m) => m.material = null); const index = this.items.indexOf(item); if (index !== -1) { this.items.splice(index, 1); } }, undo: () => { this.editor.scene!.addMaterial(material); bindedMeshes.forEach((m) => m.material = material); this.items.push(item); }, }) } /** * Adds a new material on the user clicks on the "Add Material..." button in the toolbar. */ private async _addMaterial(type: string): Promise<void> { const name = await Dialog.Show("Material Name", "Please provide a name for the new material to created."); const ctor = BabylonTools.Instantiate(`BABYLON.${type}`); const material = new ctor(name, this.editor.scene!); material.id = Tools.RandomId(); if (material instanceof NodeMaterial) { material.setToDefault(); material.build(true); } this.refresh(); } /** * Adds a new Node Material from the given snippet Id. */ private async _addNodeMaterialFromWeb(): Promise<void> { const snippetId = await Dialog.Show("Snippet Id", "Please provide the Id of the snippet."); Overlay.Show("Loading From Snippet...", true); try { const material = await NodeMaterial.ParseFromSnippetAsync(snippetId, this.editor.scene!); material.id = Tools.RandomId(); } catch (e) { Alert.Show("Failed to load from snippet", e.message); } Overlay.Hide(); this.refresh(); } /** * Called on the user wants to save the material. * @param item the item select when the user wants to save a material. */ private async _handleSaveMaterialPreset(item: IAssetComponentItem): Promise<void> { const zip = this.getZippedMaterial(item.key); if (!zip) { return; } let destination = await Tools.ShowSaveFileDialog("Save Material Preset"); const task = this.editor.addTaskFeedback(0, "Saving Material..."); const extension = extname(destination); if (extension !== ".zip") { destination += ".zip"; } this.editor.updateTaskFeedback(task, 50, "Writing preset..."); zip.writeZip(destination); this.editor.updateTaskFeedback(task, 100, "Done"); this.editor.closeTaskFeedback(task, 500); } /** * Called when the user wants to load a material from a preset. */ private async _handleLoadFromPreset(): Promise<void> { const files = await Tools.ShowNativeOpenMultipleFileDialog(); const task = this.editor.addTaskFeedback(0, "Loading presets..."); for (let i = 0; i < files.length; i++) { const file = files[i]; const material = this.loadMaterialFromZip(file.path); if (material) { material.id = Tools.RandomId(); } this.editor.updateTaskFeedback(task, (i / files.length) * 100, `Loaded preset "${material?.name}"`); await Tools.Wait(500); }; this.editor.updateTaskFeedback(task, 100, "Done"); this.editor.closeTaskFeedback(task, 1000); this.editor.assets.refresh(); } /** * Clears the unused textures in the project. */ private _clearUnusedMaterials(): void { if (this.editor.preview.state.isIsolatedMode) { return; } const toRemove = this.editor.scene!.materials.concat(this.editor.scene!.multiMaterials).filter((m) => m !== this.editor.scene!.defaultMaterial && !(m instanceof ShaderMaterial)); toRemove.forEach((material) => { if (!material || material.metadata?.isLocked) { return; } const bindedMesh = this.editor.scene!.meshes.find((m) => !m._masterMesh && m.material === material); // Used directly by a mesh, return. if (bindedMesh) { return; } // Search in multi materials const bindedMultiMaterial = this.editor.scene!.multiMaterials.find((mm) => mm.subMaterials.find((sm) => sm === material)); if (bindedMultiMaterial) { return; } // Not used, remove material. material.dispose(true, false); this.editor.console.logInfo(`Removed unused material "${material.name}"`); const itemIndex = this.items.findIndex((i) => i.key === material.id); if (itemIndex !== -1) { this.items.splice(itemIndex, 1); } }); this.refresh(); } }
the_stack
export namespace DeviceManagementModels { /** * * @export * @class RequiredError * @extends {Error} */ export class RequiredError extends Error { name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } } /** * * @export * @interface Device */ export interface Device { /** * id of the device * @type {string} * @memberof Device */ id?: string; /** * id of the Device Type this device belongs to * @type {string} * @memberof Device */ deviceTypeId?: string; /** * serial number of the device * @type {string} * @memberof Device */ serialNumber?: string; /** * creation date of the device * @type {string} * @memberof Device */ createdAt?: string; /** * id of the Asset that created Device will be mapped to * @type {string} * @memberof Device */ assetId?: string; /** * list of ids referring to the Agent(s) that are responsible for this device * @type {Array<string>} * @memberof Device */ agents?: Array<string>; /** * free json block for storing additional properties / characteristics of the device * @type {any} * @memberof Device */ properties?: any; } /** * * @export * @interface DeviceCreation */ export interface DeviceCreation { /** * id of the Device Type this device belongs to * @type {string} * @memberof DeviceCreation */ deviceTypeId: string; /** * serial number of the device * @type {string} * @memberof DeviceCreation */ serialNumber?: string; /** * id of the Asset that created Device will be mapped to * @type {string} * @memberof DeviceCreation */ assetId?: string; /** * list of ids referring to the Agent(s) that are responsible for this device * @type {Array<string>} * @memberof DeviceCreation */ agents?: Array<string>; /** * free json block for storing additional properties / characteristics of the device * @type {any} * @memberof DeviceCreation */ properties?: any; } /** * * @export * @interface DeviceType */ export interface DeviceType { /** * * @type {string} * @memberof DeviceType */ id?: string; /** * Owner tenant of the device type * @type {string} * @memberof DeviceType */ owner?: string; /** * Unique, user defined text to reference a device type * @type {string} * @memberof DeviceType */ code: string; /** * Unique, Id of the mapped assetTypeId * @type {string} * @memberof DeviceType */ assetTypeId: string; /** * * @type {string} * @memberof DeviceType */ name: string; /** * * @type {string} * @memberof DeviceType */ description: string; /** * creation date of the device type * @type {string} * @memberof DeviceType */ createdAt?: string; /** * free json block for storing additional properties / characteristics of the device type * @type {any} * @memberof DeviceType */ properties?: any; } /** * * @export * @interface DeviceTypeUpdate */ export interface DeviceTypeUpdate { /** * * @type {string} * @memberof DeviceTypeUpdate */ name?: string; /** * * @type {string} * @memberof DeviceTypeUpdate */ description?: string; /** * free json block for storing additional properties / characteristics of the device type * @type {any} * @memberof DeviceTypeUpdate */ properties?: any; } /** * * @export * @interface DeviceUpdate */ export interface DeviceUpdate { /** * serial number of the device * @type {string} * @memberof DeviceUpdate */ serialNumber?: string; /** * list of ids referring to the Agent(s) that are responsible for this device * @type {Array<string>} * @memberof DeviceUpdate */ agents?: Array<string>; /** * free json block for storing additional properties / characteristics of the device * @type {any} * @memberof DeviceUpdate */ properties?: any; } /** * * @export * @interface ErrorResponse */ export interface ErrorResponse { /** * * @type {Array<Error>} * @memberof ErrorResponse */ errors?: Array<Error>; } /** * * @export * @interface ModelError */ export interface ModelError { /** * identifier code for the reason of the error * @type {string} * @memberof ModelError */ code?: string; /** * log correlation ID * @type {string} * @memberof ModelError */ logref?: string; /** * error message * @type {string} * @memberof ModelError */ message?: string; } /** * paginated list of devices * @export * @interface PaginatedDevice */ export interface PaginatedDevice { /** * * @type {Array<Device>} * @memberof PaginatedDevice */ content?: Array<Device>; /** * * @type {any} * @memberof PaginatedDevice */ page?: any; } /** * paginated list of device types * @export * @interface PaginatedDeviceType */ export interface PaginatedDeviceType { /** * * @type {Array<DeviceType>} * @memberof PaginatedDeviceType */ content?: Array<DeviceType>; /** * * @type {any} * @memberof PaginatedDeviceType */ page?: any; } } export namespace DeviceStatusModels { /** * * @export * @class RequiredError * @extends {Error} */ export class RequiredError extends Error { name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } } /** * * @export * @interface DataConfigHealth */ export interface DataConfigHealth { /** * * @type {Date} * @memberof DataConfigHealth */ lastUpdate?: Date; /** * * @type {string} * @memberof DataConfigHealth */ configurationId: string; /** * * @type {Array<DataSourceHealth>} * @memberof DataConfigHealth */ dataSources: Array<DataSourceHealth>; } /** * * @export * @interface DataConfigHealthInput */ export interface DataConfigHealthInput { /** * * @type {Date} * @memberof DataConfigHealthInput */ lastUpdate?: Date; /** * * @type {string} * @memberof DataConfigHealthInput */ configurationId: string; /** * * @type {Array<DataSourceHealthNestedInput>} * @memberof DataConfigHealthInput */ dataSources: Array<DataSourceHealthNestedInput>; } /** * * @export * @interface DataConfigHealthNestedInput */ export interface DataConfigHealthNestedInput { /** * * @type {Date} * @memberof DataConfigHealthNestedInput */ lastUpdate?: Date; /** * * @type {string} * @memberof DataConfigHealthNestedInput */ configurationId: string; /** * * @type {Array<DataSourceHealthNestedInput>} * @memberof DataConfigHealthNestedInput */ dataSources: Array<DataSourceHealthNestedInput>; } /** * * @export * @interface DataPointHealth */ export interface DataPointHealth { /** * * @type {Date} * @memberof DataPointHealth */ lastUpdate?: Date; /** * * @type {string} * @memberof DataPointHealth */ dataPointId: string; /** * * @type {HealthStatus} * @memberof DataPointHealth */ health: HealthStatus; /** * * @type {string} * @memberof DataPointHealth */ message?: string; /** * * @type {Date} * @memberof DataPointHealth */ lastErrorTime?: Date; /** * * @type {string} * @memberof DataPointHealth */ lastErrorMessage?: string; /** * * @type {string} * @memberof DataPointHealth */ lastErrorCode?: string; /** * * @type {Date} * @memberof DataPointHealth */ lastSuccessfulReadTime?: Date; } /** * * @export * @interface DataPointHealthNestedInput */ export interface DataPointHealthNestedInput { /** * * @type {Date} * @memberof DataPointHealthNestedInput */ lastUpdate?: Date; /** * * @type {string} * @memberof DataPointHealthNestedInput */ dataPointId: string; /** * * @type {HealthStatus} * @memberof DataPointHealthNestedInput */ health: HealthStatus; /** * * @type {string} * @memberof DataPointHealthNestedInput */ message?: string; /** * * @type {string} * @memberof DataPointHealthNestedInput */ errorCode?: string; } /** * * @export * @interface DataSourceHealth */ export interface DataSourceHealth { /** * * @type {Date} * @memberof DataSourceHealth */ lastUpdate?: Date; /** * * @type {string} * @memberof DataSourceHealth */ name: string; /** * * @type {string} * @memberof DataSourceHealth */ dataSourceId?: string; /** * * @type {HealthStatus} * @memberof DataSourceHealth */ health: HealthStatus; /** * * @type {string} * @memberof DataSourceHealth */ message?: string; /** * * @type {Array<DataPointHealth>} * @memberof DataSourceHealth */ dataPoints?: Array<DataPointHealth>; } /** * * @export * @interface DataSourceHealthNestedInput */ export interface DataSourceHealthNestedInput { /** * * @type {Date} * @memberof DataSourceHealthNestedInput */ lastUpdate?: Date; /** * * @type {string} * @memberof DataSourceHealthNestedInput */ name: string; /** * * @type {string} * @memberof DataSourceHealthNestedInput */ dataSourceId?: string; /** * * @type {HealthStatus} * @memberof DataSourceHealthNestedInput */ health: HealthStatus; /** * * @type {string} * @memberof DataSourceHealthNestedInput */ message?: string; /** * * @type {Array<DataPointHealthNestedInput>} * @memberof DataSourceHealthNestedInput */ dataPoints?: Array<DataPointHealthNestedInput>; } /** * * @export * @interface DeviceHealthStatusReport */ export interface DeviceHealthStatusReport { /** * * @type {Date} * @memberof DeviceHealthStatusReport */ lastUpdate?: Date; /** * * @type {OverallDeviceHealth} * @memberof DeviceHealthStatusReport */ overall?: OverallDeviceHealth; /** * * @type {DataConfigHealth} * @memberof DeviceHealthStatusReport */ dataConfigHealth?: DataConfigHealth; /** * * @type {{ [key: string]: any; }} * @memberof DeviceHealthStatusReport */ customConfigHealth?: { [key: string]: any; }; } /** * * @export * @interface DeviceHealthStatusReportInput */ export interface DeviceHealthStatusReportInput { /** * * @type {OverallDeviceHealth} * @memberof DeviceHealthStatusReportInput */ overall?: OverallDeviceHealth; /** * * @type {DataConfigHealthNestedInput} * @memberof DeviceHealthStatusReportInput */ dataConfigHealth?: DataConfigHealthNestedInput; /** * * @type {{ [key: string]: any; }} * @memberof DeviceHealthStatusReportInput */ customConfigHealth?: { [key: string]: any; }; } /** * * @export * @interface ErrorResponse */ export interface ErrorResponse { /** * * @type {Array<Error>} * @memberof ErrorResponse */ errors?: Array<Error>; } /** * * @export * @enum {string} */ export enum HealthStatus { OK = <any> "OK", WARNING = <any> "WARNING", ERROR = <any> "ERROR" } /** * * @export * @interface Heartbeat */ export interface Heartbeat { /** * * @type {Date} * @memberof Heartbeat */ lastUpdate: Date; /** * * @type {boolean} * @memberof Heartbeat */ online: boolean; } /** * collection of installation records for software installed on a device * @export * @interface InventoryApplicationArray */ export interface InventoryApplicationArray extends Array<InventoryApplicationEntry> { } /** * installation record for a single edge application installed on a device * @export * @interface InventoryApplicationEntry */ export interface InventoryApplicationEntry { /** * unique, version independent id of the edge application product * @type {string} * @memberof InventoryApplicationEntry */ softwareId: string; /** * the version of the software; uniquely identifies a edge application release in combination with softwareId * @type {string} * @memberof InventoryApplicationEntry */ version: string; /** * * @type {SoftwareTypeApplication} * @memberof InventoryApplicationEntry */ type: SoftwareTypeApplication; /** * optional; short, human readable description of the edge application, will be displayed directly to end user if the installed edge application is not known to the backend * @type {string} * @memberof InventoryApplicationEntry */ description?: string; /** * optional; time of installation; current time will be used if omitted * @type {Date} * @memberof InventoryApplicationEntry */ installedAt: Date; } /** * collection of installation records for software installed on a device * @export * @interface InventoryArray */ export interface InventoryArray extends Array<InventoryEntry> { } /** * installation record for a single software installed on a device * @export * @interface InventoryEntry */ export interface InventoryEntry { /** * unique, version independent id of the software product * @type {string} * @memberof InventoryEntry */ softwareId: string; /** * the version of the software; uniquely identifies a software release in combination with softwareId * @type {string} * @memberof InventoryEntry */ version: string; /** * * @type {SoftwareType} * @memberof InventoryEntry */ type: SoftwareType; /** * optional; short, human readable description of the software, will be displayed directly to end user if the installed software is not known to the backend * @type {string} * @memberof InventoryEntry */ description?: string; /** * optional; time of installation; current time will be used if omitted * @type {Date} * @memberof InventoryEntry */ installedAt: Date; } /** * installation record for a single firmware installed on a device * @export * @interface InventoryFirmwareEntry */ export interface InventoryFirmwareEntry { /** * unique, version independent id of the firmware product * @type {string} * @memberof InventoryFirmwareEntry */ softwareId: string; /** * the version of the software; uniquely identifies a firmware release in combination with softwareId * @type {string} * @memberof InventoryFirmwareEntry */ version: string; /** * * @type {SoftwareTypeFirmware} * @memberof InventoryFirmwareEntry */ type: SoftwareTypeFirmware; /** * optional; short, human readable description of the firmware, will be displayed directly to end user if the installed firmware is not known to the backend * @type {string} * @memberof InventoryFirmwareEntry */ description?: string; /** * optional; time of installation; current time will be used if omitted * @type {Date} * @memberof InventoryFirmwareEntry */ installedAt: Date; } /** * * @export * @interface ModelError */ export interface ModelError { /** * identifier code for the reason of the error * @type {string} * @memberof ModelError */ code?: string; /** * log correlation ID * @type {string} * @memberof ModelError */ logref?: string; /** * error message * @type {string} * @memberof ModelError */ message?: string; } /** * * @export * @interface OnlineStatus */ export interface OnlineStatus { /** * * @type {Heartbeat} * @memberof OnlineStatus */ heartbeat: Heartbeat; } /** * * @export * @interface OverallDeviceHealth */ export interface OverallDeviceHealth { /** * * @type {Date} * @memberof OverallDeviceHealth */ lastUpdate?: Date; /** * * @type {HealthStatus} * @memberof OverallDeviceHealth */ health: HealthStatus; /** * * @type {string} * @memberof OverallDeviceHealth */ message?: string; } /** * * @export * @interface PaginatedSoftwareInventoryRecord */ export interface PaginatedSoftwareInventoryRecord { /** * * @type {Array<SoftwareInventoryRecord>} * @memberof PaginatedSoftwareInventoryRecord */ content?: Array<SoftwareInventoryRecord>; /** * * @type {any} * @memberof PaginatedSoftwareInventoryRecord */ page?: any; } /** * information about a software release installed on a device * @export * @interface SoftwareInventoryRecord */ export interface SoftwareInventoryRecord { /** * id of the inventory record * @type {string} * @memberof SoftwareInventoryRecord */ id?: string; /** * * @type {string} * @memberof SoftwareInventoryRecord */ deviceId?: string; /** * * @type {string} * @memberof SoftwareInventoryRecord */ softwareType?: SoftwareInventoryRecord.SoftwareTypeEnum; /** * id of the software \"product\" (version independent id) * @type {string} * @memberof SoftwareInventoryRecord */ softwareId?: string; /** * id of the software release (version dependent id) * @type {string} * @memberof SoftwareInventoryRecord */ softwareReleaseId?: string; /** * version number of the software release * @type {string} * @memberof SoftwareInventoryRecord */ version?: string; /** * installation time (accuracy depends on device side implementation) * @type {Date} * @memberof SoftwareInventoryRecord */ installedAt?: Date; /** * source of information, `MANUAL` indicated the device notified the backend that the software is present; SWDEPLOY indicated the software was installed via the software deployment service of the backend * @type {string} * @memberof SoftwareInventoryRecord */ installedBy?: SoftwareInventoryRecord.InstalledByEnum; } /** * @export * @namespace SoftwareInventoryRecord */ export namespace SoftwareInventoryRecord { /** * @export * @enum {string} */ export enum SoftwareTypeEnum { FIRMWARE = <any> "FIRMWARE", APP = <any> "APP" } /** * @export * @enum {string} */ export enum InstalledByEnum { MANUAL = <any> "MANUAL", SWDEPLOY = <any> "SWDEPLOY" } } /** * the type of software, will be extended over time with new values * @export * @enum {string} */ export enum SoftwareType { FIRMWARE = <any> "FIRMWARE", APP = <any> "APP" } /** * the type representation of edge applications * @export * @enum {string} */ export enum SoftwareTypeApplication { APP = <any> "APP" } /** * the type representation of firmware * @export * @enum {string} */ export enum SoftwareTypeFirmware { FIRMWARE = <any> "FIRMWARE" } } export namespace DeviceConfigurationModels { /** * * @export * @class RequiredError * @extends {Error} */ export class RequiredError extends Error { name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } } /** * * @export * @interface ConfigurationFile */ export interface ConfigurationFile { /** * unique \"path\" of the file * @type {string} * @memberof ConfigurationFile */ path: string; /** * optional description of the file's content or purpose * @type {string} * @memberof ConfigurationFile */ description?: string; } /** * * @export * @interface ConfigurationFileReference */ export interface ConfigurationFileReference { /** * name of the file * @type {string} * @memberof ConfigurationFileReference */ name: string; /** * download URI * @type {string} * @memberof ConfigurationFileReference */ uri: string; /** * hash of the file in format `<algorithm>:<hash in hex>` * @type {string} * @memberof ConfigurationFileReference */ checksum: string; } /** * information about a single state of the state machine * @export * @interface ConfigurationStateInfo */ export interface ConfigurationStateInfo { /** * date and time when the state was first entered * @type {Date} * @memberof ConfigurationStateInfo */ entered?: Date; /** * date and time the state was last updated, will differ from \"entered\" if state is updated repeatedly * @type {Date} * @memberof ConfigurationStateInfo */ updated?: Date; /** * progress in current state as value in [0.0, 1.0] * @type {number} * @memberof ConfigurationStateInfo */ progress?: number; /** * status message / info, free text from device * @type {string} * @memberof ConfigurationStateInfo */ message?: string; /** * arbitrary block of json data, should be used to report additional information such as error details, stack traces, etc; max size in string representation is 20k * @type {any} * @memberof ConfigurationStateInfo */ details?: any; /** * name of the state * @type {string} * @memberof ConfigurationStateInfo */ state?: ConfigurationStateInfo.StateEnum; } /** * @export * @namespace ConfigurationStateInfo */ export namespace ConfigurationStateInfo { /** * @export * @enum {string} */ export enum StateEnum { CREATED = <any> "CREATED", CONFIGURE = <any> "CONFIGURE", CONFIGURING = <any> "CONFIGURING", CONFIGURED = <any> "CONFIGURED", CANCELED = <any> "CANCELED", FAILED = <any> "FAILED" } } /** * a configuration update task * @export * @interface ConfigurationTask */ export interface ConfigurationTask { /** * unique id of the task * @type {string} * @memberof ConfigurationTask */ id?: string; /** * unique id of the device owning the task * @type {string} * @memberof ConfigurationTask */ deviceId?: string; /** * list of files to be updated as part of this task * @type {Array<ConfigurationFileReference>} * @memberof ConfigurationTask */ files?: Array<ConfigurationFileReference>; /** * optional; arbitrary, user defined block of json containing additional information for the device * @type {any} * @memberof ConfigurationTask */ customData?: any; /** * creation time of the task * @type {Date} * @memberof ConfigurationTask */ createdAt?: Date; /** * * @type {ConfigurationStateInfo} * @memberof ConfigurationTask */ currentState?: ConfigurationStateInfo; /** * * @type {Target} * @memberof ConfigurationTask */ target?: Target; /** * list of history to be updated as part of this task * @type {Array<ConfigurationStateInfo>} * @memberof ConfigurationTask */ history?: Array<ConfigurationStateInfo>; /** * list of history to be updated as part of this task * @type {Array<Transition>} * @memberof ConfigurationTask */ transitions?: Array<Transition>; } /** * * @export * @interface ErrorResponse */ export interface ErrorResponse { /** * * @type {Array<Error>} * @memberof ErrorResponse */ errors?: Array<Error>; } /** * * @export * @interface FileMetaData */ export interface FileMetaData { /** * * @type {string} * @memberof FileMetaData */ description?: string; /** * * @type {string} * @memberof FileMetaData */ head?: string; /** * * @type {string} * @memberof FileMetaData */ id?: string; /** * * @type {string} * @memberof FileMetaData */ path?: string; } /** * paginated list of files meta data * @export * @interface PaginatedFileMetaData */ export interface PaginatedFileMetaData { /** * * @type {Array<FileMetaData>} * @memberof PaginatedFileMetaData */ content?: Array<FileMetaData>; /** * * @type {any} * @memberof PaginatedFileMetaData */ page?: any; } /** * * @export * @interface ModelError */ export interface ModelError { /** * identifier code for the reason of the error * @type {string} * @memberof ModelError */ code?: string; /** * log correlation ID * @type {string} * @memberof ModelError */ logref?: string; /** * error message * @type {string} * @memberof ModelError */ message?: string; } /** * paginated list of configuration update tasks * @export * @interface PaginatedConfigurationTask */ export interface PaginatedConfigurationTask { /** * * @type {Array<ConfigurationTask>} * @memberof PaginatedConfigurationTask */ content?: Array<ConfigurationTask>; /** * * @type {any} * @memberof PaginatedConfigurationTask */ page?: any; } /** * Content of the file * @export * @interface Payload */ export interface Payload { } /** * * @export * @interface RevisionMetaData */ export interface RevisionMetaData { /** * the hash of the file revision, also serves as unique identifier of the revision (content based addressing) * @type {string} * @memberof RevisionMetaData */ hash?: string; /** * the id of the file this revision belongs to * @type {string} * @memberof RevisionMetaData */ fileId?: string; /** * length of the content (=file size in bytes) * @type {number} * @memberof RevisionMetaData */ contentLength?: number; /** * content type of the content as used by http (MIME type + charset or other attributes) * @type {string} * @memberof RevisionMetaData */ contentType?: string; } /** * paginated list of files meta data * @export * @interface PaginatedRevisionMetaData */ export interface PaginatedRevisionMetaData { /** * * @type {Array<RevisionMetaData>} * @memberof PaginatedRevisionMetaData */ content?: Array<RevisionMetaData>; /** * * @type {any} * @memberof PaginatedRevisionMetaData */ page?: any; } /** * target of the task in the device * @export * @interface Target */ export interface Target { /** * target address of the task in the device * @type {string} * @memberof Target */ address?: string; } /** * * @export * @interface TaskDefinition */ export interface TaskDefinition { /** * * @type {Array<ConfigurationFileReference>} * @memberof TaskDefinition */ files: Array<ConfigurationFileReference>; /** * optional; arbitrary, user defined block of json containing additional information for the device * @type {{ [key: string]: any; }} * @memberof TaskDefinition */ customData?: { [key: string]: any; }; /** * optional; arbitrary, user defined block of json containing target * @type {any} * @memberof TaskDefinition */ target?: any; } /** * a transition state * @export * @interface Transition */ export interface Transition { /** * current transition of the task * @type {string} * @memberof Transition */ from?: string; /** * next transition of the task * @type {string} * @memberof Transition */ to?: string; } /** * * @export * @interface Updatetask */ export interface Updatetask { /** * * @type {string} * @memberof Updatetask */ state: Updatetask.StateEnum; /** * progress in current state as value in [0.0, 1.0] * @type {number} * @memberof Updatetask */ progress: number; /** * optional; status message / info, free text from device * @type {string} * @memberof Updatetask */ message?: string; /** * optional; arbitrary block of json data, should be used to report additional information such as error details, stack traces, etc; max size in string representation is 20k * @type {any} * @memberof Updatetask */ details?: any; } /** * @export * @namespace Updatetask */ export namespace Updatetask { /** * @export * @enum {string} */ export enum StateEnum { CONFIGURING = <any> "CONFIGURING", CONFIGURED = <any> "CONFIGURED", CANCELED = <any> "CANCELED", FAILED = <any> "FAILED" } } } export namespace DeploymentWorkflowModels { /** * * @export * @class RequiredError * @extends {Error} */ export class RequiredError extends Error { name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } } /** * * @export * @interface CustomTransition */ export interface CustomTransition { /** * * @type {string} * @memberof CustomTransition */ from: string; /** * * @type {string} * @memberof CustomTransition */ to: string; /** * * @type {TransitionType} * @memberof CustomTransition */ type: TransitionType; /** * * @type {{ [key: string]: any; }} * @memberof CustomTransition */ details?: { [key: string]: any; }; } /** * * @export * @interface ErrorResponse */ export interface ErrorResponse { /** * * @type {Array<Error>} * @memberof ErrorResponse */ errors?: Array<Error>; } /** * * @export * @interface Instance */ export interface Instance { /** * * @type {string} * @memberof Instance */ id?: string; /** * * @type {string} * @memberof Instance */ deviceId?: string; /** * date and time when the instance was created * @type {Date} * @memberof Instance */ createdAt?: Date; /** * * @type {StateInfo} * @memberof Instance */ currentState?: StateInfo; /** * * @type {Array<StateInfo>} * @memberof Instance */ history?: Array<StateInfo>; /** * * @type {InstanceModel} * @memberof Instance */ model?: InstanceModel; /** * * @type {{ [key: string]: any; }} * @memberof Instance */ data?: { [key: string]: any; }; } /** * * @export * @interface InstanceModel */ export interface InstanceModel { /** * * @type {string} * @memberof InstanceModel */ key?: string; /** * * @type {Array<State>} * @memberof InstanceModel */ states?: Array<State>; /** * * @type {Array<CustomTransition>} * @memberof InstanceModel */ transitions?: Array<CustomTransition>; /** * * @type {Array<StateGroup>} * @memberof InstanceModel */ stateGroups?: Array<StateGroup>; } /** * * @export * @interface InstanceRequest */ export interface InstanceRequest { /** * * @type {string} * @memberof InstanceRequest */ deviceId?: string; /** * * @type {ModelCustomization} * @memberof InstanceRequest */ model?: ModelCustomization; /** * * @type {{ [key: string]: any; }} * @memberof InstanceRequest */ data?: { [key: string]: any; }; } /** * * @export * @interface Model */ export interface Model { /** * User provided unique model name * @type {string} * @memberof Model */ key?: string; /** * * @type {Array<State>} * @memberof Model */ states?: Array<State>; /** * * @type {Array<Transition>} * @memberof Model */ transitions?: Array<Transition>; /** * * @type {Array<StateGroup>} * @memberof Model */ groups?: Array<StateGroup>; } /** * * @export * @interface ModelCustomization */ export interface ModelCustomization { /** * * @type {string} * @memberof ModelCustomization */ key?: string; /** * * @type {Array<CustomTransition>} * @memberof ModelCustomization */ customTransitions?: Array<CustomTransition>; } /** * * @export * @interface ModelError */ export interface ModelError { /** * identifier code for the reason of the error * @type {string} * @memberof ModelError */ code?: string; /** * log correlation ID * @type {string} * @memberof ModelError */ logref?: string; /** * error message * @type {string} * @memberof ModelError */ message?: string; } /** * paginated list of instances * @export * @interface PaginatedInstanceList */ export interface PaginatedInstanceList { /** * * @type {Array<Instance>} * @memberof PaginatedInstanceList */ content?: Array<Instance>; /** * * @type {any} * @memberof PaginatedInstanceList */ page?: any; } /** * * @export * @interface State */ export interface State { /** * * @type {string} * @memberof State */ name: string; /** * * @type {string} * @memberof State */ description: string; /** * * @type {boolean} * @memberof State */ initial?: boolean; /** * * @type {boolean} * @memberof State */ _final?: boolean; /** * * @type {boolean} * @memberof State */ cancel?: boolean; } /** * * @export * @interface StateGroup */ export interface StateGroup { /** * * @type {string} * @memberof StateGroup */ name?: string; /** * * @type {Array<string>} * @memberof StateGroup */ states?: Array<string>; } /** * information about a single state of the state machine * @export * @interface StateInfo */ export interface StateInfo { /** * date and time when the state was first entered * @type {Date} * @memberof StateInfo */ entered?: Date; /** * date and time the state was last updated, will differ from \"entered\" if state is updated repeatedly * @type {Date} * @memberof StateInfo */ updated?: Date; /** * progress in current state as value in [0.0, 1.0] * @type {number} * @memberof StateInfo */ progress?: number; /** * status message / info, free text from device * @type {string} * @memberof StateInfo */ message?: string; /** * arbitrary block of json data, should be used to report additional information such as error details, stack traces, etc; max size in string representation is 20k * @type {{ [key: string]: any; }} * @memberof StateInfo */ details?: { [key: string]: any; }; /** * name of the state * @type {string} * @memberof StateInfo */ state?: string; } /** * * @export * @interface Transition */ export interface Transition { /** * * @type {string} * @memberof Transition */ from: string; /** * * @type {string} * @memberof Transition */ to: string; /** * * @type {TransitionType} * @memberof Transition */ type: TransitionType; /** * * @type {Array<TransitionType>} * @memberof Transition */ allowedTypes?: Array<TransitionType>; } /** * * @export * @enum {string} */ export enum TransitionType { INSTANTANEOUS = <any> "INSTANTANEOUS", BACKENDTRIGGER = <any> "BACKEND_TRIGGER", DEVICETRIGGER = <any> "DEVICE_TRIGGER", BACKENDTIMETRIGGER = <any> "BACKEND_TIME_TRIGGER", DEVICETIMETRIGGER = <any> "DEVICE_TIME_TRIGGER" } } export namespace EdgeAppInstanceModels { /** * * @export * @class RequiredError * @extends {Error} */ export class RequiredError extends Error { name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } } /** * * @export * @interface ApplicationInstance */ export interface ApplicationInstance { /** * * @type {string} * @memberof ApplicationInstance */ name: string; /** * * @type {string} * @memberof ApplicationInstance */ appInstanceId: string; /** * * @type {string} * @memberof ApplicationInstance */ deviceId: string; /** * * @type {string} * @memberof ApplicationInstance */ releaseId: string; /** * * @type {string} * @memberof ApplicationInstance */ applicationId: string; } /** * paginated list of app instance configurations * @export * @interface PaginatedApplicationInstance */ export interface PaginatedApplicationInstance { /** * * @type {Array<ApplicationInstance>} * @memberof PaginatedApplicationInstance */ content?: Array<ApplicationInstance>; /** * * @type {any} * @memberof PaginatedApplicationInstance */ page?: any; } /** * * @export * @interface ApplicationInstanceLifeCycleResource */ export interface ApplicationInstanceLifeCycleResource { /** * * @type {string} * @memberof ApplicationInstanceLifeCycleResource */ id?: string; /** * * @type {string} * @memberof ApplicationInstanceLifeCycleResource */ status?: ApplicationInstanceLifeCycleResource.StatusEnum; } /** * @export * @namespace ApplicationInstanceLifeCycleResource */ export namespace ApplicationInstanceLifeCycleResource { /** * @export * @enum {string} */ export enum StatusEnum { STOPPED = <any> "STOPPED", RUNNING = <any> "RUNNING" } } /** * * @export * @interface ApplicationInstanceLifeCycleStatus */ export interface ApplicationInstanceLifeCycleStatus { /** * * @type {string} * @memberof ApplicationInstanceLifeCycleStatus */ status?: ApplicationInstanceLifeCycleStatus.StatusEnum; } /** * @export * @namespace ApplicationInstanceLifeCycleStatus */ export namespace ApplicationInstanceLifeCycleStatus { /** * @export * @enum {string} */ export enum StatusEnum { STOPPED = <any> "STOPPED", RUNNING = <any> "RUNNING" } } /** * * @export * @interface ApplicationInstanceResource */ export interface ApplicationInstanceResource { /** * * @type {string} * @memberof ApplicationInstanceResource */ id?: string; /** * * @type {string} * @memberof ApplicationInstanceResource */ name?: string; /** * * @type {string} * @memberof ApplicationInstanceResource */ deviceId?: string; /** * * @type {string} * @memberof ApplicationInstanceResource */ releaseId?: string; /** * * @type {string} * @memberof ApplicationInstanceResource */ applicationId?: string; /** * * @type {string} * @memberof ApplicationInstanceResource */ status?: ApplicationInstanceResource.StatusEnum; } /** * @export * @namespace ApplicationInstanceResource */ export namespace ApplicationInstanceResource { /** * @export * @enum {string} */ export enum StatusEnum { STOPPED = <any> "STOPPED", RUNNING = <any> "RUNNING" } } /** * * @export * @interface ErrorResponse */ export interface ErrorResponse { /** * * @type {Array<any>} * @memberof ErrorResponse */ errors?: Array<any>; } /** * * @export * @interface InstanceConfiguration */ export interface InstanceConfiguration { /** * ID of the device * @type {string} * @memberof InstanceConfiguration */ deviceId: string; /** * ID of the application product * @type {string} * @memberof InstanceConfiguration */ appId: string; /** * ID of the application release * @type {string} * @memberof InstanceConfiguration */ appReleaseId: string; /** * ID of the application instance * @type {string} * @memberof InstanceConfiguration */ appInstanceId: string; /** * User defined custom properties * @type {{ [key: string]: any; }} * @memberof InstanceConfiguration */ configuration: { [key: string]: any; }; } /** * * @export * @interface InstanceConfigurationResource */ export interface InstanceConfigurationResource { /** * ID of the device * @type {string} * @memberof InstanceConfigurationResource */ deviceId?: string; /** * ID of the application product * @type {string} * @memberof InstanceConfigurationResource */ appId?: string; /** * ID of the application release * @type {string} * @memberof InstanceConfigurationResource */ appReleaseId?: string; /** * ID of the application instance * @type {string} * @memberof InstanceConfigurationResource */ appInstanceId?: string; /** * User defined custom properties * @type {{ [key: string]: any; }} * @memberof InstanceConfigurationResource */ configuration?: { [key: string]: any; }; } /** * paginated list of app instance configurations * @export * @interface PaginatedInstanceConfigurationResource */ export interface PaginatedInstanceConfigurationResource { /** * * @type {Array<InstanceConfigurationResource>} * @memberof PaginatedInstanceConfigurationResource */ content?: Array<InstanceConfigurationResource>; /** * * @type {any} * @memberof PaginatedInstanceConfigurationResource */ page?: any; } /** * * @export * @interface ProcessInstanceConfiguration */ export interface ProcessInstanceConfiguration { /** * * @type {Array<any>} * @memberof ProcessInstanceConfiguration */ instanceConfigurations?: Array<any>; } } export namespace EdgeAppDeploymentModels { /** * * @export */ export const COLLECTION_FORMATS = { csv: ",", ssv: " ", tsv: "\t", pipes: "|", }; /** * * @export * @class RequiredError * @extends {Error} */ export class RequiredError extends Error { name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } } /** * * @export * @interface ErrorResponse */ export interface ErrorResponse { /** * * @type {Array<any>} * @memberof ErrorResponse */ errors?: Array<any>; } /** * * @export * @interface Task */ export interface Task { /** * ID of the device (Will be taken from path if omitted) * @type {string} * @memberof Task */ deviceId: string; /** * Globally unique ID of the software product (Version independent) * @type {string} * @memberof Task */ softwareId: string; /** * Globally unique ID of the release (Version dependent) * @type {string} * @memberof Task */ softwareReleaseId: string; /** * Arbitrary, user defined block of json contaning additional information for the device * @type {{ [key: string]: any; }} * @memberof Task */ customData?: { [key: string]: any; }; } /** * * @export * @interface TaskResource */ export interface TaskResource { /** * ID of the task * @type {string} * @memberof TaskResource */ id?: string; /** * ID of the device owning the task * @type {string} * @memberof TaskResource */ deviceId?: string; /** * Type of software artifact * @type {string} * @memberof TaskResource */ softwareType?: TaskResource.SoftwareTypeEnum; /** * Globally unique ID of the software product (Version independent) * @type {string} * @memberof TaskResource */ softwareId?: string; /** * Globally unique ID of the software release (Version dependent) * @type {string} * @memberof TaskResource */ softwareReleaseId?: string; /** * The version of the software release as human readable string * @type {string} * @memberof TaskResource */ softwareVersion?: string; /** * * @type {any} * @memberof TaskResource */ transitions?: any; /** * * @type {any} * @memberof TaskResource */ history?: any; /** * * @type {Array<any>} * @memberof TaskResource */ artifacts?: Array<any>; /** * Arbitrary, user defined block of json containing additional information for the device * @type {{ [key: string]: any; }} * @memberof TaskResource */ customData?: { [key: string]: any; }; /** * Datetime when the task was created * @type {Date} * @memberof TaskResource */ createdAt?: Date; /** * * @type {any} * @memberof TaskResource */ currentState?: any; } /** * paginated list of task ressources * @export * @interface PaginatedTaskResource */ export interface PaginatedTaskResource { /** * * @type {Array<TaskResource>} * @memberof PaginatedTaskResource */ content?: Array<TaskResource>; /** * * @type {any} * @memberof PaginatedTaskResource */ page?: any; } /** * @export * @namespace TaskResource */ export namespace TaskResource { /** * @export * @enum {string} */ export enum SoftwareTypeEnum { APP = <any> "APP" } } /** * * @export * @interface TaskStatus */ export interface TaskStatus { /** * The new state of the task (might be same as current state) * @type {string} * @memberof TaskStatus */ state: TaskStatus.StateEnum; /** * Progress in current state as value in [0.0, 1.0] * @type {number} * @memberof TaskStatus */ progress: number; /** * Status message * @type {string} * @memberof TaskStatus */ message?: string; /** * Arbitrary block of json data, should be used to report additional information such as error details, stack traces and etc * @type {{ [key: string]: any; }} * @memberof TaskStatus */ details?: { [key: string]: any; }; } /** * @export * @namespace TaskStatus */ export namespace TaskStatus { /** * @export * @enum {string} */ export enum StateEnum { DOWNLOAD = <any> "DOWNLOAD", INSTALL = <any> "INSTALL", ACTIVATE = <any> "ACTIVATE", CANCELED = <any> "CANCELED", FAILED = <any> "FAILED" } } /** * * @export * @interface TermsAndConditions */ export interface TermsAndConditions { /** * ID of the device * @type {string} * @memberof TermsAndConditions */ deviceId: string; /** * ID of the application release * @type {string} * @memberof TermsAndConditions */ releaseId: string; } /** * * @export * @interface TermsAndConditionsResource */ export interface TermsAndConditionsResource { /** * ID of the device * @type {string} * @memberof TermsAndConditionsResource */ deviceId?: string; /** * ID of the application release * @type {string} * @memberof TermsAndConditionsResource */ releaseId?: string; /** * * @type {Date} * @memberof TermsAndConditionsResource */ firstAccepted?: Date; } } export namespace FirmwareDeploymentModels { /** * * @export */ export const COLLECTION_FORMATS = { csv: ",", ssv: " ", tsv: "\t", pipes: "|", }; /** * * @export * @class RequiredError * @extends {Error} */ export class RequiredError extends Error { name: "RequiredError" = "RequiredError"; constructor(public field: string, msg?: string) { super(msg); } } /** * * @export * @interface ErrorResponse */ export interface ErrorResponse { /** * * @type {Array<Error>} * @memberof ErrorResponse */ errors?: Array<Error>; } /** * * @export * @interface InstallationArtifact */ export interface InstallationArtifact { /** * name of the file * @type {string} * @memberof InstallationArtifact */ name: string; /** * download URI * @type {string} * @memberof InstallationArtifact */ uri: string; /** * hash of the file in format `<algorithm>:<hash in hex>` * @type {string} * @memberof InstallationArtifact */ checksum: string; /** * expiry time for `uri` * @type {Date} * @memberof InstallationArtifact */ validUntil?: Date; } /** * information about a single state of the state machine * @export * @interface InstallationStateInfo */ export interface InstallationStateInfo { /** * date and time when the state was first entered * @type {Date} * @memberof InstallationStateInfo */ entered?: Date; /** * date and time the state was last updated, will differ from \"entered\" if state is updated repeatedly * @type {Date} * @memberof InstallationStateInfo */ updated?: Date; /** * progress in current state as value in [0.0, 1.0] * @type {number} * @memberof InstallationStateInfo */ progress?: number; /** * status message / info, free text from device * @type {string} * @memberof InstallationStateInfo */ message?: string; /** * arbitrary block of json data, should be used to report additional information such as error details, stack traces, etc; max size in string representation is 20k * @type {any} * @memberof InstallationStateInfo */ details?: any; /** * name of the state * @type {string} * @memberof InstallationStateInfo */ state?: InstallationStateInfo.StateEnum; } /** * @export * @namespace InstallationStateInfo */ export namespace InstallationStateInfo { /** * @export * @enum {string} */ export enum StateEnum { CREATED = <any> "CREATED", DOWNLOAD = <any> "DOWNLOAD", DOWNLOADING = <any> "DOWNLOADING", DOWNLOADED = <any> "DOWNLOADED", INSTALL = <any> "INSTALL", INSTALLING = <any> "INSTALLING", INSTALLED = <any> "INSTALLED", ACTIVATE = <any> "ACTIVATE", ACTIVATING = <any> "ACTIVATING", ACTIVATED = <any> "ACTIVATED", CANCELED = <any> "CANCELED", FAILED = <any> "FAILED" } } /** * single task * @export * @interface InstallationTask */ export interface InstallationTask { /** * globally unique id of the task * @type {string} * @memberof InstallationTask */ id?: string; /** * id of the device owning the task * @type {string} * @memberof InstallationTask */ deviceId?: string; /** * type of software artifact: firmware, app, etc; list will be extended in future releases * @type {string} * @memberof InstallationTask */ softwareType?: InstallationTask.SoftwareTypeEnum; /** * globally unique id of the software product (version independent id) * @type {string} * @memberof InstallationTask */ softwareId?: string; /** * globally unique id of the specific release (version dependent) * @type {string} * @memberof InstallationTask */ softwareReleaseId?: string; /** * the version of the software as human readable string * @type {string} * @memberof InstallationTask */ softwareVersion?: string; /** * Indicates whether to install or remove the software * @type {string} * @memberof InstallationTask */ actionType?: InstallationTask.ActionTypeEnum; /** * if set to true, task is going to be cancelled * @type {boolean} * @memberof InstallationTask */ shouldCancel?: boolean; /** * possible set of transitions * @type {Array<Transition>} * @memberof InstallationTask */ transitions?: Array<Transition>; /** * previously passed states of task * @type {Array<InstallationStateInfo>} * @memberof InstallationTask */ history?: Array<InstallationStateInfo>; /** * * @type {Array<InstallationArtifact>} * @memberof InstallationTask */ artifacts?: Array<InstallationArtifact>; /** * optional; arbitrary, user defined block of json containing additional information for the device * @type {{ [key: string]: any; }} * @memberof InstallationTask */ customData?: { [key: string]: any; }; /** * date and time when the task was created * @type {Date} * @memberof InstallationTask */ createdAt?: Date; /** * * @type {InstallationStateInfo} * @memberof InstallationTask */ currentState?: InstallationStateInfo; } /** * @export * @namespace InstallationTask */ export namespace InstallationTask { /** * @export * @enum {string} */ export enum SoftwareTypeEnum { FIRMWARE = <any> "FIRMWARE", APP = <any> "APP" } /** * @export * @enum {string} */ export enum ActionTypeEnum { INSTALL = <any> "INSTALL", REMOVE = <any> "REMOVE" } } /** * * @export * @interface InstallationTaskInfo */ export interface InstallationTaskInfo { /** * optional, id of the device; will be taken from path if omitted * @type {string} * @memberof InstallationTaskInfo */ deviceId?: string; /** * type of software artifact (firmware, app, etc); list will be extended in future releases * @type {string} * @memberof InstallationTaskInfo */ softwareType: InstallationTaskInfo.SoftwareTypeEnum; /** * globally unique id of the software product (version independent id) * @type {string} * @memberof InstallationTaskInfo */ softwareId: string; /** * globally unique id of the specific release (version dependent) * @type {string} * @memberof InstallationTaskInfo */ softwareReleaseId: string; /** * custom transitions * @type {Array<Transition>} * @memberof InstallationTaskInfo */ transitions?: Array<Transition>; /** * optional; arbitrary, user defined block of json containing additional information for the device * @type {{ [key: string]: any; }} * @memberof InstallationTaskInfo */ customData?: { [key: string]: any; }; } /** * @export * @namespace InstallationTaskInfo */ export namespace InstallationTaskInfo { /** * @export * @enum {string} */ export enum SoftwareTypeEnum { FIRMWARE = <any> "FIRMWARE", APP = <any> "APP" } } /** * * @export * @interface ModelError */ export interface ModelError { /** * identifier code for the reason of the error * @type {string} * @memberof ModelError */ code?: string; /** * log correlation ID * @type {string} * @memberof ModelError */ logref?: string; /** * error message * @type {string} * @memberof ModelError */ message?: string; } /** * paginated list of configuration update tasks * @export * @interface PaginatedInstallationTask */ export interface PaginatedInstallationTask { /** * * @type {Array<InstallationTask>} * @memberof PaginatedInstallationTask */ content?: Array<InstallationTask>; /** * * @type {any} * @memberof PaginatedInstallationTask */ page?: any; } /** * backend sent progress update * @export * @interface TaskUpdate */ export interface TaskUpdate { /** * the new state of the task (might be same as current state) * @type {string} * @memberof TaskUpdate */ state: TaskUpdate.StateEnum; /** * progress in current state as value in [0.0, 1.0] * @type {number} * @memberof TaskUpdate */ progress: number; /** * optional; status message / info, free text from backend * @type {string} * @memberof TaskUpdate */ message?: string; /** * arbitrary block of json data, should be used to report additional information such as error details, stack traces, etc; max size in string representation is 20k * @type {any} * @memberof TaskUpdate */ details?: any; } /** * @export * @namespace TaskUpdate */ export namespace TaskUpdate { /** * @export * @enum {string} */ export enum StateEnum { CREATED = <any> "CREATED", DOWNLOAD = <any> "DOWNLOAD", DOWNLOADING = <any> "DOWNLOADING", DOWNLOADED = <any> "DOWNLOADED", INSTALL = <any> "INSTALL", INSTALLING = <any> "INSTALLING", INSTALLED = <any> "INSTALLED", ACTIVATE = <any> "ACTIVATE", ACTIVATING = <any> "ACTIVATING", ACTIVATED = <any> "ACTIVATED", CANCELED = <any> "CANCELED", FAILED = <any> "FAILED" } } /** * * @export * @interface TermsAndConditionsAcceptance */ export interface TermsAndConditionsAcceptance { /** * * @type {string} * @memberof TermsAndConditionsAcceptance */ deviceId?: string; /** * * @type {string} * @memberof TermsAndConditionsAcceptance */ releaseId?: string; } /** * * @export * @interface TermsAndConditionsRecord */ export interface TermsAndConditionsRecord { /** * * @type {string} * @memberof TermsAndConditionsRecord */ deviceId?: string; /** * * @type {string} * @memberof TermsAndConditionsRecord */ releaseId?: string; /** * * @type {Date} * @memberof TermsAndConditionsRecord */ firstAccepted?: Date; /** * * @type {string} * @memberof TermsAndConditionsRecord */ softwareId?: string; /** * * @type {string} * @memberof TermsAndConditionsRecord */ bundleId?: string; } /** * Information about the transition status * @export * @interface Transition */ export interface Transition { /** * type of the transition * @type {string} * @memberof Transition */ type?: string; /** * name of the state * @type {string} * @memberof Transition */ from?: Transition.FromEnum; /** * name of the state * @type {string} * @memberof Transition */ to?: Transition.ToEnum; /** * * @type {any} * @memberof Transition */ details?: any; } /** * @export * @namespace Transition */ export namespace Transition { /** * @export * @enum {string} */ export enum FromEnum { CREATED = <any> "CREATED", DOWNLOAD = <any> "DOWNLOAD", DOWNLOADING = <any> "DOWNLOADING", DOWNLOADED = <any> "DOWNLOADED", INSTALL = <any> "INSTALL", INSTALLING = <any> "INSTALLING", INSTALLED = <any> "INSTALLED", ACTIVATE = <any> "ACTIVATE", ACTIVATING = <any> "ACTIVATING", ACTIVATED = <any> "ACTIVATED", CANCELED = <any> "CANCELED", FAILED = <any> "FAILED" } /** * @export * @enum {string} */ export enum ToEnum { CREATED = <any> "CREATED", DOWNLOAD = <any> "DOWNLOAD", DOWNLOADING = <any> "DOWNLOADING", DOWNLOADED = <any> "DOWNLOADED", INSTALL = <any> "INSTALL", INSTALLING = <any> "INSTALLING", INSTALLED = <any> "INSTALLED", ACTIVATE = <any> "ACTIVATE", ACTIVATING = <any> "ACTIVATING", ACTIVATED = <any> "ACTIVATED", CANCELED = <any> "CANCELED", FAILED = <any> "FAILED" } } }
the_stack
import assert from 'assert'; import { Injectable } from '@nestjs/common'; import { hexToU8a, u8aToBuffer } from '@polkadot/util'; import { blake2AsHex } from '@polkadot/util-crypto'; import { GraphQLModelsRelationsEnums } from '@subql/common/graphql/types'; import { Entity, Store } from '@subql/types'; import { camelCase, flatten, upperFirst, isEqual } from 'lodash'; import { QueryTypes, Sequelize, Transaction, Utils } from 'sequelize'; import { NodeConfig } from '../configure/NodeConfig'; import { modelsTypeToModelAttributes } from '../utils/graphql'; import { getLogger } from '../utils/logger'; import { camelCaseObjectKey } from '../utils/object'; import { commentConstraintQuery, createUniqueIndexQuery, getFkConstraint, smartTags, } from '../utils/sync-helper'; import { MetadataFactory, MetadataRepo } from './entities/Metadata.entity'; import { PoiFactory, PoiRepo, ProofOfIndex } from './entities/Poi.entity'; import { PoiService } from './poi.service'; import { StoreOperations } from './StoreOperations'; import { OperationType } from './types'; const logger = getLogger('store'); const NULL_MERKEL_ROOT = hexToU8a('0x00'); interface IndexField { entityName: string; fieldName: string; isUnique: boolean; type: string; } @Injectable() export class StoreService { private tx?: Transaction; private modelIndexedFields: IndexField[]; private schema: string; private modelsRelations: GraphQLModelsRelationsEnums; private poiRepo: PoiRepo; private metaDataRepo: MetadataRepo; private operationStack: StoreOperations; constructor( private sequelize: Sequelize, private config: NodeConfig, private poiService: PoiService, ) {} async init( modelsRelations: GraphQLModelsRelationsEnums, schema: string, ): Promise<void> { this.schema = schema; this.modelsRelations = modelsRelations; try { await this.syncSchema(this.schema); } catch (e) { logger.error(e, `Having a problem when syncing schema`); process.exit(1); } try { this.modelIndexedFields = await this.getAllIndexFields(this.schema); } catch (e) { logger.error(e, `Having a problem when get indexed fields`); process.exit(1); } } async syncSchema(schema: string): Promise<void> { const enumTypeMap = new Map<string, string>(); for (const e of this.modelsRelations.enums) { // We shouldn't set the typename to e.name because it could potentially create SQL injection, // using a replacement at the type name location doesn't work. const enumTypeName = `${schema}_enum_${this.enumNameToHash(e.name)}`; const [results] = await this.sequelize.query( `select e.enumlabel as enum_value from pg_type t join pg_enum e on t.oid = e.enumtypid where t.typname = ?;`, { replacements: [enumTypeName] }, ); if (results.length === 0) { await this.sequelize.query( `CREATE TYPE "${enumTypeName}" as ENUM (${e.values .map(() => '?') .join(',')});`, { replacements: e.values, }, ); } else { const currentValues = results.map((v: any) => v.enum_value); // Assert the existing enum is same // Make it a function to not execute potentially big joins unless needed if (!isEqual(e.values, currentValues)) { throw new Error( `\n * Can't modify enum "${ e.name }" between runs: \n * Before: [${currentValues.join( `,`, )}] \n * After : [${e.values.join( ',', )}] \n * You must rerun the project to do such a change`, ); } } const comment = `@enum\\n@enumName ${e.name}${ e.description ? `\\n ${e.description}` : '' }`; await this.sequelize.query(`COMMENT ON TYPE "${enumTypeName}" IS E?`, { replacements: [comment], }); enumTypeMap.set(e.name, `"${enumTypeName}"`); } for (const model of this.modelsRelations.models) { const attributes = modelsTypeToModelAttributes(model, enumTypeMap); const indexes = model.indexes.map(({ fields, unique, using }) => ({ fields: fields.map((field) => Utils.underscoredIf(field, true)), unique, using, })); if (indexes.length > this.config.indexCountLimit) { throw new Error(`too many indexes on entity ${model.name}`); } this.sequelize.define(model.name, attributes, { underscored: true, comment: model.description, freezeTableName: false, createdAt: this.config.timestampField, updatedAt: this.config.timestampField, schema, indexes, }); } const extraQueries = []; for (const relation of this.modelsRelations.relations) { const model = this.sequelize.model(relation.from); const relatedModel = this.sequelize.model(relation.to); switch (relation.type) { case 'belongsTo': { model.belongsTo(relatedModel, { foreignKey: relation.foreignKey }); break; } case 'hasOne': { const rel = model.hasOne(relatedModel, { foreignKey: relation.foreignKey, }); const fkConstraint = getFkConstraint( rel.target.tableName, rel.foreignKey, ); const tags = smartTags({ singleForeignFieldName: relation.fieldName, }); extraQueries.push( commentConstraintQuery( `"${schema}"."${rel.target.tableName}"`, fkConstraint, tags, ), createUniqueIndexQuery( schema, relatedModel.tableName, relation.foreignKey, ), ); break; } case 'hasMany': { const rel = model.hasMany(relatedModel, { foreignKey: relation.foreignKey, }); const fkConstraint = getFkConstraint( rel.target.tableName, rel.foreignKey, ); const tags = smartTags({ foreignFieldName: relation.fieldName, }); extraQueries.push( commentConstraintQuery( `"${schema}"."${rel.target.tableName}"`, fkConstraint, tags, ), ); break; } default: throw new Error('Relation type is not supported'); } } if (this.config.proofOfIndex) { this.poiRepo = PoiFactory(this.sequelize, schema); } this.metaDataRepo = MetadataFactory(this.sequelize, schema); await this.sequelize.sync(); for (const query of extraQueries) { await this.sequelize.query(query); } } enumNameToHash(enumName: string): string { return blake2AsHex(enumName).substr(2, 10); } setTransaction(tx: Transaction) { this.tx = tx; tx.afterCommit(() => (this.tx = undefined)); if (this.config.proofOfIndex) { this.operationStack = new StoreOperations(this.modelsRelations.models); } } async setMetadata( key: string, value: string | number | boolean, ): Promise<void> { assert(this.metaDataRepo, `model _metadata does not exist`); await this.metaDataRepo.upsert({ key, value }); } async setPoi(tx: Transaction, blockPoi: ProofOfIndex): Promise<void> { assert(this.poiRepo, `model _poi does not exist`); blockPoi.chainBlockHash = u8aToBuffer(blockPoi.chainBlockHash); blockPoi.hash = u8aToBuffer(blockPoi.hash); blockPoi.parentHash = u8aToBuffer(blockPoi.parentHash); await this.poiRepo.upsert(blockPoi, { transaction: tx }); } getOperationMerkleRoot(): Uint8Array { this.operationStack.makeOperationMerkleTree(); const merkelRoot = this.operationStack.getOperationMerkleRoot(); if (merkelRoot === null) { return NULL_MERKEL_ROOT; } return merkelRoot; } private async getAllIndexFields(schema: string) { const fields: IndexField[][] = []; for (const entity of this.modelsRelations.models) { const model = this.sequelize.model(entity.name); const tableFields = await this.packEntityFields( schema, entity.name, model.tableName, ); fields.push(tableFields); } return flatten(fields); } private async packEntityFields( schema: string, entity: string, table: string, ): Promise<IndexField[]> { const rows = await this.sequelize.query( `select '${entity}' as entity_name, a.attname as field_name, idx.indisunique as is_unique, am.amname as type from pg_index idx JOIN pg_class cls ON cls.oid=idx.indexrelid JOIN pg_class tab ON tab.oid=idx.indrelid JOIN pg_am am ON am.oid=cls.relam, pg_namespace n, pg_attribute a where n.nspname = '${schema}' and tab.relname = '${table}' and a.attrelid = tab.oid and a.attnum = ANY(idx.indkey) and not idx.indisprimary group by n.nspname, a.attname, tab.relname, idx.indisunique, am.amname`, { type: QueryTypes.SELECT, }, ); return rows.map((result) => camelCaseObjectKey(result)) as IndexField[]; } getStore(): Store { return { get: async (entity: string, id: string): Promise<Entity | undefined> => { const model = this.sequelize.model(entity); assert(model, `model ${entity} not exists`); const record = await model.findOne({ where: { id }, transaction: this.tx, }); return record?.toJSON() as Entity; }, getByField: async ( entity: string, field: string, value, ): Promise<Entity[] | undefined> => { const model = this.sequelize.model(entity); assert(model, `model ${entity} not exists`); const indexed = this.modelIndexedFields.findIndex( (indexField) => upperFirst(camelCase(indexField.entityName)) === entity && camelCase(indexField.fieldName) === field, ) > -1; assert( indexed, `to query by field ${field}, an index must be created on model ${entity}`, ); const records = await model.findAll({ where: { [field]: value }, transaction: this.tx, limit: this.config.queryLimit, }); return records.map((record) => record.toJSON() as Entity); }, getOneByField: async ( entity: string, field: string, value, ): Promise<Entity | undefined> => { const model = this.sequelize.model(entity); assert(model, `model ${entity} not exists`); const indexed = this.modelIndexedFields.findIndex( (indexField) => upperFirst(camelCase(indexField.entityName)) === entity && camelCase(indexField.fieldName) === field && indexField.isUnique, ) > -1; assert( indexed, `to query by field ${field}, an unique index must be created on model ${entity}`, ); const record = await model.findOne({ where: { [field]: value }, transaction: this.tx, }); return record?.toJSON() as Entity; }, set: async (entity: string, _id: string, data: Entity): Promise<void> => { const model = this.sequelize.model(entity); assert(model, `model ${entity} not exists`); await model.upsert(data, { transaction: this.tx }); if (this.config.proofOfIndex) { this.operationStack.put(OperationType.Set, entity, data); } }, bulkCreate: async (entity: string, data: Entity[]): Promise<void> => { const model = this.sequelize.model(entity); assert(model, `model ${entity} not exists`); await model.bulkCreate(data, { transaction: this.tx }); if (this.config.proofOfIndex) { for (const item of data) { this.operationStack.put(OperationType.Set, entity, item); } } }, remove: async (entity: string, id: string): Promise<void> => { const model = this.sequelize.model(entity); assert(model, `model ${entity} not exists`); await model.destroy({ where: { id }, transaction: this.tx }); if (this.config.proofOfIndex) { this.operationStack.put(OperationType.Remove, entity, id); } }, }; } }
the_stack
import React from 'react' import { css, jsx } from '@emotion/react' import { OptionsType } from 'react-select' import { animated } from 'react-spring' import { ArrayControlDescription, BaseControlDescription, ControlDescription, FolderControlDescription, HigherLevelControlDescription, isBaseControlDescription, ObjectControlDescription, PropertyControls, RegularControlDescription, TupleControlDescription, UnionControlDescription, } from 'utopia-api' import { PathForSceneProps } from '../../../../core/model/scene-utils' import { mapToArray } from '../../../../core/shared/object-utils' import { ElementPath, PropertyPath } from '../../../../core/shared/project-file-types' import * as PP from '../../../../core/shared/property-path' import * as EP from '../../../../core/shared/element-path' import { useKeepReferenceEqualityIfPossible } from '../../../../utils/react-performance' import Utils from '../../../../utils/utils' import { getParseErrorDetails, ParseError, ParseResult } from '../../../../utils/value-parser-utils' import { Tooltip, //TODO: switch last component to functional component and make use of 'useColorTheme': colorTheme as colorThemeConst, useColorTheme, UtopiaTheme, InspectorSectionHeader, SimpleFlexRow, SquareButton, PopupList, Icons, VerySubdued, FlexRow, } from '../../../../uuiui' import { CSSCursor, getControlStyles } from '../../../../uuiui-deps' import { InspectorContextMenuWrapper } from '../../../context-menu-wrapper' import { addOnUnsetValues } from '../../common/context-menu-items' import { useControlForUnionControl, useGetPropertyControlsForSelectedComponents, useInspectorInfoForPropertyControl, } from '../../common/property-controls-hooks' import { ControlStyles, ControlStatus } from '../../common/control-status' import { InspectorInfo } from '../../common/property-path-hooks' import { useArraySuperControl } from '../../controls/array-supercontrol' import { SelectOption } from '../../controls/select-control' import { UIGridRow } from '../../widgets/ui-grid-row' import { PropertyLabel } from '../../widgets/property-label' import { PropertyRow } from '../../widgets/property-row' import { CheckboxPropertyControl, ColorPropertyControl, PopUpListPropertyControl, EulerPropertyControl, ExpressionPopUpListPropertyControl, Matrix3PropertyControl, Matrix4PropertyControl, NumberInputPropertyControl, RadioPropertyControl, ControlForPropProps, ExpressionInputPropertyControl, StringInputPropertyControl, VectorPropertyControl, } from './property-control-controls' import { ComponentInfoBox } from './component-info-box' import { ExpandableIndicator } from '../../../navigator/navigator-item/expandable-indicator' import { when } from '../../../../utils/react-conditionals' import { PropertyControlsSection } from './property-controls-section' import type { ReactEventHandlers } from 'react-use-gesture/dist/types' function useComponentPropsInspectorInfo( partialPath: PropertyPath, addPropsToPath: boolean, control: RegularControlDescription, ) { const propertyPath = addPropsToPath ? PP.append(PathForSceneProps, partialPath) : partialPath return useInspectorInfoForPropertyControl(propertyPath, control) } const ControlForProp = React.memo((props: ControlForPropProps<BaseControlDescription>) => { const { controlDescription } = props if (controlDescription == null) { return null } else { switch (controlDescription.control) { case 'checkbox': return <CheckboxPropertyControl {...props} controlDescription={controlDescription} /> case 'color': return <ColorPropertyControl {...props} controlDescription={controlDescription} /> case 'euler': return <EulerPropertyControl {...props} controlDescription={controlDescription} /> case 'expression-input': return <ExpressionInputPropertyControl {...props} controlDescription={controlDescription} /> case 'expression-popuplist': return ( <ExpressionPopUpListPropertyControl {...props} controlDescription={controlDescription} /> ) case 'none': return null case 'matrix3': return <Matrix3PropertyControl {...props} controlDescription={controlDescription} /> case 'matrix4': return <Matrix4PropertyControl {...props} controlDescription={controlDescription} /> case 'number-input': return <NumberInputPropertyControl {...props} controlDescription={controlDescription} /> case 'popuplist': return <PopUpListPropertyControl {...props} controlDescription={controlDescription} /> case 'radio': return <RadioPropertyControl {...props} controlDescription={controlDescription} /> case 'string-input': return <StringInputPropertyControl {...props} controlDescription={controlDescription} /> case 'style-controls': return null case 'vector2': case 'vector3': case 'vector4': return <VectorPropertyControl {...props} controlDescription={controlDescription} /> default: return null } } }) interface ParseErrorProps { parseError: ParseError } export const ParseErrorControl = React.memo((props: ParseErrorProps) => { const details = getParseErrorDetails(props.parseError) return ( <div> <Tooltip title={`${details.path}`}> <span>{details.description}</span> </Tooltip> </div> ) }) const WarningTooltip = React.memo(({ warning }: { warning: string }) => { const colorTheme = useColorTheme() return ( <Tooltip title={warning}> <div style={{ width: 5, height: 5, background: colorTheme.warningBgSolid.value, borderRadius: '50%', marginRight: 4, }} /> </Tooltip> ) }) interface RowForInvalidControlProps { propName: string title: string propertyError: ParseError warningTooltip?: string } export const RowForInvalidControl = React.memo((props: RowForInvalidControlProps) => { const propPath = [PP.create([props.propName])] const warning = props.warningTooltip == null ? null : <WarningTooltip warning={props.warningTooltip} /> return ( <UIGridRow padded={true} variant='<--1fr--><--1fr-->'> <PropertyLabel target={propPath}> {warning} {props.title} </PropertyLabel> <ParseErrorControl parseError={props.propertyError} /> </UIGridRow> ) }) interface AbstractRowForControlProps { propPath: PropertyPath isScene: boolean setGlobalCursor: (cursor: CSSCursor | null) => void indentationLevel: number focusOnMount: boolean } function labelForControl(propPath: PropertyPath, control: RegularControlDescription): string { return control.label ?? PP.lastPartToString(propPath) } function getLabelControlStyle( controlDescription: ControlDescription, propMetadata: InspectorInfo<any>, ): ControlStyles { if ( (controlDescription.control === 'expression-input' || controlDescription.control === 'expression-popuplist') && propMetadata.controlStatus === 'controlled' ) { return getControlStyles('simple') } else { return propMetadata.controlStyles } } interface RowForBaseControlProps extends AbstractRowForControlProps { label?: React.ComponentType<any> // TODO Before Merge this probably should not be a component controlDescription: BaseControlDescription } const RowForBaseControl = React.memo((props: RowForBaseControlProps) => { const { propPath, controlDescription, isScene } = props const title = labelForControl(propPath, controlDescription) const propName = `${PP.lastPart(propPath)}` const indentation = props.indentationLevel * 8 const propMetadata = useComponentPropsInspectorInfo(propPath, isScene, controlDescription) const contextMenuItems = Utils.stripNulls([ addOnUnsetValues([propName], propMetadata.onUnsetValues), ]) const labelControlStyle = React.useMemo( () => getLabelControlStyle(controlDescription, propMetadata), [controlDescription, propMetadata], ) const propertyLabel = props.label == null ? ( <PropertyLabel controlStyles={labelControlStyle} target={[propPath]} style={{ textTransform: 'capitalize', paddingLeft: indentation, alignSelf: 'flex-start', }} > <Tooltip title={title}> <span style={{ marginTop: 3, lineHeight: `${UtopiaTheme.layout.inputHeight.default}px`, }} > {title} </span> </Tooltip> </PropertyLabel> ) : ( <props.label /> ) if (controlDescription.control === 'none') { // do not list anything for `none` controls return null } return ( <InspectorContextMenuWrapper id={`context-menu-for-${propName}`} items={contextMenuItems} data={null} > <UIGridRow padded={false} style={{ paddingLeft: 0, paddingRight: 8, paddingTop: 3, paddingBottom: 3 }} variant='<--1fr--><--1fr-->' > {propertyLabel} <ControlForProp propPath={propPath} propName={propName} controlDescription={controlDescription} propMetadata={propMetadata} setGlobalCursor={props.setGlobalCursor} focusOnMount={props.focusOnMount} /> </UIGridRow> </InspectorContextMenuWrapper> ) }) interface RowForArrayControlProps extends AbstractRowForControlProps { controlDescription: ArrayControlDescription } const RowForArrayControl = React.memo((props: RowForArrayControlProps) => { const { propPath, controlDescription, isScene } = props const title = labelForControl(propPath, controlDescription) const { value, onSubmitValue, propertyStatus } = useComponentPropsInspectorInfo( propPath, isScene, controlDescription, ) const rowHeight = UtopiaTheme.layout.rowHeight.normal const transformedValue = Array.isArray(value) ? value : [value] const { springs, bind } = useArraySuperControl(transformedValue, onSubmitValue, rowHeight, false) const [insertingRow, setInsertingRow] = React.useState(false) const toggleInsertRow = React.useCallback(() => setInsertingRow((current) => !current), []) React.useEffect(() => setInsertingRow(false), [springs.length]) return ( <React.Fragment> <InspectorSectionHeader> <SimpleFlexRow style={{ flexGrow: 1 }}> <PropertyLabel target={[propPath]} style={{ textTransform: 'capitalize' }}> {title} </PropertyLabel> {propertyStatus.overwritable ? ( <SquareButton highlight onMouseDown={toggleInsertRow}> {insertingRow ? ( <Icons.Minus style={{ paddingTop: 1 }} color={propertyStatus.controlled ? 'primary' : 'secondary'} width={16} height={16} /> ) : ( <Icons.Plus style={{ paddingTop: 1 }} color={propertyStatus.controlled ? 'primary' : 'secondary'} width={16} height={16} /> )} </SquareButton> ) : null} </SimpleFlexRow> </InspectorSectionHeader> <div style={{ height: rowHeight * springs.length, }} > {springs.map((springStyle, index) => ( <ArrayControlItem springStyle={springStyle} bind={bind} key={index} //FIXME this causes the row drag handle to jump after finishing the re-order index={index} propPath={propPath} isScene={props.isScene} controlDescription={controlDescription} focusOnMount={props.focusOnMount} setGlobalCursor={props.setGlobalCursor} /> ))} </div> {insertingRow ? ( <RowForControl controlDescription={controlDescription.propertyControl} isScene={isScene} propPath={PP.appendPropertyPathElems(propPath, [springs.length])} setGlobalCursor={props.setGlobalCursor} indentationLevel={1} focusOnMount={false} /> ) : null} </React.Fragment> ) }) interface ArrayControlItemProps { springStyle: { [x: string]: any; [x: number]: any } bind: (...args: any[]) => ReactEventHandlers propPath: PropertyPath index: number isScene: boolean controlDescription: ArrayControlDescription focusOnMount: boolean setGlobalCursor: (cursor: CSSCursor | null) => void } const ArrayControlItem = React.memo((props: ArrayControlItemProps) => { const colorTheme = useColorTheme() const { bind, propPath, index, isScene, springStyle, controlDescription } = props const propPathWithIndex = PP.appendPropertyPathElems(propPath, [index]) const propMetadata = useComponentPropsInspectorInfo( propPathWithIndex, isScene, controlDescription, ) const contextMenuItems = Utils.stripNulls([addOnUnsetValues([index], propMetadata.onUnsetValues)]) const rowHeight = UtopiaTheme.layout.rowHeight.normal return ( <InspectorContextMenuWrapper id={`context-menu-for-${PP.toString(propPathWithIndex)}`} items={contextMenuItems} data={null} key={index} > <animated.div {...bind(index)} style={{ ...springStyle, width: '100%', position: 'absolute', height: rowHeight, }} css={{ '& > .handle': { opacity: 0, }, '&:hover > .handle': { opacity: 1, }, }} > <RowForControl controlDescription={controlDescription.propertyControl} isScene={isScene} propPath={PP.appendPropertyPathElems(propPath, [index])} setGlobalCursor={props.setGlobalCursor} indentationLevel={1} focusOnMount={props.focusOnMount && index === 0} /> <div style={{ position: 'absolute', top: 0, bottom: 0, display: 'flex', alignItems: 'center', }} className='handle' > <svg width='5px' height='23px' viewBox='0 0 4 23'> <g stroke={colorTheme.border3.value} strokeWidth='1' fill='none' fillRule='evenodd' strokeLinecap='round' > <line x1='1' y1='1.5' x2='1' y2='21'></line> <line x1='4' y1='1.5' x2='4' y2='21'></line> </g> </svg> </div> </animated.div> </InspectorContextMenuWrapper> ) }) interface RowForTupleControlProps extends AbstractRowForControlProps { controlDescription: TupleControlDescription } const RowForTupleControl = React.memo((props: RowForTupleControlProps) => { const { propPath, controlDescription, isScene } = props const title = labelForControl(propPath, controlDescription) const { value, onSubmitValue, propertyStatus } = useComponentPropsInspectorInfo( propPath, isScene, controlDescription, ) const rowHeight = UtopiaTheme.layout.rowHeight.normal const transformedValue = Array.isArray(value) ? value : [value] const boundedTransformedValue = transformedValue.slice( 0, controlDescription.propertyControls.length, ) return ( <React.Fragment> <InspectorSectionHeader> <SimpleFlexRow style={{ flexGrow: 1 }}> <PropertyLabel target={[propPath]} style={{ textTransform: 'capitalize' }}> {title} </PropertyLabel> </SimpleFlexRow> </InspectorSectionHeader> <div style={{ height: rowHeight * boundedTransformedValue.length, }} > {boundedTransformedValue.map((_, index) => ( <TupleControlItem key={index} index={index} propPath={propPath} isScene={props.isScene} controlDescription={controlDescription} setGlobalCursor={props.setGlobalCursor} /> ))} </div> </React.Fragment> ) }) interface TupleControlItemProps { propPath: PropertyPath index: number isScene: boolean controlDescription: TupleControlDescription setGlobalCursor: (cursor: CSSCursor | null) => void } const TupleControlItem = React.memo((props: TupleControlItemProps) => { const { propPath, index, isScene, controlDescription } = props const propPathWithIndex = PP.appendPropertyPathElems(propPath, [index]) const propMetadata = useComponentPropsInspectorInfo( propPathWithIndex, isScene, controlDescription, ) const contextMenuItems = Utils.stripNulls([addOnUnsetValues([index], propMetadata.onUnsetValues)]) return ( <InspectorContextMenuWrapper id={`context-menu-for-${PP.toString(propPathWithIndex)}`} items={contextMenuItems} data={null} key={index} > <RowForControl controlDescription={controlDescription.propertyControls[index]} isScene={isScene} propPath={PP.appendPropertyPathElems(propPath, [index])} setGlobalCursor={props.setGlobalCursor} indentationLevel={1} focusOnMount={false} /> </InspectorContextMenuWrapper> ) }) interface ObjectIndicatorProps { open: boolean } const ObjectIndicator = (props: ObjectIndicatorProps) => { const colorTheme = useColorTheme() return ( <div style={{ border: `1px solid ${colorTheme.bg3.value}`, paddingLeft: 2, paddingRight: 2, borderRadius: 4, lineHeight: 1, fontSize: 9, color: colorTheme.fg6.value, background: props.open ? 'transparent' : colorTheme.bg2.value, }} > ⋯ </div> ) } interface RowForObjectControlProps extends AbstractRowForControlProps { controlDescription: ObjectControlDescription } const RowForObjectControl = React.memo((props: RowForObjectControlProps) => { const [open, setOpen] = React.useState(true) const handleOnClick = React.useCallback(() => setOpen(!open), [setOpen, open]) const { propPath, controlDescription, isScene } = props const title = labelForControl(propPath, controlDescription) const indentation = props.indentationLevel * 8 const propMetadata = useComponentPropsInspectorInfo(propPath, isScene, controlDescription) const contextMenuItems = Utils.stripNulls([ addOnUnsetValues([PP.lastPart(propPath)], propMetadata.onUnsetValues), ]) return ( <div css={{ marginTop: 8, marginBottom: 8, '&:hover': { boxShadow: 'inset 1px 0px 0px 0px hsla(0,0%,0%,20%)', background: 'hsl(0,0%,0%,1%)', }, '&:focus-within': { boxShadow: 'inset 1px 0px 0px 0px hsla(0,0%,0%,20%)', background: 'hsl(0,0%,0%,1%)', }, }} > <div onClick={handleOnClick}> <InspectorContextMenuWrapper id={`context-menu-for-${PP.toString(propPath)}`} items={contextMenuItems} data={null} > <SimpleFlexRow style={{ flexGrow: 1, paddingRight: 8 }}> <PropertyLabel target={[propPath]} style={{ textTransform: 'capitalize', paddingLeft: indentation, display: 'flex', alignItems: 'center', height: 34, fontWeight: 500, gap: 4, cursor: 'pointer', }} > {title} <ObjectIndicator open={open} /> </PropertyLabel> </SimpleFlexRow> </InspectorContextMenuWrapper> </div> {when( open, mapToArray((innerControl: RegularControlDescription, prop: string, index: number) => { const innerPropPath = PP.appendPropertyPathElems(propPath, [prop]) return ( <RowForControl key={`object-control-row-${PP.toString(innerPropPath)}`} controlDescription={innerControl} isScene={isScene} propPath={innerPropPath} setGlobalCursor={props.setGlobalCursor} indentationLevel={props.indentationLevel + 1} focusOnMount={props.focusOnMount && index === 0} /> ) }, controlDescription.object), )} </div> ) }) interface RowForUnionControlProps extends AbstractRowForControlProps { controlDescription: UnionControlDescription } const RowForUnionControl = React.memo((props: RowForUnionControlProps) => { const { propPath, controlDescription } = props const title = labelForControl(propPath, controlDescription) const suitableControl = useControlForUnionControl(propPath, controlDescription) const [controlToUse, setControlToUse] = React.useState(suitableControl) const labelOptions: OptionsType<SelectOption> = controlDescription.controls.map((control) => { const label = control.label ?? control.control return { value: control, label: label, } }) const onLabelChangeValue = React.useCallback( (option: SelectOption) => { if (option.value !== controlToUse) { setControlToUse(option.value) } }, [controlToUse, setControlToUse], ) const simpleControlStyles = getControlStyles('simple') const label = React.useMemo( () => ( <PopupList value={{ value: controlToUse, label: title, }} options={labelOptions} onSubmitValue={onLabelChangeValue} containerMode='showBorderOnHover' controlStyles={simpleControlStyles} style={{ maxWidth: '100%', overflow: 'hidden', }} /> ), [controlToUse, labelOptions, onLabelChangeValue, simpleControlStyles, title], ) const labelAsRenderProp = React.useCallback(() => label, [label]) if (controlToUse == null) { return null } else if (isBaseControlDescription(controlToUse)) { return ( <RowForBaseControl {...props} label={labelAsRenderProp} controlDescription={controlToUse} focusOnMount={false} /> ) } else { return ( <React.Fragment> {label} <RowForControl {...props} controlDescription={controlToUse} focusOnMount={false} /> </React.Fragment> ) } }) interface RowForControlProps extends AbstractRowForControlProps { controlDescription: RegularControlDescription } export const RowForControl = React.memo((props: RowForControlProps) => { const { controlDescription } = props if (isBaseControlDescription(controlDescription)) { return <RowForBaseControl {...props} controlDescription={controlDescription} /> } else { switch (controlDescription.control) { case 'array': return <RowForArrayControl {...props} controlDescription={controlDescription} /> case 'object': return <RowForObjectControl {...props} controlDescription={controlDescription} /> case 'tuple': return <RowForTupleControl {...props} controlDescription={controlDescription} /> case 'union': return <RowForUnionControl {...props} controlDescription={controlDescription} /> default: const _exhaustiveCheck: never = controlDescription throw new Error(`Unhandled control ${JSON.stringify(controlDescription)}`) } } }) export interface ComponentSectionProps { isScene: boolean } export const ComponentSectionInner = React.memo((props: ComponentSectionProps) => { const colorTheme = useColorTheme() const propertyControlsAndTargets = useKeepReferenceEqualityIfPossible( useGetPropertyControlsForSelectedComponents(), ) const [sectionExpanded, setSectionExpanded] = React.useState(true) const toggleSection = React.useCallback(() => { setSectionExpanded((currentlyExpanded) => !currentlyExpanded) }, [setSectionExpanded]) return ( <React.Fragment> <InspectorSectionHeader> <FlexRow style={{ flexGrow: 1, color: colorTheme.primary.value, gap: 8 }}> <Icons.Component color='primary' /> <span>Component </span> </FlexRow> <SquareButton highlight onClick={toggleSection}> <ExpandableIndicator testId='component-section-expand' visible collapsed={!sectionExpanded} selected={false} /> </SquareButton> </InspectorSectionHeader> {when( sectionExpanded, <React.Fragment> {/* Information about the component as a whole */} <ComponentInfoBox /> {/* List of component props with controls */} {propertyControlsAndTargets.map((controlsAndTargets) => ( <PropertyControlsSection key={EP.toString(controlsAndTargets.targets[0])} propertyControls={controlsAndTargets.controls} targets={controlsAndTargets.targets} isScene={props.isScene} detectedPropsAndValuesWithoutControls={ controlsAndTargets.detectedPropsAndValuesWithoutControls } detectedPropsWithNoValue={controlsAndTargets.detectedPropsWithNoValue} propsWithControlsButNoValue={controlsAndTargets.propsWithControlsButNoValue} /> ))} </React.Fragment>, )} </React.Fragment> ) }) export interface ComponentSectionState { errorOccurred: boolean } export class ComponentSection extends React.Component< ComponentSectionProps, ComponentSectionState > { constructor(props: ComponentSectionProps) { super(props) this.state = { errorOccurred: false } } static getDerivedStateFromError(error: Error): ComponentSectionState { return { errorOccurred: true, } } componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void { console.error('Error occurred in component section.', error, errorInfo) } render() { if (this.state.errorOccurred) { return ( <React.Fragment> <InspectorSectionHeader>Component props</InspectorSectionHeader> <PropertyRow style={{ gridTemplateColumns: '2fr 4fr', }} > <span style={{ paddingTop: 4, color: colorThemeConst.errorForeground.value }}> Invalid propertyControls value </span> </PropertyRow> </React.Fragment> ) } else { return <ComponentSectionInner {...this.props} /> } } }
the_stack
import * as assert from 'assert'; import { merge } from 'vs/platform/userDataSync/common/keybindingsMerge'; import { TestUserDataSyncUtilService } from 'vs/platform/userDataSync/test/common/userDataSyncClient'; suite('KeybindingsMerge - No Conflicts', () => { test('merge when local and remote are same with one entry', async () => { const localContent = stringify([{ key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }]); const remoteContent = stringify([{ key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }]); const actual = await mergeKeybindings(localContent, remoteContent, null); assert.ok(!actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, localContent); }); test('merge when local and remote are same with similar when contexts', async () => { const localContent = stringify([{ key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }]); const remoteContent = stringify([{ key: 'alt+c', command: 'a', when: '!editorReadonly && editorTextFocus' }]); const actual = await mergeKeybindings(localContent, remoteContent, null); assert.ok(!actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, localContent); }); test('merge when local and remote has entries in different order', async () => { const localContent = stringify([ { key: 'alt+d', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+a', command: 'a', when: 'editorTextFocus' } ]); const remoteContent = stringify([ { key: 'alt+a', command: 'a', when: 'editorTextFocus' }, { key: 'alt+d', command: 'a', when: 'editorTextFocus && !editorReadonly' } ]); const actual = await mergeKeybindings(localContent, remoteContent, null); assert.ok(!actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, localContent); }); test('merge when local and remote are same with multiple entries', async () => { const localContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, { key: 'cmd+c', command: 'b', args: { text: '`' } } ]); const remoteContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, { key: 'cmd+c', command: 'b', args: { text: '`' } } ]); const actual = await mergeKeybindings(localContent, remoteContent, null); assert.ok(!actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, localContent); }); test('merge when local and remote are same with different base content', async () => { const localContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, { key: 'cmd+c', command: 'b', args: { text: '`' } } ]); const baseContent = stringify([ { key: 'ctrl+c', command: 'e' }, { key: 'shift+d', command: 'd', args: { text: '`' } } ]); const remoteContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, { key: 'cmd+c', command: 'b', args: { text: '`' } } ]); const actual = await mergeKeybindings(localContent, remoteContent, baseContent); assert.ok(!actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, localContent); }); test('merge when local and remote are same with multiple entries in different order', async () => { const localContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, { key: 'cmd+c', command: 'b', args: { text: '`' } } ]); const remoteContent = stringify([ { key: 'cmd+c', command: 'b', args: { text: '`' } }, { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, ]); const actual = await mergeKeybindings(localContent, remoteContent, null); assert.ok(!actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, localContent); }); test('merge when local and remote are same when remove entry is in different order', async () => { const localContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, { key: 'cmd+c', command: 'b', args: { text: '`' } } ]); const remoteContent = stringify([ { key: 'alt+d', command: '-a' }, { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'cmd+c', command: 'b', args: { text: '`' } }, ]); const actual = await mergeKeybindings(localContent, remoteContent, null); assert.ok(!actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, localContent); }); test('merge when a new entry is added to remote', async () => { const localContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, ]); const remoteContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, { key: 'cmd+c', command: 'b', args: { text: '`' } }, ]); const actual = await mergeKeybindings(localContent, remoteContent, null); assert.ok(actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, remoteContent); }); test('merge when multiple new entries are added to remote', async () => { const localContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, ]); const remoteContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, { key: 'cmd+c', command: 'b', args: { text: '`' } }, { key: 'cmd+d', command: 'c' }, ]); const actual = await mergeKeybindings(localContent, remoteContent, null); assert.ok(actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, remoteContent); }); test('merge when multiple new entries are added to remote from base and local has not changed', async () => { const localContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, ]); const remoteContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, { key: 'cmd+c', command: 'b', args: { text: '`' } }, { key: 'cmd+d', command: 'c' }, ]); const actual = await mergeKeybindings(localContent, remoteContent, localContent); assert.ok(actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, remoteContent); }); test('merge when an entry is removed from remote from base and local has not changed', async () => { const localContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, { key: 'cmd+c', command: 'b', args: { text: '`' } }, ]); const remoteContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, ]); const actual = await mergeKeybindings(localContent, remoteContent, localContent); assert.ok(actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, remoteContent); }); test('merge when an entry (same command) is removed from remote from base and local has not changed', async () => { const localContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, ]); const remoteContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, ]); const actual = await mergeKeybindings(localContent, remoteContent, localContent); assert.ok(actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, remoteContent); }); test('merge when an entry is updated in remote from base and local has not changed', async () => { const localContent = stringify([ { key: 'alt+d', command: 'a', when: 'editorTextFocus && !editorReadonly' }, ]); const remoteContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, ]); const actual = await mergeKeybindings(localContent, remoteContent, localContent); assert.ok(actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, remoteContent); }); test('merge when a command with multiple entries is updated from remote from base and local has not changed', async () => { const localContent = stringify([ { key: 'shift+c', command: 'c' }, { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: 'b' }, { key: 'cmd+c', command: 'a' }, ]); const remoteContent = stringify([ { key: 'shift+c', command: 'c' }, { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: 'b' }, { key: 'cmd+d', command: 'a' }, ]); const actual = await mergeKeybindings(localContent, remoteContent, localContent); assert.ok(actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, remoteContent); }); test('merge when remote has moved forwareded with multiple changes and local stays with base', async () => { const localContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'cmd+c', command: 'b', args: { text: '`' } }, { key: 'alt+d', command: '-a' }, { key: 'cmd+e', command: 'd' }, { key: 'cmd+d', command: 'c', when: 'context1' }, ]); const remoteContent = stringify([ { key: 'alt+d', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'cmd+e', command: 'd' }, { key: 'alt+d', command: '-a' }, { key: 'alt+f', command: 'f' }, { key: 'alt+d', command: '-f' }, { key: 'cmd+d', command: 'c', when: 'context1' }, { key: 'cmd+c', command: '-c' }, ]); const actual = await mergeKeybindings(localContent, remoteContent, localContent); assert.ok(actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, remoteContent); }); test('merge when a new entry is added to local', async () => { const localContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, { key: 'cmd+c', command: 'b', args: { text: '`' } }, ]); const remoteContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, ]); const actual = await mergeKeybindings(localContent, remoteContent, null); assert.ok(actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, localContent); }); test('merge when multiple new entries are added to local', async () => { const localContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, { key: 'cmd+c', command: 'b', args: { text: '`' } }, { key: 'cmd+d', command: 'c' }, ]); const remoteContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, ]); const actual = await mergeKeybindings(localContent, remoteContent, null); assert.ok(actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, localContent); }); test('merge when multiple new entries are added to local from base and remote is not changed', async () => { const localContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, { key: 'cmd+c', command: 'b', args: { text: '`' } }, { key: 'cmd+d', command: 'c' }, ]); const remoteContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, ]); const actual = await mergeKeybindings(localContent, remoteContent, remoteContent); assert.ok(actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, localContent); }); test('merge when an entry is removed from local from base and remote has not changed', async () => { const localContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, ]); const remoteContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, { key: 'cmd+c', command: 'b', args: { text: '`' } }, ]); const actual = await mergeKeybindings(localContent, remoteContent, remoteContent); assert.ok(actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, localContent); }); test('merge when an entry (with same command) is removed from local from base and remote has not changed', async () => { const localContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, ]); const remoteContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: '-a' }, ]); const actual = await mergeKeybindings(localContent, remoteContent, remoteContent); assert.ok(actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, localContent); }); test('merge when an entry is updated in local from base and remote has not changed', async () => { const localContent = stringify([ { key: 'alt+d', command: 'a', when: 'editorTextFocus' }, ]); const remoteContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, ]); const actual = await mergeKeybindings(localContent, remoteContent, remoteContent); assert.ok(actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, localContent); }); test('merge when a command with multiple entries is updated from local from base and remote has not changed', async () => { const localContent = stringify([ { key: 'shift+c', command: 'c' }, { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: 'b' }, { key: 'cmd+c', command: 'a' }, ]); const remoteContent = stringify([ { key: 'shift+c', command: 'c' }, { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+d', command: 'b' }, { key: 'cmd+d', command: 'a' }, ]); const actual = await mergeKeybindings(localContent, remoteContent, remoteContent); assert.ok(actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, localContent); }); test('merge when local has moved forwareded with multiple changes and remote stays with base', async () => { const localContent = stringify([ { key: 'alt+d', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'cmd+e', command: 'd' }, { key: 'alt+d', command: '-a' }, { key: 'alt+f', command: 'f' }, { key: 'alt+d', command: '-f' }, { key: 'cmd+d', command: 'c', when: 'context1' }, { key: 'cmd+c', command: '-c' }, ]); const remoteContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'cmd+c', command: 'b', args: { text: '`' } }, { key: 'alt+d', command: '-a' }, { key: 'cmd+e', command: 'd' }, { key: 'cmd+d', command: 'c', when: 'context1' }, ]); const expected = stringify([ { key: 'alt+d', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'cmd+e', command: 'd' }, { key: 'alt+d', command: '-a' }, { key: 'alt+f', command: 'f' }, { key: 'alt+d', command: '-f' }, { key: 'cmd+d', command: 'c', when: 'context1' }, { key: 'cmd+c', command: '-c' }, ]); const actual = await mergeKeybindings(localContent, remoteContent, remoteContent); assert.ok(actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, expected); }); test('merge when local and remote has moved forwareded with conflicts', async () => { const baseContent = stringify([ { key: 'alt+d', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'ctrl+c', command: '-a' }, { key: 'cmd+e', command: 'd' }, { key: 'alt+a', command: 'f' }, { key: 'alt+d', command: '-f' }, { key: 'cmd+d', command: 'c', when: 'context1' }, { key: 'cmd+c', command: '-c' }, ]); const localContent = stringify([ { key: 'alt+d', command: '-f' }, { key: 'cmd+e', command: 'd' }, { key: 'cmd+c', command: '-c' }, { key: 'cmd+d', command: 'c', when: 'context1' }, { key: 'alt+a', command: 'f' }, { key: 'alt+e', command: 'e' }, ]); const remoteContent = stringify([ { key: 'alt+a', command: 'f' }, { key: 'cmd+c', command: '-c' }, { key: 'cmd+d', command: 'd' }, { key: 'alt+d', command: '-f' }, { key: 'alt+c', command: 'c', when: 'context1' }, { key: 'alt+g', command: 'g', when: 'context2' }, ]); const expected = stringify([ { key: 'alt+d', command: '-f' }, { key: 'cmd+d', command: 'd' }, { key: 'cmd+c', command: '-c' }, { key: 'alt+c', command: 'c', when: 'context1' }, { key: 'alt+a', command: 'f' }, { key: 'alt+e', command: 'e' }, { key: 'alt+g', command: 'g', when: 'context2' }, ]); const actual = await mergeKeybindings(localContent, remoteContent, baseContent); assert.ok(actual.hasChanges); assert.ok(!actual.hasConflicts); assert.strictEqual(actual.mergeContent, expected); }); test('merge when local and remote with one entry but different value', async () => { const localContent = stringify([{ key: 'alt+d', command: 'a', when: 'editorTextFocus && !editorReadonly' }]); const remoteContent = stringify([{ key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }]); const actual = await mergeKeybindings(localContent, remoteContent, null); assert.ok(actual.hasChanges); assert.ok(actual.hasConflicts); assert.strictEqual(actual.mergeContent, `[ { "key": "alt+d", "command": "a", "when": "editorTextFocus && !editorReadonly" } ]`); }); test('merge when local and remote with different keybinding', async () => { const localContent = stringify([ { key: 'alt+d', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+a', command: '-a', when: 'editorTextFocus && !editorReadonly' } ]); const remoteContent = stringify([ { key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+a', command: '-a', when: 'editorTextFocus && !editorReadonly' } ]); const actual = await mergeKeybindings(localContent, remoteContent, null); assert.ok(actual.hasChanges); assert.ok(actual.hasConflicts); assert.strictEqual(actual.mergeContent, `[ { "key": "alt+d", "command": "a", "when": "editorTextFocus && !editorReadonly" }, { "key": "alt+a", "command": "-a", "when": "editorTextFocus && !editorReadonly" } ]`); }); test('merge when the entry is removed in local but updated in remote', async () => { const baseContent = stringify([{ key: 'alt+d', command: 'a', when: 'editorTextFocus && !editorReadonly' }]); const localContent = stringify([]); const remoteContent = stringify([{ key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }]); const actual = await mergeKeybindings(localContent, remoteContent, baseContent); assert.ok(actual.hasChanges); assert.ok(actual.hasConflicts); assert.strictEqual(actual.mergeContent, `[]`); }); test('merge when the entry is removed in local but updated in remote and a new entry is added in local', async () => { const baseContent = stringify([{ key: 'alt+d', command: 'a', when: 'editorTextFocus && !editorReadonly' }]); const localContent = stringify([{ key: 'alt+b', command: 'b' }]); const remoteContent = stringify([{ key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }]); const actual = await mergeKeybindings(localContent, remoteContent, baseContent); assert.ok(actual.hasChanges); assert.ok(actual.hasConflicts); assert.strictEqual(actual.mergeContent, `[ { "key": "alt+b", "command": "b" } ]`); }); test('merge when the entry is removed in remote but updated in local', async () => { const baseContent = stringify([{ key: 'alt+d', command: 'a', when: 'editorTextFocus && !editorReadonly' }]); const localContent = stringify([{ key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }]); const remoteContent = stringify([]); const actual = await mergeKeybindings(localContent, remoteContent, baseContent); assert.ok(actual.hasChanges); assert.ok(actual.hasConflicts); assert.strictEqual(actual.mergeContent, `[ { "key": "alt+c", "command": "a", "when": "editorTextFocus && !editorReadonly" } ]`); }); test('merge when the entry is removed in remote but updated in local and a new entry is added in remote', async () => { const baseContent = stringify([{ key: 'alt+d', command: 'a', when: 'editorTextFocus && !editorReadonly' }]); const localContent = stringify([{ key: 'alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }]); const remoteContent = stringify([{ key: 'alt+b', command: 'b' }]); const actual = await mergeKeybindings(localContent, remoteContent, baseContent); assert.ok(actual.hasChanges); assert.ok(actual.hasConflicts); assert.strictEqual(actual.mergeContent, `[ { "key": "alt+c", "command": "a", "when": "editorTextFocus && !editorReadonly" }, { "key": "alt+b", "command": "b" } ]`); }); test('merge when local and remote has moved forwareded with conflicts', async () => { const baseContent = stringify([ { key: 'alt+d', command: 'a', when: 'editorTextFocus && !editorReadonly' }, { key: 'alt+c', command: '-a' }, { key: 'cmd+e', command: 'd' }, { key: 'alt+a', command: 'f' }, { key: 'alt+d', command: '-f' }, { key: 'cmd+d', command: 'c', when: 'context1' }, { key: 'cmd+c', command: '-c' }, ]); const localContent = stringify([ { key: 'alt+d', command: '-f' }, { key: 'cmd+e', command: 'd' }, { key: 'cmd+c', command: '-c' }, { key: 'cmd+d', command: 'c', when: 'context1' }, { key: 'alt+a', command: 'f' }, { key: 'alt+e', command: 'e' }, ]); const remoteContent = stringify([ { key: 'alt+a', command: 'f' }, { key: 'cmd+c', command: '-c' }, { key: 'cmd+d', command: 'd' }, { key: 'alt+d', command: '-f' }, { key: 'alt+c', command: 'c', when: 'context1' }, { key: 'alt+g', command: 'g', when: 'context2' }, ]); const actual = await mergeKeybindings(localContent, remoteContent, baseContent); assert.ok(actual.hasChanges); assert.ok(actual.hasConflicts); assert.strictEqual(actual.mergeContent, `[ { "key": "alt+d", "command": "-f" }, { "key": "cmd+d", "command": "d" }, { "key": "cmd+c", "command": "-c" }, { "key": "cmd+d", "command": "c", "when": "context1" }, { "key": "alt+a", "command": "f" }, { "key": "alt+e", "command": "e" }, { "key": "alt+g", "command": "g", "when": "context2" } ]`); }); }); async function mergeKeybindings(localContent: string, remoteContent: string, baseContent: string | null) { const userDataSyncUtilService = new TestUserDataSyncUtilService(); const formattingOptions = await userDataSyncUtilService.resolveFormattingOptions(); return merge(localContent, remoteContent, baseContent, formattingOptions, userDataSyncUtilService); } function stringify(value: any): string { return JSON.stringify(value, null, '\t'); }
the_stack
import {Driver} from "../Driver.ts"; import {ConnectionIsNotSetError} from "../../error/ConnectionIsNotSetError.ts"; import {DriverPackageNotInstalledError} from "../../error/DriverPackageNotInstalledError.ts"; import {OracleQueryRunner} from "./OracleQueryRunner.ts"; import {ObjectLiteral} from "../../common/ObjectLiteral.ts"; import {ColumnMetadata} from "../../metadata/ColumnMetadata.ts"; import {DateUtils} from "../../util/DateUtils.ts"; import {PlatformTools} from "../../platform/PlatformTools.ts"; import {Connection} from "../../connection/Connection.ts"; import {RdbmsSchemaBuilder} from "../../schema-builder/RdbmsSchemaBuilder.ts"; import {OracleConnectionOptions} from "./OracleConnectionOptions.ts"; import {MappedColumnTypes} from "../types/MappedColumnTypes.ts"; import {ColumnType} from "../types/ColumnTypes.ts"; import {DataTypeDefaults} from "../types/DataTypeDefaults.ts"; import {TableColumn} from "../../schema-builder/table/TableColumn.ts"; import {OracleConnectionCredentialsOptions} from "./OracleConnectionCredentialsOptions.ts"; import {DriverUtils} from "../DriverUtils.ts"; import {EntityMetadata} from "../../metadata/EntityMetadata.ts"; import {OrmUtils} from "../../util/OrmUtils.ts"; import {ApplyValueTransformers} from "../../util/ApplyValueTransformers.ts"; /** * Organizes communication with Oracle RDBMS. */ export class OracleDriver implements Driver { // ------------------------------------------------------------------------- // Public Properties // ------------------------------------------------------------------------- /** * Connection used by driver. */ connection: Connection; /** * Underlying oracle library. */ oracle: any; /** * Pool for master database. */ master: any; /** * Pool for slave databases. * Used in replication. */ slaves: any[] = []; // ------------------------------------------------------------------------- // Public Implemented Properties // ------------------------------------------------------------------------- /** * Connection options. */ options: OracleConnectionOptions; /** * Master database used to perform all write queries. */ database?: string; /** * Indicates if replication is enabled. */ isReplicated: boolean = false; /** * Indicates if tree tables are supported by this driver. */ treeSupport = true; /** * Gets list of supported column data types by a driver. * * @see https://www.techonthenet.com/oracle/datatypes.php * @see https://docs.oracle.com/cd/B28359_01/server.111/b28318/datatype.htm#CNCPT012 */ supportedDataTypes: ColumnType[] = [ "char", "nchar", "nvarchar2", "varchar2", "long", "raw", "long raw", "number", "numeric", "float", "dec", "decimal", "integer", "int", "smallint", "real", "double precision", "date", "timestamp", "timestamp with time zone", "timestamp with local time zone", "interval year to month", "interval day to second", "bfile", "blob", "clob", "nclob", "rowid", "urowid" ]; /** * Gets list of spatial column data types. */ spatialTypes: ColumnType[] = []; /** * Gets list of column data types that support length by a driver. */ withLengthColumnTypes: ColumnType[] = [ "char", "nchar", "nvarchar2", "varchar2", "varchar", "raw" ]; /** * Gets list of column data types that support precision by a driver. */ withPrecisionColumnTypes: ColumnType[] = [ "number", "float", "timestamp", "timestamp with time zone", "timestamp with local time zone" ]; /** * Gets list of column data types that support scale by a driver. */ withScaleColumnTypes: ColumnType[] = [ "number" ]; /** * Orm has special columns and we need to know what database column types should be for those types. * Column types are driver dependant. */ mappedDataTypes: MappedColumnTypes = { createDate: "timestamp", createDateDefault: "CURRENT_TIMESTAMP", updateDate: "timestamp", updateDateDefault: "CURRENT_TIMESTAMP", version: "number", treeLevel: "number", migrationId: "number", migrationName: "varchar2", migrationTimestamp: "number", cacheId: "number", cacheIdentifier: "varchar2", cacheTime: "number", cacheDuration: "number", cacheQuery: "clob", cacheResult: "clob", metadataType: "varchar2", metadataDatabase: "varchar2", metadataSchema: "varchar2", metadataTable: "varchar2", metadataName: "varchar2", metadataValue: "clob", }; /** * Default values of length, precision and scale depends on column data type. * Used in the cases when length/precision/scale is not specified by user. */ dataTypeDefaults: DataTypeDefaults = { "char": { length: 1 }, "nchar": { length: 1 }, "varchar": { length: 255 }, "varchar2": { length: 255 }, "nvarchar2": { length: 255 }, "raw": { length: 2000 }, "float": { precision: 126 }, "timestamp": { precision: 6 }, "timestamp with time zone": { precision: 6 }, "timestamp with local time zone": { precision: 6 } }; /** * Max length allowed by Oracle for aliases. * @see https://docs.oracle.com/database/121/SQLRF/sql_elements008.htm#SQLRF51129 * > The following list of rules applies to both quoted and nonquoted identifiers unless otherwise indicated * > Names must be from 1 to 30 bytes long with these exceptions: * > [...] * * Since Oracle 12.2 (with a compatible driver/client), the limit has been set to 128. * @see https://docs.oracle.com/en/database/oracle/oracle-database/12.2/sqlrf/Database-Object-Names-and-Qualifiers.html * * > If COMPATIBLE is set to a value of 12.2 or higher, then names must be from 1 to 128 bytes long with these exceptions */ maxAliasLength = 30; // ------------------------------------------------------------------------- // Constructor // ------------------------------------------------------------------------- constructor(connection: Connection) { this.connection = connection; this.options = connection.options as any; // TODO(uki00a) avoid using any // load oracle package this.loadDependencies(); // extra oracle setup this.oracle.outFormat = this.oracle.OBJECT; // Object.assign(connection.options, DriverUtils.buildDriverOptions(connection.options)); // todo: do it better way // validate options to make sure everything is set // if (!this.options.host) // throw new DriverOptionNotSetError("host"); // if (!this.options.username) // throw new DriverOptionNotSetError("username"); // if (!this.options.sid) // throw new DriverOptionNotSetError("sid"); // } // ------------------------------------------------------------------------- // Public Methods // ------------------------------------------------------------------------- /** * Performs connection to the database. * Based on pooling options, it can either create connection immediately, * either create a pool and create connection when needed. */ async connect(): Promise<void> { this.oracle.fetchAsString = [ this.oracle.CLOB ]; this.oracle.fetchAsBuffer = [ this.oracle.BLOB ]; if (this.options.replication) { this.slaves = await Promise.all(this.options.replication.slaves.map(slave => { return this.createPool(this.options, slave); })); this.master = await this.createPool(this.options, this.options.replication.master); this.database = this.options.replication.master.database; } else { this.master = await this.createPool(this.options, this.options); this.database = this.options.database; } } /** * Makes any action after connection (e.g. create extensions in Postgres driver). */ afterConnect(): Promise<void> { return Promise.resolve(); } /** * Closes connection with the database. */ async disconnect(): Promise<void> { if (!this.master) return Promise.reject(new ConnectionIsNotSetError("oracle")); await this.closePool(this.master); await Promise.all(this.slaves.map(slave => this.closePool(slave))); this.master = undefined; this.slaves = []; } /** * Creates a schema builder used to build and sync a schema. */ createSchemaBuilder() { return new RdbmsSchemaBuilder(this.connection); } /** * Creates a query runner used to execute database queries. */ createQueryRunner(mode: "master"|"slave" = "master") { return new OracleQueryRunner(this, mode); } /** * Replaces parameters in the given sql with special escaping character * and an array of parameter names to be passed to a query. */ escapeQueryWithParameters(sql: string, parameters: ObjectLiteral, nativeParameters: ObjectLiteral): [string, any[]] { const escapedParameters: any[] = Object.keys(nativeParameters).map(key => { if (typeof nativeParameters[key] === "boolean") return nativeParameters[key] ? 1 : 0; return nativeParameters[key]; }); if (!parameters || !Object.keys(parameters).length) return [sql, escapedParameters]; const keys = Object.keys(parameters).map(parameter => "(:(\\.\\.\\.)?" + parameter + "\\b)").join("|"); sql = sql.replace(new RegExp(keys, "g"), (key: string) => { let value: any; let isArray = false; if (key.substr(0, 4) === ":...") { isArray = true; value = parameters[key.substr(4)]; } else { value = parameters[key.substr(1)]; } if (isArray) { return value.map((v: any, index: number) => { escapedParameters.push(v); return `:${key.substr(4)}${index}`; }).join(", "); } else if (value instanceof Function) { return value(); } else if (typeof value === "boolean") { return value ? 1 : 0; } else { escapedParameters.push(value); return key; } }); // todo: make replace only in value statements, otherwise problems return [sql, escapedParameters]; } /** * Escapes a column name. */ escape(columnName: string): string { return `"${columnName}"`; } /** * Build full table name with database name, schema name and table name. * Oracle does not support table schemas. One user can have only one schema. */ buildTableName(tableName: string, schema?: string, database?: string): string { return tableName; } /** * Prepares given value to a value to be persisted, based on its column type and metadata. */ preparePersistentValue(value: any, columnMetadata: ColumnMetadata): any { if (columnMetadata.transformer) value = ApplyValueTransformers.transformTo(columnMetadata.transformer, value); if (value === null || value === undefined) return value; if (columnMetadata.type === Boolean) { return value ? 1 : 0; } else if (columnMetadata.type === "date") { if (typeof value === "string") value = value.replace(/[^0-9-]/g, ""); return () => `TO_DATE('${DateUtils.mixedDateToDateString(value)}', 'YYYY-MM-DD')`; } else if (columnMetadata.type === Date || columnMetadata.type === "timestamp" || columnMetadata.type === "timestamp with time zone" || columnMetadata.type === "timestamp with local time zone") { return DateUtils.mixedDateToDate(value); } else if (columnMetadata.type === "simple-array") { return DateUtils.simpleArrayToString(value); } else if (columnMetadata.type === "simple-json") { return DateUtils.simpleJsonToString(value); } return value; } /** * Prepares given value to a value to be persisted, based on its column type or metadata. */ prepareHydratedValue(value: any, columnMetadata: ColumnMetadata): any { if (value === null || value === undefined) return columnMetadata.transformer ? ApplyValueTransformers.transformFrom(columnMetadata.transformer, value) : value; if (columnMetadata.type === Boolean) { value = value ? true : false; } else if (columnMetadata.type === "date") { value = DateUtils.mixedDateToDateString(value); } else if (columnMetadata.type === "time") { value = DateUtils.mixedTimeToString(value); } else if (columnMetadata.type === Date || columnMetadata.type === "timestamp" || columnMetadata.type === "timestamp with time zone" || columnMetadata.type === "timestamp with local time zone") { value = DateUtils.normalizeHydratedDate(value); } else if (columnMetadata.type === "json") { value = JSON.parse(value); } else if (columnMetadata.type === "simple-array") { value = DateUtils.stringToSimpleArray(value); } else if (columnMetadata.type === "simple-json") { value = DateUtils.stringToSimpleJson(value); } if (columnMetadata.transformer) value = ApplyValueTransformers.transformFrom(columnMetadata.transformer, value); return value; } /** * Creates a database type from a given column metadata. */ normalizeType(column: { type?: ColumnType, length?: number|string, precision?: number|null, scale?: number, isArray?: boolean }): string { if (column.type === Number || column.type === Boolean || column.type === "numeric" || column.type === "dec" || column.type === "decimal" || column.type === "int" || column.type === "integer" || column.type === "smallint") { return "number"; } else if (column.type === "real" || column.type === "double precision") { return "float"; } else if (column.type === String || column.type === "varchar") { return "varchar2"; } else if (column.type === Date) { return "timestamp"; } else if (column.type === "uuid") { return "varchar2"; } else if (column.type === "simple-array") { return "clob"; } else if (column.type === "simple-json") { return "clob"; } else { return column.type as string || ""; } } /** * Normalizes "default" value of the column. */ normalizeDefault(columnMetadata: ColumnMetadata): string { const defaultValue = columnMetadata.default; if (typeof defaultValue === "number") { return "" + defaultValue; } else if (typeof defaultValue === "boolean") { return defaultValue === true ? "1" : "0"; } else if (typeof defaultValue === "function") { return defaultValue(); } else if (typeof defaultValue === "string") { return `'${defaultValue}'`; } else { return defaultValue; } } /** * Normalizes "isUnique" value of the column. */ normalizeIsUnique(column: ColumnMetadata): boolean { return column.entityMetadata.uniques.some(uq => uq.columns.length === 1 && uq.columns[0] === column); } /** * Calculates column length taking into account the default length values. */ getColumnLength(column: ColumnMetadata|TableColumn): string { if (column.length) return column.length.toString(); switch (column.type) { case String: case "varchar": case "varchar2": case "nvarchar2": return "255"; case "raw": return "2000"; case "uuid": return "36"; default: return ""; } } createFullType(column: TableColumn): string { let type = column.type; // used 'getColumnLength()' method, because in Oracle column length is required for some data types. if (this.getColumnLength(column)) { type += `(${this.getColumnLength(column)})`; } else if (column.precision !== null && column.precision !== undefined && column.scale !== null && column.scale !== undefined) { type += "(" + column.precision + "," + column.scale + ")"; } else if (column.precision !== null && column.precision !== undefined) { type += "(" + column.precision + ")"; } if (column.type === "timestamp with time zone") { type = "TIMESTAMP" + (column.precision !== null && column.precision !== undefined ? "(" + column.precision + ")" : "") + " WITH TIME ZONE"; } else if (column.type === "timestamp with local time zone") { type = "TIMESTAMP" + (column.precision !== null && column.precision !== undefined ? "(" + column.precision + ")" : "") + " WITH LOCAL TIME ZONE"; } if (column.isArray) type += " array"; return type; } /** * Obtains a new database connection to a master server. * Used for replication. * If replication is not setup then returns default connection's database connection. */ obtainMasterConnection(): Promise<any> { return new Promise<any>((ok, fail) => { this.master.getConnection((err: any, connection: any, release: Function) => { if (err) return fail(err); ok(connection); }); }); } /** * Obtains a new database connection to a slave server. * Used for replication. * If replication is not setup then returns master (default) connection's database connection. */ obtainSlaveConnection(): Promise<any> { if (!this.slaves.length) return this.obtainMasterConnection(); return new Promise<any>((ok, fail) => { const random = Math.floor(Math.random() * this.slaves.length); this.slaves[random].getConnection((err: any, connection: any) => { if (err) return fail(err); ok(connection); }); }); } /** * Creates generated map of values generated or returned by database after INSERT query. */ createGeneratedMap(metadata: EntityMetadata, insertResult: ObjectLiteral) { if (!insertResult) return undefined; return Object.keys(insertResult).reduce((map, key) => { const column = metadata.findColumnWithDatabaseName(key); if (column) { OrmUtils.mergeDeep(map, column.createValueMap(this.prepareHydratedValue(insertResult[key], column))); } return map; }, {} as ObjectLiteral); } /** * Differentiate columns of this table and columns from the given column metadatas columns * and returns only changed. */ findChangedColumns(tableColumns: TableColumn[], columnMetadatas: ColumnMetadata[]): ColumnMetadata[] { return columnMetadatas.filter(columnMetadata => { const tableColumn = tableColumns.find(c => c.name === columnMetadata.databaseName); if (!tableColumn) return false; // we don't need new columns, we only need exist and changed return tableColumn.name !== columnMetadata.databaseName || tableColumn.type !== this.normalizeType(columnMetadata) || tableColumn.length !== columnMetadata.length || tableColumn.precision !== columnMetadata.precision || tableColumn.scale !== columnMetadata.scale // || tableColumn.comment !== columnMetadata.comment || // todo || this.normalizeDefault(columnMetadata) !== tableColumn.default || tableColumn.isPrimary !== columnMetadata.isPrimary || tableColumn.isNullable !== columnMetadata.isNullable || tableColumn.isUnique !== this.normalizeIsUnique(columnMetadata) || (columnMetadata.generationStrategy !== "uuid" && tableColumn.isGenerated !== columnMetadata.isGenerated); }); } /** * Returns true if driver supports RETURNING / OUTPUT statement. */ isReturningSqlSupported(): boolean { return true; } /** * Returns true if driver supports uuid values generation on its own. */ isUUIDGenerationSupported(): boolean { return false; } /** * Creates an escaped parameter. */ createParameter(parameterName: string, index: number): string { return ":" + parameterName; } /** * Converts column type in to native oracle type. */ columnTypeToNativeParameter(type: ColumnType): any { switch (this.normalizeType({ type: type as any })) { case "number": case "numeric": case "int": case "integer": case "smallint": case "dec": case "decimal": return this.oracle.NUMBER; case "char": case "nchar": case "nvarchar2": case "varchar2": return this.oracle.STRING; case "blob": return this.oracle.BLOB; case "clob": return this.oracle.CLOB; case "date": case "timestamp": case "timestamp with time zone": case "timestamp with local time zone": return this.oracle.DATE; } } // ------------------------------------------------------------------------- // Protected Methods // ------------------------------------------------------------------------- /** * Loads all driver dependencies. */ protected loadDependencies(): void { try { this.oracle = PlatformTools.load("oracledb"); } catch (e) { throw new DriverPackageNotInstalledError("Oracle", "oracledb"); } } /** * Creates a new connection pool for a given database credentials. */ protected async createPool(options: OracleConnectionOptions, credentials: OracleConnectionCredentialsOptions): Promise<any> { credentials = Object.assign({}, credentials, DriverUtils.buildDriverOptions(credentials)); // todo: do it better way // build connection options for the driver const connectionOptions = Object.assign({}, { user: credentials.username, password: credentials.password, connectString: credentials.connectString ? credentials.connectString : credentials.host + ":" + credentials.port + "/" + credentials.sid, }, options.extra || {}); // pooling is enabled either when its set explicitly to true, // either when its not defined at all (e.g. enabled by default) return new Promise<void>((ok, fail) => { this.oracle.createPool(connectionOptions, (err: any, pool: any) => { if (err) return fail(err); ok(pool); }); }); } /** * Closes connection pool. */ protected async closePool(pool: any): Promise<void> { return new Promise<void>((ok, fail) => { pool.close((err: any) => err ? fail(err) : ok()); pool = undefined; }); } }
the_stack
import { ParamDefinition as PD } from '../../../mol-util/param-definition'; import { Vec3 } from '../../../mol-math/linear-algebra'; import { NumberArray } from '../../../mol-util/type-helpers'; import { VisualContext } from '../../visual'; import { Unit, Structure, ElementIndex } from '../../../mol-model/structure'; import { Theme } from '../../../mol-theme/theme'; import { Mesh } from '../../../mol-geo/geometry/mesh/mesh'; import { MeshBuilder } from '../../../mol-geo/geometry/mesh/mesh-builder'; import { Segmentation } from '../../../mol-data/int'; import { CylinderProps } from '../../../mol-geo/primitive/cylinder'; import { isNucleic, isPurineBase, isPyrimidineBase } from '../../../mol-model/structure/model/types'; import { addCylinder } from '../../../mol-geo/geometry/mesh/builder/cylinder'; import { addSphere } from '../../../mol-geo/geometry/mesh/builder/sphere'; import { UnitsMeshParams, UnitsVisual, UnitsMeshVisual } from '../units-visual'; import { NucleotideLocationIterator, getNucleotideElementLoci, eachNucleotideElement } from './util/nucleotide'; import { VisualUpdateState } from '../../util'; import { BaseGeometry } from '../../../mol-geo/geometry/base'; import { Sphere3D } from '../../../mol-math/geometry'; // TODO support rings for multiple locations (including from microheterogeneity) const pTrace = Vec3.zero(); const pN1 = Vec3.zero(); const pC2 = Vec3.zero(); const pN3 = Vec3.zero(); const pC4 = Vec3.zero(); const pC5 = Vec3.zero(); const pC6 = Vec3.zero(); const pN7 = Vec3.zero(); const pC8 = Vec3.zero(); const pN9 = Vec3.zero(); const normal = Vec3.zero(); export const NucleotideRingMeshParams = { sizeFactor: PD.Numeric(0.2, { min: 0, max: 10, step: 0.01 }), radialSegments: PD.Numeric(16, { min: 2, max: 56, step: 2 }, BaseGeometry.CustomQualityParamInfo), detail: PD.Numeric(0, { min: 0, max: 3, step: 1 }, BaseGeometry.CustomQualityParamInfo), }; export const DefaultNucleotideRingMeshProps = PD.getDefaultValues(NucleotideRingMeshParams); export type NucleotideRingProps = typeof DefaultNucleotideRingMeshProps const positionsRing5_6 = new Float32Array(2 * 9 * 3); const stripIndicesRing5_6 = new Uint32Array([0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 14, 15, 12, 13, 8, 9, 10, 11, 0, 1]); const fanIndicesTopRing5_6 = new Uint32Array([8, 12, 14, 16, 6, 4, 2, 0, 10]); const fanIndicesBottomRing5_6 = new Uint32Array([9, 11, 1, 3, 5, 7, 17, 15, 13]); const positionsRing6 = new Float32Array(2 * 6 * 3); const stripIndicesRing6 = new Uint32Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1]); const fanIndicesTopRing6 = new Uint32Array([0, 10, 8, 6, 4, 2]); const fanIndicesBottomRing6 = new Uint32Array([1, 3, 5, 7, 9, 11]); const tmpShiftV = Vec3.zero(); function shiftPositions(out: NumberArray, dir: Vec3, ...positions: Vec3[]) { for (let i = 0, il = positions.length; i < il; ++i) { const v = positions[i]; Vec3.toArray(Vec3.add(tmpShiftV, v, dir), out, (i * 2) * 3); Vec3.toArray(Vec3.sub(tmpShiftV, v, dir), out, (i * 2 + 1) * 3); } } function createNucleotideRingMesh(ctx: VisualContext, unit: Unit, structure: Structure, theme: Theme, props: NucleotideRingProps, mesh?: Mesh) { if (!Unit.isAtomic(unit)) return Mesh.createEmpty(mesh); const nucleotideElementCount = unit.nucleotideElements.length; if (!nucleotideElementCount) return Mesh.createEmpty(mesh); const { sizeFactor, radialSegments, detail } = props; const vertexCount = nucleotideElementCount * (26 + radialSegments * 2); const builderState = MeshBuilder.createState(vertexCount, vertexCount / 4, mesh); const { elements, model } = unit; const { chainAtomSegments, residueAtomSegments, atoms, index: atomicIndex } = model.atomicHierarchy; const { moleculeType, traceElementIndex } = model.atomicHierarchy.derived.residue; const { label_comp_id } = atoms; const pos = unit.conformation.invariantPosition; const chainIt = Segmentation.transientSegments(chainAtomSegments, elements); const residueIt = Segmentation.transientSegments(residueAtomSegments, elements); const radius = 1 * sizeFactor; const halfThickness = 1.25 * sizeFactor; const cylinderProps: CylinderProps = { radiusTop: 1 * sizeFactor, radiusBottom: 1 * sizeFactor, radialSegments }; let i = 0; while (chainIt.hasNext) { residueIt.setSegment(chainIt.move()); while (residueIt.hasNext) { const { index: residueIndex } = residueIt.move(); if (isNucleic(moleculeType[residueIndex])) { const compId = label_comp_id.value(residueAtomSegments.offsets[residueIndex]); let idxTrace: ElementIndex | -1 = -1, idxN1: ElementIndex | -1 = -1, idxC2: ElementIndex | -1 = -1, idxN3: ElementIndex | -1 = -1, idxC4: ElementIndex | -1 = -1, idxC5: ElementIndex | -1 = -1, idxC6: ElementIndex | -1 = -1, idxN7: ElementIndex | -1 = -1, idxC8: ElementIndex | -1 = -1, idxN9: ElementIndex | -1 = -1; builderState.currentGroup = i; let isPurine = isPurineBase(compId); let isPyrimidine = isPyrimidineBase(compId); if (!isPurine && !isPyrimidine) { // detect Purine or Pyrimidin based on geometry const idxC4 = atomicIndex.findAtomOnResidue(residueIndex, 'C4'); const idxN9 = atomicIndex.findAtomOnResidue(residueIndex, 'N9'); if (idxC4 !== -1 && idxN9 !== -1 && Vec3.distance(pos(idxC4, pC4), pos(idxN9, pN9)) < 1.6) { isPurine = true; } else { isPyrimidine = true; } } if (isPurine) { idxTrace = traceElementIndex[residueIndex]; idxN1 = atomicIndex.findAtomOnResidue(residueIndex, 'N1'); idxC2 = atomicIndex.findAtomOnResidue(residueIndex, 'C2'); idxN3 = atomicIndex.findAtomOnResidue(residueIndex, 'N3'); idxC4 = atomicIndex.findAtomOnResidue(residueIndex, 'C4'); idxC5 = atomicIndex.findAtomOnResidue(residueIndex, 'C5'); if (idxC5 === -1) { // modified ring, e.g. DP idxC5 = atomicIndex.findAtomOnResidue(residueIndex, 'N5'); } idxC6 = atomicIndex.findAtomOnResidue(residueIndex, 'C6'); idxN7 = atomicIndex.findAtomOnResidue(residueIndex, 'N7'); if (idxN7 === -1) { // modified ring, e.g. DP idxN7 = atomicIndex.findAtomOnResidue(residueIndex, 'C7'); } idxC8 = atomicIndex.findAtomOnResidue(residueIndex, 'C8'); idxN9 = atomicIndex.findAtomOnResidue(residueIndex, 'N9'); if (idxN9 !== -1 && idxTrace !== -1) { pos(idxN9, pN9); pos(idxTrace, pTrace); builderState.currentGroup = i; addCylinder(builderState, pN9, pTrace, 1, cylinderProps); addSphere(builderState, pN9, radius, detail); } if (idxN1 !== -1 && idxC2 !== -1 && idxN3 !== -1 && idxC4 !== -1 && idxC5 !== -1 && idxC6 !== -1 && idxN7 !== -1 && idxC8 !== -1 && idxN9 !== -1) { pos(idxN1, pN1); pos(idxC2, pC2); pos(idxN3, pN3); pos(idxC4, pC4); pos(idxC5, pC5); pos(idxC6, pC6); pos(idxN7, pN7); pos(idxC8, pC8); Vec3.triangleNormal(normal, pN1, pC4, pC5); Vec3.scale(normal, normal, halfThickness); shiftPositions(positionsRing5_6, normal, pN1, pC2, pN3, pC4, pC5, pC6, pN7, pC8, pN9); MeshBuilder.addTriangleStrip(builderState, positionsRing5_6, stripIndicesRing5_6); MeshBuilder.addTriangleFan(builderState, positionsRing5_6, fanIndicesTopRing5_6); MeshBuilder.addTriangleFan(builderState, positionsRing5_6, fanIndicesBottomRing5_6); } } else if (isPyrimidine) { idxTrace = traceElementIndex[residueIndex]; idxN1 = atomicIndex.findAtomOnResidue(residueIndex, 'N1'); if (idxN1 === -1) { // modified ring, e.g. DZ idxN1 = atomicIndex.findAtomOnResidue(residueIndex, 'C1'); } idxC2 = atomicIndex.findAtomOnResidue(residueIndex, 'C2'); idxN3 = atomicIndex.findAtomOnResidue(residueIndex, 'N3'); idxC4 = atomicIndex.findAtomOnResidue(residueIndex, 'C4'); idxC5 = atomicIndex.findAtomOnResidue(residueIndex, 'C5'); idxC6 = atomicIndex.findAtomOnResidue(residueIndex, 'C6'); if (idxN1 !== -1 && idxTrace !== -1) { pos(idxN1, pN1); pos(idxTrace, pTrace); builderState.currentGroup = i; addCylinder(builderState, pN1, pTrace, 1, cylinderProps); addSphere(builderState, pN1, radius, detail); } if (idxN1 !== -1 && idxC2 !== -1 && idxN3 !== -1 && idxC4 !== -1 && idxC5 !== -1 && idxC6 !== -1) { pos(idxC2, pC2); pos(idxN3, pN3); pos(idxC4, pC4); pos(idxC5, pC5); pos(idxC6, pC6); Vec3.triangleNormal(normal, pN1, pC4, pC5); Vec3.scale(normal, normal, halfThickness); shiftPositions(positionsRing6, normal, pN1, pC2, pN3, pC4, pC5, pC6); MeshBuilder.addTriangleStrip(builderState, positionsRing6, stripIndicesRing6); MeshBuilder.addTriangleFan(builderState, positionsRing6, fanIndicesTopRing6); MeshBuilder.addTriangleFan(builderState, positionsRing6, fanIndicesBottomRing6); } } ++i; } } } const m = MeshBuilder.getMesh(builderState); const sphere = Sphere3D.expand(Sphere3D(), unit.boundary.sphere, 1 * props.sizeFactor); m.setBoundingSphere(sphere); return m; } export const NucleotideRingParams = { ...UnitsMeshParams, ...NucleotideRingMeshParams }; export type NucleotideRingParams = typeof NucleotideRingParams export function NucleotideRingVisual(materialId: number): UnitsVisual<NucleotideRingParams> { return UnitsMeshVisual<NucleotideRingParams>({ defaultProps: PD.getDefaultValues(NucleotideRingParams), createGeometry: createNucleotideRingMesh, createLocationIterator: NucleotideLocationIterator.fromGroup, getLoci: getNucleotideElementLoci, eachLocation: eachNucleotideElement, setUpdateState: (state: VisualUpdateState, newProps: PD.Values<NucleotideRingParams>, currentProps: PD.Values<NucleotideRingParams>) => { state.createGeometry = ( newProps.sizeFactor !== currentProps.sizeFactor || newProps.radialSegments !== currentProps.radialSegments ); } }, materialId); }
the_stack
import { Boxed, isBoxed } from './boxing'; import { deepEquals, isEmpty } from './util'; export type FormControlValueTypes = Boxed<any> | string | number | boolean | null | undefined; export type NgrxFormControlId = string; /** * This type represents a collection of named errors. */ export interface ValidationErrors { readonly [key: string]: any; } export interface KeyValue { [key: string]: any; } /** * Base interface for all types of form states. */ export interface AbstractControlState<TValue> { /** * The unique ID of the form state. Usually this is the name or index * of the control in the form value prefixed by the ID of the containing * group or array, e.g. `MY_FORM.someTextInput` or `MY_FORM.0`. */ readonly id: string; /** * The value of the form state. */ readonly value: TValue; /** * This property is `true` if the state does not have any errors. */ readonly isValid: boolean; /** * This property is `true` if the state has at least one error. */ readonly isInvalid: boolean; /** * The errors of the state. This property always has a value. * If the state has no errors the property is set to `{}`. */ readonly errors: ValidationErrors; /** * The names of all asynchronous validations currently running * for the state. */ readonly pendingValidations: readonly string[]; /** * This property indicates whether the control is currently being * asynchronously validated. */ readonly isValidationPending: boolean; /** * This property indicates whether the state is enabled. When it * is `false` the `errors` are always `{}` (i.e. the state is * always valid if disabled) and `pendingValidations` is always `[]` * (i.e. all pending validations are cancelled). */ readonly isEnabled: boolean; /** * This property indicates whether the state is disabled. When it * is `true` the `errors` are always `{}` (i.e. the state is * always valid if disabled) and `pendingValidations` is always `[]` * (i.e. all pending validations are cancelled). */ readonly isDisabled: boolean; /** * This property is set to `true` as soon as the state's value changes. */ readonly isDirty: boolean; /** * This property is `true` as long as the state's value never changed. */ readonly isPristine: boolean; /** * This property is set to `true` as soon as the state is touched. */ readonly isTouched: boolean; /** * This property is `true` as long as the state is not touched. */ readonly isUntouched: boolean; /** * This property is set to `true` as soon as the state is submitted. */ readonly isSubmitted: boolean; /** * This property is `true` as long as the state is not submitted. */ readonly isUnsubmitted: boolean; /** * This property is a container for user-defined metadata (e.g. if * you wanted to count the number of times a state's value has been * changed, what keys were pressed on an input, or how often a form * has been submitted etc.). While it is possible to store this kind * of information outside of **ngrx-forms** in your own state the * `userDefinedProperties` allow you to store your own metadata * directly in the state. */ readonly userDefinedProperties: KeyValue; } /** * State associated with a form control, i.e. an HTML form * element in the view (e.g. `input`, `select`, `textarea` etc.). */ export interface FormControlState<TValue extends FormControlValueTypes> extends AbstractControlState<TValue> { /** * The value of the form state. Form controls only support values of * type `string`, `number`, `boolean`, `null`, and `undefined` to * keep the state string serializable. */ readonly value: TValue; /** * This property is `true` if the form control does not have any errors. */ readonly isValid: boolean; /** * This property is `true` if the form control has at least one error. */ readonly isInvalid: boolean; /** * The errors of the form control. This property always has a value. * If the control has no errors the property is set to `{}`. */ readonly errors: ValidationErrors; /** * The names of all asynchronous validations currently running for the * form control. */ readonly pendingValidations: readonly string[]; /** * This property indicates whether the control is currently being * asynchronously validated (i.e. this is `true` if and only if * `pendingValidations` is not empty). */ readonly isValidationPending: boolean; /** * This property indicates whether the form control is enabled. * When it is `false` the `errors` are always `{}` (i.e. the form * control is always valid if disabled) and `pendingValidations` * is always `[]` (i.e. all pending validations are cancelled). */ readonly isEnabled: boolean; /** * This property indicates whether the form control is disabled. * When it is `true` the `errors` are always `{}` (i.e. the form * control is always valid if disabled) and `pendingValidations` * is always `[]` (i.e. all pending validations are cancelled). */ readonly isDisabled: boolean; /** * This property is set to `true` as soon as the underlying * `FormViewAdapter` or `ControlValueAccessor` reports a new * value for the first time. */ readonly isDirty: boolean; /** * This property is `true` as long as the underlying * `FormViewAdapter` or `ControlValueAccessor` has never * reported a new value. */ readonly isPristine: boolean; /** * This property is set to `true` based on the rules of the * underlying `FormViewAdapter` (usually on `blur` for most form * elements). */ readonly isTouched: boolean; /** * This property is `true` as long as the control is not touched. */ readonly isUntouched: boolean; /** * This property is set to `true` as soon as the group or array * containing this form control is submitted. A form control can * never be submitted on its own. */ readonly isSubmitted: boolean; /** * This property is `true` as long as the state is not submitted. */ readonly isUnsubmitted: boolean; /** * This property is set to `true` if the form control currently * has focus. This feature is opt-in. To enable it you have to * enable it for a given form element like this: * ```html <input [ngrxFormControlState]="state" [ngrxEnableFocusTracking]="true" /> ``` */ readonly isFocused: boolean; /** * This property is `true` if the control currently does not have * focus or focus tracking is not enabled for the form control. */ readonly isUnfocused: boolean; } /** * This type represents the child control states of a form group. */ export type FormGroupControls<TValue> = { readonly [controlId in keyof TValue]: FormState<TValue[controlId]>; }; /** * Form groups are collections of named controls. Just like controls * groups are represented as plain state objects. The state of a * group is determined almost fully by its child states. */ export interface FormGroupState<TValue extends KeyValue> extends AbstractControlState<TValue> { /** * The aggregated value of the form group. The value is computed by * aggregating the values of all children, e.g. * ```typescript { child1: 'some value', child2: { nestedChild: 10, }, } ``` */ readonly value: TValue; /** * This property is `true` if the form group does not have any errors * itself and none of its children have any errors. */ readonly isValid: boolean; /** * This property is `true` if the form group or any of its children * have at least one error. */ readonly isInvalid: boolean; /** * The errors of the form group. This property is computed by merging * the errors of the group with the errors of all its children where * the child errors are a property of the `errors` object prefixed with * an underscore, e.g. * ``` { groupError: true, _child: { childError: true, }, } ``` * * If neither the group nor any children have errors the property is * set to `{}`. */ readonly errors: ValidationErrors; /** * The names of all asynchronous validations currently running for the * form group. */ readonly pendingValidations: readonly string[]; /** * This property indicates whether the group or any of its children * are currently being asynchronously validated. */ readonly isValidationPending: boolean; /** * This property indicates whether the form group is enabled. It is * `true` if and only if at least one of its child states is * enabled. When it is `false` the `errors` are always `{}` (i.e. * the form group is always valid if disabled) and `pendingValidations` * is always `[]` (i.e. all pending validations are cancelled). */ readonly isEnabled: boolean; /** * This property indicates whether the form group is disabled. It is * `true` if and only if all of its child state are disabled. When * it is `true` the `errors` are always `{}` (i.e. the form group * is always valid if disabled) and `pendingValidations` is always * `[]` (i.e. all pending validations are cancelled). */ readonly isDisabled: boolean; /** * This property is `true` if and only if at least one of the form * group's child states is marked as dirty. */ readonly isDirty: boolean; /** * This property is `true` if and only if all of the form group's * child states are pristine. */ readonly isPristine: boolean; /** * This property is `true` if and only if at least one of the form * group's child states is marked as touched. */ readonly isTouched: boolean; /** * This property is `true` if and only if all of the form group's * child states are untouched. */ readonly isUntouched: boolean; /** * This property is set to `true` as soon as the form group is * submitted. This is tracked by the `NgrxFormDirective`, which * needs to be applied to a form like this: * ```html <form [ngrxFormState]="groupState"> </form> ``` * * Note that applying this directive to a form prevents normal form * submission since that does not make much sense for ngrx forms. */ readonly isSubmitted: boolean; /** * This property is `true` as long as the state is not submitted. */ readonly isUnsubmitted: boolean; /** * This property contains all child states of the form group. As * you may have noticed the type of each child state is * `AbstractControlState` which sometimes forces you to cast the * state explicitly. It is not possible to improve this typing * until [conditional mapped types](https://github.com/Microsoft/TypeScript/issues/12424) * are added to TypeScript. */ readonly controls: FormGroupControls<TValue>; } /** * Form arrays are collections of controls. They are represented as * plain state arrays. The state of an array is determined almost * fully by its child states. */ export interface FormArrayState<TValue> extends AbstractControlState<readonly TValue[]> { /** * The aggregated value of the form array. The value is computed by * aggregating the values of all children into an array. */ readonly value: TValue[]; /** * This property is `true` if the form array does not have any errors * itself and none of its children have any errors. */ readonly isValid: boolean; /** * This property is `true` if the form array or any of its children * have at least one error. */ readonly isInvalid: boolean; /** * The errors of the form array. This property is computed by merging * the errors of the array with the errors of all its children where * the child errors are a property of the `errors` object prefixed with * an underscore, e.g. * ``` { arrayError: true, _0: { childError: true, }, } ``` * * If neither the array nor any children have errors the property is * set to `{}`. */ readonly errors: ValidationErrors; /** * The names of all asynchronous validations currently running for the * form array. */ readonly pendingValidations: readonly string[]; /** * This property indicates whether the array or any of its children * are currently being asynchronously validated. */ readonly isValidationPending: boolean; /** * This property indicates whether the form array is enabled. It is * `true` if and only if at least one of its child states is * enabled. When it is `false` the `errors` are always `{}` (i.e. * the form array is always valid if disabled) and `pendingValidations` * is always `[]` (i.e. all pending validations are cancelled). */ readonly isEnabled: boolean; /** * This property indicates whether the form array is disabled. It is * `true` if and only if all of its child states are disabled. When * it is `true` the `errors` are always `{}` (i.e. the form array * is always valid if disabled) and `pendingValidations` is always * `[]` (i.e. all pending validations are cancelled). */ readonly isDisabled: boolean; /** * This property is `true` if and only if at least one of the form * array's child states is marked as dirty. */ readonly isDirty: boolean; /** * This property is `true` if and only if all of the form array's * child states are pristine. */ readonly isPristine: boolean; /** * This property is `true` if and only if at least one of the form * array's child states is marked as touched. */ readonly isTouched: boolean; /** * This property is `true` if and only if all of the form array's * child states are untouched. */ readonly isUntouched: boolean; /** * This property is set to `true` as soon as the form array is * submitted. This is tracked by the `NgrxFormDirective`, which * needs to be applied to a form like this: * ```html <form [ngrxFormState]="arrayState"> </form> ``` * * Note that applying this directive to a form prevents normal form * submission since that does not make much sense for ngrx forms. */ readonly isSubmitted: boolean; /** * This property is `true` as long as the state is not submitted. */ readonly isUnsubmitted: boolean; /** * This property contains all child states of the form array. As * you may have noticed the type of each child state is * `AbstractControlState` which sometimes forces you to cast the * state explicitly. It is not possible to improve this typing * until [conditional mapped types](https://github.com/Microsoft/TypeScript/issues/12424) * are added to TypeScript. */ readonly controls: readonly FormState<TValue>[]; } /** * This is a helper type that allows working around the distributiveness * of conditional types. */ export interface InferenceWrapper<T> { t: T; } /** * This is a helper type that infers the correct form state type based * on the boxed type contained in the inference wrapper. */ export type InferredBoxedFormState<T extends InferenceWrapper<any>> = T extends InferenceWrapper<Boxed<infer U>> ? FormControlState<Boxed<U>> : T extends InferenceWrapper<Boxed<infer U> | undefined> ? FormControlState<Boxed<U> | undefined> : T extends InferenceWrapper<Boxed<infer U> | null> ? FormControlState<Boxed<U> | null> : T extends InferenceWrapper<Boxed<infer U> | undefined | null> ? FormControlState<Boxed<U> | undefined | null> : never ; /** * This is a helper type that infers the correct form state type based * on the string type contained in the inference wrapper. */ export type InferredStringFormState<T extends InferenceWrapper<any>> = T extends InferenceWrapper<string> ? FormControlState<string> : T extends InferenceWrapper<string | undefined> ? FormControlState<string | undefined> : T extends InferenceWrapper<string | null> ? FormControlState<string | null> : T extends InferenceWrapper<string | undefined | null> ? FormControlState<string | undefined | null> : never ; /** * This is a helper type that infers the correct form state type based * on the number type contained in the inference wrapper. */ export type InferredNumberFormState<T extends InferenceWrapper<any>> = T extends InferenceWrapper<number> ? FormControlState<number> : T extends InferenceWrapper<number | undefined> ? FormControlState<number | undefined> : T extends InferenceWrapper<number | null> ? FormControlState<number | null> : T extends InferenceWrapper<number | undefined | null> ? FormControlState<number | undefined | null> : never ; /** * This is a helper type that infers the correct form state type based * on the boolean type contained in the inference wrapper. */ export type InferredBooleanFormState<T extends InferenceWrapper<any>> = T extends InferenceWrapper<boolean> ? FormControlState<boolean> : T extends InferenceWrapper<boolean | undefined> ? FormControlState<boolean | undefined> : T extends InferenceWrapper<boolean | null> ? FormControlState<boolean | null> : T extends InferenceWrapper<boolean | undefined | null> ? FormControlState<boolean | undefined | null> : never ; /** * This is a helper type that infers the correct form state type based * on the type contained in the inference wrapper. */ export type InferredFormState<T extends InferenceWrapper<any>> = // (ab)use 'symbol' to catch 'any' typing T extends InferenceWrapper<symbol> ? AbstractControlState<any> : T extends InferenceWrapper<undefined> ? AbstractControlState<any> : T extends InferenceWrapper<null> ? AbstractControlState<any> // control : T extends InferenceWrapper<Boxed<any> | undefined | null> ? InferredBoxedFormState<T> : T extends InferenceWrapper<string | undefined | null> ? InferredStringFormState<T> : T extends InferenceWrapper<number | undefined | null> ? InferredNumberFormState<T> : T extends InferenceWrapper<boolean | undefined | null> ? InferredBooleanFormState<T> // array : T extends InferenceWrapper<readonly (infer U)[] | undefined | null> ? FormArrayState<U> // group : T extends InferenceWrapper<infer U | undefined | null> ? FormGroupState<U> // fallback type (this case should never (no pun intended) be hit) : never ; /** * This is a type that can infer the concrete type of a form state based * on the given type parameter. */ export type FormState<T> = InferredFormState<InferenceWrapper<T>>; /** * This function determines if a value is a form state. */ export function isFormState<TValue = any>(state: any): state is FormState<TValue> { return !!state && state.hasOwnProperty('id') && state.hasOwnProperty('value') && state.hasOwnProperty('errors'); } /** * This function determines if a value is an array state. */ export function isArrayState<TValue = any>(state: any): state is FormArrayState<TValue> { return isFormState(state) && state.hasOwnProperty('controls') && Array.isArray((state as any).controls); } /** * This function determines if a value is a group state. */ export function isGroupState<TValue = any>(state: any): state is FormGroupState<TValue> { return isFormState(state) && state.hasOwnProperty('controls') && !Array.isArray((state as any).controls) && typeof (state as any).controls !== 'function'; } export function createChildState<TValue>(id: string, childValue: TValue): FormState<TValue> { if (isBoxed(childValue)) { return createFormControlState<any>(id, childValue) as FormState<TValue>; } if (childValue !== null && Array.isArray(childValue)) { return createFormArrayState(id, childValue as any[]) as FormState<TValue>; } if (childValue !== null && typeof childValue === 'object') { return createFormGroupState(id, childValue) as FormState<TValue>; } return createFormControlState<any>(id, childValue) as FormState<TValue>; } export function verifyFormControlValueIsValid<TValue>(value: TValue) { if (value === null || ['string', 'number', 'boolean', 'undefined'].indexOf(typeof value) >= 0) { return value; } if (!isBoxed(value)) { const errorMsg = 'Form control states only support undefined, null, string, number, and boolean values as well as boxed values'; throw new Error(`${errorMsg}; got ${JSON.stringify(value)} of type ${typeof value}`); // `; } if (value.value === null || ['string', 'number', 'boolean', 'undefined'].indexOf(typeof value.value) >= 0) { return value; } const serialized = JSON.stringify(value); const deserialized = JSON.parse(serialized); if (deepEquals(value, deserialized, { treatUndefinedAndMissingKeyAsSame: true })) { return value; } throw new Error(`A form control value must be serializable (i.e. value === JSON.parse(JSON.stringify(value))), got: ${JSON.stringify(value)}`); } /** * This function creates a form control state with an ID and a value. */ export function createFormControlState<TValue extends FormControlValueTypes>( id: NgrxFormControlId, value: TValue, ): FormControlState<TValue> { return { id, value: verifyFormControlValueIsValid(value), errors: {}, pendingValidations: [], isValidationPending: false, isValid: true, isInvalid: false, isEnabled: true, isDisabled: false, isDirty: false, isPristine: true, isTouched: false, isUntouched: true, isSubmitted: false, isUnsubmitted: true, isFocused: false, isUnfocused: true, userDefinedProperties: {}, }; } export function getFormGroupValue<TValue extends KeyValue>( controls: FormGroupControls<TValue>, originalValue: TValue, ): TValue { let hasChanged = Object.keys(originalValue).length !== Object.keys(controls).length; const newValue = Object.keys(controls).reduce((res, key: keyof TValue) => { hasChanged = hasChanged || originalValue[key] !== controls[key].value; res[key] = controls[key].value; return res; }, {} as TValue); return hasChanged ? newValue : originalValue; } export function getFormGroupErrors<TValue extends KeyValue>( controls: FormGroupControls<TValue>, originalErrors: ValidationErrors, ): ValidationErrors { let hasChanged = false; const groupErrors = Object.keys(originalErrors) .filter(key => !key.startsWith('_')) .reduce((res, key) => Object.assign(res, { [key]: originalErrors[key] }), {} as ValidationErrors); const newErrors = Object.keys(controls).reduce((res, key: any) => { const controlErrors = controls[key].errors; if (!isEmpty(controlErrors)) { hasChanged = hasChanged || originalErrors[`_${key}`] !== controlErrors; Object.assign(res, { [`_${key}`]: controls[key].errors }); } else { hasChanged = hasChanged || originalErrors.hasOwnProperty(`_${key}`); } return res; }, groupErrors); hasChanged = hasChanged || Object.keys(originalErrors).length !== Object.keys(newErrors).length; return hasChanged ? newErrors : originalErrors; } export function computeGroupState<TValue extends KeyValue>( id: string, controls: FormGroupControls<TValue>, value: TValue, errors: ValidationErrors, pendingValidations: readonly string[], userDefinedProperties: KeyValue, flags: { wasOrShouldBeDirty?: boolean; wasOrShouldBeEnabled?: boolean; wasOrShouldBeTouched?: boolean; wasOrShouldBeSubmitted?: boolean; }, ): FormGroupState<TValue> { value = getFormGroupValue<TValue>(controls, value); errors = getFormGroupErrors(controls, errors); const isValid = isEmpty(errors); const isDirty = flags.wasOrShouldBeDirty || Object.keys(controls).some(key => controls[key].isDirty); const isEnabled = flags.wasOrShouldBeEnabled || Object.keys(controls).some(key => controls[key].isEnabled); const isTouched = flags.wasOrShouldBeTouched || Object.keys(controls).some(key => controls[key].isTouched); const isSubmitted = flags.wasOrShouldBeSubmitted || Object.keys(controls).some(key => controls[key].isSubmitted); const isValidationPending = pendingValidations.length > 0 || Object.keys(controls).some(key => controls[key].isValidationPending); return { id, value, errors, pendingValidations, isValidationPending, isValid, isInvalid: !isValid, isEnabled, isDisabled: !isEnabled, isDirty, isPristine: !isDirty, isTouched, isUntouched: !isTouched, isSubmitted, isUnsubmitted: !isSubmitted, userDefinedProperties, controls, }; } /** * This function creates a form group state with an ID and a value. * From the value the shape of the group state is inferred, i.e. * object properties are inferred as form groups, array properties * are inferred as form arrays, and primitive properties are inferred * as form controls. */ export function createFormGroupState<TValue extends KeyValue>( id: NgrxFormControlId, initialValue: TValue, ): FormGroupState<TValue> { const controls = Object.keys(initialValue) .map((key: keyof TValue) => [key, createChildState(`${id}.${key}`, initialValue[key])] as [string, FormState<any>]) .reduce((res, [controlId, state]) => Object.assign(res, { [controlId]: state }), {} as FormGroupControls<TValue>); return computeGroupState(id, controls, initialValue, {}, [], {}, { wasOrShouldBeEnabled: true }); } function getFormArrayValue<TValue>( controls: readonly AbstractControlState<TValue>[], originalValue: TValue[], ): TValue[] { let hasChanged = Object.keys(originalValue).length !== Object.keys(controls).length; const newValue = controls.map((state, i) => { hasChanged = hasChanged || originalValue[i] !== state.value; return state.value; }); return hasChanged ? newValue : originalValue; } function getFormArrayErrors<TValue>( controls: readonly AbstractControlState<TValue>[], originalErrors: ValidationErrors, ): ValidationErrors { let hasChanged = false; const groupErrors = Object.keys(originalErrors) .filter(key => !key.startsWith('_')) .reduce((res, key) => Object.assign(res, { [key]: originalErrors[key] }), {} as ValidationErrors); const newErrors = controls.reduce((res, state, i) => { const controlErrors = state.errors; if (!isEmpty(controlErrors)) { hasChanged = hasChanged || originalErrors[`_${i}`] !== controlErrors; Object.assign(res, { [`_${i}`]: controlErrors }); } else { hasChanged = hasChanged || originalErrors.hasOwnProperty(`_${i}`); } return res; }, groupErrors); hasChanged = hasChanged || Object.keys(originalErrors).length !== Object.keys(newErrors).length; return hasChanged ? newErrors : originalErrors; } export function computeArrayState<TValue>( id: string, inferredControls: readonly FormState<TValue>[], value: TValue[], errors: ValidationErrors, pendingValidations: readonly string[], userDefinedProperties: KeyValue, flags: { wasOrShouldBeDirty?: boolean; wasOrShouldBeEnabled?: boolean; wasOrShouldBeTouched?: boolean; wasOrShouldBeSubmitted?: boolean; }, ): FormArrayState<TValue> { const controls = inferredControls as readonly AbstractControlState<any>[]; value = getFormArrayValue<TValue>(controls, value); errors = getFormArrayErrors(controls, errors); const isValid = isEmpty(errors); const isDirty = flags.wasOrShouldBeDirty || controls.some(state => state.isDirty); const isEnabled = flags.wasOrShouldBeEnabled || controls.some(state => state.isEnabled); const isTouched = flags.wasOrShouldBeTouched || controls.some(state => state.isTouched); const isSubmitted = flags.wasOrShouldBeSubmitted || controls.some(state => state.isSubmitted); const isValidationPending = pendingValidations.length > 0 || controls.some(state => state.isValidationPending); return { id, value, errors, pendingValidations, isValidationPending, isValid, isInvalid: !isValid, isEnabled, isDisabled: !isEnabled, isDirty, isPristine: !isDirty, isTouched, isUntouched: !isTouched, isSubmitted, isUnsubmitted: !isSubmitted, userDefinedProperties, controls: inferredControls, }; } /** * This function creates a form array state with an ID and a value. * From the value the shape of the array state is inferred, i.e. * object values are inferred as form groups, array values * are inferred as form arrays, and primitive values are inferred * as form controls. */ export function createFormArrayState<TValue>( id: NgrxFormControlId, initialValue: TValue[], ): FormArrayState<TValue> { const controls = initialValue .map((value, i) => createChildState(`${id}.${i}`, value)); return computeArrayState(id, controls, initialValue, {}, [], {}, { wasOrShouldBeEnabled: true }); }
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 datapipelines_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; } /** * Data pipelines API * * Data Pipelines provides an interface for creating, updating, and managing recurring Data Analytics jobs. * * @example * ```js * const {google} = require('googleapis'); * const datapipelines = google.datapipelines('v1'); * ``` */ export class Datapipelines { context: APIRequestContext; projects: Resource$Projects; constructor(options: GlobalOptions, google?: GoogleConfigurable) { this.context = { _options: options || {}, google, }; this.projects = new Resource$Projects(this.context); } } /** * Pipeline job details specific to the Dataflow API. This is encapsulated here to allow for more executors to store their specific details separately. */ export interface Schema$GoogleCloudDatapipelinesV1DataflowJobDetails { /** * Output only. The current number of workers used to run the jobs. Only set to a value if the job is still running. */ currentWorkers?: number | null; /** * Cached version of all the metrics of interest for the job. This value gets stored here when the job is terminated. As long as the job is running, this field is populated from the Dataflow API. */ resourceInfo?: {[key: string]: number} | null; /** * Output only. The SDK version used to run the job. */ sdkVersion?: Schema$GoogleCloudDatapipelinesV1SdkVersion; } /** * The environment values to be set at runtime for a Flex Template. */ export interface Schema$GoogleCloudDatapipelinesV1FlexTemplateRuntimeEnvironment { /** * Additional experiment flags for the job. */ additionalExperiments?: string[] | null; /** * Additional user labels to be specified for the job. Keys and values must follow the restrictions specified in the [labeling restrictions](https://cloud.google.com/compute/docs/labeling-resources#restrictions). An object containing a list of key/value pairs. Example: `{ "name": "wrench", "mass": "1kg", "count": "3" \}`. */ additionalUserLabels?: {[key: string]: string} | null; /** * Whether to enable Streaming Engine for the job. */ enableStreamingEngine?: boolean | null; /** * Set FlexRS goal for the job. https://cloud.google.com/dataflow/docs/guides/flexrs */ flexrsGoal?: string | null; /** * Configuration for VM IPs. */ ipConfiguration?: string | null; /** * Name for the Cloud KMS key for the job. Key format is: projects//locations//keyRings//cryptoKeys/ */ kmsKeyName?: string | null; /** * The machine type to use for the job. Defaults to the value from the template if not specified. */ machineType?: string | null; /** * The maximum number of Compute Engine instances to be made available to your pipeline during execution, from 1 to 1000. */ maxWorkers?: number | null; /** * Network to which VMs will be assigned. If empty or unspecified, the service will use the network "default". */ network?: string | null; /** * The initial number of Compute Engine instances for the job. */ numWorkers?: number | null; /** * The email address of the service account to run the job as. */ serviceAccountEmail?: string | null; /** * Subnetwork to which VMs will be assigned, if desired. You can specify a subnetwork using either a complete URL or an abbreviated path. Expected to be of the form "https://www.googleapis.com/compute/v1/projects/HOST_PROJECT_ID/regions/REGION/subnetworks/SUBNETWORK" or "regions/REGION/subnetworks/SUBNETWORK". If the subnetwork is located in a Shared VPC network, you must use the complete URL. */ subnetwork?: string | null; /** * The Cloud Storage path to use for temporary files. Must be a valid Cloud Storage URL, beginning with `gs://`. */ tempLocation?: string | null; /** * The Compute Engine region (https://cloud.google.com/compute/docs/regions-zones/regions-zones) in which worker processing should occur, e.g. "us-west1". Mutually exclusive with worker_zone. If neither worker_region nor worker_zone is specified, defaults to the control plane region. */ workerRegion?: string | null; /** * The Compute Engine zone (https://cloud.google.com/compute/docs/regions-zones/regions-zones) in which worker processing should occur, e.g. "us-west1-a". Mutually exclusive with worker_region. If neither worker_region nor worker_zone is specified, a zone in the control plane region is chosen based on available capacity. If both `worker_zone` and `zone` are set, `worker_zone` takes precedence. */ workerZone?: string | null; /** * The Compute Engine [availability zone](https://cloud.google.com/compute/docs/regions-zones/regions-zones) for launching worker instances to run your pipeline. In the future, worker_zone will take precedence. */ zone?: string | null; } /** * Definition of the job information maintained by the pipeline. Fields in this entity are retrieved from the executor API (e.g. Dataflow API). */ export interface Schema$GoogleCloudDatapipelinesV1Job { /** * Output only. The time of job creation. */ createTime?: string | null; /** * All the details that are specific to a Dataflow job. */ dataflowJobDetails?: Schema$GoogleCloudDatapipelinesV1DataflowJobDetails; /** * Output only. The time of job termination. This is absent if the job is still running. */ endTime?: string | null; /** * Output only. The internal ID for the job. */ id?: string | null; /** * Required. The fully qualified resource name for the job. */ name?: string | null; /** * The current state of the job. */ state?: string | null; /** * Status capturing any error code or message related to job creation or execution. */ status?: Schema$GoogleRpcStatus; } /** * Launch Flex Template parameter. */ export interface Schema$GoogleCloudDatapipelinesV1LaunchFlexTemplateParameter { /** * Cloud Storage path to a file with a JSON-serialized ContainerSpec as content. */ containerSpecGcsPath?: string | null; /** * The runtime environment for the Flex Template job. */ environment?: Schema$GoogleCloudDatapipelinesV1FlexTemplateRuntimeEnvironment; /** * Required. The job name to use for the created job. For an update job request, the job name should be the same as the existing running job. */ jobName?: string | null; /** * Launch options for this Flex Template job. This is a common set of options across languages and templates. This should not be used to pass job parameters. */ launchOptions?: {[key: string]: string} | null; /** * The parameters for the Flex Template. Example: `{"num_workers":"5"\}` */ parameters?: {[key: string]: string} | null; /** * Use this to pass transform name mappings for streaming update jobs. Example: `{"oldTransformName":"newTransformName",...\}` */ transformNameMappings?: {[key: string]: string} | null; /** * Set this to true if you are sending a request to update a running streaming job. When set, the job name should be the same as the running job. */ update?: boolean | null; } /** * A request to launch a Dataflow job from a Flex Template. */ export interface Schema$GoogleCloudDatapipelinesV1LaunchFlexTemplateRequest { /** * Required. Parameter to launch a job from a Flex Template. */ launchParameter?: Schema$GoogleCloudDatapipelinesV1LaunchFlexTemplateParameter; /** * Required. The [regional endpoint] (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints) to which to direct the request. For example, `us-central1`, `us-west1`. */ location?: string | null; /** * Required. The ID of the Cloud Platform project that the job belongs to. */ projectId?: string | null; /** * If true, the request is validated but not actually executed. Defaults to false. */ validateOnly?: boolean | null; } /** * Parameters to provide to the template being launched. */ export interface Schema$GoogleCloudDatapipelinesV1LaunchTemplateParameters { /** * The runtime environment for the job. */ environment?: Schema$GoogleCloudDatapipelinesV1RuntimeEnvironment; /** * Required. The job name to use for the created job. */ jobName?: string | null; /** * The runtime parameters to pass to the job. */ parameters?: {[key: string]: string} | null; /** * Map of transform name prefixes of the job to be replaced to the corresponding name prefixes of the new job. Only applicable when updating a pipeline. */ transformNameMapping?: {[key: string]: string} | null; /** * If set, replace the existing pipeline with the name specified by jobName with this pipeline, preserving state. */ update?: boolean | null; } /** * A request to launch a template. */ export interface Schema$GoogleCloudDatapipelinesV1LaunchTemplateRequest { /** * A Cloud Storage path to the template from which to create the job. Must be a valid Cloud Storage URL, beginning with 'gs://'. */ gcsPath?: string | null; /** * The parameters of the template to launch. This should be part of the body of the POST request. */ launchParameters?: Schema$GoogleCloudDatapipelinesV1LaunchTemplateParameters; /** * The [regional endpoint] (https://cloud.google.com/dataflow/docs/concepts/regional-endpoints) to which to direct the request. */ location?: string | null; /** * Required. The ID of the Cloud Platform project that the job belongs to. */ projectId?: string | null; /** * If true, the request is validated but not actually executed. Defaults to false. */ validateOnly?: boolean | null; } /** * Response message for ListPipelines. */ export interface Schema$GoogleCloudDatapipelinesV1ListPipelinesResponse { /** * A token, which can be sent as `page_token` to retrieve the next page. If this field is omitted, there are no subsequent pages. */ nextPageToken?: string | null; /** * Results that matched the filter criteria and were accessible to the caller. Results are always in descending order of pipeline creation date. */ pipelines?: Schema$GoogleCloudDatapipelinesV1Pipeline[]; } /** * The main pipeline entity and all the needed metadata to launch and manage linked jobs. */ export interface Schema$GoogleCloudDatapipelinesV1Pipeline { /** * Output only. Immutable. The timestamp when the pipeline was initially created. Set by the Data Pipelines service. */ createTime?: string | null; /** * Required. The display name of the pipeline. It can contain only letters ([A-Za-z]), numbers ([0-9]), hyphens (-), and underscores (_). */ displayName?: string | null; /** * Output only. Number of jobs. */ jobCount?: number | null; /** * Output only. Immutable. The timestamp when the pipeline was last modified. Set by the Data Pipelines service. */ lastUpdateTime?: string | null; /** * The pipeline name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/pipelines/PIPELINE_ID`. * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), and periods (.). For more information, see [Identifying projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the pipeline's location. The list of available locations can be obtained by calling ListLocations. Note that the Data Pipelines service is not available in all regions. It depends on Cloud Scheduler, an App Engine application, so it's only available in [App Engine regions](https://cloud.google.com/about/locations#region). * `PIPELINE_ID` is the ID of the pipeline. Must be unique for the selected project and location. */ name?: string | null; /** * Immutable. The sources of the pipeline (for example, Dataplex). The keys and values are set by the corresponding sources during pipeline creation. */ pipelineSources?: {[key: string]: string} | null; /** * Internal scheduling information for a pipeline. If this information is provided, periodic jobs will be created per the schedule. If not, users are responsible for creating jobs externally. */ scheduleInfo?: Schema$GoogleCloudDatapipelinesV1ScheduleSpec; /** * Optional. A service account email to be used with the Cloud Scheduler job. If not specified, the default compute engine service account will be used. */ schedulerServiceAccountEmail?: string | null; /** * Required. The state of the pipeline. When the pipeline is created, the state is set to 'PIPELINE_STATE_ACTIVE' by default. State changes can be requested by setting the state to stopping, paused, or resuming. State cannot be changed through UpdatePipeline requests. */ state?: string | null; /** * Required. The type of the pipeline. This field affects the scheduling of the pipeline and the type of metrics to show for the pipeline. */ type?: string | null; /** * Workload information for creating new jobs. */ workload?: Schema$GoogleCloudDatapipelinesV1Workload; } /** * Request message for RunPipeline */ export interface Schema$GoogleCloudDatapipelinesV1RunPipelineRequest {} /** * Response message for RunPipeline */ export interface Schema$GoogleCloudDatapipelinesV1RunPipelineResponse { /** * Job that was created as part of RunPipeline operation. */ job?: Schema$GoogleCloudDatapipelinesV1Job; } /** * The environment values to set at runtime. */ export interface Schema$GoogleCloudDatapipelinesV1RuntimeEnvironment { /** * Additional experiment flags for the job. */ additionalExperiments?: string[] | null; /** * Additional user labels to be specified for the job. Keys and values should follow the restrictions specified in the [labeling restrictions](https://cloud.google.com/compute/docs/labeling-resources#restrictions) page. An object containing a list of key/value pairs. Example: { "name": "wrench", "mass": "1kg", "count": "3" \}. */ additionalUserLabels?: {[key: string]: string} | null; /** * Whether to bypass the safety checks for the job's temporary directory. Use with caution. */ bypassTempDirValidation?: boolean | null; /** * Whether to enable Streaming Engine for the job. */ enableStreamingEngine?: boolean | null; /** * Configuration for VM IPs. */ ipConfiguration?: string | null; /** * Name for the Cloud KMS key for the job. The key format is: projects//locations//keyRings//cryptoKeys/ */ kmsKeyName?: string | null; /** * The machine type to use for the job. Defaults to the value from the template if not specified. */ machineType?: string | null; /** * The maximum number of Compute Engine instances to be made available to your pipeline during execution, from 1 to 1000. */ maxWorkers?: number | null; /** * Network to which VMs will be assigned. If empty or unspecified, the service will use the network "default". */ network?: string | null; /** * The initial number of Compute Engine instances for the job. */ numWorkers?: number | null; /** * The email address of the service account to run the job as. */ serviceAccountEmail?: string | null; /** * Subnetwork to which VMs will be assigned, if desired. You can specify a subnetwork using either a complete URL or an abbreviated path. Expected to be of the form "https://www.googleapis.com/compute/v1/projects/HOST_PROJECT_ID/regions/REGION/subnetworks/SUBNETWORK" or "regions/REGION/subnetworks/SUBNETWORK". If the subnetwork is located in a Shared VPC network, you must use the complete URL. */ subnetwork?: string | null; /** * The Cloud Storage path to use for temporary files. Must be a valid Cloud Storage URL, beginning with `gs://`. */ tempLocation?: string | null; /** * The Compute Engine region (https://cloud.google.com/compute/docs/regions-zones/regions-zones) in which worker processing should occur, e.g. "us-west1". Mutually exclusive with worker_zone. If neither worker_region nor worker_zone is specified, default to the control plane's region. */ workerRegion?: string | null; /** * The Compute Engine zone (https://cloud.google.com/compute/docs/regions-zones/regions-zones) in which worker processing should occur, e.g. "us-west1-a". Mutually exclusive with worker_region. If neither worker_region nor worker_zone is specified, a zone in the control plane's region is chosen based on available capacity. If both `worker_zone` and `zone` are set, `worker_zone` takes precedence. */ workerZone?: string | null; /** * The Compute Engine [availability zone](https://cloud.google.com/compute/docs/regions-zones/regions-zones) for launching worker instances to run your pipeline. In the future, worker_zone will take precedence. */ zone?: string | null; } /** * Details of the schedule the pipeline runs on. */ export interface Schema$GoogleCloudDatapipelinesV1ScheduleSpec { /** * Output only. When the next Scheduler job is going to run. */ nextJobTime?: string | null; /** * Unix-cron format of the schedule. This information is retrieved from the linked Cloud Scheduler. */ schedule?: string | null; /** * Timezone ID. This matches the timezone IDs used by the Cloud Scheduler API. If empty, UTC time is assumed. */ timeZone?: string | null; } /** * The version of the SDK used to run the job. */ export interface Schema$GoogleCloudDatapipelinesV1SdkVersion { /** * The support status for this SDK version. */ sdkSupportStatus?: string | null; /** * The version of the SDK used to run the job. */ version?: string | null; /** * A readable string describing the version of the SDK. */ versionDisplayName?: string | null; } /** * Request message for StopPipeline. */ export interface Schema$GoogleCloudDatapipelinesV1StopPipelineRequest {} /** * Workload details for creating the pipeline jobs. */ export interface Schema$GoogleCloudDatapipelinesV1Workload { /** * Template information and additional parameters needed to launch a Dataflow job using the flex launch API. */ dataflowFlexTemplateRequest?: Schema$GoogleCloudDatapipelinesV1LaunchFlexTemplateRequest; /** * Template information and additional parameters needed to launch a Dataflow job using the standard launch API. */ dataflowLaunchTemplateRequest?: Schema$GoogleCloudDatapipelinesV1LaunchTemplateRequest; } /** * 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); \} The JSON representation for `Empty` is empty JSON object `{\}`. */ export interface Schema$GoogleProtobufEmpty {} /** * The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */ export interface Schema$GoogleRpcStatus { /** * The status code, which should be an enum value of google.rpc.Code. */ code?: number | null; /** * A list of messages that carry the error details. There is a common set of message types for APIs to use. */ details?: Array<{[key: string]: any}> | null; /** * A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */ message?: string | null; } export class Resource$Projects { context: APIRequestContext; locations: Resource$Projects$Locations; constructor(context: APIRequestContext) { this.context = context; this.locations = new Resource$Projects$Locations(this.context); } } export class Resource$Projects$Locations { context: APIRequestContext; pipelines: Resource$Projects$Locations$Pipelines; constructor(context: APIRequestContext) { this.context = context; this.pipelines = new Resource$Projects$Locations$Pipelines(this.context); } /** * Lists pipelines. Returns a "NOT_FOUND" error if the list is empty. Returns a "FORBIDDEN" error if the caller doesn't have permission to access it. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/datapipelines.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 datapipelines = google.datapipelines('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'], * }); * * // 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 datapipelines.projects.locations.listPipelines({ * // An expression for filtering the results of the request. If unspecified, all pipelines will be returned. Multiple filters can be applied and must be comma separated. Fields eligible for filtering are: + `type`: The type of the pipeline (streaming or batch). Allowed values are `ALL`, `BATCH`, and `STREAMING`. + `executor_type`: The type of pipeline execution layer. This is always Dataflow for now, but more executors may be added later. Allowed values are `ALL` and `DATAFLOW`. + `status`: The activity status of the pipeline. Allowed values are `ALL`, `ACTIVE`, `ARCHIVED`, and `PAUSED`. For example, to limit results to active batch processing pipelines: type:BATCH,status:ACTIVE * filter: 'placeholder-value', * // The maximum number of entities to return. The service may return fewer than this value, even if there are additional pages. If unspecified, the max limit is yet to be determined by the backend implementation. * pageSize: 'placeholder-value', * // A page token, received from a previous `ListPipelines` call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to `ListPipelines` must match the call that provided the page token. * pageToken: 'placeholder-value', * // Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. * parent: 'projects/my-project/locations/my-location', * }); * console.log(res.data); * * // Example response * // { * // "nextPageToken": "my_nextPageToken", * // "pipelines": [] * // } * } * * 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. */ listPipelines( params: Params$Resource$Projects$Locations$Listpipelines, options: StreamMethodOptions ): GaxiosPromise<Readable>; listPipelines( params?: Params$Resource$Projects$Locations$Listpipelines, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudDatapipelinesV1ListPipelinesResponse>; listPipelines( params: Params$Resource$Projects$Locations$Listpipelines, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; listPipelines( params: Params$Resource$Projects$Locations$Listpipelines, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1ListPipelinesResponse>, callback: BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1ListPipelinesResponse> ): void; listPipelines( params: Params$Resource$Projects$Locations$Listpipelines, callback: BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1ListPipelinesResponse> ): void; listPipelines( callback: BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1ListPipelinesResponse> ): void; listPipelines( paramsOrCallback?: | Params$Resource$Projects$Locations$Listpipelines | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1ListPipelinesResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1ListPipelinesResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1ListPipelinesResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudDatapipelinesV1ListPipelinesResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Listpipelines; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Listpipelines; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://datapipelines.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudDatapipelinesV1ListPipelinesResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudDatapipelinesV1ListPipelinesResponse>( parameters ); } } } export interface Params$Resource$Projects$Locations$Listpipelines extends StandardParameters { /** * An expression for filtering the results of the request. If unspecified, all pipelines will be returned. Multiple filters can be applied and must be comma separated. Fields eligible for filtering are: + `type`: The type of the pipeline (streaming or batch). Allowed values are `ALL`, `BATCH`, and `STREAMING`. + `executor_type`: The type of pipeline execution layer. This is always Dataflow for now, but more executors may be added later. Allowed values are `ALL` and `DATAFLOW`. + `status`: The activity status of the pipeline. Allowed values are `ALL`, `ACTIVE`, `ARCHIVED`, and `PAUSED`. For example, to limit results to active batch processing pipelines: type:BATCH,status:ACTIVE */ filter?: string; /** * The maximum number of entities to return. The service may return fewer than this value, even if there are additional pages. If unspecified, the max limit is yet to be determined by the backend implementation. */ pageSize?: number; /** * A page token, received from a previous `ListPipelines` call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to `ListPipelines` must match the call that provided the page token. */ pageToken?: string; /** * Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ parent?: string; } export class Resource$Projects$Locations$Pipelines { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Creates a pipeline. For a batch pipeline, you can pass scheduler information. Data Pipelines uses the scheduler information to create an internal scheduler that runs jobs periodically. If the internal scheduler is not configured, you can use RunPipeline to run jobs. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/datapipelines.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 datapipelines = google.datapipelines('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'], * }); * * // 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 datapipelines.projects.locations.pipelines.create({ * // Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. * parent: 'projects/my-project/locations/my-location', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "createTime": "my_createTime", * // "displayName": "my_displayName", * // "jobCount": 0, * // "lastUpdateTime": "my_lastUpdateTime", * // "name": "my_name", * // "pipelineSources": {}, * // "scheduleInfo": {}, * // "schedulerServiceAccountEmail": "my_schedulerServiceAccountEmail", * // "state": "my_state", * // "type": "my_type", * // "workload": {} * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "createTime": "my_createTime", * // "displayName": "my_displayName", * // "jobCount": 0, * // "lastUpdateTime": "my_lastUpdateTime", * // "name": "my_name", * // "pipelineSources": {}, * // "scheduleInfo": {}, * // "schedulerServiceAccountEmail": "my_schedulerServiceAccountEmail", * // "state": "my_state", * // "type": "my_type", * // "workload": {} * // } * } * * 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$Locations$Pipelines$Create, options: StreamMethodOptions ): GaxiosPromise<Readable>; create( params?: Params$Resource$Projects$Locations$Pipelines$Create, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudDatapipelinesV1Pipeline>; create( params: Params$Resource$Projects$Locations$Pipelines$Create, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; create( params: Params$Resource$Projects$Locations$Pipelines$Create, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline>, callback: BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> ): void; create( params: Params$Resource$Projects$Locations$Pipelines$Create, callback: BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> ): void; create( callback: BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> ): void; create( paramsOrCallback?: | Params$Resource$Projects$Locations$Pipelines$Create | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudDatapipelinesV1Pipeline> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Pipelines$Create; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Pipelines$Create; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://datapipelines.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/pipelines').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudDatapipelinesV1Pipeline>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudDatapipelinesV1Pipeline>( parameters ); } } /** * Deletes a pipeline. If a scheduler job is attached to the pipeline, it will be deleted. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/datapipelines.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 datapipelines = google.datapipelines('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'], * }); * * // 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 datapipelines.projects.locations.pipelines.delete({ * // Required. The pipeline name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/pipelines/PIPELINE_ID`. * name: 'projects/my-project/locations/my-location/pipelines/my-pipeline', * }); * 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$Locations$Pipelines$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Projects$Locations$Pipelines$Delete, options?: MethodOptions ): GaxiosPromise<Schema$GoogleProtobufEmpty>; delete( params: Params$Resource$Projects$Locations$Pipelines$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Projects$Locations$Pipelines$Delete, options: MethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty>, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; delete( params: Params$Resource$Projects$Locations$Pipelines$Delete, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; delete(callback: BodyResponseCallback<Schema$GoogleProtobufEmpty>): void; delete( paramsOrCallback?: | Params$Resource$Projects$Locations$Pipelines$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$Locations$Pipelines$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Pipelines$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://datapipelines.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); } } /** * Looks up a single pipeline. Returns a "NOT_FOUND" error if no such pipeline exists. Returns a "FORBIDDEN" error if the caller doesn't have permission to access it. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/datapipelines.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 datapipelines = google.datapipelines('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'], * }); * * // 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 datapipelines.projects.locations.pipelines.get({ * // Required. The pipeeline name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/pipelines/PIPELINE_ID`. * name: 'projects/my-project/locations/my-location/pipelines/my-pipeline', * }); * console.log(res.data); * * // Example response * // { * // "createTime": "my_createTime", * // "displayName": "my_displayName", * // "jobCount": 0, * // "lastUpdateTime": "my_lastUpdateTime", * // "name": "my_name", * // "pipelineSources": {}, * // "scheduleInfo": {}, * // "schedulerServiceAccountEmail": "my_schedulerServiceAccountEmail", * // "state": "my_state", * // "type": "my_type", * // "workload": {} * // } * } * * 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$Locations$Pipelines$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Locations$Pipelines$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudDatapipelinesV1Pipeline>; get( params: Params$Resource$Projects$Locations$Pipelines$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Locations$Pipelines$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline>, callback: BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> ): void; get( params: Params$Resource$Projects$Locations$Pipelines$Get, callback: BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> ): void; get( callback: BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> ): void; get( paramsOrCallback?: | Params$Resource$Projects$Locations$Pipelines$Get | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudDatapipelinesV1Pipeline> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Pipelines$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Pipelines$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://datapipelines.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$GoogleCloudDatapipelinesV1Pipeline>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudDatapipelinesV1Pipeline>( parameters ); } } /** * Updates a pipeline. If successful, the updated [Pipeline] is returned. Returns `NOT_FOUND` if the pipeline doesn't exist. If UpdatePipeline does not return successfully, you can retry the UpdatePipeline request until you receive a successful response. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/datapipelines.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 datapipelines = google.datapipelines('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'], * }); * * // 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 datapipelines.projects.locations.pipelines.patch({ * // The pipeline name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/pipelines/PIPELINE_ID`. * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), and periods (.). For more information, see [Identifying projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the pipeline's location. The list of available locations can be obtained by calling ListLocations. Note that the Data Pipelines service is not available in all regions. It depends on Cloud Scheduler, an App Engine application, so it's only available in [App Engine regions](https://cloud.google.com/about/locations#region). * `PIPELINE_ID` is the ID of the pipeline. Must be unique for the selected project and location. * name: 'projects/my-project/locations/my-location/pipelines/my-pipeline', * // The list of fields to be updated. * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "createTime": "my_createTime", * // "displayName": "my_displayName", * // "jobCount": 0, * // "lastUpdateTime": "my_lastUpdateTime", * // "name": "my_name", * // "pipelineSources": {}, * // "scheduleInfo": {}, * // "schedulerServiceAccountEmail": "my_schedulerServiceAccountEmail", * // "state": "my_state", * // "type": "my_type", * // "workload": {} * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "createTime": "my_createTime", * // "displayName": "my_displayName", * // "jobCount": 0, * // "lastUpdateTime": "my_lastUpdateTime", * // "name": "my_name", * // "pipelineSources": {}, * // "scheduleInfo": {}, * // "schedulerServiceAccountEmail": "my_schedulerServiceAccountEmail", * // "state": "my_state", * // "type": "my_type", * // "workload": {} * // } * } * * 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$Locations$Pipelines$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Projects$Locations$Pipelines$Patch, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudDatapipelinesV1Pipeline>; patch( params: Params$Resource$Projects$Locations$Pipelines$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Projects$Locations$Pipelines$Patch, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline>, callback: BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> ): void; patch( params: Params$Resource$Projects$Locations$Pipelines$Patch, callback: BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> ): void; patch( callback: BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> ): void; patch( paramsOrCallback?: | Params$Resource$Projects$Locations$Pipelines$Patch | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudDatapipelinesV1Pipeline> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Pipelines$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Pipelines$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://datapipelines.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$GoogleCloudDatapipelinesV1Pipeline>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudDatapipelinesV1Pipeline>( parameters ); } } /** * Creates a job for the specified pipeline directly. You can use this method when the internal scheduler is not configured and you want to trigger the job directly or through an external system. Returns a "NOT_FOUND" error if the pipeline doesn't exist. Returns a "FOBIDDEN" error if the user doesn't have permission to access the pipeline or run jobs for the pipeline. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/datapipelines.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 datapipelines = google.datapipelines('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'], * }); * * // 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 datapipelines.projects.locations.pipelines.run({ * // Required. The pipeline name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/pipelines/PIPELINE_ID`. * name: 'projects/my-project/locations/my-location/pipelines/my-pipeline', * * // Request body metadata * requestBody: { * // request body parameters * // {} * }, * }); * console.log(res.data); * * // Example response * // { * // "job": {} * // } * } * * 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. */ run( params: Params$Resource$Projects$Locations$Pipelines$Run, options: StreamMethodOptions ): GaxiosPromise<Readable>; run( params?: Params$Resource$Projects$Locations$Pipelines$Run, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudDatapipelinesV1RunPipelineResponse>; run( params: Params$Resource$Projects$Locations$Pipelines$Run, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; run( params: Params$Resource$Projects$Locations$Pipelines$Run, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1RunPipelineResponse>, callback: BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1RunPipelineResponse> ): void; run( params: Params$Resource$Projects$Locations$Pipelines$Run, callback: BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1RunPipelineResponse> ): void; run( callback: BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1RunPipelineResponse> ): void; run( paramsOrCallback?: | Params$Resource$Projects$Locations$Pipelines$Run | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1RunPipelineResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1RunPipelineResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1RunPipelineResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudDatapipelinesV1RunPipelineResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Pipelines$Run; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Pipelines$Run; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://datapipelines.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}:run').replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudDatapipelinesV1RunPipelineResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudDatapipelinesV1RunPipelineResponse>( parameters ); } } /** * Freezes pipeline execution permanently. If there's a corresponding scheduler entry, it's deleted, and the pipeline state is changed to "ARCHIVED". However, pipeline metadata is retained. Upon success, the pipeline state is updated to ARCHIVED. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/datapipelines.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 datapipelines = google.datapipelines('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'], * }); * * // 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 datapipelines.projects.locations.pipelines.stop({ * // Required. The pipeline name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/pipelines/PIPELINE_ID`. * name: 'projects/my-project/locations/my-location/pipelines/my-pipeline', * * // Request body metadata * requestBody: { * // request body parameters * // {} * }, * }); * console.log(res.data); * * // Example response * // { * // "createTime": "my_createTime", * // "displayName": "my_displayName", * // "jobCount": 0, * // "lastUpdateTime": "my_lastUpdateTime", * // "name": "my_name", * // "pipelineSources": {}, * // "scheduleInfo": {}, * // "schedulerServiceAccountEmail": "my_schedulerServiceAccountEmail", * // "state": "my_state", * // "type": "my_type", * // "workload": {} * // } * } * * 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. */ stop( params: Params$Resource$Projects$Locations$Pipelines$Stop, options: StreamMethodOptions ): GaxiosPromise<Readable>; stop( params?: Params$Resource$Projects$Locations$Pipelines$Stop, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudDatapipelinesV1Pipeline>; stop( params: Params$Resource$Projects$Locations$Pipelines$Stop, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; stop( params: Params$Resource$Projects$Locations$Pipelines$Stop, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline>, callback: BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> ): void; stop( params: Params$Resource$Projects$Locations$Pipelines$Stop, callback: BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> ): void; stop( callback: BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> ): void; stop( paramsOrCallback?: | Params$Resource$Projects$Locations$Pipelines$Stop | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudDatapipelinesV1Pipeline> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudDatapipelinesV1Pipeline> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Locations$Pipelines$Stop; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Locations$Pipelines$Stop; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://datapipelines.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}:stop').replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudDatapipelinesV1Pipeline>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudDatapipelinesV1Pipeline>( parameters ); } } } export interface Params$Resource$Projects$Locations$Pipelines$Create extends StandardParameters { /** * Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ parent?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudDatapipelinesV1Pipeline; } export interface Params$Resource$Projects$Locations$Pipelines$Delete extends StandardParameters { /** * Required. The pipeline name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/pipelines/PIPELINE_ID`. */ name?: string; } export interface Params$Resource$Projects$Locations$Pipelines$Get extends StandardParameters { /** * Required. The pipeeline name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/pipelines/PIPELINE_ID`. */ name?: string; } export interface Params$Resource$Projects$Locations$Pipelines$Patch extends StandardParameters { /** * The pipeline name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/pipelines/PIPELINE_ID`. * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), and periods (.). For more information, see [Identifying projects](https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the pipeline's location. The list of available locations can be obtained by calling ListLocations. Note that the Data Pipelines service is not available in all regions. It depends on Cloud Scheduler, an App Engine application, so it's only available in [App Engine regions](https://cloud.google.com/about/locations#region). * `PIPELINE_ID` is the ID of the pipeline. Must be unique for the selected project and location. */ name?: string; /** * The list of fields to be updated. */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudDatapipelinesV1Pipeline; } export interface Params$Resource$Projects$Locations$Pipelines$Run extends StandardParameters { /** * Required. The pipeline name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/pipelines/PIPELINE_ID`. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudDatapipelinesV1RunPipelineRequest; } export interface Params$Resource$Projects$Locations$Pipelines$Stop extends StandardParameters { /** * Required. The pipeline name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/pipelines/PIPELINE_ID`. */ name?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudDatapipelinesV1StopPipelineRequest; } }
the_stack
'use strict'; import { IStringDictionary, INumberDictionary } from 'vs/base/common/collections'; import URI from 'vs/base/common/uri'; import { EventEmitter } from 'vs/base/common/eventEmitter'; import { IDisposable } from 'vs/base/common/lifecycle'; import { IModelService } from 'vs/editor/common/services/modelService'; import { ILineMatcher, createLineMatcher, ProblemMatcher, ProblemMatch, ApplyToKind, WatchingPattern, getResource } from 'vs/platform/markers/common/problemMatcher'; import { IMarkerService, IMarkerData } from 'vs/platform/markers/common/markers'; export namespace ProblemCollectorEvents { export let WatchingBeginDetected: string = 'watchingBeginDetected'; export let WatchingEndDetected: string = 'watchingEndDetected'; } export interface IProblemMatcher { processLine(line:string):void; } export class AbstractProblemCollector extends EventEmitter implements IDisposable { private matchers: INumberDictionary<ILineMatcher[]>; private activeMatcher : ILineMatcher; private _numberOfMatches: number; private buffer: string[]; private bufferLength: number; private openModels: IStringDictionary<boolean>; private modelListeners: IDisposable[]; constructor(problemMatchers: ProblemMatcher[], private modelService: IModelService) { super(); this.matchers = Object.create(null); this.bufferLength = 1; problemMatchers.map(elem => createLineMatcher(elem)).forEach((matcher) => { let length = matcher.matchLength; if (length > this.bufferLength) { this.bufferLength = length; } let value = this.matchers[length]; if (!value) { value = []; this.matchers[length] = value; } value.push(matcher); }); this.buffer = []; this.activeMatcher = null; this.openModels = Object.create(null); this.modelListeners = []; this.modelService.onModelAdded((model) => { this.openModels[model.uri.toString()] = true; }, this, this.modelListeners); this.modelService.onModelRemoved((model) => { delete this.openModels[model.uri.toString()]; }, this, this.modelListeners); this.modelService.getModels().forEach(model => this.openModels[model.uri.toString()] = true); } public dispose() { this.modelListeners.forEach(disposable => disposable.dispose()); } public get numberOfMatches(): number { return this._numberOfMatches; } protected tryFindMarker(line: string): ProblemMatch { let result: ProblemMatch = null; if (this.activeMatcher) { result = this.activeMatcher.next(line); if (result) { this._numberOfMatches++; return result; } this.clearBuffer(); this.activeMatcher = null; } if (this.buffer.length < this.bufferLength) { this.buffer.push(line); } else { let end = this.buffer.length - 1; for (let i = 0; i < end; i++) { this.buffer[i] = this.buffer[i + 1]; } this.buffer[end] = line; } result = this.tryMatchers(); if (result) { this.clearBuffer(); } return result; } protected isOpen(resource: URI): boolean { return !!this.openModels[resource.toString()]; } protected shouldApplyMatch(result: ProblemMatch): boolean { switch(result.description.applyTo) { case ApplyToKind.allDocuments: return true; case ApplyToKind.openDocuments: return this.openModels[result.resource.toString()]; case ApplyToKind.closedDocuments: return !this.openModels[result.resource.toString()]; default: return true; } } private tryMatchers(): ProblemMatch { this.activeMatcher = null; let length = this.buffer.length; for (let startIndex = 0; startIndex < length; startIndex++) { let candidates = this.matchers[length - startIndex]; if (!candidates) { continue; } for (let i = 0; i < candidates.length; i++) { let matcher = candidates[i]; let result = matcher.handle(this.buffer, startIndex); if (result.match) { this._numberOfMatches++; if (result.continue) { this.activeMatcher = matcher; } return result.match; } } } return null; } private clearBuffer(): void { if (this.buffer.length > 0) { this.buffer = []; } } } export enum ProblemHandlingStrategy { Clean } export class StartStopProblemCollector extends AbstractProblemCollector implements IProblemMatcher { private owners: string[]; private markerService: IMarkerService; private strategy: ProblemHandlingStrategy; // Global state private currentResourcesWithMarkers: IStringDictionary<URI[]>; private reportedResourcesWithMarkers: IStringDictionary<IStringDictionary<URI>>; // Current State private currentResource: URI = null; private currentResourceAsString: string = null; private markers: IStringDictionary<IMarkerData[]> = Object.create(null); constructor(problemMatchers: ProblemMatcher[], markerService:IMarkerService, modelService: IModelService, strategy: ProblemHandlingStrategy = ProblemHandlingStrategy.Clean) { super(problemMatchers, modelService); let ownerSet:{ [key:string]:boolean; } = Object.create(null); problemMatchers.forEach(description => ownerSet[description.owner] = true); this.owners = Object.keys(ownerSet); this.markerService = markerService; this.strategy = strategy; this.currentResourcesWithMarkers = Object.create(null); this.reportedResourcesWithMarkers = Object.create(null); this.owners.forEach((owner) => { this.currentResourcesWithMarkers[owner] = this.markerService.read({owner: owner}).map(m => m.resource); this.reportedResourcesWithMarkers[owner] = Object.create(null); }); this.currentResource = null; this.currentResourceAsString = null; this.markers = Object.create(null); } public processLine(line:string):void { let markerMatch = this.tryFindMarker(line); if (!markerMatch) { return; } let owner = markerMatch.description.owner; let resource = markerMatch.resource; let resourceAsString = resource.toString(); let shouldApplyMatch = this.shouldApplyMatch(markerMatch); if (shouldApplyMatch) { if (this.currentResourceAsString !== resourceAsString) { if (this.currentResource) { Object.keys(this.markers).forEach((owner) => { this.markerService.changeOne(owner, this.currentResource, this.markers[owner]); }); this.markers = Object.create(null); } this.reportedResourcesWithMarkers[owner][resourceAsString] = resource; this.currentResource = resource; this.currentResourceAsString = resourceAsString; } let markerData = this.markers[owner]; if (!markerData) { markerData = []; this.markers[owner] = markerData; } markerData.push(markerMatch.marker); } else { this.reportedResourcesWithMarkers[owner][resourceAsString] = resource; } } public done(): void { if (this.currentResource) { Object.keys(this.markers).forEach((owner) => { this.markerService.changeOne(owner, this.currentResource, this.markers[owner]); }); } if (this.strategy === ProblemHandlingStrategy.Clean) { Object.keys(this.currentResourcesWithMarkers).forEach((owner) => { let toRemove:URI[] = []; let withMarkers = this.reportedResourcesWithMarkers[owner]; this.currentResourcesWithMarkers[owner].forEach((resource) => { if (!withMarkers[resource.toString()]) { toRemove.push(resource); } }); this.markerService.remove(owner, toRemove); }); } this.currentResource = null; this.currentResourceAsString = null; this.markers = Object.create(null); } } interface OwnedWatchingPattern { problemMatcher: ProblemMatcher; pattern: WatchingPattern; } export class WatchingProblemCollector extends AbstractProblemCollector implements IProblemMatcher { private problemMatchers: ProblemMatcher[]; private watchingBeginsPatterns: OwnedWatchingPattern[]; private watchingEndsPatterns: OwnedWatchingPattern[]; private markerService: IMarkerService; // Current State private currentResource: URI; private currentResourceAsString: string; private markers: IStringDictionary<IMarkerData[]>; // Cleaning state private ignoreOpenResourcesByOwner: IStringDictionary<boolean>; private resourcesToClean: IStringDictionary<IStringDictionary<URI>>; constructor(problemMatchers: ProblemMatcher[], markerService: IMarkerService, modelService: IModelService) { super(problemMatchers, modelService); this.problemMatchers = problemMatchers; this.markerService = markerService; this.resetCurrentResource(); this.resourcesToClean = Object.create(null); this.ignoreOpenResourcesByOwner = Object.create(null); this.watchingBeginsPatterns = []; this.watchingEndsPatterns = []; this.problemMatchers.forEach(matcher => { if (matcher.watching) { this.watchingBeginsPatterns.push({ problemMatcher: matcher, pattern: matcher.watching.beginsPattern }); this.watchingEndsPatterns.push({ problemMatcher: matcher, pattern: matcher.watching.endsPattern }); } }); } public aboutToStart(): void { this.problemMatchers.forEach(matcher => { if (matcher.watching && matcher.watching.activeOnStart) { this.emit(ProblemCollectorEvents.WatchingBeginDetected, {}); this.recordResourcesToClean(matcher.owner); } let value: boolean = this.ignoreOpenResourcesByOwner[matcher.owner]; if (!value) { this.ignoreOpenResourcesByOwner[matcher.owner] = (matcher.applyTo === ApplyToKind.closedDocuments); } else { let newValue = value && (matcher.applyTo === ApplyToKind.closedDocuments); if (newValue !== value) { this.ignoreOpenResourcesByOwner[matcher.owner] = newValue; } } }); } public processLine(line: string): void { if (this.tryBegin(line) || this.tryFinish(line)) { return; } let markerMatch = this.tryFindMarker(line); if (!markerMatch) { return; } let resource = markerMatch.resource; let owner = markerMatch.description.owner; let resourceAsString = resource.toString(); let shouldApplyMatch = this.shouldApplyMatch(markerMatch); if (shouldApplyMatch) { if (this.currentResourceAsString !== resourceAsString) { this.removeResourceToClean(owner, resourceAsString); if (this.currentResource) { this.deliverMarkersForCurrentResource(); } this.currentResource = resource; this.currentResourceAsString = resourceAsString; } let markerData = this.markers[owner]; if (!markerData) { markerData = []; this.markers[owner] = markerData; } markerData.push(markerMatch.marker); } else { this.removeResourceToClean(owner, resourceAsString); } } public forceDelivery(): void { this.deliverMarkersForCurrentResource(false); Object.keys(this.resourcesToClean).forEach((owner) => { this.cleanMarkers(owner, false); }); this.resourcesToClean = Object.create(null); } private tryBegin(line: string): boolean { let result = false; for (let i = 0; i < this.watchingBeginsPatterns.length; i++) { let beginMatcher = this.watchingBeginsPatterns[i]; let matches = beginMatcher.pattern.regexp.exec(line); if (matches) { this.emit(ProblemCollectorEvents.WatchingBeginDetected, {}); result = true; let owner = beginMatcher.problemMatcher.owner; if (matches[1]) { let resource = getResource(matches[1], beginMatcher.problemMatcher); if (this.currentResourceAsString && this.currentResourceAsString === resource.toString()) { this.resetCurrentResource(); } this.recordResourceToClean(owner, resource); } else { this.recordResourcesToClean(owner); this.resetCurrentResource(); } } } return result; } private tryFinish(line: string): boolean { let result = false; for (let i = 0; i < this.watchingEndsPatterns.length; i++) { let endMatcher = this.watchingEndsPatterns[i]; let matches = endMatcher.pattern.regexp.exec(line); if (matches) { this.emit(ProblemCollectorEvents.WatchingEndDetected, {}); result = true; let owner = endMatcher.problemMatcher.owner; this.cleanMarkers(owner); this.deliverMarkersForCurrentResource(); } } return result; } private recordResourcesToClean(owner: string): void { let resourceSetToClean = this.getResourceSetToClean(owner); this.markerService.read({ owner: owner }).forEach(marker => resourceSetToClean[marker.resource.toString()] = marker.resource); } private recordResourceToClean(owner: string, resource: URI): void { this.getResourceSetToClean(owner)[resource.toString()] = resource; } private removeResourceToClean(owner: string, resource: string): void { let resourceSet = this.resourcesToClean[owner]; if (resourceSet) { delete resourceSet[resource]; } } private cleanMarkers(owner: string, remove: boolean = true): void { let resourceSet = this.resourcesToClean[owner]; if (resourceSet) { let toClean = Object.keys(resourceSet).map(key => resourceSet[key]).filter(resource => { // Check whether we need to ignore open documents for this owner. return this.ignoreOpenResourcesByOwner[owner] ? !this.isOpen(resource) : true; }); this.markerService.remove(owner, toClean); if (remove) { delete this.resourcesToClean[owner]; } } } private deliverMarkersForCurrentResource(resetCurrentResource: boolean = true): void { if (this.currentResource) { Object.keys(this.markers).forEach((owner) => { this.markerService.changeOne(owner, this.currentResource, this.markers[owner]); }); } if (resetCurrentResource) { this.resetCurrentResource(); } } private getResourceSetToClean(owner: string): IStringDictionary<URI> { let result = this.resourcesToClean[owner]; if (!result) { result = Object.create(null); this.resourcesToClean[owner] = result; } return result; } private resetCurrentResource(): void { this.currentResource = null; this.currentResourceAsString = null; this.markers = Object.create(null); } }
the_stack
import * as path from 'path'; import { Template } from '@aws-cdk/assertions'; import * as cognito from '@aws-cdk/aws-cognito'; import * as lambda from '@aws-cdk/aws-lambda'; import * as cdk from '@aws-cdk/core'; import * as appsync from '../lib'; // GIVEN let stack: cdk.Stack; beforeEach(() => { stack = new cdk.Stack(); }); describe('AppSync API Key Authorization', () => { test('AppSync creates default api key', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), }); // THEN Template.fromStack(stack).resourceCountIs('AWS::AppSync::ApiKey', 1); }); test('AppSync creates api key from additionalAuthorizationModes', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.IAM }, additionalAuthorizationModes: [ { authorizationType: appsync.AuthorizationType.API_KEY }, ], }, }); // THEN Template.fromStack(stack).resourceCountIs('AWS::AppSync::ApiKey', 1); }); test('AppSync does not create unspecified api key from additionalAuthorizationModes', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.IAM }, }, }); // THEN Template.fromStack(stack).resourceCountIs('AWS::AppSync::ApiKey', 0); }); test('appsync does not create unspecified api key with empty additionalAuthorizationModes', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.IAM }, additionalAuthorizationModes: [], }, }); // THEN Template.fromStack(stack).resourceCountIs('AWS::AppSync::ApiKey', 0); }); test('appsync creates configured api key with additionalAuthorizationModes', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.IAM }, additionalAuthorizationModes: [{ authorizationType: appsync.AuthorizationType.API_KEY, apiKeyConfig: { description: 'Custom Description' }, }], }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::ApiKey', { Description: 'Custom Description', }); }); test('apiKeyConfig creates default with valid expiration date', () => { const expirationDate: number = cdk.Expiration.after(cdk.Duration.days(10)).toEpoch(); // WHEN new appsync.GraphqlApi(stack, 'API', { name: 'apiKeyUnitTest', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.auth.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.API_KEY, apiKeyConfig: { expires: cdk.Expiration.after(cdk.Duration.days(10)), }, }, }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::ApiKey', { ApiId: { 'Fn::GetAtt': ['API62EA1CFF', 'ApiId'] }, Expires: expirationDate, }); }); test('apiKeyConfig fails if expire argument less than a day', () => { // WHEN const when = () => { new appsync.GraphqlApi(stack, 'API', { name: 'apiKeyUnitTest', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.auth.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.API_KEY, apiKeyConfig: { expires: cdk.Expiration.after(cdk.Duration.hours(1)), }, }, }, }); }; // THEN expect(when).toThrowError('API key expiration must be between 1 and 365 days.'); }); test('apiKeyConfig fails if expire argument greater than 365 day', () => { // WHEN const when = () => { new appsync.GraphqlApi(stack, 'API', { name: 'apiKeyUnitTest', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.auth.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.API_KEY, apiKeyConfig: { expires: cdk.Expiration.after(cdk.Duration.days(366)), }, }, }, }); }; // THEN expect(when).toThrowError('API key expiration must be between 1 and 365 days.'); }); test('appsync creates configured api key with additionalAuthorizationModes (not as first element)', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.IAM }, additionalAuthorizationModes: [ { authorizationType: appsync.AuthorizationType.USER_POOL, userPoolConfig: { userPool: new cognito.UserPool(stack, 'myPool') }, }, { authorizationType: appsync.AuthorizationType.API_KEY, apiKeyConfig: { description: 'Custom Description' }, }, ], }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::ApiKey', { Description: 'Custom Description', }); }); test('appsync fails when empty default and API_KEY in additional', () => { // THEN expect(() => { new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { additionalAuthorizationModes: [{ authorizationType: appsync.AuthorizationType.API_KEY, }], }, }); }).toThrowError('You can\'t duplicate API_KEY configuration. See https://docs.aws.amazon.com/appsync/latest/devguide/security.html'); }); test('appsync fails when multiple API_KEY auth modes', () => { // THEN expect(() => { new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.API_KEY }, additionalAuthorizationModes: [{ authorizationType: appsync.AuthorizationType.API_KEY, }], }, }); }).toThrowError('You can\'t duplicate API_KEY configuration. See https://docs.aws.amazon.com/appsync/latest/devguide/security.html'); }); test('appsync fails when multiple API_KEY auth modes in additionalXxx', () => { // THEN expect(() => { new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.IAM }, additionalAuthorizationModes: [ { authorizationType: appsync.AuthorizationType.API_KEY }, { authorizationType: appsync.AuthorizationType.API_KEY }, ], }, }); }).toThrowError('You can\'t duplicate API_KEY configuration. See https://docs.aws.amazon.com/appsync/latest/devguide/security.html'); }); }); describe('AppSync IAM Authorization', () => { test('Iam authorization configurable in default authorization', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.IAM }, }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::GraphQLApi', { AuthenticationType: 'AWS_IAM', }); }); test('Iam authorization configurable in additional authorization', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { additionalAuthorizationModes: [{ authorizationType: appsync.AuthorizationType.IAM }], }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::GraphQLApi', { AdditionalAuthenticationProviders: [{ AuthenticationType: 'AWS_IAM' }], }); }); test('appsync fails when multiple iam auth modes', () => { // THEN expect(() => { new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.IAM }, additionalAuthorizationModes: [{ authorizationType: appsync.AuthorizationType.IAM }], }, }); }).toThrowError('You can\'t duplicate IAM configuration. See https://docs.aws.amazon.com/appsync/latest/devguide/security.html'); }); test('appsync fails when multiple IAM auth modes in additionalXxx', () => { // THEN expect(() => { new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { additionalAuthorizationModes: [ { authorizationType: appsync.AuthorizationType.IAM }, { authorizationType: appsync.AuthorizationType.IAM }, ], }, }); }).toThrowError('You can\'t duplicate IAM configuration. See https://docs.aws.amazon.com/appsync/latest/devguide/security.html'); }); }); describe('AppSync User Pool Authorization', () => { let userPool: cognito.UserPool; beforeEach(() => { userPool = new cognito.UserPool(stack, 'pool'); }); test('User Pool authorization configurable in default authorization has default configuration', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.USER_POOL, userPoolConfig: { userPool }, }, }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::GraphQLApi', { AuthenticationType: 'AMAZON_COGNITO_USER_POOLS', UserPoolConfig: { AwsRegion: { Ref: 'AWS::Region' }, DefaultAction: 'ALLOW', UserPoolId: { Ref: 'pool056F3F7E' }, }, }); }); test('User Pool authorization configurable in default authorization', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.USER_POOL, userPoolConfig: { userPool, appIdClientRegex: 'test', defaultAction: appsync.UserPoolDefaultAction.DENY, }, }, }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::GraphQLApi', { AuthenticationType: 'AMAZON_COGNITO_USER_POOLS', UserPoolConfig: { AwsRegion: { Ref: 'AWS::Region' }, DefaultAction: 'DENY', AppIdClientRegex: 'test', UserPoolId: { Ref: 'pool056F3F7E' }, }, }); }); test('User Pool authorization configurable in additional authorization has default configuration', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { additionalAuthorizationModes: [{ authorizationType: appsync.AuthorizationType.USER_POOL, userPoolConfig: { userPool }, }], }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::GraphQLApi', { AdditionalAuthenticationProviders: [{ AuthenticationType: 'AMAZON_COGNITO_USER_POOLS', UserPoolConfig: { AwsRegion: { Ref: 'AWS::Region' }, UserPoolId: { Ref: 'pool056F3F7E' }, }, }], }); }); test('User Pool property defaultAction does not configure when in additional auth', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { additionalAuthorizationModes: [{ authorizationType: appsync.AuthorizationType.USER_POOL, userPoolConfig: { userPool, appIdClientRegex: 'test', defaultAction: appsync.UserPoolDefaultAction.DENY, }, }], }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::GraphQLApi', { AdditionalAuthenticationProviders: [{ AuthenticationType: 'AMAZON_COGNITO_USER_POOLS', UserPoolConfig: { AwsRegion: { Ref: 'AWS::Region' }, AppIdClientRegex: 'test', UserPoolId: { Ref: 'pool056F3F7E' }, }, }], }); }); test('User Pool property defaultAction does not configure when in additional auth (complex)', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.USER_POOL, userPoolConfig: { userPool }, }, additionalAuthorizationModes: [ { authorizationType: appsync.AuthorizationType.USER_POOL, userPoolConfig: { userPool }, }, { authorizationType: appsync.AuthorizationType.USER_POOL, userPoolConfig: { userPool, appIdClientRegex: 'test', defaultAction: appsync.UserPoolDefaultAction.DENY, }, }, ], }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::GraphQLApi', { AuthenticationType: 'AMAZON_COGNITO_USER_POOLS', UserPoolConfig: { AwsRegion: { Ref: 'AWS::Region' }, DefaultAction: 'ALLOW', UserPoolId: { Ref: 'pool056F3F7E' }, }, AdditionalAuthenticationProviders: [ { AuthenticationType: 'AMAZON_COGNITO_USER_POOLS', UserPoolConfig: { AwsRegion: { Ref: 'AWS::Region' }, UserPoolId: { Ref: 'pool056F3F7E' }, }, }, { AuthenticationType: 'AMAZON_COGNITO_USER_POOLS', UserPoolConfig: { AwsRegion: { Ref: 'AWS::Region' }, AppIdClientRegex: 'test', UserPoolId: { Ref: 'pool056F3F7E' }, }, }, ], }); }); }); describe('AppSync OIDC Authorization', () => { test('OIDC authorization configurable in default authorization has default configuration', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.OIDC, openIdConnectConfig: { oidcProvider: 'test' }, }, }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::GraphQLApi', { AuthenticationType: 'OPENID_CONNECT', OpenIDConnectConfig: { Issuer: 'test', }, }); }); test('User Pool authorization configurable in default authorization', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.OIDC, openIdConnectConfig: { oidcProvider: 'test', clientId: 'id', tokenExpiryFromAuth: 1, tokenExpiryFromIssue: 1, }, }, }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::GraphQLApi', { AuthenticationType: 'OPENID_CONNECT', OpenIDConnectConfig: { AuthTTL: 1, ClientId: 'id', IatTTL: 1, Issuer: 'test', }, }); }); test('OIDC authorization configurable in additional authorization has default configuration', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { additionalAuthorizationModes: [{ authorizationType: appsync.AuthorizationType.OIDC, openIdConnectConfig: { oidcProvider: 'test' }, }], }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::GraphQLApi', { AdditionalAuthenticationProviders: [{ AuthenticationType: 'OPENID_CONNECT', OpenIDConnectConfig: { Issuer: 'test', }, }], }); }); test('User Pool authorization configurable in additional authorization', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { additionalAuthorizationModes: [{ authorizationType: appsync.AuthorizationType.OIDC, openIdConnectConfig: { oidcProvider: 'test', clientId: 'id', tokenExpiryFromAuth: 1, tokenExpiryFromIssue: 1, }, }], }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::GraphQLApi', { AdditionalAuthenticationProviders: [{ AuthenticationType: 'OPENID_CONNECT', OpenIDConnectConfig: { AuthTTL: 1, ClientId: 'id', IatTTL: 1, Issuer: 'test', }, }], }); }); test('User Pool authorization configurable in with multiple authorization', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.OIDC, openIdConnectConfig: { oidcProvider: 'test' }, }, additionalAuthorizationModes: [ { authorizationType: appsync.AuthorizationType.OIDC, openIdConnectConfig: { oidcProvider: 'test1', clientId: 'id', tokenExpiryFromAuth: 1, tokenExpiryFromIssue: 1, }, }, { authorizationType: appsync.AuthorizationType.OIDC, openIdConnectConfig: { oidcProvider: 'test2', clientId: 'id', tokenExpiryFromAuth: 1, tokenExpiryFromIssue: 1, }, }, ], }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::GraphQLApi', { AuthenticationType: 'OPENID_CONNECT', OpenIDConnectConfig: { Issuer: 'test' }, AdditionalAuthenticationProviders: [ { AuthenticationType: 'OPENID_CONNECT', OpenIDConnectConfig: { AuthTTL: 1, ClientId: 'id', IatTTL: 1, Issuer: 'test1', }, }, { AuthenticationType: 'OPENID_CONNECT', OpenIDConnectConfig: { AuthTTL: 1, ClientId: 'id', IatTTL: 1, Issuer: 'test2', }, }, ], }); }); }); describe('AppSync Lambda Authorization', () => { let fn: lambda.Function; beforeEach(() => { fn = new lambda.Function(stack, 'auth-function', { runtime: lambda.Runtime.NODEJS_14_X, handler: 'index.handler', code: lambda.Code.fromInline('/* lambda authentication code here.*/'), }); }); test('Lambda authorization configurable in default authorization has default configuration', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.LAMBDA, lambdaAuthorizerConfig: { handler: fn, }, }, }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::GraphQLApi', { AuthenticationType: 'AWS_LAMBDA', LambdaAuthorizerConfig: { AuthorizerUri: { 'Fn::GetAtt': [ 'authfunction96361832', 'Arn', ], }, }, }); }); test('Lambda authorization configurable in default authorization', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.LAMBDA, lambdaAuthorizerConfig: { handler: fn, resultsCacheTtl: cdk.Duration.seconds(300), validationRegex: 'custom-.*', }, }, }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::GraphQLApi', { AuthenticationType: 'AWS_LAMBDA', LambdaAuthorizerConfig: { AuthorizerUri: { 'Fn::GetAtt': [ 'authfunction96361832', 'Arn', ], }, AuthorizerResultTtlInSeconds: 300, IdentityValidationExpression: 'custom-.*', }, }); }); test('Lambda authorization configurable in additional authorization has default configuration', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { additionalAuthorizationModes: [{ authorizationType: appsync.AuthorizationType.LAMBDA, lambdaAuthorizerConfig: { handler: fn, }, }], }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::GraphQLApi', { AdditionalAuthenticationProviders: [{ AuthenticationType: 'AWS_LAMBDA', LambdaAuthorizerConfig: { AuthorizerUri: { 'Fn::GetAtt': [ 'authfunction96361832', 'Arn', ], }, }, }], }); }); test('Lambda authorization configurable in additional authorization', () => { // WHEN new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { additionalAuthorizationModes: [{ authorizationType: appsync.AuthorizationType.LAMBDA, lambdaAuthorizerConfig: { handler: fn, resultsCacheTtl: cdk.Duration.seconds(300), validationRegex: 'custom-.*', }, }], }, }); // THEN Template.fromStack(stack).hasResourceProperties('AWS::AppSync::GraphQLApi', { AdditionalAuthenticationProviders: [{ AuthenticationType: 'AWS_LAMBDA', LambdaAuthorizerConfig: { AuthorizerUri: { 'Fn::GetAtt': [ 'authfunction96361832', 'Arn', ], }, AuthorizerResultTtlInSeconds: 300, IdentityValidationExpression: 'custom-.*', }, }], }); }); test('Lambda authorization throws with multiple lambda authorization', () => { expect(() => new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.LAMBDA, lambdaAuthorizerConfig: { handler: fn, }, }, additionalAuthorizationModes: [ { authorizationType: appsync.AuthorizationType.LAMBDA, lambdaAuthorizerConfig: { handler: fn, resultsCacheTtl: cdk.Duration.seconds(300), validationRegex: 'custom-.*', }, }, ], }, })).toThrow('You can only have a single AWS Lambda function configured to authorize your API.'); expect(() => new appsync.GraphqlApi(stack, 'api2', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.IAM }, additionalAuthorizationModes: [ { authorizationType: appsync.AuthorizationType.LAMBDA, lambdaAuthorizerConfig: { handler: fn, resultsCacheTtl: cdk.Duration.seconds(300), validationRegex: 'custom-.*', }, }, { authorizationType: appsync.AuthorizationType.LAMBDA, lambdaAuthorizerConfig: { handler: fn, resultsCacheTtl: cdk.Duration.seconds(300), validationRegex: 'custom-.*', }, }, ], }, })).toThrow('You can only have a single AWS Lambda function configured to authorize your API.'); }); test('throws if authorization type and mode do not match', () => { expect(() => new appsync.GraphqlApi(stack, 'api', { name: 'api', schema: appsync.Schema.fromAsset(path.join(__dirname, 'appsync.test.graphql')), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.LAMBDA, openIdConnectConfig: { oidcProvider: 'test' }, }, }, })).toThrow('Missing Lambda Configuration'); }); });
the_stack
module WinJSTests { "use strict"; var testRootEl, newItems, disposedItemsCount, disposedItems, actionHistory = {}; // Stores dispose/render history for each item var ListView = <typeof WinJS.UI.PrivateListView> WinJS.UI.ListView; function pushAction(item, action) { if (!actionHistory[item.index]) { actionHistory[item.index] = []; } actionHistory[item.index].push(action); } function checkDisposeBeforeRender(index) { Helper.ListView.elementsEqual(["dispose", "render"], actionHistory[index]); } function setupListView(element, layoutName) { function groupKey(data) { return data.group; } function groupData(data) { return { title: data.group }; } function createRenderer() { return function renderer(itemPromise) { return itemPromise.then(function (item) { var element = document.createElement("div"); element.style.width = element.style.height = "100px"; element.textContent = item.data.title; return element; }); }; } var items = []; for (var i = 0; i < 100; i++) { var gKey = String.fromCharCode("A".charCodeAt(0) + Math.floor(i / 10)); items.push({ group: gKey, title: "Tile" + gKey + i }); } var list = new WinJS.Binding.List(items).createGrouped(groupKey, groupData); return new ListView(element, { layout: new WinJS.UI[layoutName](), itemDataSource: list.dataSource, itemTemplate: createRenderer(), groupDataSource: list.groups.dataSource, groupHeaderTemplate: createRenderer() }); } function itemRenderer(id, async?) { var source: any = document.getElementById(id).cloneNode(true); source.id = ""; return function itemRenderer(itemPromise): any { newItems++; var element = source.cloneNode(true); element.msRendererPromise = itemPromise. then(function (item) { WinJS.Utilities.markDisposable(element, function () { pushAction(item, "dispose"); disposedItems.push(item.data.title); }); pushAction(item, "render"); element.myDataConnectionExpando = item.data.id; element.children[0].textContent = item.data.title; }); if (async) { return WinJS.Promise.timeout(Math.floor(Math.random() * 1000)).then(function () { return element; }); } else { return element; } }; } function checkSelection(listview, index, selected) { var tile = listview.elementFromIndex(index).parentNode; LiveUnit.Assert.areEqual(selected, WinJS.Utilities.hasClass(tile, WinJS.UI._selectedClass)); } function checkTile(listview, index) { var tile = listview.elementFromIndex(index), container = Helper.ListView.containerFrom(tile), left = Math.floor(index / 3) * 100, top = (index - 3 * Math.floor(index / 3)) * 100; LiveUnit.Assert.areEqual("Tile" + index, tile.textContent); LiveUnit.Assert.areEqual(left, Helper.ListView.offsetLeftFromSurface(listview, container), "Error in tile " + index); LiveUnit.Assert.areEqual(top, Helper.ListView.offsetTopFromSurface(listview, container), "Error in tile " + index); } function testDispose(layoutName, complete) { var element = document.getElementById("reuseTestPlaceholder"), myData = new WinJS.Binding.List(); for (var i = 0; i < 300; i++) { myData.push({ title: i }); } var listview = new WinJS.UI.ListView(element, { layout: new WinJS.UI[layoutName](), itemDataSource: myData.dataSource, itemTemplate: itemRenderer("reuseTestTemplate"), }); var expectedReleasedItems = []; var tests = [ // Make sure the initial state is what we are expecting function () { var expected = 9 * 3; LiveUnit.Assert.areEqual(expected, Helper.ListView.getRealizedCount(element)); LiveUnit.Assert.areEqual(expected, newItems); LiveUnit.Assert.areEqual(0, disposedItemsCount); Helper.ListView.elementsEqual([], disposedItems); }, // In the following tests, note that: // 0, 7, and 26 are realized items so manipulating them should trigger calls to dispose. // 45 and 100 are unrealized items so manipulating them should not trigger calls to dispose. // Ensure changing an item in the data source triggers a call to dispose function () { function checkChangeItem(index, newData, additionalDisposeItems) { myData.setAt(index, newData); expectedReleasedItems = expectedReleasedItems.concat(additionalDisposeItems); Helper.ListView.elementsEqual(expectedReleasedItems, disposedItems); // If the item was disposed, ensure it was disposed before it was rendered if (additionalDisposeItems.length > 0) { checkDisposeBeforeRender(index); } actionHistory = {}; } actionHistory = {}; checkChangeItem(0, { title: "Zero" }, [0]); checkChangeItem(45, { title: "Fourty-five" }, []); checkChangeItem(26, { title: "Twenty-six" }, [26]); checkChangeItem(7, { title: "Seven" }, [7]); checkChangeItem(100, { title: "One Hundred" }, []); }, // Ensure removing items from the data source triggers a call to dispose function () { function removeItems(startIndex, howMany, additionalDisposeItems) { myData.splice(startIndex, howMany); expectedReleasedItems = expectedReleasedItems.concat(additionalDisposeItems); } removeItems(45, 1, []); removeItems(26, 1, ["Twenty-six"]); removeItems(0, 1, ["Zero"]); removeItems(1, 10, [2, 3, 4, 5, 6, "Seven", 8, 9, 10, 11]); removeItems(100, 1, []); Helper.ListView.waitForDeferredAction(listview)().then(function () { // Unlike change notifications, remove notifications don't call dispose until // the animation completes. Helper.ListView.elementsEqual(expectedReleasedItems.sort(), disposedItems.sort()); complete(); }); } ]; Helper.ListView.runTests(listview, tests); }; // Check that items, group headers, and grouping elements are not leaked in the DOM // after the user scrolls. For example, check that there isn't a win-item in the DOM // which isn't associated with any of the realized items. function domCleanupAfterScrollingTest(layoutName, complete) { function expectedNumberOfItemsInDom() { var count = 0; listView._view.items.each(function (index, itemElement, itemData) { count++; }); return count; } function expectedNumberOfGroupsInDom() { return listView._groups.groups.reduce(function (count, group) { return group.elements || group.header ? count + 1 : count; }, 0); } var newNode = document.createElement("div"); newNode.style.width = "300px"; newNode.style.height = "300px"; testRootEl.appendChild(newNode); var listView = setupListView(newNode, layoutName); var tests = [ function () { listView.ensureVisible(99); return true; }, function () { listView.ensureVisible(0); return true; }, function () { // Wait 1 second for the ARIA attributes to be set. Then we can find the // grouping elements in the DOM by their role. setTimeout(function () { LiveUnit.Assert.areEqual(expectedNumberOfItemsInDom(), listView._canvas.querySelectorAll(".win-item").length, "Incorrect number of items in the DOM"); LiveUnit.Assert.areEqual(expectedNumberOfGroupsInDom(), listView._canvas.querySelectorAll(".win-groupheader").length, "Incorrect number of group headers in the DOM"); testRootEl.removeChild(newNode); complete(); }, 1000); }, ]; Helper.ListView.runTests(listView, tests); } export class ReuseTests { setUp() { LiveUnit.LoggingCore.logComment("In setup"); testRootEl = document.createElement("div"); testRootEl.className = "file-listview-css"; var newNode = document.createElement("div"); newNode.id = "ReuseTests"; newNode.innerHTML = "<div id='reuseTestPlaceholder'></div>" + "<div id='reuseTestTemplate' class='reuseTemplateClass'>" + " <div></div>" + "</div>" + "<div id='reuseGroupTestTemplate' class='reuseGroupTemplateClass'>" + " <div></div>" + "</div>" testRootEl.appendChild(newNode); document.body.appendChild(testRootEl); newItems = 0; disposedItemsCount = 0; disposedItems = []; } tearDown() { LiveUnit.LoggingCore.logComment("In tearDown"); WinJS.Utilities.disposeSubTree(testRootEl); document.body.removeChild(testRootEl); } // Ensures dispose is called due to the following data source changes: // - Item changed // - Item removed testDispose_GridLayout(complete) { testDispose("GridLayout", complete); } testDomCleanupAfterScrolling_GridLayout(complete) { domCleanupAfterScrollingTest("GridLayout", complete); } } function generateChangeSelected(layoutName) { ReuseTests.prototype["testChangeSelected" + layoutName] = function (complete) { var items = []; for (var i = 0; i < 100; i++) { items.push({ title: "Tile" + i }); } var list = new WinJS.Binding.List(items); function renderer(itemPromise, recycled) { return itemPromise.then(function (item) { var element = recycled; if (!element) { element = document.createElement("div"); element.style.width = element.style.height = "100px"; } element.textContent = item.data.title; return element; }); } var newNode = document.createElement("div"); newNode.style.width = "600px"; newNode.style.height = "600px"; testRootEl.appendChild(newNode); var listView = new WinJS.UI.ListView(newNode, { itemDataSource: list.dataSource, itemTemplate: renderer, layout: new WinJS.UI[layoutName]() }); listView.selection.set(0); function checkTile(listview, index, text, selected) { var tile = listview.elementFromIndex(index), wrapper = tile.parentNode; LiveUnit.Assert.areEqual(text, tile.textContent); LiveUnit.Assert.areEqual(selected, WinJS.Utilities.hasClass(wrapper, WinJS.UI._selectedClass)); LiveUnit.Assert.areEqual(selected, tile.getAttribute("aria-selected") === "true"); LiveUnit.Assert.areEqual(selected, WinJS.Utilities._isSelectionRendered(wrapper)); } var tests = [ function () { checkTile(listView, 0, "Tile0", true); checkTile(listView, 1, "Tile1", false); list.setAt(0, { title: "Changed" }); return true; }, function () { checkTile(listView, 0, "Changed", true); checkTile(listView, 1, "Tile1", false); testRootEl.removeChild(newNode); complete(); }, ]; Helper.ListView.runTests(listView, tests); }; }; generateChangeSelected("ListLayout"); function generateAriaCleanup(layoutName) { ReuseTests.prototype["testAriaCleanup" + layoutName] = function (complete) { var items = []; for (var i = 0; i < 100; i++) { items.push({ title: "Tile" + i }); } var list = new WinJS.Binding.List(items); function renderer(itemPromise, recycled) { return itemPromise.then(function (item) { var element = recycled; if (!element) { element = document.createElement("div"); element.style.width = element.style.height = "100px"; } element.textContent = item.data.title; return element; }); } var newNode = document.createElement("div"); newNode.style.width = "300px"; newNode.style.height = "300px"; testRootEl.appendChild(newNode); var listView = new WinJS.UI.ListView(newNode, { itemDataSource: list.dataSource, itemTemplate: renderer }); listView.selection.set([0, 1, 2, 3]); Helper.ListView.waitForReady(listView)().then(function () { LiveUnit.Assert.areEqual(4, newNode.querySelectorAll("[aria-selected='true']").length); listView.ensureVisible(99); return Helper.ListView.waitForDeferredAction(listView)(); }).then(function () { LiveUnit.Assert.areEqual(0, newNode.querySelectorAll("[aria-selected='true']").length); listView.ensureVisible(0); return Helper.ListView.waitForDeferredAction(listView)(); }).then(function () { LiveUnit.Assert.areEqual(4, newNode.querySelectorAll("[aria-selected='true']").length); testRootEl.removeChild(newNode); complete(); }) }; }; generateAriaCleanup("GridLayout"); } // register the object as a test class by passing in the name LiveUnit.registerTestClass("WinJSTests.ReuseTests");
the_stack
import crypto from 'crypto'; import Timeout from 'await-timeout'; import { ethers } from 'ethers'; import { CBR_Address, bigNumberify, } from './CBR'; import util from 'util'; import { num, hexlify, AnyBackendTy, checkedBigNumberify, bytesEq, } from './shared_backend'; import type { MapRefT } from './shared_backend'; // => import { process } from './shim'; export { hexlify } from './shared_backend'; export const bigNumberToBigInt = (x:BigNumber): bigint => BigInt(x.toHexString()); type BigNumber = ethers.BigNumber; export type CurrencyAmount = string | number | BigNumber | bigint export type {Connector} from './ConnectorMode'; let DEBUG: boolean = truthyEnv(process.env.REACH_DEBUG); export const setDEBUG = (b: boolean) => { if (b === false || b === true) { DEBUG = b; } else { throw Error(`Expected bool, got ${JSON.stringify(b)}`); } }; export const getDEBUG = (): boolean => { return DEBUG; }; export const debug = (...msgs: any) => { if (getDEBUG()) { // Print arrays/objects in full instead of the default depth of 2 const betterMsgs = msgs.map((msg: any) => ["object", "array"].includes(typeof msg) && util && util.inspect instanceof Function ? util.inspect(msg, false, null, true) : msg); void(betterMsgs); // Print objects for indentation, colors, etc... console.log(new Date(), `DEBUG:`, ...msgs); } }; export type IBackendViewInfo<ConnectorTy extends AnyBackendTy> = { ty: ConnectorTy, decode: (i:number, svs:Array<any>, args:Array<any>) => Promise<any>, }; const isUntaggedView = (x: any) => { return 'ty' in x && 'decode' in x; } export type IBackendViewsInfo<ConnectorTy extends AnyBackendTy> = {[viewi: number]: Array<ConnectorTy>}; export type TaggedBackendView<ConnectorTy extends AnyBackendTy> = {[keyn:string]: IBackendViewInfo<ConnectorTy>} export type IBackendViews<ConnectorTy extends AnyBackendTy> = { views: IBackendViewsInfo<ConnectorTy>, infos: { [viewn: string]: TaggedBackendView<ConnectorTy> | IBackendViewInfo<ConnectorTy>, }, }; export type IBackendMaps<ConnectorTy extends AnyBackendTy> = { mapDataTy: ConnectorTy, }; export type IViewLib = { viewMapRef: any, }; export type IBackend<ConnectorTy extends AnyBackendTy> = { _backendVersion: number, _getViews: (stdlib:Object, viewlib:IViewLib) => IBackendViews<ConnectorTy>, _getMaps: (stdlib:Object) => IBackendMaps<ConnectorTy>, _Participants: {[n: string]: any}, _APIs: {[n: string]: any | {[n: string]: any}}, _getEvents: (stdlib:Object) => ({ [n:string]: [any] }) }; export type OnProgress = (obj: {current: BigNumber, target: BigNumber}) => any; export type WPArgs = { host: string | undefined, port: number, output: 'silent', timeout: number, } export type MkPayAmt<Token> = [ BigNumber, Array<[BigNumber, Token]> ]; export type IRecvNoTimeout<RawAddress> = { didTimeout: false, didSend: boolean, data: Array<unknown>, from: RawAddress, time: BigNumber, secs: BigNumber, getOutput: (o_mode:string, o_lab:string, o_ctc:any, o_val:any) => Promise<any>, }; export type IRecv<RawAddress> = IRecvNoTimeout<RawAddress> | { didTimeout: true, }; export type TimeArg = [ ('time' | 'secs'), BigNumber ]; export type ISendRecvArgs<RawAddress, Token, ConnectorTy extends AnyBackendTy> = { funcNum: number, evt_cnt: number, tys: Array<ConnectorTy>, args: Array<any>, pay: MkPayAmt<Token>, out_tys: Array<ConnectorTy>, onlyIf: boolean, soloSend: boolean, timeoutAt: TimeArg | undefined, lct: BigNumber, sim_p: (fake: IRecv<RawAddress>) => Promise<ISimRes<Token>>, }; export type IRecvArgs<ConnectorTy extends AnyBackendTy> = { funcNum: number, evt_cnt: number, out_tys: Array<ConnectorTy>, didSend: boolean, waitIfNotPresent: boolean, timeoutAt: TimeArg | undefined, }; export type ParticipantVal = (io:any) => Promise<any>; export type ParticipantMap = {[key: string]: ParticipantVal}; export type ViewVal = (...args:any) => Promise<any>; export type ViewFunMap = {[key: string]: ViewVal}; export type ViewMap = {[key: string]: ViewVal | ViewFunMap}; export type APIMap = ViewMap; export type EventMap = { [key: string]: any } export type IContractCompiled<ContractInfo, RawAddress, Token, ConnectorTy extends AnyBackendTy> = { getContractInfo: () => Promise<ContractInfo>, getContractAddress: () => Promise<CBR_Address>, waitUntilTime: (v:BigNumber) => Promise<BigNumber>, waitUntilSecs: (v:BigNumber) => Promise<BigNumber>, selfAddress: () => CBR_Address, // Not RawAddress! iam: (some_addr: RawAddress) => RawAddress, stdlib: Object, sendrecv: (args:ISendRecvArgs<RawAddress, Token, ConnectorTy>) => Promise<IRecv<RawAddress>>, recv: (args:IRecvArgs<ConnectorTy>) => Promise<IRecv<RawAddress>>, getState: (v:BigNumber, ctcs:Array<ConnectorTy>) => Promise<Array<any>>, apiMapRef: (i:number, ty:ConnectorTy) => MapRefT<any>, }; export type ISetupArgs<ContractInfo, VerifyResult> = { setInfo: (info: ContractInfo) => void, getInfo: () => Promise<ContractInfo>, setTrustedVerifyResult: (vr:VerifyResult) => void, getTrustedVerifyResult: () => (VerifyResult|undefined), }; export type ISetupViewArgs<ContractInfo, VerifyResult> = Omit<ISetupArgs<ContractInfo, VerifyResult>, ("setInfo")>; export type ISetupEventArgs<ContractInfo, VerifyResult> = Omit<ISetupArgs<ContractInfo, VerifyResult>, ("setInfo")>; export type ISetupRes<ContractInfo, RawAddress, Token, ConnectorTy extends AnyBackendTy> = Pick<IContractCompiled<ContractInfo, RawAddress, Token, ConnectorTy>, ("getContractInfo"|"getContractAddress"|"sendrecv"|"recv"|"getState"|"apiMapRef")>; export type IStdContractArgs<ContractInfo, VerifyResult, RawAddress, Token, ConnectorTy extends AnyBackendTy> = { bin: IBackend<ConnectorTy>, setupView: ISetupView<ContractInfo, VerifyResult, ConnectorTy>, setupEvents: ISetupEvent<ContractInfo, VerifyResult>, givenInfoP: (Promise<ContractInfo>|undefined) _setup: (args: ISetupArgs<ContractInfo, VerifyResult>) => ISetupRes<ContractInfo, RawAddress, Token, ConnectorTy>, } & Omit<IContractCompiled<ContractInfo, RawAddress, Token, ConnectorTy>, ("getContractInfo"|"getContractAddress"|"sendrecv"|"recv"|"getState"|"apiMapRef")>; export type IContract<ContractInfo, RawAddress, Token, ConnectorTy extends AnyBackendTy> = { getInfo: () => Promise<ContractInfo>, getViews: () => ViewMap, getContractAddress: () => Promise<CBR_Address>, // backend-specific participants: ParticipantMap, p: ParticipantMap views: ViewMap, v: ViewMap, unsafeViews: ViewMap, apis: APIMap, a: APIMap, safeApis: APIMap, e: EventMap, events: EventMap, // for compiled output _initialize: () => IContractCompiled<ContractInfo, RawAddress, Token, ConnectorTy>, }; export type ISetupView<ContractInfo, VerifyResult, ConnectorTy extends AnyBackendTy> = (args:ISetupViewArgs<ContractInfo, VerifyResult>) => { viewLib: IViewLib, getView1: ((views:IBackendViewsInfo<ConnectorTy>, v:string, k:string|undefined, vi:IBackendViewInfo<ConnectorTy>, isSafe: boolean) => ViewVal) }; export type ISetupEvent<ContractInfo, VerifyResult> = (args:ISetupEventArgs<ContractInfo, VerifyResult>) => { createEventStream : (event: string, tys: any[]) => { lastTime: () => Promise<Time>, next: () => Promise<any>, seek: (t: Time) => void, seekNow: () => Promise<void>, monitor: (onEvent: (x:any) => void) => Promise<void> } } export type Time = BigNumber; export type Event<T> = { when: Time, what: T } export type EventStream<T> = { // mvp seek: (t:Time) => void, next: () => Promise<Event<T>> // additional seekNow: () => void, lastTime: () => Time, // why can't TS handle a function type as arg monitor: (f: any) => void } export const stdVerifyContract = async <ContractInfo, VerifyResult>( stdArgs: Pick<ISetupViewArgs<ContractInfo, VerifyResult>, ("getTrustedVerifyResult"|"setTrustedVerifyResult")>, doVerify: (() => Promise<VerifyResult>) ): Promise<VerifyResult> => { const { getTrustedVerifyResult, setTrustedVerifyResult } = stdArgs; let r = getTrustedVerifyResult(); if ( r ) { return r; } r = await doVerify(); setTrustedVerifyResult(r); return r; }; export const stdContract = <ContractInfo, VerifyResult, RawAddress, Token, ConnectorTy extends AnyBackendTy>( stdContractArgs: IStdContractArgs<ContractInfo, VerifyResult, RawAddress, Token, ConnectorTy>): IContract<ContractInfo, RawAddress, Token, ConnectorTy> => { const { bin, waitUntilTime, waitUntilSecs, selfAddress, iam, stdlib, setupView, setupEvents, _setup, givenInfoP } = stdContractArgs; type SomeSetupArgs = Pick<ISetupArgs<ContractInfo, VerifyResult>, ("setInfo"|"getInfo")>; const { setInfo, getInfo }: SomeSetupArgs = (() => { let _setInfo = (info:ContractInfo) => { throw Error(`Cannot set info(${JSON.stringify(info)}) (i.e. deploy) when acc.contract called with contract info`); return; }; if ( givenInfoP !== undefined ) { return { setInfo: _setInfo, getInfo: (() => givenInfoP), }; } else { let beenSet = false; const _infoP: Promise<ContractInfo> = new Promise((resolve) => { _setInfo = (info:ContractInfo) => { if ( beenSet ) { throw Error(`Cannot set info(${JSON.stringify(info)}), i.e. deploy, twice`); } resolve(info); beenSet = true; }; }); return { setInfo: _setInfo, getInfo: (() => _infoP), }; } })(); let trustedVerifyResult:any = undefined; const getTrustedVerifyResult = () => trustedVerifyResult; const setTrustedVerifyResult = (x:any) => { trustedVerifyResult = x; }; const viewArgs = { getInfo, setTrustedVerifyResult, getTrustedVerifyResult }; const setupArgs = { ...viewArgs, setInfo }; const _initialize = () => { const { getContractInfo, getContractAddress, sendrecv, recv, getState, apiMapRef } = _setup(setupArgs); return { selfAddress, iam, stdlib, waitUntilTime, waitUntilSecs, getContractInfo, getContractAddress, sendrecv, recv, getState, apiMapRef, }; }; const ctcC = { _initialize }; const { viewLib, getView1 } = setupView(viewArgs); const views_bin = bin._getViews({reachStdlib: stdlib}, viewLib); const mkViews = (isSafe: boolean) => objectMap(views_bin.infos, ((v:string, vm: TaggedBackendView<ConnectorTy> | IBackendViewInfo<ConnectorTy>) => isUntaggedView(vm) ? getView1(views_bin.views, v, undefined, vm as IBackendViewInfo<ConnectorTy>, isSafe) : objectMap(vm as TaggedBackendView<ConnectorTy>, ((k:string, vi:IBackendViewInfo<ConnectorTy>) => getView1(views_bin.views, v, k, vi, isSafe))))); const views = mkViews(true); const unsafeViews = mkViews(false); const participants = objectMap(bin._Participants, ((pn:string, p:any) => { void(pn); return ((io:any) => { return p(ctcC, io); }); })); const mkApis = (isSafe = false) => objectMap(bin._APIs, ((an:string, am:any) => { const f = (afn:string|undefined, ab:any) => { const mk = (sep: string) => (afn === undefined) ? `${an}` : `${an}${sep}${afn}`; const bp = mk(`_`); delete participants[bp]; const bl = mk(`.`); return (...args:any[]) => { const terminal = { terminated: bl }; let theResolve: (x:any) => void; let theReject: (x:any) => void; const p = new Promise((resolve, reject) => { theResolve = resolve; theReject = reject; }); const fail = (err: Error) => { if (isSafe) { theResolve(['None', null]); } else { theReject(err); } }; debug(`${bl}: start`, args); ab(ctcC, { "in": (() => { debug(`${bl}: in`, args); return args }), "out": ((oargs:any[], res:any) => { debug(`${bl}: out`, oargs, res); theResolve(isSafe ? ['Some', res] : res); throw terminal; }), }).catch((err:any) => { if ( Object.is(err, terminal) ) { debug(`${bl}: done`); } else { fail(new Error(`${bl} errored with ${err}`)); } }).then((res:any) => { fail(new Error(`${bl} returned with ${JSON.stringify(res)}`)); }); return p; }; }; return (typeof am === 'object') ? objectMap(am, f) : f(undefined, am); })); const apis = mkApis(false); const safeApis = mkApis(true); const eventMap = bin._getEvents({ reachStdlib: stdlib }); const { createEventStream } = setupEvents(viewArgs); const events = objectMap(eventMap, ((k:string, v: any) => Array.isArray(v) // untagged ? createEventStream(k, v) : objectMap(v, ((kp, vp: any) => createEventStream(k + "_" + kp, vp))))); return { ...ctcC, getInfo, getContractAddress: (() => _initialize().getContractAddress()), participants, p: participants, views, v: views, getViews: () => { console.log(`WARNING: ctc.getViews() is deprecated; use ctc.views or ctc.v instead.`); return views; }, unsafeViews, apis, a: apis, safeApis, events, e: events, }; }; export type IAccount<NetworkAccount, Backend, Contract, ContractInfo, Token> = { networkAccount: NetworkAccount, deploy: (bin: Backend) => Contract, attach: (bin: Backend, ctcInfoP: Promise<ContractInfo>) => Contract, contract: (bin: Backend, ctcInfoP?: Promise<ContractInfo>) => Contract, stdlib: Object, getAddress: () => string, setDebugLabel: (lab: string) => IAccount<NetworkAccount, Backend, Contract, ContractInfo, Token>, tokenAccept: (token: Token) => Promise<void>, tokenAccepted: (token: Token) => Promise<boolean>, tokenMetadata: (token: Token) => Promise<any>, }; export const stdAccount = <NetworkAccount, Backend, Contract, ContractInfo, Token>( orig:Omit<IAccount<NetworkAccount, Backend, Contract, ContractInfo, Token>, ("deploy"|"attach")>): IAccount<NetworkAccount, Backend, Contract, ContractInfo, Token> => { return { ...orig, deploy: (bin: Backend) => { console.log(`WARNING: acc.deploy(bin) is deprecated; use acc.contract(bin) instead. Deployment is implied by the first publication.`); return orig.contract(bin, undefined); }, attach: (bin: Backend, ctcInfoP: Promise<ContractInfo>) => { console.log(`WARNING: acc.attach(bin, info) is deprecated; use acc.contract(bin, info) instead. Attachment is implied by reception of the first publication.`); return orig.contract(bin, ctcInfoP); }, }; }; export type IAccountTransferable<NetworkAccount> = IAccount<NetworkAccount, any, any, any, any> | { networkAccount: NetworkAccount, } export type ISimRes<Token> = { txns: Array<ISimTxn<Token>>, mapRefs: Array<string>, isHalt : boolean, }; export type ISimTxn<Token> = { kind: 'to'|'init', amt: BigNumber, tok: Token|undefined, } | { kind: 'from', to: string, amt: BigNumber, tok: Token|undefined, } | { kind: 'halt', tok: Token|undefined, } | { kind: 'tokenNew', n: any, s: any, u: any m: any, p: BigNumber, d: BigNumber|undefined, } | { kind: 'tokenBurn', tok: Token, amt: BigNumber, } | { kind: 'tokenDestroy', tok: Token, }; /** * @description Create a getter/setter, where the getter defaults to memoizing a thunk */ export function replaceableThunk<T>(thunk: () => T): [() => T, (val: T) => void] { let called = false; let res: T | null = null; function get(): T { if (!called) { called = true; res = thunk(); } return res as T; } function set(val: T): void { if (called) { throw Error(`Cannot re-set value once already set`); } res = val; called = true; } return [get, set]; } /** * @description Only perform side effects from thunk on the first call. */ export function memoizeThunk<T>(thunk: () => T): () => T { return replaceableThunk(thunk)[0]; } /** * @description ascLabels[i] = label; labelMap[label] = i; */ export const labelMaps = (co: { [key: string]: unknown }): { ascLabels: Array<string>, labelMap: {[key: string]: number} } => { const ascLabels = Object.keys(co).sort(); const labelMap: { [key: string]: number } = {}; for (const i in ascLabels) { labelMap[ascLabels[i]] = parseInt(i); } return {ascLabels, labelMap}; } /** @description Check that a stringy env value doesn't look falsy. */ export function truthyEnv(v: string|undefined|null): v is string { if (!v) return false; return ![ '0', 'false', 'f', '#f', 'no', 'off', 'n', '', ].includes(v && v.toLowerCase && v.toLowerCase()); } export const envDefault = <T>(v: string|undefined|null, d: T): string|T => (v === undefined || v === null) ? d : v; export const envDefaultNoEmpty = <T>(v: string|undefined|null, d: T): string|T => { const v2 = envDefault(v, d); return v2 === '' ? d : v2; } type DigestMode = 'keccak256' | 'sha256'; export const makeDigest = (mode: DigestMode, prep: any) => (t:any, v:any) => { void(hexlify); // const args = [t, v]; // debug('digest(', args, ') =>'); const kekCat = prep(t, v); // debug('digest(', args, ') => internal(', hexlify(kekCat), ')'); const f = mode === 'keccak256' ? ethers.utils.keccak256 : ethers.utils.sha256; const r = f(kekCat); debug('digest', {mode, prep, t, v, kekCat, f, r}); // debug('keccak(', args, ') => internal(', hexlify(kekCat), ') => ', r); return r; }; export const hexToString = ethers.utils.toUtf8String; const byteToHex = (b: number): string => (b & 0xFF).toString(16).padStart(2, '0'); const byteArrayToHex = (b: any): string => Array.from(b, byteToHex).join(''); const hexTo0x = (h: string): string => '0x' + h.replace(/^0x/, ''); export const hexToBigNumber = (h: string): BigNumber => bigNumberify(hexTo0x(h)); export const makeRandom = (width:number) => { const randomUInt = (): BigNumber => hexToBigNumber(byteArrayToHex(crypto.randomBytes(width))); const hasRandom = { random: randomUInt, }; return { randomUInt, hasRandom }; }; export const makeArith = (m:BigNumber) => { const check = (x: BigNumber) => checkedBigNumberify(`internal`, m, x); const add = (a: num, b: num): BigNumber => check(bigNumberify(a).add(bigNumberify(b))); const sub = (a: num, b: num): BigNumber => check(bigNumberify(a).sub(bigNumberify(b))); const mod = (a: num, b: num): BigNumber => check(bigNumberify(a).mod(bigNumberify(b))); const mul = (a: num, b: num): BigNumber => check(bigNumberify(a).mul(bigNumberify(b))); const div = (a: num, b: num): BigNumber => check(bigNumberify(a).div(bigNumberify(b))); const muldiv = (a: num, b: num, c: num): BigNumber => { const prod = bigNumberify(a).mul(bigNumberify(b)); return check( prod.div(bigNumberify(c)) ); }; return { add, sub, mod, mul, div, muldiv }; }; export const argsSlice = <T>(args: Array<T>, cnt: number): Array<T> => cnt == 0 ? [] : args.slice(-1 * cnt); export const argsSplit = <T>(args: Array<T>, cnt: number): [ Array<T>, Array<T> ] => cnt == 0 ? [args, []] : [ args.slice(0, args.length - cnt), args.slice(-1 * cnt) ]; export const objectMap = <A,B>(object: {[key:string]: A}, mapFn: ((k:string, a:A) => B)): {[key:string]: B} => Object.keys(object).reduce(function(result: {[key:string]: B}, key:string) { result[key] = mapFn(key, object[key]) return result; }, {}); export const mkAddressEq = (T_Address: {canonicalize: (addr:any) => any} ) => (x:any, y:any): boolean => bytesEq(T_Address.canonicalize(x), T_Address.canonicalize(y)); export const ensureConnectorAvailable = (bin:any, conn: string, jsVer: number, connVer: number) => { checkVersion(bin._backendVersion, jsVer, `JavaScript backend`); const connectors = bin._Connectors; const conn_bin = connectors[conn]; if ( ! conn_bin ) { throw (new Error(`The application was not compiled for the ${conn} connector, only: ${Object.keys(connectors)}`)); } checkVersion(conn_bin.version, connVer, `${conn} backend`); }; export const checkVersion = (actual:number, expected:number, label:string): void => { if ( actual !== expected ) { const older = (actual === undefined) || (actual < expected); const more = older ? `update your compiler and recompile!` : `updated your standard library and rerun!`; throw Error(`This Reach compiled ${label} does not match the expectations of this Reach standard library: expected ${expected}, but got ${actual}; ${more}`); } }; const argHelper = (xs: any[], f: (_:any) => any, op: (a: any, b: any) => boolean) => { if (xs.length == 0) { return undefined; } return xs.reduce((accum: any, x: any) => op(f(x), f(accum)) ? x : accum, xs[0]); } export const argMax = (xs: any[], f: (_:any) => any) => argHelper(xs, f, (a, b) => a > b); export const argMin = (xs: any[], f: (_:any) => any) => argHelper(xs, f, (a, b) => a < b); export const make_newTestAccounts = <X>(newTestAccount: (bal:any) => Promise<X>): ((k:number, bal:any) => Promise<Array<X>>) => (k:number, bal:any): Promise<Array<X>> => Promise.all((new Array(k)).fill(1).map((_:any): Promise<X> => newTestAccount(bal))); export const make_waitUntilX = (label: string, getCurrent: () => Promise<BigNumber>, step: (target:BigNumber) => Promise<BigNumber>) => async (target: BigNumber, onProgress?: OnProgress): Promise<BigNumber> => { const onProg = onProgress || (() => {}); let current = await getCurrent(); const notify = () => { const o = { current, target }; debug(`waitUntilX:`, label, o); onProg(o); }; while (current.lt(target)) { debug('waitUntilX', { label, current, target }); current = await step(current.add(1)); notify(); } notify(); return current; }; export const checkTimeout = async (runningIsolated:(() => boolean), getTimeSecs: ((now:BigNumber) => Promise<BigNumber>), timeoutAt: TimeArg | undefined, nowTimeN: number): Promise<boolean> => { debug('checkTimeout', { timeoutAt, nowTimeN }); if ( ! timeoutAt ) { return false; } const [ mode, val ] = timeoutAt; const nowTime = bigNumberify(nowTimeN); if ( mode === 'time' ) { return val.lte(nowTime); } else if ( mode === 'secs' ) { try { const nowSecs = await getTimeSecs(nowTime); return val.lte(nowSecs); } catch (e) { debug('checkTimeout','err', `${e}` ); if ( runningIsolated() ) { const nowSecs = Math.floor(Date.now() / 1000); debug('checkTimeout','isolated',val.toString(),nowSecs); return val.lt(nowSecs - 1); } return false; } } else { throw new Error(`invalid TimeArg mode`); } }; export class Signal { p: Promise<boolean>; r: (a:boolean) => void; constructor() { this.r = (a) => { void(a); throw new Error(`signal never initialized`); }; const me = this; this.p = new Promise((resolve) => { me.r = resolve; }); } wait() { return this.p; } notify() { this.r(true); } }; export class Lock { locked: boolean; constructor() { this.locked = false; } async acquire(): Promise<void> { let x = 1; while ( this.locked ) { await Timeout.set(Math.min(512, x)); x = x * 2; } this.locked = true; } release() { this.locked = false; } async runWith<X>(f: (() => Promise<X>)): Promise<X> { await this.acquire(); try { const r = await f(); this.release(); return r; } catch (e:any) { this.release(); throw e; } } } // Given a func that takes an optional arg, and a Maybe arg: // f: (arg?: X) => Y // arg: Maybe<X> // // You can apply the function like this: // f(...argMay) export type Some<T> = [T]; export type None = []; export type Maybe<T> = None | Some<T>; export function isNone<T>(m: Maybe<T>): m is None { return m.length === 0; } export function isSome<T>(m: Maybe<T>): m is Some<T> { return !isNone(m); } export const Some = <T>(m: T): Some<T> => [m]; export const None: None = []; export const retryLoop = async <T>(lab: any, f: (() => Promise<T>)) => { let retries = 0; while ( true ) { try { return await f(); } catch (e:any) { console.log(`retryLoop`, { lab, retries, e }); retries++; } } };
the_stack
import idb, {ObjectStore} from 'idb'; import rs from 'jsrsasign'; import {crypto} from '../../platform/crypto-web.js'; import {decode, encode} from './base64.js'; import {DeviceKey, Key, PrivateKey, PublicKey, RecoveryKey, SessionKey, WrappedKey} from './keys.js'; import {KeyGenerator, KeyStorage} from './manager.js'; import {TestableKey} from './testing/cryptotestutils.js'; const DEVICE_KEY_ALGORITHM = 'RSA-OAEP'; const X509_CERTIFICATE_ALGORITHM = 'RSA-OAEP'; const X509_CERTIFICATE_HASH_ALGORITHM = 'SHA-1'; const DEVICE_KEY_HASH_ALGORITHM = 'SHA-512'; const STORAGE_KEY_ALGORITHM = 'AES-GCM'; const ARCS_CRYPTO_STORE_NAME = 'ArcsKeyManagementStore'; const ARCS_CRYPTO_INDEXDB_NAME = 'ArcsKeyManagement'; /** * A CryptoKey or CryptoKeyPair that is capable of being stored in IndexDB key storage. */ class WebCryptoStorableKey<T extends CryptoKey | CryptoKeyPair> { protected key: T; constructor(key: T) { this.key = key; } algorithm(): string { return (this.key as CryptoKey).algorithm ? (this.key as CryptoKey).algorithm.name : (this.key as CryptoKeyPair).publicKey.algorithm.name; } storableKey(): T { return this.key; } } /** * An AES-GCM symmetric key in raw formatted encrypted using an RSA-OAEP public key. * We use a symmetrically derived key for the shared secret instead of just random numbers. There are two * reasons for this. * * First, WebCrypto treats CryptoKeys specially in that the material is can be setup to * never be exposed the application, so when we generate these secrets, we can hide them from JS by declaring * them non-extractable or usable for wrapping or encrypting only. * * Secondly, we eventually want to move off of RSA-OAEP and use ECDH, and ECDH doesn't support encryption or wrapping * of randomly generated bits. */ class WebCryptoWrappedKey implements WrappedKey { wrappedKeyData: Uint8Array; wrappedBy: PublicKey; constructor(wrappedKeyData: Uint8Array, wrappedBy: PublicKey) { this.wrappedKeyData = wrappedKeyData; this.wrappedBy = wrappedBy; } algorithm(): string { return this.wrappedBy.algorithm(); } public unwrap(privKey: PrivateKey): PromiseLike<SessionKey> { const webPrivKey = privKey as WebCryptoPrivateKey; return crypto.subtle.unwrapKey( 'raw', this.wrappedKeyData, webPrivKey.cryptoKey(), { name: privKey.algorithm() }, { name: STORAGE_KEY_ALGORITHM, }, true, ['encrypt', 'decrypt'] ).then(key => new WebCryptoSessionKey(key)); } rewrap(privKey: PrivateKey, pubKey: PublicKey): PromiseLike<WrappedKey> { return this.unwrap(privKey).then(skey => skey.disposeToWrappedKeyUsing(pubKey)); } export(): string { return encode(this.wrappedKeyData.buffer as ArrayBuffer); } fingerprint(): PromiseLike<string> { return Promise.resolve(encode(this.wrappedKeyData.buffer as ArrayBuffer)); } } /** * An implementation of PrivateKey using WebCrypto. */ class WebCryptoPrivateKey extends WebCryptoStorableKey<CryptoKey> implements PrivateKey { constructor(key: CryptoKey) { super(key); } cryptoKey() { return this.storableKey(); } } /** * An implementation of PublicKey using WebCrypto. */ class WebCryptoPublicKey extends WebCryptoStorableKey<CryptoKey> implements PublicKey { constructor(key: CryptoKey) { super(key); } cryptoKey() { return this.storableKey(); } static digest(str: string): PromiseLike<string> { return WebCryptoPublicKey.sha256(str); } static hex(buffer: ArrayBuffer): string { const hexCodes: string[] = []; const view = new DataView(buffer); for (let i = 0; i < view.byteLength; i += 4) { // Using getUint32 reduces the number of iterations needed (we process 4 bytes each time) const value = view.getUint32(i); // toString(16) will give the hex representation of the number without padding const stringValue = value.toString(16); // We use concatenation and slice for padding const padding = '00000000'; const paddedValue = (padding + stringValue).slice(-padding.length); hexCodes.push(paddedValue); } // Join all the hex strings into one return hexCodes.join(''); } static sha256(str: string): PromiseLike<string> { // We transform the string into an arraybuffer. const buffer = new Uint8Array(str.split('').map(x => x.charCodeAt(0))); return crypto.subtle.digest('SHA-256', buffer).then((hash) => WebCryptoPublicKey.hex(hash)); } fingerprint(): PromiseLike<string> { return crypto.subtle.exportKey('jwk', this.cryptoKey()) // Use the modulus 'n' as the fingerprint since 'e' is fixed .then(key => WebCryptoPublicKey.digest(key['n'])); } } class WebCryptoSessionKey implements SessionKey, TestableKey { // Visible/Used for testing only. decrypt(buffer: ArrayBuffer, iv: Uint8Array): PromiseLike<ArrayBuffer> { return crypto.subtle.decrypt({ name: this.algorithm(), iv, }, this.sessionKey, buffer); } // Visible/Used for testing only. encrypt(buffer: ArrayBuffer, iv: Uint8Array): PromiseLike<ArrayBuffer> { return crypto.subtle.encrypt( { name: this.algorithm(), iv }, this.sessionKey, buffer); } sessionKey: CryptoKey; constructor(sessionKey: CryptoKey) { this.sessionKey = sessionKey; } /** * This encodes the session key as a hexadecimal string. * TODO: this is a temporary hack for the provisioning App's QR-scanning procedure which will be * removed once the the key-blessing algorithm is implemented. */ export():PromiseLike<string> { return crypto.subtle.exportKey('raw', this.sessionKey).then((raw) => { const buf = new Uint8Array(raw); let res = ''; buf.forEach((x) => res += (x < 16 ? '0' : '') + x.toString(16)); return res; }); } algorithm(): string { return this.sessionKey.algorithm.name; } /** * Encrypts this session key with the private key, and makes a best effort to destroy the session * key material (presumably erased during garbage collection). * @param pkey */ disposeToWrappedKeyUsing(pkey: PublicKey): PromiseLike<WrappedKey> { try { const webPkey = pkey as WebCryptoPublicKey; const rawWrappedKey = crypto.subtle.wrapKey('raw', this.sessionKey, (pkey as WebCryptoPublicKey).cryptoKey(), { //these are the wrapping key's algorithm options name: webPkey.algorithm(), } ); return rawWrappedKey.then(rawKey => new WebCryptoWrappedKey(new Uint8Array(rawKey), pkey)); } finally { // Hopefully this frees the underlying key material this.sessionKey = null; } } isDisposed(): boolean { return this.sessionKey != null; } } class WebCryptoDeviceKey extends WebCryptoStorableKey<CryptoKeyPair> implements DeviceKey { algorithm(): string { return this.publicKey().algorithm(); } constructor(key: CryptoKeyPair) { super(key); } privateKey(): PrivateKey { return new WebCryptoPrivateKey(this.key.privateKey); } publicKey(): PublicKey { return new WebCryptoPublicKey(this.key.publicKey); } /** * Returns a fingerprint of the public key of the devicekey pair. */ fingerprint(): PromiseLike<string> { return this.publicKey().fingerprint(); } } /** * Implementation of KeyGenerator using WebCrypto interface. */ export class WebCryptoKeyGenerator implements KeyGenerator { generateWrappedStorageKey(deviceKey: DeviceKey): PromiseLike<WrappedKey> { const generatedKey: PromiseLike<CryptoKey> = crypto.subtle.generateKey({name: 'AES-GCM', length: 256}, true, ['encrypt', 'decrypt', 'wrapKey', 'unwrapKey']); return generatedKey.then(key => new WebCryptoSessionKey(key)) .then(skey => skey.disposeToWrappedKeyUsing(deviceKey.publicKey())); } static getInstance() { // TODO: may want to reuse instance in future return new WebCryptoKeyGenerator(); } generateAndStoreRecoveryKey(): PromiseLike<RecoveryKey> { // TODO: Implement throw new Error('Not implemented'); } generateDeviceKey(): PromiseLike<DeviceKey> { const generatedKey: PromiseLike<CryptoKeyPair> = crypto.subtle.generateKey( { hash: {name: DEVICE_KEY_HASH_ALGORITHM}, // TODO: Note, RSA-OAEP is deprecated, we should move to ECDH in the future, but it // doesn't use key-wrapping, instead it uses a different mechanism: key-derivation. name: DEVICE_KEY_ALGORITHM, modulusLength: 2048, // exponent is only allowed to be 3 or 65537 for RSA publicExponent: new Uint8Array([0x01, 0x00, 0x01]), }, // false means the key material is not visible to the application false, ['encrypt', 'decrypt', 'wrapKey', 'unwrapKey']); return generatedKey.then(key => new WebCryptoDeviceKey(key)); } /** * Decodes X509 PEM certificates, extracts their key material, and returns a PublicKey. * @param pemKey */ importKey(pemKey: string): PromiseLike<PublicKey> { const key = rs.KEYUTIL.getKey(pemKey); const jwk = rs.KEYUTIL.getJWKFromKey(key); return crypto.subtle.importKey('jwk', jwk as JsonWebKey, { name: X509_CERTIFICATE_ALGORITHM, hash: {name: X509_CERTIFICATE_HASH_ALGORITHM} }, true, ['encrypt', 'wrapKey']).then(ikey => new WebCryptoPublicKey(ikey)); } async importWrappedKey(wrappedKey: string, wrappedBy: PublicKey):Promise<WrappedKey> { const decodedKey = decode(wrappedKey); return Promise.resolve(new WebCryptoWrappedKey(decodedKey, wrappedBy)); } } interface KeyRecord { keyFingerPrint: string; key: CryptoKey|CryptoKeyPair|Uint8Array; wrappingKeyFingerprint?: string; } /** * The Web Crypto spec states that IndexDB may be used to store CryptoKey objects without ever exposing * key material to the application: https://www.w3.org/TR/WebCryptoAPI/#concepts-key-storage */ export class WebCryptoKeyIndexedDBStorage implements KeyStorage { async runOnStore<T>(fn: (store: ObjectStore<KeyRecord, IDBValidKey>) => PromiseLike<T>) { try { const db = await idb.open(ARCS_CRYPTO_INDEXDB_NAME, 1, upgradeDB => upgradeDB.createObjectStore(ARCS_CRYPTO_STORE_NAME, {keyPath: 'keyFingerPrint'})); const tx = db.transaction(ARCS_CRYPTO_STORE_NAME, 'readwrite'); const store = tx.objectStore<KeyRecord, IDBValidKey>(ARCS_CRYPTO_STORE_NAME); const result = await fn(store); await tx.complete; db.close(); return Promise.resolve(result); } catch (e) { return Promise.reject(e); } } async find(keyId: string): Promise<Key|null> { const result:KeyRecord = await this.runOnStore(async store => { return store.get(keyId); }); if (!result) { return Promise.resolve(null); } if (result.key && result.key['privateKey'] && result.key['publicKey']) { return Promise.resolve(new WebCryptoDeviceKey(result.key as CryptoKeyPair)); } else if (result.key instanceof CryptoKey) { return Promise.resolve(new WebCryptoPublicKey(result.key as CryptoKey)); } else if (result.key instanceof Uint8Array) { const wrappedBy = await this.find(result.wrappingKeyFingerprint) as PublicKey; return Promise.resolve(new WebCryptoWrappedKey(result.key as Uint8Array, wrappedBy)); } throw new Error('Unrecognized key type found in keystore.'); } async write(keyFingerPrint: string, key: DeviceKey|WrappedKey): Promise<string> { if (key instanceof WebCryptoStorableKey) { const skey = key as WebCryptoStorableKey<CryptoKey>; await this.runOnStore(async store => { return store.put({keyFingerPrint, key: skey.storableKey()}); }); return keyFingerPrint; } else if (key instanceof WebCryptoWrappedKey) { const wrappedKey = key as WebCryptoWrappedKey; const wrappingKeyFingerprint = await wrappedKey.wrappedBy.fingerprint(); await this.runOnStore(async store => { return store.put({keyFingerPrint, key: wrappedKey.wrappedKeyData, wrappingKeyFingerprint}); }); return keyFingerPrint; } throw new Error('Can\'t write key that isn\'t StorableKey or WrappedKey.'); } static getInstance() { // TODO: If IndexDB open/close is expensive, we may want to reuse instances. return new WebCryptoKeyIndexedDBStorage(); } }
the_stack
import { KeyedTemplate, Length, View } from "ui/core/view"; import { GridLayout } from "ui/layouts/grid-layout"; import * as utils from "utils/utils"; import { GridViewBase, colWidthProperty, itemTemplatesProperty, orientationProperty, paddingBottomProperty, paddingLeftProperty, paddingRightProperty, paddingTopProperty, rowHeightProperty, } from "./grid-view-common"; import { GridItemEventData, Orientation, ScrollEventData } from "."; export * from "./grid-view-common"; // Used to designate a view as as a DUMMY created view (to cope with angular view generation) const DUMMY = "DUMMY"; export class GridView extends GridViewBase { public nativeView: android.support.v7.widget.RecyclerView; public _realizedItems = new Map<android.view.View, View>(); public createNativeView() { initGridViewRecyclerView(); const recyclerView = new GridViewRecyclerView(this._context, new WeakRef(this)); initGridViewAdapter(); const adapter = new GridViewAdapter(new WeakRef(this)); adapter.setHasStableIds(true); recyclerView.setAdapter(adapter); (recyclerView as any).adapter = adapter; const orientation = this._getLayoutManagarOrientation(); const layoutManager = new android.support.v7.widget.GridLayoutManager(this._context, 1); recyclerView.setLayoutManager(layoutManager); layoutManager.setOrientation(orientation); (recyclerView as any).layoutManager = layoutManager; initGridViewScrollListener(); const scrollListener = new GridViewScrollListener(new WeakRef(this)); recyclerView.addOnScrollListener(scrollListener); (recyclerView as any).scrollListener = scrollListener; return recyclerView; } public initNativeView() { super.initNativeView(); const nativeView = this.nativeView as any; nativeView.adapter.owner = new WeakRef(this); nativeView.scrollListener.owner = new WeakRef(this); nativeView.owner = new WeakRef(this); colWidthProperty.coerce(this); rowHeightProperty.coerce(this); } public disposeNativeView() { // clear the cache this.eachChildView((view) => { view.parent._removeView(view); return true; }); this._realizedItems.clear(); const nativeView = this.nativeView as any; this.nativeView.removeOnScrollListener(nativeView.scrollListener); nativeView.scrollListener = null; nativeView.adapter = null; nativeView.layoutManager = null; super.disposeNativeView(); } get android(): android.support.v7.widget.RecyclerView { return this.nativeView; } get _childrenCount(): number { return this._realizedItems.size; } public [paddingTopProperty.getDefault](): number { return ((this.nativeView as any) as android.view.View).getPaddingTop(); } public [paddingTopProperty.setNative](value: Length) { this._setPadding({ top: this.effectivePaddingTop }); } public [paddingRightProperty.getDefault](): number { return ((this.nativeView as any) as android.view.View).getPaddingRight(); } public [paddingRightProperty.setNative](value: Length) { this._setPadding({ right: this.effectivePaddingRight }); } public [paddingBottomProperty.getDefault](): number { return ((this.nativeView as any) as android.view.View).getPaddingBottom(); } public [paddingBottomProperty.setNative](value: Length) { this._setPadding({ bottom: this.effectivePaddingBottom }); } public [paddingLeftProperty.getDefault](): number { return ((this.nativeView as any) as android.view.View).getPaddingLeft(); } public [paddingLeftProperty.setNative](value: Length) { this._setPadding({ left: this.effectivePaddingLeft }); } public [orientationProperty.getDefault](): Orientation { const layoutManager = this.nativeView.getLayoutManager() as android.support.v7.widget.GridLayoutManager; if (layoutManager.getOrientation() === android.support.v7.widget.LinearLayoutManager.HORIZONTAL) { return "horizontal"; } return "vertical"; } public [orientationProperty.setNative](value: Orientation) { const layoutManager = this.nativeView.getLayoutManager() as android.support.v7.widget.GridLayoutManager; if (value === "horizontal") { layoutManager.setOrientation(android.support.v7.widget.LinearLayoutManager.HORIZONTAL); } else { layoutManager.setOrientation(android.support.v7.widget.LinearLayoutManager.VERTICAL); } } public [itemTemplatesProperty.getDefault](): KeyedTemplate[] { return null; } public [itemTemplatesProperty.setNative](value: KeyedTemplate[]) { this._itemTemplatesInternal = new Array<KeyedTemplate>(this._defaultTemplate); if (value) { this._itemTemplatesInternal = this._itemTemplatesInternal.concat(value); } this.nativeViewProtected.setAdapter(new GridViewAdapter(new WeakRef(this))); this.refresh(); } public eachChildView(callback: (child: View) => boolean): void { this._realizedItems.forEach((view, key) => { callback(view); }); } public onLayout(left: number, top: number, right: number, bottom: number) { super.onLayout(left, top, right, bottom); this.refresh(); } public refresh() { if (!this.nativeView || !this.nativeView.getAdapter()) { return; } const layoutManager = this.nativeView.getLayoutManager() as android.support.v7.widget.GridLayoutManager; let spanCount: number; if (this.orientation === "horizontal") { spanCount = Math.max(Math.floor(this._innerHeight / this._effectiveRowHeight), 1) || 1; } else { spanCount = Math.max(Math.floor(this._innerWidth / this._effectiveColWidth), 1) || 1; } layoutManager.setSpanCount(spanCount); this.nativeView.getAdapter().notifyDataSetChanged(); } public scrollToIndex(index: number, animated: boolean = true) { if (animated) { this.nativeView.smoothScrollToPosition(index); } else { this.nativeView.scrollToPosition(index); } } private _setPadding(newPadding: { top?: number, right?: number, bottom?: number, left?: number }) { const nativeView: android.view.View = this.nativeView as any; const padding = { top: nativeView.getPaddingTop(), right: nativeView.getPaddingRight(), bottom: nativeView.getPaddingBottom(), left: nativeView.getPaddingLeft() }; // tslint:disable-next-line:prefer-object-spread const newValue = Object.assign(padding, newPadding); nativeView.setPadding(newValue.left, newValue.top, newValue.right, newValue.bottom); } private _getLayoutManagarOrientation() { let orientation = android.support.v7.widget.LinearLayoutManager.VERTICAL; if (this.orientation === "horizontal") { orientation = android.support.v7.widget.LinearLayoutManager.HORIZONTAL; } return orientation; } } // Snapshot friendly GridViewScrollListener interface GridViewScrollListener extends android.support.v7.widget.RecyclerView.OnScrollListener { // tslint:disable-next-line:no-misused-new new(owner: WeakRef<GridView>): GridViewScrollListener; } let GridViewScrollListener: GridViewScrollListener; function initGridViewScrollListener() { if (GridViewScrollListener) { return; } class GridViewScrollListenerImpl extends android.support.v7.widget.RecyclerView.OnScrollListener { constructor(private owner: WeakRef<GridView>) { super(); return global.__native(this); } public onScrolled(view: android.support.v7.widget.RecyclerView, dx: number, dy: number) { const owner: GridView = this.owner.get(); if (!owner) { return; } owner.notify<ScrollEventData>({ eventName: GridViewBase.scrollEvent, object: owner, scrollX: dx, scrollY: dy, }); const lastVisibleItemPos = (view.getLayoutManager() as android.support.v7.widget.GridLayoutManager).findLastCompletelyVisibleItemPosition(); if (owner && owner.items) { const itemCount = owner.items.length - 1; if (lastVisibleItemPos === itemCount) { owner.notify({ eventName: GridViewBase.loadMoreItemsEvent, object: owner }); } } } public onScrollStateChanged(view: android.support.v7.widget.RecyclerView, newState: number) { // Not Needed } } GridViewScrollListener = GridViewScrollListenerImpl as any; } // END snapshot friendly GridViewScrollListener // Snapshot friendly GridViewAdapter interface GridViewAdapter extends android.support.v7.widget.RecyclerView.Adapter { // tslint:disable-next-line:no-misused-new new(owner: WeakRef<GridView>): GridViewAdapter; } let GridViewAdapter: GridViewAdapter; function initGridViewAdapter() { if (GridViewAdapter) { return; } @Interfaces([android.view.View.OnClickListener]) class GridViewCellHolder extends android.support.v7.widget.RecyclerView.ViewHolder implements android.view.View.OnClickListener { constructor(private owner: WeakRef<View>, private gridView: WeakRef<GridView>) { super(owner.get().android); const nativeThis = global.__native(this); const nativeView = owner.get().android as android.view.View; nativeView.setOnClickListener(nativeThis); return nativeThis; } get view(): View { return this.owner ? this.owner.get() : null; } public onClick(v: android.view.View) { const gridView = this.gridView.get(); gridView.notify<GridItemEventData>({ eventName: GridViewBase.itemTapEvent, object: gridView, index: this.getAdapterPosition(), view: this.view, android: v, ios: undefined, }); } } class GridViewAdapterImpl extends android.support.v7.widget.RecyclerView.Adapter { constructor(private owner: WeakRef<GridView>) { super(); return global.__native(this); } public getItemCount() { const owner = this.owner.get(); return owner.items ? owner.items.length : 0; } public getItem(i: number) { const owner = this.owner.get(); if (owner && owner.items && i < owner.items.length) { return owner._getDataItem(i); } return null; } public getItemId(i: number) { const owner = this.owner.get(); const item = this.getItem(i); let id = i; if (this.owner && item && owner.items) { id = owner.itemIdGenerator(item, i, owner.items); } return long(id); } public getItemViewType(index: number) { const owner = this.owner.get(); const template = owner._getItemTemplate(index); const itemViewType = owner._itemTemplatesInternal.indexOf(template); return itemViewType; } public onCreateViewHolder(parent: android.view.ViewGroup, viewType: number): android.support.v7.widget.RecyclerView.ViewHolder { const owner = this.owner.get(); const template = owner._itemTemplatesInternal[viewType]; let view = template.createView(); if (!view) { view = new GridLayout(); view[DUMMY] = true; } owner._addView(view); owner._realizedItems.set(view.android, view); return new GridViewCellHolder(new WeakRef(view), new WeakRef(owner)); } public onBindViewHolder(vh: GridViewCellHolder, index: number) { const owner = this.owner.get(); const args: GridItemEventData = { eventName: GridViewBase.itemLoadingEvent, object: owner, index, // This is needed as the angular view generation with a single template is done in the event handler // for this event (????). That;s why if we created above an empty StackLayout, we must send `null` // sp that the angular handler initializes the correct view. view: vh.view[DUMMY] ? null : vh.view, android: vh, ios: undefined, }; owner.notify(args); if (vh.view[DUMMY]) { (vh.view as GridLayout).addChild(args.view); vh.view[DUMMY] = undefined; } if (owner.orientation === "horizontal") { vh.view.width = utils.layout.toDeviceIndependentPixels(owner._effectiveColWidth); } else { vh.view.height = utils.layout.toDeviceIndependentPixels(owner._effectiveRowHeight); } owner._prepareItem(vh.view, index); } } GridViewAdapter = GridViewAdapterImpl as any; } // END Snapshot friendly GridViewAdapter // Snapshot friendly GridViewRecyclerView interface GridViewRecyclerView extends android.support.v7.widget.RecyclerView { // tslint:disable-next-line:no-misused-new new(context: any, owner: WeakRef<GridView>): GridViewRecyclerView; } let GridViewRecyclerView: GridViewRecyclerView; function initGridViewRecyclerView() { if (GridViewRecyclerView) { return; } class GridViewRecyclerViewImpl extends android.support.v7.widget.RecyclerView { constructor(context: android.content.Context, private owner: WeakRef<GridView>) { super(context); return global.__native(this); } public onLayout(changed: boolean, l: number, t: number, r: number, b: number) { if (changed) { const owner = this.owner.get(); owner.onLayout(l, t, r, b); } super.onLayout(changed, l, t, r, b); } } GridViewRecyclerView = GridViewRecyclerViewImpl as any; } // END Snapshot friendly GridViewRecyclerView
the_stack
import { loadScript } from "../src/index"; import type { PayPalNamespace } from "."; // eslint-disable-next-line @typescript-eslint/no-unused-vars const loadScriptBasicPromise: Promise<PayPalNamespace | null> = loadScript({ "client-id": "test", }); loadScript({ "client-id": "test", currency: "USD", "data-page-type": "checkout", "disable-funding": "card", }); loadScript({ "client-id": "test" }) .then((paypal) => { if (!(paypal && paypal.Buttons)) return; paypal.Buttons().render("#container"); paypal.Buttons().render(document.createElement("div")); // window.paypal also works window.paypal.Buttons().render("#container"); // minimal createOrder and onApprove payload paypal.Buttons({ createOrder: (data, actions) => { return actions.order.create({ purchase_units: [ { amount: { value: "88.44", }, }, ], }); }, onApprove: function (data, actions) { return actions.order.capture().then((details) => { console.log(details.payer.name.given_name); }); }, }); // authorize a payment // https://developer.paypal.com/docs/business/checkout/add-capabilities/authorization/ paypal.Buttons({ createOrder: (data, actions) => { return actions.order.create({ intent: "AUTHORIZE", purchase_units: [ { amount: { currency_code: "USD", value: "100.00", }, }, ], }); }, onApprove: (data, actions) => { return actions.order.authorize().then((authorization) => { const authorizationID = authorization.purchase_units[0].payments .authorizations[0].id; // call your server to validate and capture the transaction // eslint-disable-next-line compat/compat return fetch("/paypal-transaction-complete", { method: "post", headers: { "content-type": "application/json", }, body: JSON.stringify({ orderID: data.orderID, authorizationID: authorizationID, }), }).then((response) => response.json()); }); }, }); // server-side integration // https://developer.paypal.com/demo/checkout/#/pattern/server paypal .Buttons({ createOrder: () => { // eslint-disable-next-line compat/compat return fetch("/demo/checkout/api/paypal/order/create/", { method: "post", }) .then((res) => res.json()) .then((orderData) => orderData.id); }, onApprove: (data, actions) => { // eslint-disable-next-line compat/compat return fetch( `/demo/checkout/api/paypal/order/${data.orderID}/capture/`, { method: "post", } ) .then((res) => res.json()) .then((orderData) => { const errorDetail = Array.isArray(orderData.details) && orderData.details[0]; if ( errorDetail && errorDetail.issue === "INSTRUMENT_DECLINED" ) { return actions.restart(); } if (errorDetail) { const msg = "Sorry, your transaction could not be processed."; return alert(msg); } const transaction = orderData.purchase_units[0].payments .captures[0]; alert( `Transaction ${transaction.status}: ${transaction.id} \n\nSee console for all available details` ); }); }, }) .render("#paypal-button-container"); // createOrder for partners // https://developer.paypal.com/docs/platforms/checkout/set-up-payments#create-order paypal.Buttons({ fundingSource: "paypal", createOrder: (data, actions) => { return actions.order.create({ intent: "CAPTURE", purchase_units: [ { amount: { currency_code: "USD", value: "100.00", }, payee: { email_address: "seller@example.com", }, payment_instruction: { disbursement_mode: "INSTANT", platform_fees: [ { amount: { currency_code: "USD", value: "25.00", }, }, ], }, }, ], }); }, }); // donations paypal.Buttons({ fundingSource: "paypal", style: { label: "donate" }, createOrder: (data, actions) => { return actions.order.create({ purchase_units: [ { amount: { value: "2.00", breakdown: { item_total: { currency_code: "USD", value: "2.00", }, }, }, items: [ { name: "donation-example", quantity: "1", unit_amount: { currency_code: "USD", value: "2.00", }, category: "DONATION", }, ], }, ], }); }, }); // createSubscription paypal.Buttons({ style: { label: "subscribe" }, createSubscription: (data, actions) => { return actions.subscription.create({ plan_id: "P-3RX123456M3469222L5IFM4I", }); }, }); // validation with onInit and onClick // https://developer.paypal.com/docs/checkout/integration-features/validation/ paypal.Buttons({ onInit: (data, actions) => { actions.disable(); interface HandleChangeInterface extends Event { target: HTMLInputElement; } document .querySelector("#check") .addEventListener( "change", (event: HandleChangeInterface) => { if (event.target.checked) { actions.enable(); } else { actions.disable(); } } ); }, onClick: () => { if ( !document.querySelector<HTMLInputElement>("#check").checked ) { document.querySelector("#error").classList.remove("hidden"); } }, }); paypal .Buttons({ onClick: (data, actions) => { // eslint-disable-next-line compat/compat return fetch("/my-api/validate", { method: "post", headers: { "content-type": "application/json", }, }) .then((res) => res.json()) .then((data) => { if (data.validationError) { document .querySelector("#error") .classList.remove("hidden"); return actions.reject(); } else { return actions.resolve(); } }); }, }) .render("#paypal-button-container"); // standalone button integration // https://developer.paypal.com/docs/business/checkout/configure-payments/standalone-buttons/#2-render-all-eligible-buttons paypal.getFundingSources().forEach((fundingSource) => { const button = paypal.Buttons({ fundingSource: fundingSource, }); if (button.isEligible()) { button.render("#paypal-button-container"); } }); // funding eligibility // https://developer.paypal.com/docs/business/javascript-sdk/javascript-sdk-reference/#funding-eligibility paypal.rememberFunding([paypal.FUNDING.VENMO]); paypal.isFundingEligible(paypal.FUNDING.VENMO); }) .catch((err) => { console.error(err); }); loadScript({ "client-id": "test", "data-namespace": "customName" }).then( (customObject) => { customObject.Buttons(); // example showing how to use the types with a custom namespace off window // eslint-disable-next-line @typescript-eslint/no-explicit-any const customObjectFromWindow = (window as any) .customName as PayPalNamespace; customObjectFromWindow.Buttons(); } ); // hosted-fields // https://developer.paypal.com/docs/business/checkout/advanced-card-payments/ loadScript({ "client-id": "test", components: "buttons,hosted-fields", "data-client-token": "123456789", }).then((paypal) => { if (paypal.HostedFields.isEligible() === false) return; paypal.HostedFields.render({ createOrder: () => { // Call your server to create the order return Promise.resolve("7632736476738"); }, styles: { ".valid": { color: "green", }, ".invalid": { color: "red", }, }, fields: { number: { selector: "#card-number", placeholder: "4111 1111 1111 1111", }, cvv: { selector: "#cvv", placeholder: "123", }, expirationDate: { selector: "#expiration-date", placeholder: "MM/YY", }, }, }).then((cardFields) => { document .querySelector("#card-form") .addEventListener("submit", (event) => { event.preventDefault(); cardFields.submit({}); }); }); });
the_stack
import '@cds/core/alert/register.js'; import '@cds/core/icon/register.js'; import '@cds/core/tree-view/register.js'; import { CdsTreeItem } from '@cds/core/tree-view'; import { html } from 'lit'; export default { title: 'Stories/Tree View', component: 'cds-tree', parameters: { options: { showPanel: true }, design: { type: 'figma', url: 'https://www.figma.com/file/v2mkhzKQdhECXOx8BElgdA/Clarity-UI-Library---light-2.2.0?node-id=51%3A668', }, }, }; // export function API(args: any) { // return html` // <cds-tree ...="${spreadProps(getElementStorybookArgs(args))}"> // <cds-tree-item expanded> // 1 // <cds-tree-item> // 1-1 // <cds-tree-item> // 1-1-1 // </cds-tree-item> // <cds-tree-item> // 1-1-2 // </cds-tree-item> // </cds-tree-item> // <cds-tree-item> // 1-2 // </cds-tree-item> // <cds-tree-item> // 1-3 // </cds-tree-item> // </cds-tree-item> // <cds-tree-item> // 2 // <cds-tree-item> // 2-1 // </cds-tree-item> // <cds-tree-item> // 2-2 // </cds-tree-item> // </cds-tree-item> // <cds-tree-item>3</cds-tree-item> // </cds-tree> // `; // } /** @website */ export function basic() { return html` <cds-tree> <cds-tree-item expanded> David Wallace (CFO) <cds-tree-item expanded> Michael Scott (Regional Manager) <cds-tree-item>Dwight K. Schrute (Assistant to the Regional Manager)</cds-tree-item> <cds-tree-item> Jim Halpert (Head of Sales) <cds-tree-item>Andy Bernard</cds-tree-item> <cds-tree-item>Stanley Hudson</cds-tree-item> <cds-tree-item>Phyllis Vance</cds-tree-item> <cds-tree-item>Todd Packer</cds-tree-item> </cds-tree-item> <cds-tree-item> Angela Martin (Head of Accounting) <cds-tree-item>Kevin Malone</cds-tree-item> <cds-tree-item>Oscar Martinez</cds-tree-item> </cds-tree-item> <cds-tree-item> Kelly Kapoor (Head of Customer Service) <cds-tree-item>Ryan Howard (Temp)</cds-tree-item> </cds-tree-item> <cds-tree-item> Creed Bratton (Quality Assurance) </cds-tree-item> <cds-tree-item> Meredith Palmer (Supplier Relations) </cds-tree-item> <cds-tree-item> Toby Flenderson (Human Resources) </cds-tree-item> <cds-tree-item> Pam Beesly (Reception) </cds-tree-item> <cds-tree-item> Darryl Philbin (Warehouse) </cds-tree-item> </cds-tree-item> </cds-tree-item> </cds-tree> `; } export function navigation() { return html` <cds-tree> <cds-tree-item expanded> The Beatles <cds-tree-item selected> <a cds-text="link" href="https://en.wikipedia.org/wiki/Abbey_Road">Abbey Road</a> </cds-tree-item> <cds-tree-item> <a cds-text="link" href="https://en.wikipedia.org/wiki/Revolver_(Beatles_album)">Revolver</a> </cds-tree-item> <cds-tree-item> <a cds-text="link" href="https://en.wikipedia.org/wiki/Rubber_Soul">Rubber Soul</a> </cds-tree-item> </cds-tree-item> </cds-tree> `; } /** @website */ export function multiSelect() { return html` <cds-tree multi-select> <cds-tree-item expanded selected> 1 <cds-tree-item disabled> 1-1 <cds-tree-item> 1-1-1 </cds-tree-item> <cds-tree-item> 1-1-2 </cds-tree-item> </cds-tree-item> <cds-tree-item selected> 1-2 </cds-tree-item> <cds-tree-item> 1-3 </cds-tree-item> </cds-tree-item> <cds-tree-item disabled selected> 2 <cds-tree-item> 2-1 </cds-tree-item> <cds-tree-item> 2-2 </cds-tree-item> </cds-tree-item> <cds-tree-item>3</cds-tree-item> </cds-tree> `; } export const async = () => { function renderTreeInfo(message: string) { document.getElementById('loadingInfo').textContent = message; } function onExpandedChange(e: any, prefix: string) { const parentNode = e.target as CdsTreeItem; parentNode.expanded = !parentNode.expanded; parentNode.loading = true; if (parentNode.expanded) { renderTreeInfo('loading children for item ' + prefix); setTimeout(() => { parentNode.loading = false; renderTreeInfo('Finished loading children for item ' + prefix); parentNode.innerHTML = ` ${prefix} <cds-tree-item> ${prefix}-1 </cds-tree-item> <cds-tree-item> ${prefix}-2 </cds-tree-item> <cds-tree-item> ${prefix}-3 </cds-tree-item> `; }, 3000); } else { parentNode.loading = false; parentNode.innerHTML = `${prefix}`; } } // I have set the aria-live attribute to assertive below because there's a VO bug that // announces it twice in polite mode if inside an iframe (which all storybook stories are). // In reality applications should be using polite in most cases. Below code snippet is just included // as an example and not part of the component. return html` <div role="region" id="treeInfo" aria-live="assertive" cds-layout="display:screen-reader-only"> <p id="loadingInfo"></p> </div> <cds-tree> <cds-tree-item expandable @expandedChange="${(e: any) => onExpandedChange(e, '1')}"> 1 </cds-tree-item> <cds-tree-item expandable @expandedChange="${(e: any) => onExpandedChange(e, '2')}"> 2 </cds-tree-item> </cds-tree> `; }; export const recursive = () => { const level1 = 3; const level2 = 3; const level3 = 3; const treeData: any = []; for (let i = 1; i <= level1; i++) { const children = []; for (let j = 1; j <= level2; j++) { const grandchildren = []; for (let k = 1; k <= level3; k++) { grandchildren.push({ display: `${i}-${j}-${k}`, children: [], }); } children.push({ display: `${i}-${j}`, children: grandchildren, }); } treeData.push({ display: i, children: children, }); } const recursiveTemplate = (data: any) => { return html` <cds-tree-item expanded> ${data.display} ${data.children.map((i: any) => recursiveTemplate(i))} </cds-tree-item> `; }; return html` <cds-tree multi-select> ${treeData.map((node: any) => html` ${recursiveTemplate(node)} `)} </cds-tree> `; }; export const interactive = () => { const onExpandedChange = { // handleEvent method is required. handleEvent(e: any) { const myTreeItem = e.target as any; myTreeItem.expanded = e.detail; }, // event listener objects can also define zero or more of the event // listener options: capture, passive, and once. capture: true, }; function updateBasedOnChildren(node: any) { if (node && node.tagName === 'CDS-TREE-ITEM') { let oneSelected = false; let oneUnselected = false; node.indeterminate = false; Array.from(node.children).forEach((c: any) => { if (c.indeterminate) { node.indeterminate = true; } if (c.selected) { oneSelected = true; if (oneUnselected) { node.indeterminate = true; } } if (!c.selected) { oneUnselected = true; if (oneSelected) { node.indeterminate = true; } } }); if (!oneSelected) { node.selected = false; } else if (!oneUnselected) { node.selected = true; } else { node.selected = false; } updateBasedOnChildren(node.parentNode); } } function updateChildren(node: any) { Array.from(node.children).forEach((c: any) => { c.indeterminate = false; c.selected = node.selected; updateChildren(c); }); } const onSelectedChange = { // handleEvent method is required. handleEvent(e: any) { const currentNode = e.target as any; if (!currentNode.disabled) { currentNode.selected = e.detail; currentNode.indeterminate = false; // update children's selected/indeterminate state updateChildren(currentNode); // update ancestors' selected/indeterminate state updateBasedOnChildren(currentNode.parentNode); } }, // event listener objects can also define zero or more of the event // listener options: capture, passive, and once. capture: true, }; return html` <a href="#" cds-text="link">link</a> <cds-tree multi-select @expandedChange="${onExpandedChange}" @selectedChange="${onSelectedChange}"> <cds-tree-item indeterminate expanded> 1 <cds-tree-item> 1-1 <cds-tree-item> 1-1-1 </cds-tree-item> <cds-tree-item> 1-1-2 </cds-tree-item> </cds-tree-item> <cds-tree-item selected> 1-2 </cds-tree-item> <cds-tree-item> 1-3 </cds-tree-item> </cds-tree-item> <cds-tree-item indeterminate> 2 <cds-tree-item selected> 2-1 </cds-tree-item> <cds-tree-item> 2-2 </cds-tree-item> </cds-tree-item> <cds-tree-item disabled>3</cds-tree-item> <cds-tree-item selected>4</cds-tree-item> </cds-tree> <a href="#" cds-text="link">link</a> `; }; /** @website */ export function customStyles() { return html` <style> .app-custom cds-tree-item { --focus-width: var(--cds-alias-object-border-width-200); --icon-transform: rotate(45deg); --cds-alias-object-interaction-background-selected: var(--cds-global-color-jade-50); --cds-alias-object-interaction-background-hover: var(--cds-global-color-jade-50); --cds-alias-object-interaction-background-active: var(--cds-global-color-jade-100); --cds-alias-object-interaction-background-highlight: var(--cds-global-color-jade-700); } .app-custom cds-tree-item[expanded] { --icon-transform: rotate(135deg); } .app-custom cds-tree-item::part(checkbox) { --color: var(--cds-global-color-jade-700); --check-color: var(--cds-global-color-jade-50); } .app-custom cds-tree-item::part(expand-collapse-icon) { --color: var(--cds-global-color-jade-700); } </style> <div> <cds-tree class="app-custom" multi-select> <cds-tree-item expanded selected> 1 <cds-tree-item disabled> 1-1 <cds-tree-item> 1-1-1 </cds-tree-item> <cds-tree-item> 1-1-2 </cds-tree-item> </cds-tree-item> <cds-tree-item selected> 1-2 </cds-tree-item> <cds-tree-item> 1-3 </cds-tree-item> </cds-tree-item> <cds-tree-item disabled selected> 2 <cds-tree-item> 2-1 </cds-tree-item> <cds-tree-item> 2-2 </cds-tree-item> </cds-tree-item> <cds-tree-item>3</cds-tree-item> </cds-tree> </div> `; } /** @website */ export function darkTheme() { return html` <div cds-theme="dark"> <cds-tree multi-select> <cds-tree-item expanded selected> 1 <cds-tree-item disabled> 1-1 <cds-tree-item> 1-1-1 </cds-tree-item> <cds-tree-item> 1-1-2 </cds-tree-item> </cds-tree-item> <cds-tree-item selected> 1-2 </cds-tree-item> <cds-tree-item> 1-3 </cds-tree-item> </cds-tree-item> <cds-tree-item disabled selected> 2 <cds-tree-item> 2-1 </cds-tree-item> <cds-tree-item> 2-2 </cds-tree-item> </cds-tree-item> <cds-tree-item>3</cds-tree-item> </cds-tree> </div> `; }
the_stack
/** DynamicsCrm.DevKit for d.ts */ declare namespace DevKit { type Guid = {}; namespace Controls { interface IControl { /** * Sets a function to be called when the OnChange event occurs * @param callback * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/addonchange */ AddOnChange(callback: (executionContext: any) => void): void; /** * Causes the OnChange event to occur on the attribute so that any script associated to that event can execute * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/fireonchange */ FireOnChange(): void; /** * Sets the focus on the control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/setfocus */ Focus(): void; /** * Removes a function from the OnChange event hander for an attribute * @param callback Specifies the function to be removed from the OnChange event * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/removeonchange */ RemoveOnChange(callback: (executionContext: any) => void): void; /** * Displays an error or recommendation notification for a control, and lets you specify actions to execute based on the notification. When you specify an error type of notification, a red "X" icon appears next to the control. When you specify a recommendation type of notification, an "i" icon appears next to the control. On Dynamics 365 for Customer Engagement apps mobile clients, tapping on the icon will display the message, and let you perform the configured action by clicking the Apply button or dismiss the message * @param notification The notification to add * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/addnotification */ AddNotification(notification: DevKit.FieldNotification): void; /** * Remove a message already displayed for a control * @param uniqueId The ID to use to clear a specific message that was set using setNotification or addNotification. If the uniqueId parameter isn’t specified, the currently displayed notification will be cleared * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/clearnotification */ ClearNotification(uniqueId: string): boolean; /** * Displays an error message for the control to indicate that data isn’t valid. When this method is used, a red "X" icon appears next to the control. On Dynamics 365 for Customer Engagement apps mobile clients, tapping on the icon will display the message * @param message The message to display * @param uniqueId The ID to use to clear this message when using the clearNotification method * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/setnotification */ SetNotification(message: string, uniqueId?: string): boolean; /** * Sets a value for an attribute to determine whether it is valid or invalid with a message. * @param valid Specify false to set the attribute value to invalid and true to set the value to valid * @param message The message to display * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/setisvalid */ SetIsValid(valid: boolean, message: string): void /** * Returns the attribute that the control is bound to. Controls that aren’t bound to an attribute (subgrid, web resource, and IFRAME) don’t have this method. An error will be thrown if you attempt to use this method on one of these controls * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getattribute * */ readonly Attribute: any /** * Returns a string value that represents the type of control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getcontroltype */ readonly ControlType: OptionSet.FieldControlType; /** * Returns a string value that represents the type of attribute * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getattributetype */ readonly AttributeType: OptionSet.FieldAttributeType; /** * Returns a string value that represents formatting options for the attribute * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getformat */ readonly Format: OptionSet.FieldFormat; /** * Returns a Boolean value indicating if there are unsaved changes to the attribute value * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getisdirty */ readonly IsDirty: boolean; /** * Returns a string representing the logical name of the attribute * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getname */ readonly AttributeName: string; /** * Returns the name assigned to the control. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getname */ readonly ControlName: string; /** * Returns the formContext.data.entity object that is the parent to all attributes * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getparent */ readonly AttributeParent: any; /** * Returns a boolean value to indicate whether the value of an attribute is valid * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/isvalid */ readonly IsValid: boolean; /** * Returns a reference to the section object that contains the control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getparent */ readonly ControlParent: any; /** * Returns an object with three Boolean properties corresponding to privileges indicating if the user can create, read or update data values for an attribute. This function is intended for use when Field Level Security modifies a user’s privileges for a particular attribute * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getuserprivilege */ readonly UserPrivilege: DevKit.FieldUserPrivilege; /** * Get/Set a value indicating whether a value for the attribute is required or recommended * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getrequiredlevel * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/setrequiredlevel */ RequiredLevel: OptionSet.FieldRequiredLevel; /** * Get/Set a indicating when data from the attribute will be submitted when the record is saved * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getsubmitmode * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/setsubmitmode */ SubmitMode: OptionSet.FieldSubmitMode; /** * Get/Set whether the control is disabled * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getdisabled * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/setdisabled */ Disabled: boolean; /** * Get/Set the label for the control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getlabel * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/setlabel */ Label: string; /** * Get/Set a value that indicates whether the control is currently visible * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getvisible * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/setvisible */ Visible: boolean; } interface IControlSelectBase extends IControl { /** * Returns a value that represents the value set for a Boolean, OptionSet or MultiOptionSet attribute when the form is opened * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getinitialvalue */ readonly InitialValue: number; } interface IProcess { /** * Adds a function as an event handler for the OnPreProcessStatusChange event so that it will be called before the business process flow status changes * @param callback The function to be executed when the business process flow status changes. The function will be added to the start of the event handler pipeline. The execution context is automatically passed as the first parameter to the function. See Execution context for more information * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/eventhandlers/addonpreprocessstatuschange */ AddOnPreProcessStatusChange(callback: (executionContext: any) => void): void; /** * Removes an event handler from the OnPreProcessStatusChange event * @param callback The function to be removed from the OnPreProcessStatusChange event * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/eventhandlers/removeonpreprocessstatuschange */ RemoveOnPreProcessStatusChange(callback: () => void): void; /** * Adds a function as an event handler for the OnPreStageChange event so that it will be called before the business process flow stage changes * @param callback The function that runs before the business process flow stage changes. The function will be added to the start of the event handler pipeline. The execution context is automatically passed as the first parameter to the function. See Execution context for more information. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/eventhandlers/addonprestagechange */ AddOnPreStageChange(callback: (executionContext: any) => void): void; /** * Removes an event handler from the OnPreStageChange event * @param callback The function to be removed from the OnPreStageChange event * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/eventhandlers/removeonprestagechange */ RemoveOnPreStageChange(callback: () => void): void; /** * Adds a function as an event handler for the OnProcessStatusChange event so that it will be called when the business process flow status changes * @param callback The function to be executed when the business process flow status changes. The function will be added to the bottom of the event handler pipeline. The execution context is automatically passed as the first parameter to the function. See Execution context for more information * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/eventhandlers/addonprocessstatuschange */ AddOnProcessStatusChange(callback: (executionContext: any) => void): void; /** * Removes an event handler from the OnProcessStatusChange event * @param callback The function to be removed from the OnProcessStatusChange event * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/eventhandlers/removeonprocessstatuschange */ RemoveOnProcessStatusChange(callback: () => void): void; /** * Adds a function as an event handler for the OnStageChange event so that it will be called when the business process flow stage changes * @param callback TThe function to be executed when the business process flow stage changes. The function will be added to the bottom of the event handler pipeline. The execution context is automatically passed as the first parameter to the function. See Execution context for more information * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/eventhandlers/addonstagechange */ AddOnStageChange(callback: (executionContext: any) => void): void; /** * Removes an event handler from the OnStageChange event * @param callback The function to be removed from the OnStageChange event * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/eventhandlers/removeonstagechange */ RemoveOnStageChange(callback: () => void): void; /** * Adds a function as an event handler for the OnStageSelected event so that it will be called when a business process flow stage is selected * @param callback The function to be executed when the business process flow stage is selected. The function will be added to the bottom of the event handler pipeline. The execution context is automatically passed as the first parameter to the function. See Execution context for more information * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/eventhandlers/addonstageselected */ AddOnStageSelected(callback: (executionContext: any) => void): void; /** * Removes an event handler from the OnStageSelected event * @param callback The function to be removed from the OnStageSelected event * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/eventhandlers/removeonstageselected */ RemoveOnStageSelected(callback: () => void): void; /** * Asynchronously retrieves the business process flows enabled for an entity that the current user can switch to * @param callback The callback function must accept a parameter that contains an object with dictionary properties where the name of the property is the Id of the business process flow and the value of the property is the name of the business process flow. The enabled processes are filtered according to the user’s privileges. The list of enabled processes is the same ones a user can see in the UI if they want to change the process manually * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/getenabledprocesses */ EnabledProcesses(callback: (processes: Array<DevKit.ProcessEnabled>) => void): void; /** * Returns all the process instances for the entity record that the calling user has access to. * @param callback The callback function is passed an object with the following attributes and their corresponding values as the key:value pair. All returned values are of string type except for CreatedOnDate * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/getprocessinstances */ ProcessInstances(callback: (processes: Array<DevKit.ProcessInstance>) => void): void; /** * Sets a completed stage as the active stage * @param stageId The ID of the completed stage for the entity to make the active stage * @param callback A function to call when the operation is complete. This callback function is passed one of the following string values to indicate the status of the operation * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/activestage/setactivestage */ SetActiveStage(stageId: string, callback: (result: "success" | "invalid" | "unreachable" | "dirtyForm") => void): void; /** * Progresses to the next stage. You can also move to a next stage in a different entity * @param callback A function to call when the operation is complete. This callback function is passed one of the following string values to indicate the status of the operation * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/navigation/movenext */ MoveNext(callback: (result: "success" | "crossEntity" | "end" | "invalid" | "dirtyForm") => void): void; /** * Moves to the previous stage. You can also move to a previous stage in a different entity * @param callback A function to call when the operation is complete. This callback function is passed one of the following string values to indicate the status of the operation * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/navigation/moveprevious */ MovePrevious(callback: (result: "success" | "crossEntity" | "beginning" | "invalid" | "dirtyForm") => void): void; /** * Sets a process instance as the active instance * @param processInstanceId The Id of the process instance to set as the active instance * @param callback A function to call when the operation is complete * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/setactiveprocessinstance */ SetActiveProcessInstance(processInstanceId: DevKit.Guid, callback: (result: "success" | "invalid") => void): void; /** * Sets a Process as the active process. If there is an active instance of the process, the entity record is loaded with the process instance ID. If there is no active instance of the process, a new process instance is created and the entity record is loaded with the process instance ID. If there are multiple instances of the current process, the record is loaded with the first instance of the active process as per the defaulting logic, that is the most recently used process instance per user * @param processId The Id of the process to set as the active process * @param callback A function to call when the operation is complete. This callback function is passed one of the following string values to indicate whether the operation succeeded * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/activeprocess/setactiveprocess */ SetActiveProcess(processId: DevKit.Guid, callback: (result: "success" | "invalid") => void): void; /** * Reflows the UI of the business process control * @param updateUi Specify true to update the UI of the process control; false otherwise * @param parentStage Specify the ID of the parent stage in the GUID format * @param nextStage Specify the ID of the next stage in the GUID format * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-process/reflow */ Reflow(updateUi: boolean, parentStage: string, nextStage: string): void; /** * Returns a Process object representing the active process * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/activeprocess/getactiveprocess */ readonly ActiveProcess: DevKit.ProcessProcess; /** * Gets the currently selected stage * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/getselectedstage */ readonly SelectedStage: DevKit.ProcessStage; /** * Returns representing the active stage * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/activestage/getactivestage */ readonly ActiveStage: DevKit.ProcessStage; /** * Returns the unique identifier of the process instance. Value represents the string representation of a GUID value * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/instance/getinstanceid */ readonly InstanceId: DevKit.Guid; /** * Returns the name of the process instance * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/instance/getinstancename */ readonly InstanceName: string; /** * Gets a collection of stages currently in the active path with methods to interact with the stages displayed in the business process flow control. The active path represents stages currently rendered in the process control based on the branching rules and current data in the record * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/activepath/getactivepath */ readonly ActivePath: DevKit.Collections<DevKit.ProcessStage>; /** * Get/Set the display state for the business process control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-process/getdisplaystate * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-process/setdisplaystate */ DisplayState: OptionSet.ProcessDisplayState; /** * Get/Set a value indicating whether the business process control is visible * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-process/getvisible * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-process/setvisible */ Visible: boolean; /** * Get/Set the current status of the process instance * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/instance/getstatus * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/instance/setstatus */ Status: OptionSet.ProcessStatus; } interface ITab { /** * Adds a function to be called when the TabStateChange event occurs * @param callback The function to be executed on the TabStateChange event. The function will be added to the bottom of the event handler pipeline. The execution context is automatically passed as the first parameter to the function. See Execution context for more information * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-tabs/addtabstatechange */ AddTabStateChange(callback: (executionContext: any) => void): void; /** * Sets the focus on the tab * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-tabs/setfocus * */ Focus(): void; /** * Removes a function to be called when the TabStateChange event occurs * @param callback The function to be removed from the TabStateChange event * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-tabs/removetabstatechange */ RemoveTabStateChange(callback: (executionContext: any) => void): void; /** * Get the name of the tab * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-tabs/getname */ readonly Name: string; /** * Get the formContext.ui object containing the tab * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-tabs/getparent */ readonly Parent: any; /** * Get/Set display state of the tab * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-tabs/getdisplaystate * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-tabs/setdisplaystate */ DisplayState: OptionSet.TabDisplayState; /** * Get/Set the label for the tab * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-tabs/getlabel * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-tabs/setlabel */ Label: string; /** * Get/Set a value that indicates whether the tab is currently visible * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-tabs/getvisible * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-tabs/setvisible */ Visible: boolean; /** * Get/Set content type of the tab * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-tabs/getcontenttype * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-tabs/setcontenttype */ ContentType: OptionSet.TabContentType; } interface IControlSelect extends IControlSelectBase { /** * Returns an option object with the value matching the argument (label or enumeration value) passed to the method * @param label The label of the option * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getoption */ Option(label: string): DevKit.TextValueNumber; /** * Returns an option object with the value matching the argument (label or enumeration value) passed to the method * @param value The enumeration value of the option * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getoption */ Option(value: number): DevKit.TextValueNumber; /** * Adds an option to a control * @param text The label for the option * @param value The value for the option * @param index The index position to place the new option in. If not provided, the option will be added to the end * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/addoption */ AddOption(text: string, value: number, index?: number): void; /** * Clears all options from a control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/clearoptions */ ClearOptions(): void; /** * Removes an option from a control * @param value The value of the option you want to remove * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/removeoption */ RemoveOption(value: number): void; /** * Returns an array of option objects representing valid options for an attribute * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getoptions */ readonly Options: Array<DevKit.TextValueNumber>; /** * Returns an array of option objects representing valid options available for a control, including a blank option and excluding any options that have been removed from the control using removeOption * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getoptions */ readonly ControlOptions: Array<DevKit.TextValueNumber>; /** * Returns a string value of the text for the currently selected option for an optionset or multiselectoptionset attribute * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/gettext */ readonly Text: string; } interface IControlText extends IControl { /** * Returns a number indicating the maximum length of a string or memo attribute * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getmaxlength */ readonly MaxLength: number; /** * Get/Set the data value for an attribute * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getvalue * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/setvalue */ Value: string; } interface IControlNumber extends IControl { /** * Returns a number indicating the maximum allowed value for an attribute * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getmax */ readonly Max: number; /** * Returns a number indicating the minimum allowed value for an attribute * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getmin */ readonly Min: number; /** * Get/Set the number of digits allowed to the right of the decimal point * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getprecision * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/setprecision */ Precision: number; /** * Get/Set the data value for an attribute. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getvalue * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/setvalue */ Value: number; } interface IQuickView { /** * Gets the controls on a form or control on form by passing an argument * @param arg You can access a single control in the constituent controls collection by passing an argument as either the name or the index value of the constituent control in a quick view control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-quickforms/getcontrol */ Controls(arg?: string | number): Array<any> | any; /** * Returns whether the data binding for the constituent controls in a quick view control is complete * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-quickforms/isloaded */ IsLoaded(): boolean; /** * Refreshes the data displayed in a quick view control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-quickforms/refresh */ Refresh(): void; /** * Sets focus on the control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-quickforms/setfocus */ Focus(): void; /** * Returns a string value that categorizes quick view controls * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-quickforms/getcontrolhttps://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-quickforms/getcontroltype */ readonly ControlType: OptionSet.FieldControlType; /** * [ReadOnly] Returns the name assigned to the quick view control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-quickforms/getname */ readonly ControlName: string; /** * Returns a reference to the section object that contains the control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-quickforms/getparent */ readonly ControlParent: any; /** * Get/Set a boolean value indicating whether the control is disabled. Or sets the state of the control to either enabled or disabled * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-quickforms/getdisabled * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-quickforms/setdisabled */ Disabled: boolean; /** * Get/Set the label for the quick view control. Or sets the label for the quick view control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-quickforms/getlabel * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-quickforms/setlabel */ Label: string; /** * Get/Set a value that indicates whether the quick view control is currently visible. Or displays or hides a control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-quickforms/getvisible * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-quickforms/setvisible */ Visible: boolean; } interface IFooter { /** * Get/Set the visibility of footer section * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-footersection/getvisible * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-footersection/setvisible */ Visible: boolean; } interface IHeader { /** * Get/Set the visibility of header section * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-headersection/getbodyvisible * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-headersection/setbodyvisible */ BodyVisible: boolean; /** * Get/Set the command bar visibility * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-headersection/getcommandbarvisible * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-headersection/setcommandbarvisible */ CommandBarVisible: boolean; /** * Get/Set the tab navigator visibility * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-headersection/gettabnavigatorvisible * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-headersection/settabnavigatorvisible */ TabNavigatorVisible: boolean; } interface Integer extends IControlNumber { } interface Decimal extends IControlNumber { } interface Double extends IControlNumber { } interface Money extends IControlNumber { } interface String extends IControlText { } interface Memo extends IControlText { } interface DateTime extends IControl { /** * Get/Set whether a date control shows the time portion of the date * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getshowtime * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/setshowtime */ ShowTime: boolean; /** * Get/Set the data value for an attribute * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getvalue * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/setvalue */ Value: any; } interface Date extends IControl { /** * Get/Set the data value for an attribute * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getvalue * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/setvalue */ Value: any; } interface Lookup extends IControl { /** * Adds filters to the results displayed in the lookup. Each filter will be combined with any previously added filters as an “AND” condition. This method can only be used in a function in an event handler for the Lookup Control PreSearch Event * @param filter The fetchXml filter element to apply * @param entityLogicaName If this is set, the filter only applies to that entity type. Otherwise, it applies to all types of entities returned * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/addcustomfilter */ AddCustomFilter(filter: string, entityLogicaName?: string): void; /** * Adds a new view for the lookup dialog box. This method doesn’t work with Owner lookups. Owner lookups are used to assign user-owned records * @param viewId The string representation of a GUID for a view * @param entityName The name of the entity * @param viewDisplayName The name of the view * @param fetchXml The fetchXml query for the view * @param layoutXml The XML that defines the layout of the view * @param isDefault Indicates whether the view should be the default view * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/addcustomview */ AddCustomView(viewId: DevKit.Guid, entityName: string, viewDisplayName: string, fetchXml: string, layoutXml: string, isDefault: boolean): void; /** * Applies changes to lookups based on values current just as the user is about to view results for the lookup * @param callback The function that will be run just before the search to provide results for a lookup occurs. You can use this function to call one of the other lookup control functions and improve the results to be displayed in the lookup. The execution context is automatically passed as the first parameter to this function * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/addpresearch */ AddPreSearch(callback: (executionContext: any) => void): void; /** * Removes event handler functions that have previously been set for the PreSearch event * @param callback The function to remove. The execution context is automatically passed as the first parameter to this function * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/removepresearch */ RemovePreSearch(callback: (executionContext: any) => void): void; /** * Adds an event handler to the OnLookupTagClick event * @param callback The function to add to the OnLookupTagClick event. The execution context is automatically passed as the first parameter to this function along with eventArgs that contain the tag value. More information: OnLookupTagClick event * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/addonlookuptagclick */ AddLookupTagClick(callback: (executionContext: any) => void): void; /** * Removes an event handler from the OnLookupTagClick event * @param callback The function to be removed from the OnLookupTagClick event * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/removeonlookuptagclick */ RemoveLookupTagClick(callback: (executionContext: any) => void): void; /** * Returns a Boolean value indicating whether the lookup represents a partylist lookup. Partylist lookups allow for multiple records to be set, such as the To: field for an email entity record * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getispartylist */ readonly IsPartyList: boolean; /** * Get/Set the data value for an attribute * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getvalue * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/setvalue */ Value: Array<DevKit.EntityReference>; /** * Get/Set the ID value of the default lookup dialog view * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getdefaultview * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/setdefaultview */ DefaultView: DevKit.Guid; /** * Get/Set the types of entities allowed in the lookup control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getentitytypes * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/setentitytypes */ EntityTypes: Array<string>; } interface Knowledge extends IControl { /** * Adds an event handler to the PostSearch event * @param callback The function to add to the PostSearch event. The execution context is automatically passed as the first parameter to this function * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/addonpostsearch */ AddPostSearch(callback: (executionContext: any) => void): void; /** * Adds an event handler to the OnResultOpened event * @param callback The function to add to the OnResultOpened event. The execution context is automatically passed as the first parameter to this function * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/addonresultopened */ AddResultOpened(callback: (executionContext: any) => void): void; /** * Adds an event handler to the OnSelection event * @param callback The function to add to the OnSelection event. The execution context is automatically passed as the first parameter to this function * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/addonselection */ AddSelection(callback: (executionContext: any) => void): void; /** * Opens a search result in the search control by specifying the result number * @param resultNumber Numerical value specifying the result number to be opened. Result number starts from 1 * @param mode Specify "Inline" or "Popout". If you do not specify a value for the argument, the default ("Inline") option is used. The "Inline" mode opens the result inline either in the reading pane of the control or in a reference panel tab in case of reference panel. The "Popout" mode opens the result in a pop-out window * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/opensearchresult */ OpenSearchResult(resultNumber: number, mode: string): boolean; /** * Removes an event handler from the PostSearch event * @param callback The function to remove from the PostSearch event * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/removeonpostsearch */ RemovePostSearch(callback: () => void): void; /** * Removes an event handler from the OnResultOpened event * @param callback The function to remove from the OnResultOpened event * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/removeonresultopened */ RemoveResultOpened(callback: () => void): void; /** * Removes an event handler from the OnSelection even * @param callback The function to remove from the OnSelection event * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/removeonselection */ RemoveSelection(callback: () => void): void; /** * Gets the count of results found in the search control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/gettotalresultcount */ readonly TotalResultCount: number; /** * Use this method to get the currently selected result of the search control. The currently selected result also represents the result that is currently open * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getselectedresults */ readonly SelectedResults: any /** * Get/Set the text used as the search criteria for the knowledge base management control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getsearchquery * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/setsearchquery */ SearchQuery: string; } interface WebResource extends IControl { /** * Returns the content window that represents an IFRAME or web resource * @param successCallback A function to call when operation is executed successfully. A content window instance representing the IFRAME or web resource is passed to the function * @param errorCallback A function to call when the operation fails * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getcontentwindow */ ContentWindow(successCallback?: (contentWindow: any) => void, errorCallback?: (error: DevKit.Error) => void): void; /** * Returns the object in the form that represents an IFRAME or web resource * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getobject */ readonly Object: any; /** * Get/Set the value of the data query string parameter passed to a Silverlight web resource * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getdata * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/setdata */ Data: string; /** * Get/Set the current URL being displayed in an IFRAME or web resource * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getsrc * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/setsrc */ Src: string; } interface IFrame extends IControl { /** * Returns the content window that represents an IFRAME or web resource. * @param successCallback A function to call when operation is executed successfully. A content window instance representing the IFRAME or web resource is passed to the function * @param errorCallback A function to call when the operation fails * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getcontentwindow */ ContentWindow(successCallback?: (contentWindow: any) => void, errorCallback?: (error: DevKit.Error) => void): void; /** * Returns the default URL that an IFRAME control is configured to display * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getinitialurl **/ readonly InitialUrl: string; /** * Returns the object in the form that represents an IFRAME or web resource * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getobject */ readonly Object: any; /** * Get/Set the current URL being displayed in an IFRAME or web resource * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getsrc * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/setsrc */ Src: string; } interface Timer extends IControl { /** * Refreshes the data displayed in a timelinewall and timer control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/refresh */ Refresh(): void; /** * Returns the state of the timer control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getstate */ readonly State: number; } interface TimelineWall extends IControl { /** * Refreshes the data displayed in a timelinewall and timer control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/refresh */ Refresh(): void; } interface Boolean extends IControlSelectBase { /** * Get/Set the data value for an attribute * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getvalue * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/setvalue */ Value: boolean; } interface OptionSet extends IControlSelect { /** * Returns the option object or an array of option objects selected in an optionset or multiselectoptionset attribute respectively * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getselectedoption */ readonly SelectedOption: DevKit.TextValueNumber; /** * Get/Set the data value for an attribute * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getvalue * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/setvalue */ Value: number; } interface MultiOptionSet extends IControlSelect { /** * Returns the option object or an array of option objects selected in an optionset or multiselectoptionset attribute respectively * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getselectedoption */ readonly SelectedOption: Array<DevKit.TextValueNumber> /** * Get/Set the data value for an attribute * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getvalue * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/setvalue */ Value: Array<number>; } interface NavigationItem { /** * Sets the focus on the item * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-navigation/setfocus */ Focus(): void; /** * Returns the name of the item * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-navigation/getid */ readonly Id: string; /** * Get/Set the label for the item * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-navigation/getlabel * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-navigation/setlabel */ Label: string; /** * Get/Set a value that indicates whether the item is currently visible * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-navigation/getvisible * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-navigation/setvisible */ Visible: boolean; } interface Section { /** * Get the name of the section * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-sections/getname */ readonly Name: string; /** * Get the tab containing the section * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-sections/getparent */ readonly Parent: any; /** * Get/Set the label for the section * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-sections/getlabel * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-sections/setlabel */ Label: string; /** * Get/Set a value that indicates whether the section is currently visible * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-sections/getvisible * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-sections/setvisible */ Visible: boolean; } interface Grid { /** * [Read-only and editable grids] Adds event handlers to the Subgrid OnLoad event event * @param callback The function to be executed when the subgrid loads. The function will be added to the bottom of the event handler pipeline. The execution context is automatically passed as the first parameter to the function. See execution context for more information. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/grids/gridcontrol/addonload */ AddOnLoad(callback: (executionContext: any) => void): void; /** * [Read-only and editable grids] Gets the URL of the current grid control * @param client Indicates the client type. You can specify one of the following values: 0: Browser | 1: MobileApplication * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/grids/gridcontrol/geturl */ Url(client: 0 | 1): string; /** * [Read-only and editable grids] Refreshes the grid * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/grids/gridcontrol/refresh */ Refresh(): void; /** * [Read-only and editable grids] Refreshes the ribbon rules for the grid control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/grids/gridcontrol/refreshribbon */ RefreshRibbon(): void; /** * [Read-only and editable grids] Displays the associated grid for the grid. This method does nothing if the grid is not filtered based on a relationship * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/grids/gridcontrol/openrelatedgrid */ OpenRelatedGrid(): void; /** * [Read-only grids] Removes event handlers from the Subgrid OnLoad event event * @param callback The function to be removed from the OnLoad event. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/grids/gridcontrol/removeonload */ RemoveOnLoad(callback: () => void): void; /** * [Read-only and editable grids] Gets the logical name of the entity data displayed in the grid * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/grids/gridcontrol/getentityname * */ readonly EntityName: string; /** * [Read-only and editable grids] Gets the FetchXML query that represents the current data, including filtered and sorted data, in the grid control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/grids/gridcontrol/getfetchxml */ readonly FetchXml: string /** * [Read-only and editable grids] Gets the grid type (grid or subgrid) * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/grids/gridcontrol/getgridtype * */ readonly GridType: OptionSet.GridType; /** * [Read-only and editable grids] Gets information about the relationship used to filter the subgrid * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/grids/gridcontrol/getrelationship * */ readonly Relationship: DevKit.GridRelationship; /** * [Read-only grid] Provides methods to get or set information about the view selector of the subgrid control. If the subgrid control is not configured to display the view selector, calling the ViewSelector methods will throw an error * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/grids/viewselector */ readonly ViewSelector: DevKit.ViewSelector; /** * [Read-only and editable grids] Returns a collection of every GridRow in the Grid * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/grids/grid/getrows */ readonly Rows: DevKit.Collections<DevKit.Controls.GridRow>; /** * [Read-only and editable grids] Returns a collection of every selected GridRow in the Grid * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/grids/grid/getselectedrows */ readonly SelectedRows: DevKit.Collections<DevKit.Controls.GridRow>; /** * [Editable grids] The single row (record) is selected in the editable grid. This event won't occur if a user selects different cells in the same row, or selects multiple rows * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/events/grid-onrecordselect */ readonly OnRecordSelect: DevKit.Controls.GridRow; /** * [Editable grids] Returns the total number of records that match the filter criteria of the view, not limited by the number visible in a single page * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/grids/grid/gettotalrecordcount */ readonly TotalRecordCount: number; } interface GridRow { /** * [Read-only and editable grids] Returns the logical name for the record in the row * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/grids/gridentity/getentityname */ readonly EntityName: string; /** * [Read-only and editable grids] Returns a Lookup value that references the record in the row * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/grids/gridentity/getentityreference */ readonly EntityReference: DevKit.EntityReference; /** * [Read-only and editable grids] Returns the Id for the record in the row * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/grids/gridentity/getid */ readonly EntityId: DevKit.Guid; /** * [Read-only grid] Returns the primary attribute value for the record in the row * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/grids/gridentity/getprimaryattributevalue */ readonly PrimaryAttributeValue: string; readonly Columns: DevKit.Collections<DevKit.Controls.GridColumn>; } interface GridColumn { /** * [Editable grids] Displays an error message for a cell to indicate that data isn’t valid * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/setnotification */ SetNotification(message: string, uniqueId?: string): boolean; /** * [Editable grids] Clears notification for a cell * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/clearnotification */ ClearNotification(uniqueId: string): boolean; /** * [Editable grids] Returns the logical name of the attribute of a selected grid row * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getname */ readonly Name: string; /** * [Editable grids] Get/Set a string value indicating whether a value for the attribute is required or recommended * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getrequiredlevel * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/setrequiredlevel */ RequiredLevel: OptionSet.FieldRequiredLevel; /** * [Editable grids] Get/Set the data value for an attribute * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/getvalue * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes/setvalue */ Value: string; /** * [Editable grids] Get/Set whether the cell is disabled * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getdisabled * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/setdisabled */ Disabled: boolean; /** * [Editable grids] Returns the label of the column that contains the cell * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/getlabel */ Label: string; } interface Note extends IControl { /** * Refreshes the data displayed in a timelinewall and timer control * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls/refresh */ Refresh(): void; } interface EmailEngagement { } interface EmailRecipient { } interface Map { } interface ActionCards { } interface AciWidget { } interface PowerBi { } interface File { } interface Image { } interface QuickView { readonly Value: any; Visible: boolean; Label: string; } } namespace WebApi { interface OptionSetValue { /** The optionset number value. E.g.: 1000000001 */ Value: number; /** The optionset formatted text. E.g. "Dynamics 365" */ readonly FormattedValue: string; } interface OptionSetValueReadonly { /** The optionset number value. E.g.: 1000000001 */ readonly Value: number; /** The optionset formatted text. E.g. "Dynamics 365" */ readonly FormattedValue: string; } interface MultiOptionSetValue { /** The optionset number values. E.g.: [1000000001, 1000000003]*/ Value: Array<number>; /** The optionset formatted texts. E.g.: ["Dynamics 2011", "Dynamics 365"] */ readonly FormattedValue: Array<string>; } interface MultiOptionSetValueReadonly { /** The optionset number values. E.g.: [1000000001, 1000000003]*/ readonly Value: Array<number>; /** The optionset formatted texts. E.g.: ["Dynamics 2011", "Dynamics 365"] */ readonly FormattedValue: Array<string>; } interface BooleanValue { /** The boollean value. E.g.: true */ Value: boolean; /** The boolean formatted text. E.g.: "Yes" */ readonly FormattedValue: string; } interface BooleanValueReadonly { /** The boollean value. E.g.: true */ readonly Value: boolean; /** The boolean formatted text. E.g.: "Yes" */ readonly FormattedValue: string; } interface DateOnlyValue { /** The date only value. Always format yyyy-MM-dd. E.g.: "2019-04-30" */ Value: string; /** The date only formatted text, base on user setting format. E.g.: "2019.04.30" */ readonly FormattedValue: string; } interface DateOnlyValueReadonly { /** The date only value. Always format yyyy-MM-dd. E.g.: "2019-04-30" */ readonly Value: string; /** The date only formatted text, base on user setting format. E.g.: "2019.04.30" */ readonly FormattedValue: string; } interface UtcDateOnlyValue { /** The UTC date only value. E.g.: "2019-04-29T17:00:00Z" */ Value: string; /** The UTC date formatted text, base on user setting format. E.g.: "30.04.2019" */ readonly FormattedValue: string; } interface UtcDateOnlyValueReadonly { /** The UTC date only value. E.g.: "2019-04-29T17:00:00Z" */ readonly Value: string; /** The UTC date formatted text, base on user setting format. E.g.: "30.04.2019" */ readonly FormattedValue: string; } interface UtcDateAndTimeValue { /** The UTC date and time value. E.g.: "2019-04-27T07:30:00Z" */ Value: string; /** The UTC date and time formatted text, base on user setting format. E.g.: "27.04.2019 02:30 CH" */ readonly FormattedValue: string; } interface UtcDateAndTimeValueReadonly { /** The UTC date and time value. E.g.: "2019-04-27T07:30:00Z" */ readonly Value: string; /** The UTC date and time formatted text, base on user setting format. E.g.: "27.04.2019 02:30 CH" */ readonly FormattedValue: string; } interface TimezoneDateOnlyValue { /** The time-zone date only value. E.g.: "2019-04-26T00:00:00Z" */ Value: string; /** The time-zone date formatted text, base on user setting format. E.g.: "26.04.2019" */ readonly FormattedValue: string; } interface TimezoneDateOnlyValueReadonly { /** The time-zone date only value. E.g.: "2019-04-26T00:00:00Z" */ readonly Value: string; /** The time-zone date formatted text, base on user setting format. E.g.: "26.04.2019" */ readonly FormattedValue: string; } interface TimezoneDateAndTimeValue { /** The time-zone date and time value. E.g.: "2019-04-28T15:30:00Z" */ Value: string; /** The time-zone date and time formatted text, base on user setting format. E.g.: "28.04.2019 03:30 CH" */ readonly FormattedValue: string; } interface TimezoneDateAndTimeValueReadonly { /** The time-zone date and time value. E.g.: "2019-04-28T15:30:00Z" */ readonly Value: string; /** The time-zone date and time formatted text, base on user setting format. E.g.: "28.04.2019 03:30 CH" */ readonly FormattedValue: string; } interface IntegerValue { /** The integer value. E.g.: 1234567 */ Value: number; /** The integer formatted text, base on user setting format. E.g.: "1.234.567" */ readonly FormattedValue: string; } interface IntegerValueReadonly { /** The integer value. E.g.: 1234567 */ readonly Value: number; /** The integer formatted text, base on user setting format. E.g.: "1.234.567" */ readonly FormattedValue: string; } interface BigIntValue { /** The big integer value. E.g.: 1234567 */ Value: number; /** The big integer formatted text, base on user setting format. E.g.: "1.234.567" */ readonly FormattedValue: string; } interface BigIntValueReadonly { /** The integer value. E.g.: 1234567 */ readonly Value: number; /** The integer formatted text, base on user setting format. E.g.: "1.234.567" */ readonly FormattedValue: string; } interface DoubleValue { /** The double value. E.g.: 1234.57 */ Value: number; /** The double formatted text, base on user setting format. E.g.: "1.234,57" */ readonly FormattedValue: string; } interface DoubleValueReadonly { /** The double value. E.g.: 1234.57 */ readonly Value: number; /** The double formatted text, base on user setting format. E.g.: "1.234,57" */ readonly FormattedValue: string; } interface DecimalValue { /** The decimal value. E.g.: 1234567.89 */ Value: number; /** The decimal formatted text, base on user setting format. E.g.: "1.234.567,89" */ readonly FormattedValue: string; } interface DecimalValueReadonly { /** The decimal value. E.g.: 1234567.89 */ readonly Value: number; /** The decimal formatted text, base on user setting format. E.g.: "1.234.567,89" */ readonly FormattedValue: string; } interface MoneyValue { /** The currency value of field. E.g.: 123456.35 */ Value: number; /** The currency formatted text, base on user setting format. E.g.: "123.456,35 $" */ readonly FormattedValue: string; } interface MoneyValueReadonly { /** The currency value of field. E.g.: 123456.35 */ readonly Value: number; /** The currency formatted text, base on user setting format. E.g.: "123.456,35 $" */ readonly FormattedValue: string; } interface StringValue { /** The string value. E.g.: "A. Datum Corporation (sample)" */ Value: string; } interface StringValueReadonly { /** The string value. E.g.: "A. Datum Corporation (sample)" */ readonly Value: string; } interface LookupValue { /** The guid value. E.g.: f55a0d1e-286b-e911-a997-000d3a802135 */ Value: DevKit.Guid; /** The name formatted text. E.g.: "A. Datum Corporation (sample)" */ readonly FormattedValue: string; } interface LookupValueReadonly { /** The guid value. E.g.: f55a0d1e-286b-e911-a997-000d3a802135 */ readonly Value: DevKit.Guid; /** The name formatted text. E.g.: "A. Datum Corporation (sample)" */ readonly FormattedValue: string; } interface GuidValue { /** The guid value. E.g.: f55a0d1e-286b-e911-a997-000d3a802135 */ Value: DevKit.Guid; } interface GuidValueReadonly { /** The guid value. E.g.: f55a0d1e-286b-e911-a997-000d3a802135 */ Value: DevKit.Guid; } interface ManagedPropertyValue{ Value: string; } interface ManagedPropertyValueReadonly{ Value: string; } interface RetrieveMultipleResponse { /** An array of JSON objects, where each object represents the retrieved entity record containing attributes and their values as key: value pairs. The Id of the entity record is retrieved by default. */ entities: Array<DevKit.KeyValueObject>; /** If the number of records being retrieved is more than the value specified in the maxPageSize parameter in the request, this attribute returns the URL to return next set of records. */ nextLink: string; } interface ExecuteRequest { /** * The name of the bound parameter for the action or function to execute. Specify undefined if you are executing a CRUD request. Specify null if the action or function to execute is not bound to any entity. Specify entity in case the action or function to execute is bound to an entity. */ boundParameter?: "entity" | undefined | null; /** Name of the action, function, or one of the following values if you are executing a CRUD request. */ operationName?: "Create" | "Retrieve" | "RetrieveMultiple" | "Update" | "Delete" | string; /** Indicates the type of operation you are executing */ operationType?: OptionSet.OperationType; /** The metadata for parameter types. */ parameterTypes: { /** The metadata for enum types. The object has two string attributes: name and value */ enumProperties?: Array<DevKit.KeyValueObject>; /** The category of the parameter type. */ structuralProperty: OptionSet.StructuralProperty; } } interface ExecuteResponse { /** Response body. */ body?: any; /** Response headers. */ headers: any; /** Indicates whether the request was successful. */ ok: boolean; /** Numeric value in the response status code.For example: 200 */ status: number; /** Description of the response status code.For example: OK */ statusText: string; /** Response type */ type: "" | "arraybuffer" | "blob" | "document" | "json" | "text"; /** Request URL of the action, function, or CRUD request that was sent to the Web API endpoint. */ url: string; } interface ChangeSetRequest { } /** * Object passed to ErrorCallbackDelegate. */ interface ErrorCallbackObject { /** * The error code. */ errorCode: number; /** * An error message describing the issue. */ message: string; } /** * Object passed to QuickCreateSuccessCallbackDelegate. */ interface OpenQuickCreateSuccessCallbackObject { /** * A lookup value which identifies the record which has been created. */ savedEntityReference: LookupValue; } /** * Object passed to OfflineOperationSuccessCallbackDelegate; */ interface OfflineOperationSuccessCallbackObject { /** * GUID of the record; */ id: string; /** * Logical name of the entity. */ logicalName: string; } /** * Object passed to OfflineErrorCallbackDelegate. */ interface OfflineErrorCallbackObject extends ErrorCallbackObject { /** * An internal error message that might contain additional details about the issue. */ debugMessage: string; } /** * Interface for asynchronous promises. Based on JQuery Promise */ interface PromiseLike<T> { /** * Attaches callbacks for the resolution and/or rejection of the Promise. * @param onFulfilled The callback to execute when the Promise is resolved. * @param onRejected The callback to execute when the Promise is rejected. * @returns A Promise for the completion of which ever callback is executed. */ then<U>(onFulfilled?: (value: T) => U | PromiseLike<U>, onRejected?: (error: any) => U | PromiseLike<U>): PromiseLike<U>; then<U>(onFulfilled?: (value: T) => U | PromiseLike<U>, onRejected?: (error: any) => void): PromiseLike<U>; /** * UNDOCUMENTED (Web Client only) Add handlers to be called when the Deferred object is rejected. */ fail<U>(onRejected?: (reason: ErrorResponse) => U | PromiseLike<U>): PromiseLike<U>; /** * UNDOCUMENTED (Web Client only): Add handlers to be called when the Deferred object is either resolved or rejected. */ always<U>(alwaysCallback: (() => U | PromiseLike<U>)): PromiseLike<U>; /** * UNDOCUMENTED (Unified Client only): Add handlers to be called when the Deferred object is rejected. */ catch<U>(onRejected?: (reason: ErrorResponse) => U | PromiseLike<U>): PromiseLike<U>; /** * UNDOCUMENTED (Unified Client only): Add handlers to be called when the Deferred object is either resolved or rejected. */ finally<U>(finallyCallback: (() => U | PromiseLike<U>)): PromiseLike<U>; } interface CreateResponse { entityType: string; id: string; } /** Interface for the Promise error response arguments */ interface ErrorResponse { errorCode: number; message: string; } } interface IEntityBaseAttribute { /** Type of an attribute */ readonly AttributeType: number; /** Display name for the attribute */ readonly DisplayName: string; /** Logical name of the entity that contains the attribute */ readonly EntityLogicalName: string; /** Logical name for the attribute */ readonly LogicalName: string; } interface EntityBooleanAttribute extends IEntityBaseAttribute { /** Default value for a Boolean option set */ readonly DefaultFormValue: boolean; /** Options for the boolean attribute where each option is a key: value pair */ readonly OptionSet: Array<KeyValueNumber>; } interface EntityEnumAttribute extends IEntityBaseAttribute { /** Options for the boolean attribute where each option is a key: value pair */ readonly OptionSet: Array<KeyValueNumber>; } interface EntityPicklistAttribute extends IEntityBaseAttribute { /** Default value for a Number option set */ readonly DefaultFormValue: number; /** Options for the boolean attribute where each option is a key: value pair */ readonly OptionSet: Array<KeyValueNumber>; } interface EntityStateAttribute extends IEntityBaseAttribute { /** * Returns the default status based on the passed in state value for an entity * @param arg statecode value */ getDefaultStatus(arg: number): number; /** * Returns possible status values (array of numbers) for a specified state value * @param arg statecode value */ getStatusValuesForState(arg: number): Array<number>; /** Options for the boolean attribute where each option is a key: value pair */ readonly OptionSet: Array<KeyValueNumber>; } interface EntityStatusAttribute extends IEntityBaseAttribute { /** * Returns the state value (number) for the specified status value (number) * @param arg statuscode value */ getState(arg: number): Array<number>; /** Options for the boolean attribute where each option is a key: value pair */ readonly OptionSet: Array<KeyValueNumber>; } interface Error { /** The error code */ readonly code: number; /** The error code */ readonly errorCode: number; /** An error message describing the issue */ readonly message: string; } interface EntityPrivilege { /** Whether the privilege can be basic access level */ readonly CanBeBasic: boolean; /** Whether the privilege can be deep access level */ readonly CanBeDeep: boolean; /** Whether the privilege for an external party can be basic access level */ readonly CanBeEntityReference: boolean; /** Whether the privilege can be global access level */ readonly CanBeGlobal: boolean; /** Whether the privilege can be local access level */ readonly CanBeLocal: boolean; /** Whether the privilege for an external party can be parent access level */ readonly CanBeParentEntityReference: boolean; /** The name of the privilege */ readonly Name: string; /** The ID of the privilege */ readonly PrivilegeId: DevKit.Guid; /** The type of operation for the privilege */ readonly PrivilegeType: OptionSet.PrivilegeType } interface EntityMetadata { /** Whether a custom activity should appear in the activity menus in the Web application. 0 indicates that the custom activity doesn't appear; 1 indicates that it does appear */ readonly ActivityTypeMask: number; /** Indicates whether to automatically move records to the owner’s default queue when a record of this type is created or assigned */ readonly AutoRouteToOwnerQueue: boolean; /** Indicates whether the entity can trigger a workflow process */ readonly CanTriggerWorkflow: boolean; /** Description for the entity */ readonly Description: string; /** Plural display name for the entity */ readonly DisplayCollectionName: string; /** Display name for the entity */ readonly DisplayName: string; /** Indicates whether the entity will enforce custom state transitions */ readonly EnforceStateTransitions: boolean; /** The hexadecimal code to represent the color to be used for this entity in the application */ readonly EntityColor: string; /** The name of the Web API entity set for this entity */ readonly EntitySetName: string; /** Indicates whether activities are associated with this entity */ readonly HasActivities: boolean; /** Indicates whether the entity is an activity */ readonly IsActivity: boolean; /** Indicates whether the email messages can be sent to an email address stored in a record of this type */ readonly IsActivityParty: boolean; /** Indicates whether the entity is enabled for business process flows */ readonly IsBusinessProcessEnabled: boolean; /** Indicates whether the entity is a business process flow entity */ readonly IsBPFEntity: boolean; /** Indicates whether the entity is a child entity */ readonly IsChildEntity: boolean; /** Indicates whether connections are enabled for this entity */ readonly IsConnectionsEnabled: boolean; /** Indicates whether the entity is a custom entity */ readonly IsCustomEntity: boolean; /** Indicates whether the entity is customizable */ readonly IsCustomizable: boolean; /** Indicates whether document management is enabled */ readonly IsDocumentManagementEnabled: boolean; /** Indicates whether the documemt recommendations is enabled */ readonly IsDocumentRecommendationsEnabled: boolean; /** Indicates whether duplicate detection is enabled */ readonly IsDuplicateDetectionEnabled: boolean; /** Indicates whether charts are enabled */ readonly IsEnabledForCharts: boolean; /** Indicates whether the entity can be imported using the Import Wizard */ readonly IsImportable: boolean; /** Indicates the entity is enabled for interactive experience.*/ readonly IsInteractionCentricEnabled: boolean; /** Indicates whether knowledge management is enabled for the entity */ readonly IsKnowledgeManagementEnabled: boolean; /** Indicates whether mail merge is enabled for this entity */ readonly IsMailMergeEnabled: boolean; /** Indicates whether the entity is part of a managed solution */ readonly IsManaged: boolean; /** Indicates whether OneNote integration is enabled for the entity */ readonly IsOneNoteIntegrationEnabled: boolean; /** Indicates whether optimistic concurrency is enabled for the entity */ readonly IsOptimisticConcurrencyEnabled: boolean; /** Indicates whether the entity is enabled for quick create forms */ readonly IsQuickCreateEnabled: boolean; /** Indicates whether the entity supports setting custom state transitions */ readonly IsStateModelAware: boolean; /** Indicates whether the entity is will be shown in Advanced Find */ readonly IsValidForAdvancedFind: boolean; /** Indicates whether Microsoft Dynamics 365 for tablets users can see data for this entity */ readonly IsVisibleInMobileClient: boolean; /** Indicates whether the entity is enabled for Unified Interface */ readonly IsEnabledInUnifiedInterface: boolean; /** The logical collection name */ readonly LogicalCollectionName: string; /** The logical name for the entity */ readonly LogicalName: string; /** The entity type code */ readonly ObjectTypeCode: number; /** The ownership type for the entity: "UserOwned" or "OrganizationOwned" */ readonly OwnershipType: string; /** The name of the attribute that is the primary id for the entity */ readonly PrimaryIdAttribute: string; /** String The name of the primary image attribute for an entity */ readonly PrimaryImageAttribute: string; /** The name of the primary attribute for an entity */ readonly PrimaryNameAttribute: string; /** The privilege metadata for the entity where each object contains the following attributes to define the security privilege for access to an entity */ readonly Privileges: Array<EntityPrivilege>; /** A collection of attribute metadata objects. The object returned depends on the type of attribute metadata */ readonly Attributes: Array<IEntityBaseAttribute | EntityBooleanAttribute | EntityEnumAttribute | EntityPicklistAttribute | EntityStateAttribute | EntityStatusAttribute>; } interface KeyValueObject { readonly key: string, readonly value: any } interface KeyValueNumber { readonly key: string, readonly value: number } interface TextValueNumber { readonly text: string, readonly value: number } interface DialogResult { /** Indicates whether the confirm button was clicked to close the dialog */ readonly confirmed: boolean; } interface FileData { /** Contents of the audio file */ readonly fileContent: string; /** Name of the audio file */ readonly fileName: string; /** Size of the audio file in KB */ readonly fileSize: number; /** Audio file MIME type */ readonly mimeType: string; } interface DateFormattingInfoCalendar { readonly MinSupportedDateTime: Date; readonly MaxSupportedDateTime: Date; readonly AlgorithmType: number; readonly CalendarType: number; readonly Eras: Array<number>; readonly TwoDigitYearMax: number; readonly IsReadOnly: boolean; } interface DateFormattingInfo { readonly AmDesignator: string; readonly AbbreviatedDayNames: Array<string>; readonly AbbreviatedMonthGenitiveNames: Array<string>; readonly AbbreviatedMonthNames: Array<string>; readonly Calendar: DateFormattingInfoCalendar; readonly CalendarWeekRule: number; readonly DateSeparator: string; readonly DayNames: Array<string>; readonly FirstDayOfWeek: number; readonly FullDateTimePattern: string; readonly LongDatePattern: string; readonly LongTimePattern: string; readonly MonthDayPattern: string; readonly MonthGenitiveNames: Array<string>; readonly MonthNames: Array<string>; readonly PmDesignator: string; readonly ShortDatePattern: string; readonly ShortTimePattern: string; readonly ShortestDayNames: Array<string>; readonly SortableDateTimePattern: string; readonly TimeSeparator: string; readonly UniversalSortableDateTimePattern: string; readonly YearMonthPattern: string; } interface AppProperty { readonly appId: string; readonly displayName: string; readonly uniqueName: string; readonly url: string; readonly webResourceId: DevKit.Guid; readonly webResourceName: string; readonly welcomePageId: DevKit.Guid; readonly welcomePageName: string; } interface FieldUserPrivilege { readonly canRead: boolean; readonly canUpdate: boolean; readonly canCreate: boolean; } interface ProcessStage { /** * Returns the status of the stage * @param callback * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/stage/getnavigationbehavior */ AllowCreateNew(callback: () => boolean): void; /** * Returns the integer value of the business process flow category * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formContext-data-process/stage/getCategory */ readonly Category: OptionSet.ProcessCategory; /** * Returns the logical name of the entity associated with the stage * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/stage/getentityname */ readonly EntityName: String; /** * Returns the unique identifier of the stage * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/stage/getid */ readonly Id: string; /** * Returns the name of the stage * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/stage/getname */ readonly Name: string; /** * Returns the status of the stage * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/stage/getstatus */ readonly Status: "active" | "inactive"; /** * Returns a navigation behavior object for a stage that can be used to define whether the Create button is available for users to create other entity record in a cross-entity business process flow navigation scenario. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/stage/getsteps */ Steps: Array<ProcessStep>; } interface ProcessStep { /** * Updates the progress of the action step. This method is supported only for the action steps. Action steps are buttons on the business process stages that users can click to trigger an on-demand workflow or action. Action step is a preview feature introduced in the Dynamics 365 for Customer Engagement apps version 9.0 release * @param stepProgress Specify the step progress * @param message An optional message that is set as the Alt text on the icon for the step * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/step/setprogress */ SetProgress(stepProgress: OptionSet.ProcessProgress, message?: string): void; /** * Returns the logical name of the attribute associated to the step * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/step/getattribute */ readonly Attribute: string; /** * Returns the name of the step * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/step/getname */ readonly Name: string; /** * Returns the progress of the action step. This method is supported only for the action steps; not for the data steps. Action steps are buttons on the business process stages that users can click to trigger an on-demand workflow or action. Action step is a preview feature introduced in the Dynamics 365 for Customer Engagement apps version 9.0 release * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/step/getprogress */ readonly Progress: OptionSet.ProcessProgress; /** * Returns a boolean value indicating whether the step is required in the business process flow * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/step/isrequired * */ readonly Required: boolean; } interface ProcessInstance extends ProcessEnabled { readonly CreatedOn: string; readonly CreatedOnDate: Date; readonly InstanceId: DevKit.Guid; readonly InstanceName: string; readonly Status: OptionSet.ProcessStatus; } interface ProcessEnabled { readonly ProcessId: DevKit.Guid; readonly ProcessName: string; } interface ProcessProcess { /** * Returns the unique identifier of the process * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/process/getid */ readonly Id: DevKit.Guid; /** * Returns the name of the process * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/process/getname */ readonly Name: string; /** * Returns a boolean value indicating whether the process is rendered * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/process/isrendered */ readonly IsRendered: boolean; /** * Returns a collection of stages in the process * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-process/process/getstages */ Stages: DevKit.Collections<ProcessStage>; } interface GridRelationship { /** Name of the attribute. */ readonly attributeName: string, /** Name of the relationship. */ readonly name: string, /** Name of the navigation property for this relationship. */ readonly navigationPropertyName: string, /** Returns one of the following values to indicate the relationship type. 0: OneToMany | 1: ManyToMany */ readonly relationshipType: 0 | 1, /** Returns one of the following values to indicate the role type of relationship. 1: Referencing | 2: AssociationEntity */ readonly roleType: 1 | 2 } interface Collections<T> { forEach(successCallback: (item: T, index: number) => void): void; get(): Array<T>; get(item: string): T; get(index: number): T; get(successCallback: (item: T, index: number) => void): Array<T>; getLength(): number; } interface ExecutionContext { /** * Retrieves a variable set using the SetSharedVariable method. * @param key The name of the variable. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/executioncontext/getsharedvariable */ GetSharedVariable(key: string): any; /** * Sets the value of a variable to be used by a handler after the current handler completes. * @param key The name of the variable. * @param value The values to set. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/executioncontext/setsharedvariable */ SetSharedVariable(key: string, value: any): void; /** * Returns a value indicating whether the save event has been canceled because the preventDefault method was used in this event hander or a previous event handler. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/save-event-arguments/isdefaultprevented */ IsDefaultPrevented(): boolean; /** * Cancels the save operation, but all remaining handlers for the event will still be executed. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/save-event-arguments/preventdefault */ SetPreventDefault(): void; /** * Cancels the save operation if the event handler has a script error, returns a rejected promise for an async event handler or the operation times out. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/save-event-arguments/preventdefaultonerror */ SetPreventDefaultOnError /** * Returns a value that indicates the order in which this handler is executed. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/executioncontext/getdepth */ readonly Depth: number; /** * Returns an object with methods to manage the events. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/executioncontext/geteventargs */ readonly EventArgs: any; /** * Returns a reference to the object that the event occurred on. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/executioncontext/geteventsource */ readonly EventSource: any; /** * Returns a reference to the form or an item on the form depending on where the method was called. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/executioncontext/getformcontext */ readonly FormContext: any; /** * Returns a value indicating how the save event was initiated by the user. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/save-event-arguments/getsavemode */ readonly SaveMode: OptionSet.SaveMode; /** * Use this method to know information about an entity being saved/updated. It returns entity ID, and entity name if success. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/save-event-arguments/getentityreference */ readonly EntityReference: DevKit.EntityReference; /** * Use this method to know whether the OnSave operation is successful or failed. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/save-event-arguments/getissavesuccess */ readonly IsSaveSuccess: boolean; /** * Use this method to know the error details on why an entity save failed. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/save-event-arguments/getsaveerrorinfo */ readonly SaveErrorInfo: string; } interface Utility { /** * Returns information about the advanced configuration settings for the organization * @param setting Name of the configuration setting * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/getadvancedconfigsetting */ AdvancedConfigSetting(setting: OptionSet.AdvancedConfigSetting): number; /** * Returns the valid state transitions for the specified entity type and state code. * @param entityName The logical name of the entity. * @param statusCode The status code to find out the allowed status transition values. * @param successCallback The function to execute when the operation succeeds. * @param errorCallback The function to execute when the operation fails. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getallowedstatustransitions */ AllowedStatusTransitions(entityName: string, statusCode: number, successCallback?: (statusCodes: Array<number>) => void, errorCallback?: (error: DevKit.Error) => void): void; /** * Returns a promise containing the default main form descriptor with the following values. * @param entityName The logical name of the entity. * @param formId The form ID of the entity. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getentitymainformdescriptor */ EntityMainFormDescriptor(entityName: string, formId: string): any; /** * Invokes the device camera to scan the barcode information, such as a product number. Note: This method is supported only for the mobile clients. * @param successCallback A function to call when the barcode value is returned as a String. * @param errorCallback A function to call when the operation fails. An error object with the message property (String) will be passed that describes the error details. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-device/getbarcodevalue */ BarcodeValue(successCallback: (result: string) => void, errorCallback: (error: DevKit.Error) => void): void; /** * Invokes the device microphone to record audio. * @param successCallback A function to call when audio is returned. A base64 encoded audio object attributes is passed to the function. * @param errorCallback A function to call when the operation fails. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-device/captureaudio */ CaptureAudio(successCallback: (result: DevKit.FileData) => void, errorCallback: (error: DevKit.Error) => void): void; /** * Invokes the device camera to capture an image. Note: This method is supported only for the mobile clients. * @param imageOption The image option. * @param successCallback A function to call when image is returned. A base64 encoded image object attributes is passed to the function. * @param errorCallback A function to call when the operation fails. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-device/captureimage */ CaptureImage(imageOption: DevKit.ImageOption, successCallback: (result: DevKit.FileData) => void, errorCallback: (error: DevKit.Error) => void): void; /** * Invokes the device camera to record video. Note: This method is supported only for the mobile clients. * @param successCallback A function to call when Video is returned. A base64 encoded video object attributes is passed to the function. * @param errorCallback A function to call when the operation fails. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-device/capturevideo */ CaptureVideo(successCallback: (result: DevKit.FileData) => void, errorCallback: (error: DevKit.Error) => void): void; /** * Closes a progress dialog box. If no progress dialog is displayed currently, this method will do nothing. You can display a progress dialog using the ShowProgressIndicator method. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/closeprogressindicator */ CloseProgressIndicator(): void; /** * Returns the name of the current business app in Customer Engagement * @param successCallback A function to call when the business app name is returned * @param errorCallback A function to call when the operation fails * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/getcurrentappname */ CurrentAppName(successCallback: (result: string) => void, errorCallback: (error: DevKit.Error) => void): void; /** * Returns the relative URL with the caching token for the specified web resource. * @param webResourceName Name of the web resource. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/getwebresourceurl */ WebResourceUrl(webResourceName: string): string; /** * Returns the properties of the current business app in Customer Engagement * @param successCallback A function to call when the business app property information is returned * @param errorCallback A function to call when the operation fails * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/getcurrentappproperties */ CurrentAppProperties(successCallback: (result: DevKit.AppProperty) => void, errorCallback: (error: DevKit.Error) => void): void; /** * Returns the current location using the device geolocation capability. Note: For the CurrentPosition method to work, the geolocation capability must be enabled on your mobile device, and the Dynamics 365 for Customer Engagement mobile clients must have permissions to access the device location, which isn't enabled by default. This method is supported only for the mobile clients. * @param successCallback A function to call when the current geolocation information is returned. A geolocation object attributes is passed to the function * @param errorCallback A function to call when the operation fails. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-device/getcurrentposition */ CurrentPosition(successCallback: (result: DevKit.PositionData) => void, errorCallback: (error: DevKit.Error) => void): void; /** * Returns the entity metadata for the specified entity. * @param entityName The logical name of the entity. * @param attributes The attributes to get metadata for. * @param successCallback A function to call when the entity metadata is returned. * @param errorCallback A function to call when the operation fails. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getentitymetadata */ EntityMetadata(entityName: string, attributes?: Array<string>, successCallback?: (result: DevKit.EntityMetadata) => void, errorCallback?: (error: DevKit.Error) => void): void; /** * Encodes the specified string so that it can be used in an HTML attribute. * @param arg String to be encoded. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-encoding/xmlencode */ HtmlAttributeEncode(arg: string): string; /** * Converts a string that has been HTML-encoded into a decoded string. * @param arg HTML-encoded string to be decoded. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-encoding/htmldecode */ HtmlDecode(arg: string): string; /** * Converts a string to an HTML-encoded string. * @param arg String to be encoded. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-encoding/htmlattributeencode */ HtmlEncode(arg: string): string; /** * Invokes an action based on the specified parameters. * @param name Name of the process action to invoke. * @param parameter An object containing input parameters for the action. You define an object using key:value pairs of items, where key is of String type. * @param successCallback A function to call when the action is invoked. * @param errorCallback A function to call when the operation fails. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/invokeprocessaction */ InvokeProcessAction(name: string, parameter: any, successCallback: (result: any) => void, errorCallback: (error: DevKit.Error) => void): void; /** * Displays the web page represented by a URL in the static area in the side pane, which appears on all pages in the Dynamics 365 for Customer Engagement apps web client. * @param url URL of the page to be loaded in the side pane static area. * @param title Title of the side pane static area. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-panel/loadpanel */ LoadPanel(url: string, title: string): void; /** * Defines the options for opening the lookup dialog * @param lookupOption * @param successCallback A function to call when the lookup control is invoked. An array of objects properties is passed * @param cancelCallback A function to call when you cancel the lookup control or the operation fails * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/lookupobjects */ LookupObjects(lookupOption: DevKit.LookupOption, successCallback: (results: Array<DevKit.EntityReference>) => void, errorCallback: (error: DevKit.Error) => void): void; /** * Displays an alert dialog containing a message and a button. * @param alertOption The strings to be used in the alert dialog. * @param window The height and width options for alert dialog. * @param successCallback A function to execute when the alert dialog is closed by either clicking the confirm button or canceled by pressing ESC. * @param errorCallback A function to execute when the operation fails. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-navigation/openalertdialog */ OpenAlertDialog(alertOption: DevKit.DialogAlertOption, window?: DevKit.Window, successCallback?: (result: string) => void, errorCallback?: (error: DevKit.Error) => void): void; /** * Displays a confirmation dialog box containing a message and two buttons. * @param confirmOption The strings to be used in the confirmation dialog. * @param window The height and width options for confirmation dialog. * @param successCallback A function to execute when the confirmation dialog is closed by clicking the confirm, cancel, or X in the top-right corner of the dialog. An object with the confirmed (Boolean) attribute is passed that indicates whether the confirm button was clicked to close the dialog. * @param errorCallback A function to execute when the operation fails. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-navigation/openconfirmdialog */ OpenConfirmDialog(confirmOption: DevKit.DialogConfirmOption, window?: DevKit.Window, successCallback?: (result: DevKit.DialogResult) => void, errorCallback?: (error: DevKit.Error) => void): void; /** * Displays an error dialog. * @param errorOptions An object to specify the options for error dialog. * @param successCallback A function to execute when the error dialog is closed. * @param errorCallback A function to execute when the operation fails. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-navigation/openerrordialog */ OpenErrorDialog(errorOptions: DevKit.DialogError, successCallback: (result: string) => void, errorCallback: (error: DevKit.Error) => void): void; /** * Opens a file. * @param file An object describing the file to open. * @param fileOption An object describing whether to open or save the file. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-navigation/openfile */ OpenFile(file: DevKit.FileData, fileOption?: DevKit.FileOption): void; /** * Opens an entity form or a quick create form. * @param formOption The open form option for opening the form. * @param formParameters A dictionary object that passes extra parameters to the form. Invalid parameters will cause an error. * @param successCallback A function to execute when the record is saved in the quick create form. This function is passed an object as a parameter. * @param errorCallback A function to execute when the operation fails. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-navigation/openform */ OpenForm(formOption: DevKit.FormOption, formParameters?: any, successCallback?: (result: DevKit.EntityReference) => void, errorCallback?: (error: DevKit.Error) => void): void; /** * Opens a URL, including file URLs. * @param url URL to open. * @param window Options to open the URL. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-navigation/openurl */ OpenUrl(url: string, window?: DevKit.Window): void; /** * Opens an HTML web resource. * @param webResourceName Name of the HTML web resource to open. * @param window Window options for opening the web resource. * @param data Data to be passed into the data parameter. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-navigation/openwebresource */ OpenWebResource(webResourceName: string, window?: DevKit.Window, data?: string): void; /** * Navigates to the specified page. * @param pageInput Input about the page to navigate to. The object definition changes depending on the type of page to navigate to: entity list or HTML web resource. * @param navigationOptions Options for navigating to a page: whether to open inline or in a dialog. If you don't specify this parameter, page is opened inline by default. * @param successCallback A function to execute on successful navigation to the page when navigating inline and on closing the dialog when navigating to a dialog. * @param errorCallback A function to execute when the operation fails. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-navigation/navigateto */ NavigateTo(pageInput: DevKit.PageInputEntityList | DevKit.PageInputHtmlWebResource | DevKit.PageInputEntityRecord | DevKit.PageInputDashboard, navigationOptions?: DevKit.NavigationOptions, successCallback?: (result: any) => void, errorCallback?: (error: DevKit.Error) => void): void; /** * Opens a dialog box to select files from your computer (web client) or mobile device (mobile clients). * @param filePickOption An object pick file option * @param successCallback A function to call when selected files are returned. An array of objects with each object having the following attributes is passed to the function. * @param errorCallback A function to call when the operation fails. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-device/pickfile */ PickFile(filePickOption: DevKit.FilePickOption, successCallback: (result: Array<DevKit.FileData>) => void, errorCallback: (error: DevKit.Error) => void): void; /** * Prefixes the current organization's unique name to a string, typically a URL path * @param path A local path to a resource * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/prependorgname */ PrependOrgName(path: string): string; /** * Refreshes the parent grid containing the specified record * @param lookupOption An object with the following properties to specify the record * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/refreshparentgrid */ RefreshParentGrid(lookupOption: DevKit.EntityReference): void; /** * Returns the localized string for a given key associated with the default web resource * @param key The key for the localized string * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getresourcestring */ Resource(key: string): string; /** * Returns the localized string for a given key associated with the specified web resource * @param webResourceName The name of the web resource. E.g.: "devkit_/resources/Resource" * @param key The key for the localized string * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getresourcestring */ ResourceString(webResourceName: string, key: string): string; /** * Displays a progress dialog with the specified message. Any subsequent call to this method will update the displayed message in the existing progress dialog with the message specified in the latest method call. The progress dialog blocks the UI until it is closed using the CloseProgressIndicator method. So, you must use this method with caution * @param message The message to be displayed in the progress dialog * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/showprogressindicator */ ShowProgressIndicator(message: string): void; /** * Encodes the specified string so that it can be used in an XML attribute. * @param arg String to be encoded. */ XmlAttributeEncode(arg: string): string; /** * Converts a string to an XML-encoded string. * @param arg String to be encoded. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-encoding/xmlattributeencode */ XmlEncode(arg: string): string; /** * Encodes the specified string so that it can be used in an HTML attribute. * @param arg String to be encoded. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-encoding/htmlattributeencode */ HtmlAttributeEncode(arg: string): string; /** * Converts a string that has been HTML-encoded into a decoded string. * @param arg HTML-encoded string to be decoded. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-encoding/htmldecode */ HtmlDecode(arg: string): string; /** * Converts a string to an HTML-encoded string. * @param arg String to be encoded. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-encoding/htmlencode */ HtmlEncode(arg: string): string; /** * Displays an error, information, warning, or success notification for an app, and lets you specify actions to execute based on the notification. * @param notification The notification to add. * @param successCallback A function to call when notification is displayed. A GUID value is passed to uniquely identify the notification. You can use the GUID value to close or dismiss the notification using the clearGlobalNotification method. * @param errorCallback A function to call when the operation fails. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-app/addglobalnotification */ AddGlobalNotification(notification: DevKit.GlobalNotification, successCallback?: (result: string) => void, errorCallback?: (error: DevKit.Error) => void): void; /** * Clears a notification in the app. * @param uniqueId The ID to use to clear a specific notification that was set using addGlobalNotification. * @param successCallback A function to call when the notification is cleared. * @param errorCallback A function to call when the operation fails. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-app/clearglobalnotification */ ClearGlobalNotification(uniqueId: string, successCallback?: (result: string) => void, errorCallback?: (error: DevKit.Error) => void): void; /** * Provides access to the methods to determine which client is being used, whether the client is connected to the server, and what kind of device is being used. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/client */ readonly Client: DevKit.Client; /** * Returns the base URL that was used to access the application * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/getclienturl */ readonly ClientUrl: string; /** * Returns the URL of the current business app in Customer Engagement * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/getcurrentappurl */ readonly CurrentAppUrl: string; /** * Returns a boolean value indicating if the Customer Engagement instance is hosted on-premises or online * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/isonpremises */ readonly IsOnPremises: boolean; /** * Returns the name of the DOM attribute expected by the Learning Path (guided help) Content Designer for identifying UI controls in the Dynamics 365 for Customer Engagement apps form. An attribute by this name must be added to the UI element that needs to be exposed to Learning Path (guided help) * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getlearningpathattributename */ readonly LearningPathAttributeName: string; /** * The method returns an object with the input property. The input property is an object with the following attributes depending on whether you are currently on the entity form or entity list * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getpagecontext * */ readonly PageContext: any; /** * Returns information about the current organization settings * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/organizationsettings */ readonly OrganizationSettings: DevKit.OrganizationSettings; /** * Returns information about the current user settings * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/usersettings */ readonly UserSettings: DevKit.UserSettings /** * Returns the version number of the Dynamics 365 for Customer Engagement apps instance. E.g.: "9.0.0.1103" * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/getversion */ readonly Version: string; } interface Client { /** * Returns a value to indicate which client the script is executing in. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/client#getclient */ readonly ClientName: OptionSet.ClientName; /** * Returns a value to indicate the state of the client. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/client#getclientstate */ readonly ClientState: OptionSet.ClientState; /** * Returns information about the kind of device the user is using. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/client#getformfactor */ readonly FormFactor: OptionSet.FormFactor; /** * Returns information whether the server is online or offline * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/client#isoffline */ readonly IsOffline: boolean; } interface OrganizationSettings { /** * Returns attributes and their values as key:value pairs that are available for the organization entity. Additional values will be available as attributes if they are specified as attribute dependencies in the web resource dependency list. The key will be the attribute logical name * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/organizationsettings#attributes */ readonly Attributes: Array<DevKit.KeyValueObject>; /** * [Deprecated] Returns the ID of the base currency for the current organization * @deprecated use {@link BaseCurrency } * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/organizationsettings#basecurrencyid * */ readonly BaseCurrencyId: DevKit.Guid; /** * Returns a lookup object containing the ID, name, and entity type of the base currency for the current organization. This method is supported only on the Unified Interface. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/organizationsettings#basecurrency */ readonly BaseCurrency: DevKit.EntityReference; /** * Returns the default country/region code for phone numbers for the current organization * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/organizationsettings#defaultcountrycode */ readonly DefaultCountryCode: string; /** * Indicates whether the auto-save option is enabled for the current organization * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/organizationsettings#isautosaveenabled */ readonly IsAutoSaveEnabled: boolean; /** * Returns the preferred language ID for the current organization * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/organizationsettings#languageid */ readonly LanguageId: number; /** * Returns the ID of the current organization * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/organizationsettings#organizationid */ readonly OrganizationId: DevKit.Guid; /** * Returns the ID of the current organization * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/organizationsettings#istrialorganization */ readonly IsTrialOrganization: boolean; /** * Returns the expiry date of the current organization if it is a trial organization. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/organizationsettings#organizationexpirydate */ readonly OrganizationExpiryDate: Date; /** * Returns a boolean indicating whether the organization is a trial organization. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/organizationsettings#uniquename */ readonly UniqueName: string; /** * Indicates whether the Skype protocol is used for the current organization * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/organizationsettings#useskypeprotocol */ readonly UseSkypeProtocol: boolean; } interface UserSettings { /** * Returns the date formatting information for the current user * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/usersettings#dateformattinginfo */ readonly DateFormattingInfo: DevKit.DateFormattingInfo; /** * Returns the ID of the default dashboard for the current user * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/usersettings#defaultdashboardid */ readonly DefaultDashboardId: DevKit.Guid; /** * Indicates whether guided help is enabled for the current user * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/usersettings#isguidedhelpenabled */ readonly IsGuidedHelpEnabled: boolean; /** * Indicates whether high contrast is enabled for the current user * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/usersettings#ishighcontrastenabled */ readonly IsHighContrastEnabled: boolean; /** * Indicates whether the language for the current user is a right-to-left (RTL) language * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/usersettings#isrtl */ readonly IsRTL: boolean; /** * Returns the language ID for the current user * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/usersettings#languageid */ readonly LanguageId: number; /** * Returns a collection of lookup objects containing the GUID and display name of each of the security role or teams that the user is associated with. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/usersettings#roles */ readonly Roles: DevKit.Collections<DevKit.EntityReference>; /** * Returns an array of strings that represent the GUID values of each of the security role privilege that the user is associated with or any teams that the user is associated with * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/usersettings#securityroleprivileges */ readonly SecurityRolePrivileges: Array<DevKit.Guid>; /** * [Deprecated] Returns an array of strings that represent the GUID values of each of the security role privilege that the user is associated with or any teams that the user is associated with * @deprecated use {@link SecurityRolePrivileges} * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/usersettings#securityroles */ readonly SecurityRoles: Array<DevKit.Guid>; /** * Returns a lookup object containing the ID, display name, and entity type of the transaction currency for the current user. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/usersettings#transactioncurrencyid */ readonly TransactionCurrency: DevKit.EntityReference; /** * [Deprecated] Returns the transaction currency ID for the current user. * @deprecated use {@link TransactionCurrency} * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/usersettings#transactioncurrency */ readonly TransactionCurrencyId: DevKit.Guid; /** * Returns the GUID of the SystemUser.Id value for the current user * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/usersettings#userid */ readonly UserId: DevKit.Guid; /** * Returns the name of the current user * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/usersettings#username */ readonly UserName: string; /** * Returns the difference in minutes between the local time and Coordinated Universal Time (UTC) * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/xrm-utility/getglobalcontext/usersettings#gettimezoneoffsetminutes-method */ readonly TimeZoneOffsetMinutes: number; } abstract class IForm { /** * Adds a function to be called when the record is saved * @param callback The function to be executed when the record is saved. The function will be added to the bottom of the event handler pipeline. The execution context is automatically passed as the first parameter to the function * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-entity/addonsave */ AddOnSave(callback: (executionContext: any) => void): void; /** * PostSave event occurs after the OnSave event is complete. This event is used to support or execute custom logic using web resources to perform after Save actions when the save event is successful or failed due to server errors * @param callback The function to add to the PostSave event. The execution context is automatically passed as the first parameter to this function * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/events/postsave */ AddPostSave(callback: (executionContext: any) => void): void; /** * Adds a function to be called when form data is loaded. * @param callback The function to be executed when the form data loads. The function will be added to the bottom of the event handler pipeline. The execution context is automatically passed as the first parameter to the function. See Execution context for more information. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data/addonload */ DataAddOnLoad(callback: (executionContext: any) => void): void; /** * Adds a function to be called on the form OnLoad event. * @param callback The function to be executed on the form OnLoad event. The function will be added to the bottom of the event handler pipeline. The execution context is automatically passed as the first parameter to the function. See Execution context for more information. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui/addonload */ UiAddOnLoad(callback: (executionContext: any) => void): void; /** * Removes form level notifications * @param uniqueId A unique identifier for the message to be cleared that was set using the SetFormNotification method * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui/clearformnotification */ ClearFormNotification(uniqueId: string): void; /** * Closes the form * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui/close * */ Close(): void; /** * Opens the specified form. When you use the navigate method while unsaved changes exist, the user is prompted to save changes before the new form can be displayed. The Onload event occurs when the new form loads * @param formId The form Id that you want navigate * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-formselector/navigate */ FormNavigate(formId: DevKit.Guid): void; /** * Returns a value that indicates whether the form is currently visible. * @param formId The form Id that you want to check visible * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-formselector/getvisible */ FormIsVisible(formId: DevKit.Guid): boolean; /** * Sets a value that indicates whether the form is visible. * @param formId The form Id that you want to set visible * @param value Specify true to show the form; false to hide the form. */ FormSetVisible(formId: DevKit.Guid, value: boolean): void; /** * Asynchronously refreshes and optionally saves all the data of the form without reloading the page * @param save true if the data should be saved after it is refreshed, otherwise false * @param successCallback A function to call when the operation succeeds * @param errorCallback A function to call when the operation fails * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data/refresh */ Refresh(save?: boolean, successCallback?: (executionContext: any) => void, errorCallback?: (error: DevKit.Error) => void): void; /** * Causes the ribbon to re-evaluate data that controls what is displayed in it * @param refreshAll Indicates whether all the ribbon command bars on the current page are refreshed. If you specify false, only the page-level ribbon command bar is refreshed. If you do not specify this parameter, by default false is passed * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui/refreshribbon */ RefreshRibbon(refreshAll?: boolean): void; /** * Removes a function to be called when the record is saved. * @param callback The function to be removed for the OnSave event * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-entity/removeonsave */ RemoveOnSave(callback: () => void): void; /** * Removes a function to be called when form data is loaded. * @param callback The function to be removed when the form data loads. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data/removeonload */ DataRemoveOnLoad(callback: () => void): void; /** * Removes a function from the form OnLoad event. * @param callback The function to be removed from the form OnLoad event. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui/removeonload */ UiRemoveOnLoad(callback: () => void): void; /** * Saves the record asynchronously with the option to set callback functions to be executed after the save operation is completed. You can also set an object to control how appointment, recurring appointment, or service activity records are processed * @param saveOption An object for specifying options for saving the record * @param successCallback A function to call when the operation succeeds * @param errorCallback A function to call when the operation fails * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data/save */ Save(saveOption?: DevKit.SaveOption, successCallback?: (executionContext: any) => void, errorCallback?: (error: DevKit.Error) => void): void; /** * Displays form level notifications * @param message The text of the message * @param level The level of the message, which defines how the message will be displayed * @param uniqueId A unique identifier for the message that can be used later with ClearFormNotification to remove the notification * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui/setformnotification */ SetFormNotification(message: string, level: OptionSet.FormNotificationLevel, uniqueId: string): boolean; /** * Sets the name of the entity to be displayed on the form. * @param arg Name of the entity to be displayed on the form. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui/setformentityname * */ SetFormEntityName(arg: string): void; /** * The Attributes collections of form Account * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/attributes * */ readonly Attributes: DevKit.Collections<any>; /** * A control represents an HTML element present on the form. Some controls are bound to a specific attribute, whereas others may represent unbound controls such as an IFRAME, Web resource, or a sub grid that has been added to the form * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/controls */ readonly Controls: DevKit.Collections<any>; /** * Returns a string representing the XML that will be sent to the server when the record is saved. Only data in fields that have changed are set to the server * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-entity/getdataxml */ readonly DataXml: string; /** * Returns a string representing the GUID value for the record * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-entity/getid */ readonly EntityId: DevKit.Guid; /** * Gets a boolean value indicating whether any fields in the form have been modified * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-entity/getisdirty */ readonly EntityIsDirty: boolean; /** * Gets a boolean value indicating whether all of the entity data is valid * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-entity/isvalid */ readonly EntityIsValid: boolean; /** * Returns a string representing the logical name of the entity for the record * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-entity/getentityname */ readonly EntityName: string; /** * Returns a lookup value that references the record * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-entity/getentityreference */ readonly EntityReference: DevKit.EntityReference; /** * Returns the ID of the form * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-formselector/getid */ readonly FormId: DevKit.Guid; /** * Returns the label of the form * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui-formselector/getlabel */ readonly FormLabel: string; /** * Gets the form type for the record * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui/getformtype */ readonly FormType: OptionSet.FormType; /** * Gets a boolean value indicating whether the form data has been modified * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data/getisdirty */ readonly DataIsDirty: boolean; /** * Gets a boolean value indicating whether all of the form data is valid. This includes the main entity and any unbound attributes * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data/isvalid */ readonly DataIsValid: boolean; /** * Gets a string for the value of the primary attribute of the entity * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-data-entity/getprimaryattributevalue */ readonly PrimaryAttributeValue: string; /** * Gets the height of the viewport in pixels. The viewport is the area of the page containing form data. It corresponds to the body of the form and does not include the navigation, header, footer or form assistant areas of the page * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui/getviewportheight * */ readonly ViewPortHeight: number; /** * Get the width of the viewport in pixels. The viewport is the area of the page containing form data. It corresponds to the body of the form and does not include the navigation, header, footer or form assistant areas of the page * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/formcontext-ui/getviewportwidth * */ readonly ViewPortWidth: number; /** * The execution context defines the event context in which your code executes. * @link https://docs.microsoft.com/en-us/powerapps/developer/model-driven-apps/clientapi/reference/execution-context * */ readonly ExecutionContext: DevKit.ExecutionContext; } interface DialogError { /** Details about the error. When you specify this, the Download Log File button is available in the error message, and clicking it will let users download a text file with the content specified in this attribute */ details?: string; /** The error code. If you just set errorCode, the message for the error code is automatically retrieved from the server and displayed in the error dialog.If you specify an invalid errorCode value, an error dialog with a default error message is displayed */ errorCode?: number; /** The message to be displayed in the error dialog */ message?: string; } interface EntityReference { /** Entity type of the record */ entityType: string; /** GUID of the record */ id: DevKit.Guid; /** Name of the record */ name?: string; } interface Window { /** Height of the window to display the resultant page in pixels */ height?: number; /** Width of the window to display the resultant page in pixels */ width?: number; } interface DialogAlertOption { /** The confirm button label.If you do not specify the button label, OK is used as the button label */ confirmButtonLabel?: string; /** The message to be displyed in the alert dialog */ text: string; } interface FileOption { openMode: OptionSet.FileOption } interface DialogConfirmOption { /** The message to be displayed in the confirmation dialog */ text: string; /** The cancel button label.If you do not specify the cancel button label, Cancel is used as the button label */ cancelButtonLabel?: string; /** The confirm button label.If you do not specify the confirm button label, OK is used as the button label */ confirmButtonLabel?: string; /** The subtitle to be displayed in the confirmation dialog */ subtitle?: string; /** The title to be displayed in the confirmation dialog */ title?: string; } interface FilePickOption { /** Image file types to select */ accept: OptionSet.FileAccept; /** Indicates whether to allow selecting multiple files */ allowMultipleFiles: boolean; /** Maximum size of the files(s) to be selected */ maximumAllowedFileSize: number; } interface LookupOption { /** Indicates whether the lookup allows more than one item to be selected */ allowMultiSelect?: boolean; /** The default entity type to use */ defaultEntityType?: string; /** The default view to use */ defaultViewId?: DevKit.Guid; /** Decides whether to display the most recently used(MRU) item. Available only for Unified Interface */ disableMru?: boolean; /** The entity types to display */ entityTypes: Array<string>; /** Used to filter the results */ filters?: Array<LookupFilter>; /** Indicates the default search term for the lookup control. */ searchText?: string; /** Indicates whether the lookup control should show the barcode scanner in mobile clients */ showBarcodeScanner?: boolean; /** The views to be available in the view picker. Only system views are supported */ viewIds?: Array<DevKit.Guid>; } interface PageInputEntityList { /** Specify "entitylist" */ pageType: "entitylist"; /** The logical name of the entity to load in the list control. */ entityName: string; /** The ID of the view to load. If you don't specify it, navigates to the default main view for the entity. */ viewId?: DevKit.Guid; /** Type of view to load. Specify "savedquery" or "userquery". */ viewType?: "savedquery" | "userquery"; } interface PageInputHtmlWebResource { /** Specify "webresource" */ pageType: "webresource"; /** The name of the web resource to load. */ webresourceName: string; /** The data to pass to the web resource. */ data?: string; } interface PageInputEntityRecordRelationship { /** Name of the attribute used for relationship. */ attributeName: string, /** Name of the relationship. */ name: string, /** Name of the navigation property for this relationship. */ navigationPropertyName: string, /** Relationship type. Specify one of the following values: 0:OneToMany | 1:ManyToMany */ relationshipType: 0 | 1; /** Role type in relationship. Specify one of the following values: 1:Referencing | 2:AssociationEntity */ roleType: 1 | 2; } interface PageInputEntityRecord { /** Specify "entityrecord" */ pageType: "entityrecord", /** Logical name of the entity to display the form for. */ entityName: string, /** ID of the entity record to display the form for. If you don't specify this value, the form will be opened in create mode. */ entityId?: DevKit.Guid, /** Designates a record that will provide default values based on mapped attribute values. */ createFromEntity?: DevKit.EntityReference, /** A dictionary object that passes extra parameters to the form. */ data?: any, /** ID of the form instance to be displayed. */ formId: DevKit.Guid, /** Indicates whether the form is navigated to from a different entity using cross-entity business process flow. */ isCrossEntityNavigate?: boolean, /** Indicates whether there are any offline sync errors. */ isOfflineSyncError?: boolean, /** ID of the business process to be displayed on the form. */ processId?: DevKit.Guid, /** ID of the business process instance to be displayed on the form. */ processInstanceId?: DevKit.Guid, /** Define a relationship object to display the related records on the form. */ relationship?: DevKit.PageInputEntityRecordRelationship, /** ID of the selected stage in business process instance. */ selectedStageId?: string } interface PageInputDashboard { /** Specify "dashboard" */ pageType: "dashboard", /** The ID of the dashboard to load. If you don't specify the ID, navigates to the default dashboard. */ dashboardId: string } interface NavigationOptions { /** Specify 1 to open the page inline; 2 to open the page in a dialog. Entity lists can only be opened inline; web resources can be opened either inline or in a dialog. */ target: 1 | 2; /** The width of dialog. To specify the width in pixels, just type a numeric value. To specify the width in percentage, specify an object of type */ width?: number | SizeValue; /** The height of dialog. To specify the width in pixels, just type a numeric value. To specify the height in percentage, specify an object of type */ height?: number | SizeValue; /** Specify 1 to open the dialog in center; 2 to open the dialog on the side. Default is 1 (center). */ position?: 1 | 2; /** The dialog title on top of the center or side dialog. */ title?: string; } interface SizeValue { /** The numerical value */ value: number; /** The unit of measurement. Specify "%" or "px". Default value is "px" */ unit: "%" | "px"; } interface LookupFilter { /** The FetchXML filter element to apply */ filterXml: string; /** The entity type to which to apply this filter */ entityLogicalName: string } interface FormOption { /** Indicates whether to display the command bar. If you do not specify this parameter, the command bar is displayed by default */ cmdbar?: boolean; /** Designates a record that will provide default values based on mapped attribute values */ createFromEntity?: EntityReference; /** ID of the entity record to display the form for */ entityId?: DevKit.Guid; /** Logical name of the entity to display the form for */ entityName?: string; /** ID of the form instance to be displayed */ formId?: DevKit.Guid; /** Height of the form window to be displayed in pixels */ height?: number; /** Controls whether the navigation bar is displayed and whether application navigation is available using the areas and subareas defined in the sitemap */ navbar?: OptionSet.FormNavBar; /** Indicates whether to display form in a new window */ openInNewWindow?: boolean; /** Specify one of the following values for the window position of the form on the screen */ windowPosition?: OptionSet.FormWindowPosition; /** ID of the business process to be displayed on the form */ processId?: DevKit.Guid; /** ID of the business process instance to be displayed on the form */ processInstanceId?: DevKit.Guid; /** Define a relationship object to display the related records on the form */ relationship?: FormRelationship; /** ID of the selected stage in business process instance */ selectedStageId?: string; /** Indicates whether to open a quick create form. If you do not specify this, by default false is passed */ useQuickCreateForm?: boolean; /** Width of the form window to be displayed in pixels */ width?: number; } interface FormRelationship { /** Name of the attribute used for relationship */ attributeName: string; /** Name of the relationship */ name: string; /** Name of the navigation property for this relationship */ navigationPropertyName: string; /** Relationship type */ relationshipType: OptionSet.FormRelationshipType; /** Role type in relationship. */ roleType: OptionSet.FormRelationshipRoleType; } interface ImageOption { /** Indicates whether to edit the image before saving */ allowEdit: boolean; /** Height of the image to capture */ height: number; /** Indicates whether to capture image using the front camera of the device */ preferFrontCamera: boolean; /** Quality of the image file in percentage */ quality: number; /** Width of the image to capture */ width: number; } interface PositionData { /** Contains a set of geographic coordinates along with associated accuracy as well as a set of other optional attributes such as altitude and speed */ coords: any; /** Represents the time when the object was acquired and is represented as DOMTimeStamp */ timestamp: any; } interface SaveOption { /** Specify a value indicating how the save event was initiated */ saveMode?: OptionSet.SaveMode; /** Indicate whether to use the Book or Reschedule messages rather than the Create or Update messages. This option is only applicable when used with appointment, recurring appointment, or service activity records */ useSchedulingEngine: boolean; } interface FieldNotification { /** A collection of objects */ actions?: Array<FieldNotificationAction>; /** The message to display in the notification. In the current release, only the first message specified in this array will be displayed. The string that you specify here appears as bold text in the notification, and is typically used for title or subject of the notification. You should limit your message to 50 characters for optimal user experience */ messages: Array<string>; /** Defines the type of notification */ notificationLevel: OptionSet.FieldNotificationLevel; /** The ID to use to clear this notification when using the clearNotification method */ uniqueId: string; } interface FieldNotificationAction { /** The body message of the notification to be displayed to the user. Limit your message to 100 characters for optimal user experience */ message?: string; /** Array of functions. The corresponding actions for the message */ actions?: Array<any>; } interface GlobalNotification { action?: GlobalNotificationAction, /** Defines the level of notification. Valid values are: 1: Success | 2: Error | 3: Warning | 4: Information */ level: 1 | 2 | 3 | 4, /** The message to display in the notification. */ message: string, /** ndicates whether or not the user can close or dismiss the notification. If you don't specify this parameter, users can't close or dismiss the notification by default. */ showCloseButton: boolean, /** Defines the type of notification. Currently, only a value of 2 is supported, which displays a message bar at the top of the app. */ type: 2 } interface GlobalNotificationAction { /** The label for the action in the message. */ actionLabel?: string, /** Function reference. The function to execute when the action label is clicked. */ eventHandler?: string } interface ViewSelector { /** Reference to the current view. */ CurrentView: DevKit.EntityReference; /** Returns a boolean value to indicate whether the view selector is visible */ readonly Visible: boolean; } } /** DynamicsCrm.DevKit for namespace OptionSet */ declare namespace OptionSet { /** */ enum StructuralProperty { /** 0 */ Unknown, /** 1 */ PrimitiveType, /** 2 */ ComplexType, /** 3 */ EnumerationType, /** 4 */ Collection, /** 5 */ EntityType } /** */ enum OperationType { /** 0 */ Action, /** 1 */ Function, /** 2 */ CRUD } /** Returns information about the kind of device the user is using. */ enum FormFactor { /** 0 */ Unknown, /** 1 */ Desktop, /** 2 */ Tablet, /** 3 */ Phone, } /** Returns a value to indicate the state of the client. */ enum ClientState { /** Online */ Online, /** Offline */ Offline, } /** Returns a value to indicate which client the script is executing in. */ enum ClientName { /** Web */ Web, /** Outlook */ Outlook, /** Mobile */ Mobile } /** Gets the form type for the record. */ enum FormType { /** 0 */ Undefined, /** 1 - Quick Create forms return 1 */ Create, /** 2 */ Update, /** 3 */ ReadOnly, /** 4 */ Disabled, /** 5 */ BulkEdit, } /** Specify options for saving the record. If no parameter is included in the method, the record will simply be saved. This is the equivalent of using the Save command */ enum SaveOption { /** saveandclose - This is the equivalent of using the Save and Close command */ SaveAndClose, /** saveandnew - This is the equivalent of the using the Save and New command */ SaveAndNew } /** Returns a value indicating how the save event was initiated by the user */ enum SaveMode { /** 1 - All entities */ Save, /** 2 - All entities */ SaveAndClose, /** 5 - All entities */ Deactivate, /** 6 - All entities */ Reactivate, /** 7 - Email */ Send, /** 15 - Lead */ Disqualify, /** 16 - Lead */ Qualify, /** 47 - User or Team */ Assign, /** 58 - Activities */ SaveAsCompleted, /** 59 - All entities */ SaveAndNew, /** 70 - All entities */ AutoSave } /** The level of the message, which defines how the message will be displayed */ enum FormNotificationLevel { /** ERROR - Notification will use the system error icon */ Error, /** WARNING - Notification will use the system warning icon */ Warning, /** INFO - Notification will use the system info icon */ Info } /** Display state of the tab */ enum TabDisplayState { /** expanded */ Expanded, /** collapsed */ Collapsed } /** The contry type of tab */ enum TabContentType { /** cardSections: The default tab behavior */ CardSections, /** singleComponent: Maximizes the content of the first component in the tab */ SingleComponent } /** */ enum ProcessDisplayState { /** expanded */ Expanded, /** collapsed */ Collapsed, /** floating */ Floating } /** Returns a string value that represents the type of attribute */ enum FieldAttributeType { /** boolean */ Boolean, /** datetime */ DateTime, /** decimal */ Decimal, /** double */ Double, /** integer */ Integer, /** lookup */ Lookup, /** memo */ Memo, /** money */ Money, /** multiselectoptionset */ MultiOptionSet, /** optionset */ OptionSet, /** string */ String } /** Returns a string value that represents formatting options for the attribute */ enum FieldFormat { /** null */ Null, /** date */ Date, /** datetime */ DateTime, /** duration */ Duration, /** email */ Email, /** language */ Language, /** none */ None, /** textarea */ TextArea, /** text */ Text, /** tickersymbol */ TickerSymbol, /** phone */ Phone, /** timezone */ TimeZone, /** url */ Url } /** Value indicating whether a value for the attribute is none or required or recommended */ enum FieldRequiredLevel { /** none */ None, /** required */ Required, /** recommended */ Recommended } /** Data from the attribute will be submitted when the record is saved */ enum FieldSubmitMode { /** always - The data is always sent with a save */ Always, /** never - The data is never sent with a save. When this is used, the field(s) in the form for this attribute cannot be edited */ Never, /** dirty - Default behavior. The data is sent with the save when it has changed */ Dirty } /** A value that categorizes controls */ enum FieldControlType { /** standard - A standard control */ Standard, /** iframe - An IFRAME control */ Iframe, /** kbsearch - A knowledge base search control */ KbSearch, /** lookup - A lookup control */ Lookup, /** multiselectoptionset - A multi-select option set control */ MultiSelectOptionset, /** notes - A notes control */ Notes, /** optionset - An option set control */ OptionSet, /** quickform - A quick view control */ QuickForm, /** subgrid - A subgrid control */ SubGrid, /** timercontrol - A timer control */ TimerControl, /** timelinewall - A timeline control (for Unified Interface) */ TimelineWall, /** webresource - A web resource control */ WebResource } /** The type of notification */ enum FieldNotificationLevel { /** ERROR */ Error, /** RECOMMENDATION */ Recommendation } /** The integer value of the business process flow category */ enum ProcessCategory { /** 0 */ Qualify, /** 1 */ Develop, /** 2 */ Propose, /** 3 */ Close, /** 4 */ Identify, /** 5 */ Research, /** 6 */ Resolve } /** The integer value status of the stage */ enum ProcessStatus { /** active */ Active, /** aborted */ Aborted, /** finished */ Finished } /** The progress of the action step */ enum ProcessProgress { /** 0 */ None, /** 1 */ Processing, /** 2 */ Completed, /** 3 */ Failure, /** 4 */ Invalid } /** The state of the timer control - This method is only supported for Unified Interface */ enum TimerState { /** 1 */ NotSet, /** 2 */ InProgress, /** 3 */ Warning, /** 4 */ Violated, /** 5 */ Success, /** 6 */ Expired, /** 7 */ Canceled, /** 8 */ Paused } /** Information about the advanced configuration settings for the organization */ enum AdvancedConfigSetting { /** MaxChildIncidentNumber */ MaxChildIncidentNumber, /** MaxIncidentMergeNumber */ MaxIncidentMergeNumber } /** Describing whether to open or save the file */ enum FileOption { /** 1 */ Open, /** 2 */ Save } /** Describes the type of operation for the privilege */ enum PrivilegeType { /** 0 - Specifies no privilege. */ None, /** 1 - The create privilege. */ Create, /** 2 - The read privilege. */ Read, /** 3 - The write privilege. */ Write, /** 4 - The delete privilege. */ Delete, /** 5 - The assign privilege. */ Assign, /** 6 - The share privilege. */ Share, /** 7 - The append privilege. */ Append, /** 8 - The append to privilege. */ AppendTo } /** */ enum FormNavBar { /** "on" - The navigation bar is displayed. This is the default behavior if the navbar parameter is not used. */ On, /** "off" - The navigation bar is not displayed. People can navigate using other user interface elements or the back and forward buttons. */ Off, /** "entity" - On an entity form, only the navigation options for related entities are available. After navigating to a related entity, a back button is displayed in the navigation bar to allow returning to the original record. */ Entity } /** */ enum FormWindowPosition { /** 1 */ Center, /** 2 */ Side } /** */ enum FormRelationshipType { /** 0 */ OneToMany, /** 1 */ ManyToMany } /** */ enum FormRelationshipRoleType { /** 1 */ Referencing, /** 2 */ AssociationEntity } /** */ enum FileAccept { /** "audio" */ Audio, /** "video" */ Video, /** "image" */ Image } /** */ enum GridType { /** 1 */ HomePageGrid, /** 2 */ Subgrid } }
the_stack
import assert from 'assert'; import { Ast, } from 'thingtalk'; import * as ThingTalkUtils from '../../utils/thingtalk'; import * as C from '../ast_manip'; import ThingpediaLoader from '../load-thingpedia'; import { AgentReplyOptions, ContextInfo, NameList, makeAgentReply, makeSimpleState, addActionParam, addAction, addQuery, } from '../state_manip'; import { isInfoPhraseCompatibleWithResult, findChainParam } from './common'; import { queryRefinement, refineFilterToAnswerQuestionOrChangeFilter, combinePreambleAndRequest, proposalReply, } from './refinement-helpers'; import { SlotBag } from '../slot_bag'; import { DirectAnswerPhrase } from './results'; export interface ListProposal { results : Ast.DialogueHistoryResultItem[]; info : SlotBag|null; action : Ast.Invocation|null; hasLearnMore : boolean; } export function listProposalKeyFn({ results, info, action, hasLearnMore } : ListProposal) { return { idType: results[0].value.id ? results[0].value.id.getType() : null, queryName: info ? info.schema!.qualifiedName : null, actionName: action ? action.schema!.qualifiedName : null, length: results.length }; } function checkInvocationCast(x : Ast.Invocation|Ast.FunctionCallExpression) : Ast.Invocation { assert(x instanceof Ast.Invocation); return x; } function checkListProposal(nameList : NameList, info : SlotBag|null, hasLearnMore : boolean) : ListProposal|null { const { ctx, results } = nameList; const resultType = results[0].value.id.getType(); const currentStmt = ctx.current!.stmt; const currentTable = currentStmt.expression; const last = currentTable.last; if ((last instanceof Ast.SliceExpression || (last instanceof Ast.ProjectionExpression && last.expression instanceof Ast.SliceExpression)) && results.length !== ctx.results!.length) return null; if (info !== null) { const idType = info.schema!.getArgType('id'); if (!idType || !idType.equals(resultType)) return null; const resultInfo = ctx.resultInfo!; if (resultInfo.projection !== null) { // check that all projected names are present for (const name of resultInfo.projection) { if (!info.has(name)) return null; } } // check that the filter uses the right set of parameters for (const result of results) { if (!isInfoPhraseCompatibleWithResult(result, info)) return null; } } else { if (ctx.resultInfo!.projection !== null) return null; } const action = ctx.nextInfo && ctx.nextInfo.isAction ? checkInvocationCast(C.getInvocation(ctx.next!)) : null; return { results, info, action, hasLearnMore }; } export type ThingpediaListProposal = [ContextInfo, SlotBag]; export function checkThingpediaListProposal(proposal : ThingpediaListProposal, additionalInfo : SlotBag|null) : ListProposal|null { const [ctx, info] = proposal; const resultInfo = ctx.resultInfo!; if (resultInfo.projection !== null) { // check that all projected names are present for (const name of resultInfo.projection) { if (!info.has(name)) return null; } } let mergedInfo : SlotBag|null = info; if (additionalInfo) { // check that the new info is truthful for (const result of ctx.results!) { if (!isInfoPhraseCompatibleWithResult(result, additionalInfo)) return null; } mergedInfo = SlotBag.merge(mergedInfo, additionalInfo); } if (!mergedInfo) return null; const action = ctx.nextInfo && ctx.nextInfo.isAction ? checkInvocationCast(C.getInvocation(ctx.next!)) : null; return { results: ctx.results!, info: mergedInfo, action, hasLearnMore: false }; } export function addActionToListProposal(nameList : NameList, action : Ast.Invocation) : ListProposal|null { const { ctx, results } = nameList; if (ctx.resultInfo!.projection !== null) return null; const currentStmt = ctx.current!.stmt; const currentTable = currentStmt.expression; const last = currentTable.last; if (last instanceof Ast.SliceExpression && results.length !== ctx.results!.length) return null; if (!results[0].value.id) return null; const resultType = results[0].value.id.getType(); if (!C.hasArgumentOfType(action, resultType)) return null; const ctxAction = ctx.nextInfo && ctx.nextInfo.isAction ? checkInvocationCast(C.getInvocation(ctx.next!)) : null; if (ctxAction && !C.isSameFunction(ctxAction.schema!, action.schema!)) return null; return { results, info: null, action, hasLearnMore: false }; } export function makeListProposalFromDirectAnswers(...phrases : DirectAnswerPhrase[]) : ListProposal|null { for (let i = 0; i < phrases.length; i++) { if (phrases[i].index !== i) return null; } const ctx = phrases[0].result.ctx; const currentStmt = ctx.current!.stmt; const currentTable = currentStmt.expression; const last = currentTable.last; if ((last instanceof Ast.SliceExpression || (last instanceof Ast.ProjectionExpression && last.expression instanceof Ast.SliceExpression)) && phrases.length !== ctx.results!.length) return null; // check that all phrases talk about the same slots (it would be weird otherwise) for (let i = 1; i < phrases.length; i++) { for (const key of phrases[i].result.info.keys()) { if (!phrases[0].result.info.has(key)) return null; } for (const key of phrases[0].result.info.keys()) { if (!phrases[i].result.info.has(key)) return null; } } const resultInfo = ctx.resultInfo!; if (resultInfo.projection !== null) { // check that all projected names are present for (const name of resultInfo.projection) { if (!phrases[0].result.info.has(name)) return null; } } // don't use a direct answer with a list if the user is issuing a query by name const filterTable = C.findFilterExpression(currentTable); if (filterTable && C.filterUsesParam(filterTable.filter, 'id')) return null; const results = ctx.results!.slice(0, phrases.length); return { results, info: null, action: null, hasLearnMore: false }; } function makeListProposalReply(ctx : ContextInfo, proposal : ListProposal) { const { results, action, hasLearnMore } = proposal; const options : AgentReplyOptions = { numResults: results.length }; if (action || hasLearnMore) options.end = false; let dialogueAct; switch (results.length) { case 2: dialogueAct = 'sys_recommend_two'; break; case 3: dialogueAct = 'sys_recommend_three'; break; case 4: dialogueAct = 'sys_recommend_four'; break; default: dialogueAct = 'sys_recommend_many'; } if (action === null) return makeAgentReply(ctx, makeSimpleState(ctx, dialogueAct, null), proposal, null, options); else return makeAgentReply(ctx, addAction(ctx, dialogueAct, action, 'proposed'), proposal, null, options); } function positiveListProposalReply(loader : ThingpediaLoader, ctx : ContextInfo, [name, acceptedAction, mustHaveAction] : [Ast.Value, Ast.Invocation|null, boolean]) { // if actionProposal === null the flow is roughly // // U: hello i am looking for a restaurant // A: how about the ... or the ... ? // U: I like the ... bla // // in this case, the agent should hit the "... is a ... restaurant in the ..." // we treat it as "execute" dialogue act and add a filter that causes the program to return a single result const proposal = ctx.aux as ListProposal; const { results, action: actionProposal } = proposal; if (!results[0].value.id) return null; let good = false; for (const result of results) { if (result.value.id.equals(name)) { good = true; break; } } if (!good) return null; if (acceptedAction === null) acceptedAction = actionProposal; if (acceptedAction === null) { if (mustHaveAction) return null; const currentStmt = ctx.current!.stmt; const currentTable = currentStmt.expression; const namefilter = new Ast.BooleanExpression.Atom(null, 'id', '==', name); const newTable = queryRefinement(currentTable, namefilter, (one, two) => new Ast.BooleanExpression.And(null, [one, two]), null); if (newTable === null) return null; return addQuery(ctx, 'execute', newTable, 'accepted'); } else { if (actionProposal !== null && !C.isSameFunction(actionProposal.schema!, acceptedAction.schema!)) return null; // do not consider a phrase of the form "play X" to be "accepting the action by name" // if the action auto-confirms, because the user is likely playing something else if (acceptedAction && name) { const confirm = ThingTalkUtils.normalizeConfirmAnnotation(acceptedAction.schema as Ast.FunctionDef); if (confirm === 'auto') return null; } const chainParam = findChainParam(results[0], acceptedAction); if (!chainParam) return null; return addActionParam(ctx, 'execute', acceptedAction, chainParam, name, 'accepted'); } } function positiveListProposalReplyActionByName(loader : ThingpediaLoader, ctx : ContextInfo, action : Ast.Invocation) { const proposal = ctx.aux as ListProposal; const { results } = proposal; if (!results[0].value.id) return null; let name = null; const acceptedAction = action.clone(); const idType = results[0].value.id.getType(); // find the chain parameter for the action, extract the name, and set the param to undefined // as the rest of the code expects for (const in_param of acceptedAction.in_params) { const arg = action.schema!.getArgument(in_param.name); assert(arg); if (arg.type.equals(idType)) { name = in_param.value; in_param.value = new Ast.Value.Undefined(true); break; } } if (!name) return null; return positiveListProposalReply(loader, ctx, [name, acceptedAction, false]); } function negativeListProposalReply(ctx : ContextInfo, [preamble, request] : [Ast.Expression|null, Ast.Expression|null]) { if (!((preamble === null || preamble instanceof Ast.FilterExpression) && (request === null || request instanceof Ast.FilterExpression))) return null; const proposal = ctx.aux as ListProposal; const { results, info } = proposal; if (!results[0].value.id) return null; const proposalType = results[0].value.id.getType(); request = combinePreambleAndRequest(preamble, request, info, proposalType); if (request === null) return null; return proposalReply(ctx, request, refineFilterToAnswerQuestionOrChangeFilter); } function listProposalLearnMoreReply(ctx : ContextInfo, name : Ast.Value) { // note: a learn more from a list proposal is different than a learn_more from a recommendation // in a recommendation, there is no change to the program, and the agent replies "what would // you like to know" // in a list proposal, we add a filter "id == " const proposal = ctx.aux as ListProposal; const { results } = proposal; if (!results[0].value.id) return null; let good = false; for (const result of results) { if (result.value.id.equals(name)) { good = true; break; } } if (!good) return null; const currentStmt = ctx.current!.stmt; const currentTable = currentStmt.expression; const namefilter = new Ast.BooleanExpression.Atom(null, 'id', '==', name); const newTable = queryRefinement(currentTable, namefilter, (one, two) => new Ast.BooleanExpression.And(null, [one, two]), null); if (newTable === null) return null; return addQuery(ctx, 'execute', newTable, 'accepted'); } export { checkListProposal, makeListProposalReply, positiveListProposalReply, positiveListProposalReplyActionByName, listProposalLearnMoreReply, negativeListProposalReply };
the_stack
import { CMakeTools } from '@cmt/cmakeTools'; import { DefaultEnvironment, expect, getFirstSystemKit } from '@test/util'; //import sinon = require('sinon'); import * as fs from 'fs'; import * as path from 'path'; suite('Debug/Launch interface', async () => { let cmt: CMakeTools; let testEnv: DefaultEnvironment; setup(async function (this: Mocha.Context) { this.timeout(100000); testEnv = new DefaultEnvironment('test/extension-tests/successful-build/project-folder', 'build', 'output.txt'); cmt = await CMakeTools.create(testEnv.vsContext, testEnv.wsContext); await cmt.setKit(await getFirstSystemKit(cmt)); testEnv.projectFolder.buildDirectory.clear(); expect(await cmt.build()).to.be.eq(0); }); teardown(async function (this: Mocha.Context) { this.timeout(30000); await cmt.asyncDispose(); testEnv.teardown(); }); test('Test call of debugger', async () => { const executablesTargets = await cmt.executableTargets; expect(executablesTargets.length).to.be.not.eq(0); await cmt.setLaunchTargetByName(executablesTargets[0].name); await cmt.debugTarget(); //sinon.assert.calledWith(testEnv.vs_debug_start_debugging); }).timeout(60000); test('Test buildTargetName for use in other extensions or launch.json', async () => { const executablesTargets = await cmt.executableTargets; expect(executablesTargets.length).to.be.not.eq(0); expect(await cmt.buildTargetName()).to.be.eq(await cmt.allTargetName); await cmt.setDefaultTarget(executablesTargets[0].name); expect(await cmt.buildTargetName()).to.be.eq(executablesTargets[0].name); }); test('Test launchTargetPath for use in other extensions or launch.json', async () => { const executablesTargets = await cmt.executableTargets; expect(executablesTargets.length).to.be.not.eq(0); await cmt.setLaunchTargetByName(executablesTargets[0].name); expect(await cmt.launchTargetPath()).to.be.eq(executablesTargets[0].path); }); test('Test launchTargetDirectory for use in other extensions or launch.json', async () => { const executablesTargets = await cmt.executableTargets; expect(executablesTargets.length).to.be.not.eq(0); await cmt.setLaunchTargetByName(executablesTargets[0].name); expect(await cmt.launchTargetDirectory()).to.be.eq(path.dirname(executablesTargets[0].path)); }); test('Test launchTargetFilename for use in other extensions or launch.json', async () => { const executablesTargets = await cmt.executableTargets; expect(executablesTargets.length).to.be.not.eq(0); await cmt.setLaunchTargetByName(executablesTargets[0].name); expect(await cmt.launchTargetFilename()).to.be.eq(path.basename(executablesTargets[0].path)); }); test('Test getLaunchTargetPath for use in other extensions or launch.json', async () => { const executablesTargets = await cmt.executableTargets; expect(executablesTargets.length).to.be.not.eq(0); await cmt.setLaunchTargetByName(executablesTargets[0].name); expect(await cmt.getLaunchTargetPath()).to.be.eq(executablesTargets[0].path); }); test('Test getLaunchTargetDirectory for use in other extensions or launch.json', async () => { const executablesTargets = await cmt.executableTargets; expect(executablesTargets.length).to.be.not.eq(0); await cmt.setLaunchTargetByName(executablesTargets[0].name); expect(await cmt.getLaunchTargetDirectory()).to.be.eq(path.dirname(executablesTargets[0].path)); }); test('Test getLaunchTargetFilename for use in other extensions or launch.json', async () => { const executablesTargets = await cmt.executableTargets; expect(executablesTargets.length).to.be.not.eq(0); await cmt.setLaunchTargetByName(executablesTargets[0].name); expect(await cmt.getLaunchTargetFilename()).to.be.eq(path.basename(executablesTargets[0].path)); }); test('Test build on launch (default)', async () => { testEnv.config.updatePartial({ buildBeforeRun: undefined }); const executablesTargets = await cmt.executableTargets; expect(executablesTargets.length).to.be.not.eq(0); await cmt.setLaunchTargetByName(executablesTargets[0].name); const launchProgramPath = await cmt.launchTargetPath(); expect(launchProgramPath).to.be.not.null; const validPath: string = launchProgramPath!; // Check that the compiled files does not exist fs.unlinkSync(validPath); expect(fs.existsSync(validPath)).to.be.false; // Check that the 'get' version does not rebuild the target await cmt.getLaunchTargetPath(); expect(fs.existsSync(validPath)).to.be.false; // Check that the original version does rebuild the target await cmt.launchTargetPath(); expect(fs.existsSync(validPath)).to.be.false; }).timeout(60000); test('Test build on launch on by config', async () => { testEnv.config.updatePartial({ buildBeforeRun: true }); const executablesTargets = await cmt.executableTargets; expect(executablesTargets.length).to.be.not.eq(0); await cmt.setLaunchTargetByName(executablesTargets[0].name); const launchProgramPath = await cmt.launchTargetPath(); expect(launchProgramPath).to.be.not.null; const validPath: string = launchProgramPath!; // Check that the compiled files does not exist fs.unlinkSync(validPath); expect(fs.existsSync(validPath)).to.be.false; await cmt.launchTargetPath(); // Check that it is compiled as a new file expect(fs.existsSync(validPath)).to.be.true; }).timeout(60000); test('Test build on launch off by config', async () => { testEnv.config.updatePartial({ buildBeforeRun: false }); const executablesTargets = await cmt.executableTargets; expect(executablesTargets.length).to.be.not.eq(0); await cmt.setLaunchTargetByName(executablesTargets[0].name); const launchProgramPath = await cmt.launchTargetPath(); expect(launchProgramPath).to.be.not.null; const validPath: string = launchProgramPath!; // Check that the compiled files does not exist fs.unlinkSync(validPath); expect(fs.existsSync(validPath)).to.be.false; await cmt.launchTargetPath(); // Check that it is compiled as a new file expect(fs.existsSync(validPath)).to.be.false; }).timeout(60000); test('Test launch target', async () => { testEnv.config.updatePartial({ buildBeforeRun: false }); const executablesTargets = await cmt.executableTargets; expect(executablesTargets.length).to.not.eq(0); await cmt.setLaunchTargetByName(executablesTargets[0].name); const launchProgramPath = await cmt.launchTargetPath(); expect(launchProgramPath).to.be.not.null; // Remove file if exists const createdFileOnExecution = path.join(path.dirname(launchProgramPath!), 'test.txt'); if (fs.existsSync(createdFileOnExecution)) { fs.unlinkSync(createdFileOnExecution); } const terminal = await cmt.launchTarget(); expect(terminal).to.be.not.null; expect(terminal!.name).to.eq('CMake/Launch'); const start = new Date(); // Needed to get launch target result await new Promise(resolve => setTimeout(resolve, 3000)); const elapsed = (new Date().getTime() - start.getTime()) / 1000; console.log(`Waited ${elapsed} seconds for output file to appear`); const exists = fs.existsSync(createdFileOnExecution); // Check that it is compiled as a new file expect(exists).to.be.true; }).timeout(60000); test('Test launch same target multiple times when newTerminal run is enabled', async () => { testEnv.config.updatePartial({ buildBeforeRun: false, launchBehavior: 'newTerminal' }); const executablesTargets = await cmt.executableTargets; expect(executablesTargets.length).to.be.not.eq(0); await cmt.setLaunchTargetByName(executablesTargets[0].name); const launchProgramPath = await cmt.launchTargetPath(); expect(launchProgramPath).to.be.not.null; // Remove file if exists const createdFileOnExecution = path.join(path.dirname(launchProgramPath!), 'test.txt'); if (fs.existsSync(createdFileOnExecution)) { fs.unlinkSync(createdFileOnExecution); } const term1 = await cmt.launchTarget(); expect(term1).to.be.not.null; const term1Pid = await term1?.processId; const term2 = await cmt.launchTarget(); expect(term2).to.be.not.null; expect(term2!.name).of.be.eq('CMake/Launch'); const term2Pid = await term2?.processId; expect(term1Pid).to.not.eq(term2Pid); }).timeout(60000); test('Test launch same target multiple times when newTerminal run is disabled', async () => { testEnv.config.updatePartial({ buildBeforeRun: false, launchBehavior: 'reuseTerminal' }); const executablesTargets = await cmt.executableTargets; expect(executablesTargets.length).to.be.not.eq(0); await cmt.setLaunchTargetByName(executablesTargets[0].name); const launchProgramPath = await cmt.launchTargetPath(); expect(launchProgramPath).to.be.not.null; // Remove file if exists const createdFileOnExecution = path.join(path.dirname(launchProgramPath!), 'test.txt'); if (fs.existsSync(createdFileOnExecution)) { fs.unlinkSync(createdFileOnExecution); } const term1 = await cmt.launchTarget(); expect(term1).to.be.not.null; const term1Pid = await term1?.processId; const term2 = await cmt.launchTarget(); expect(term2).to.be.not.null; const term2Pid = await term2?.processId; expect(term1Pid).to.eq(term2Pid); }).timeout(60000); });
the_stack
import { shorthands, makeStyles, mergeClasses } from '@fluentui/react-make-styles'; import { createCustomFocusIndicatorStyle } from '@fluentui/react-tabster'; import type { ButtonState } from './Button.types'; export const buttonClassName = 'fui-Button'; // TODO: These are named in design specs but not hoisted to global/alias yet. // We're tracking these here to determine how we can hoist them. export const buttonSpacing = { smallest: '2px', smaller: '4px', small: '6px', medium: '8px', large: '12px', larger: '16px', }; const useRootStyles = makeStyles({ // Base styles base: theme => ({ alignItems: 'center', display: 'inline-flex', justifyContent: 'center', verticalAlign: 'middle', ...shorthands.margin(0), maxWidth: '280px', ...shorthands.overflow('hidden'), textOverflow: 'ellipsis', whiteSpace: 'nowrap', backgroundColor: theme.colorNeutralBackground1, color: theme.colorNeutralForeground1, ...shorthands.border(theme.strokeWidthThin, 'solid', theme.colorNeutralStroke1), fontFamily: theme.fontFamilyBase, outlineStyle: 'none', ':hover': { backgroundColor: theme.colorNeutralBackground1Hover, ...shorthands.borderColor(theme.colorNeutralStroke1Hover), color: theme.colorNeutralForeground1, cursor: 'pointer', }, ':active': { backgroundColor: theme.colorNeutralBackground1Pressed, ...shorthands.borderColor(theme.colorNeutralStroke1Pressed), color: theme.colorNeutralForeground1, outlineStyle: 'none', }, }), // Block styles block: { maxWidth: '100%', width: '100%', }, // Appearance variations outline: theme => ({ backgroundColor: theme.colorTransparentBackground, ':hover': { backgroundColor: theme.colorTransparentBackgroundHover, }, ':active': { backgroundColor: theme.colorTransparentBackgroundPressed, }, }), primary: theme => ({ backgroundColor: theme.colorBrandBackground, ...shorthands.borderColor('transparent'), color: theme.colorNeutralForegroundOnBrand, ':hover': { backgroundColor: theme.colorBrandBackgroundHover, ...shorthands.borderColor('transparent'), color: theme.colorNeutralForegroundOnBrand, }, ':active': { backgroundColor: theme.colorBrandBackgroundPressed, ...shorthands.borderColor('transparent'), color: theme.colorNeutralForegroundOnBrand, }, }), subtle: theme => ({ backgroundColor: theme.colorSubtleBackground, ...shorthands.borderColor('transparent'), color: theme.colorNeutralForeground2, ':hover': { backgroundColor: theme.colorSubtleBackgroundHover, ...shorthands.borderColor('transparent'), color: theme.colorNeutralForeground2BrandHover, }, ':active': { backgroundColor: theme.colorSubtleBackgroundPressed, ...shorthands.borderColor('transparent'), color: theme.colorNeutralForeground2BrandPressed, }, }), transparent: theme => ({ backgroundColor: theme.colorTransparentBackground, ...shorthands.borderColor('transparent'), color: theme.colorNeutralForeground2, ':hover': { backgroundColor: theme.colorTransparentBackgroundHover, ...shorthands.borderColor('transparent'), color: theme.colorNeutralForeground2BrandHover, }, ':active': { backgroundColor: theme.colorTransparentBackgroundPressed, ...shorthands.borderColor('transparent'), color: theme.colorNeutralForeground2BrandPressed, }, }), // Shape variations circular: theme => ({ ...shorthands.borderRadius(theme.borderRadiusCircular), }), rounded: { /* The borderRadius rounded styles are handled in the size variations */ }, square: theme => ({ ...shorthands.borderRadius(theme.borderRadiusNone), }), // Size variations small: theme => ({ ...shorthands.gap(buttonSpacing.smaller), ...shorthands.padding('0', buttonSpacing.medium), height: '24px', minWidth: '64px', ...shorthands.borderRadius(theme.borderRadiusSmall), fontSize: theme.fontSizeBase200, fontWeight: theme.fontWeightRegular, lineHeight: theme.lineHeightBase200, }), medium: theme => ({ ...shorthands.gap(buttonSpacing.small), ...shorthands.padding('0', buttonSpacing.large), height: '32px', minWidth: '96px', ...shorthands.borderRadius(theme.borderRadiusMedium), fontSize: theme.fontSizeBase300, fontWeight: theme.fontWeightSemibold, lineHeight: theme.lineHeightBase300, }), large: theme => ({ ...shorthands.gap(buttonSpacing.small), ...shorthands.padding('0', buttonSpacing.larger), height: '40px', minWidth: '96px', ...shorthands.borderRadius(theme.borderRadiusMedium), fontSize: theme.fontSizeBase400, fontWeight: theme.fontWeightSemibold, lineHeight: theme.lineHeightBase400, }), }); const useRootDisabledStyles = makeStyles({ // Base styles base: theme => ({ backgroundColor: theme.colorNeutralBackgroundDisabled, ...shorthands.borderColor(theme.colorNeutralStrokeDisabled), color: theme.colorNeutralForegroundDisabled, cursor: 'not-allowed', ':hover': { backgroundColor: theme.colorNeutralBackgroundDisabled, ...shorthands.borderColor(theme.colorNeutralStrokeDisabled), color: theme.colorNeutralForegroundDisabled, cursor: 'not-allowed', }, ':active': { backgroundColor: theme.colorNeutralBackgroundDisabled, ...shorthands.borderColor(theme.colorNeutralStrokeDisabled), color: theme.colorNeutralForegroundDisabled, cursor: 'not-allowed', }, }), // Appearance variations outline: theme => ({ backgroundColor: theme.colorTransparentBackground, ':hover': { backgroundColor: theme.colorTransparentBackgroundHover, }, ':active': { backgroundColor: theme.colorTransparentBackgroundPressed, }, }), primary: { ...shorthands.borderColor('transparent'), ':hover': { ...shorthands.borderColor('transparent'), }, ':active': { ...shorthands.borderColor('transparent'), }, }, subtle: { backgroundColor: 'transparent', ...shorthands.borderColor('transparent'), ':hover': { backgroundColor: 'transparent', ...shorthands.borderColor('transparent'), }, ':active': { backgroundColor: 'transparent', ...shorthands.borderColor('transparent'), }, }, transparent: { backgroundColor: 'transparent', ...shorthands.borderColor('transparent'), ':hover': { backgroundColor: 'transparent', ...shorthands.borderColor('transparent'), }, ':active': { backgroundColor: 'transparent', ...shorthands.borderColor('transparent'), }, }, }); const useRootFocusStyles = makeStyles({ // TODO: `overflow: 'hidden'` on the root does not pay well with `position: absolute` // used by the outline pseudo-element. Need to introduce a text container for children and set // overflow there so that default focus outline can work // // base: theme => createFocusOutlineStyle(theme), // circular: theme => // createFocusOutlineStyle(theme, { style: { outlineRadius: theme.global.borderRadius.circular } }), // primary: theme => createFocusOutlineStyle(theme, { style: { outlineOffset: '2px' } }), // square: theme => createFocusOutlineStyle(theme, { style: { outlineRadius: theme.global.borderRadius.none } }), base: createCustomFocusIndicatorStyle(theme => ({ ...shorthands.borderColor('transparent'), outlineColor: 'transparent', outlineWidth: '2px', outlineStyle: 'solid', boxShadow: ` ${theme.shadow4}, 0 0 0 2px ${theme.colorStrokeFocus2} `, zIndex: 1, })), circular: createCustomFocusIndicatorStyle(theme => ({ ...shorthands.borderRadius(theme.borderRadiusCircular), })), rounded: {}, // Primary styles primary: createCustomFocusIndicatorStyle(theme => ({ ...shorthands.borderColor(theme.colorNeutralForegroundOnBrand), boxShadow: `${theme.shadow2}, 0 0 0 2px ${theme.colorStrokeFocus2}`, })), square: createCustomFocusIndicatorStyle(theme => ({ ...shorthands.borderRadius(theme.borderRadiusNone), })), // Size variations small: createCustomFocusIndicatorStyle(theme => ({ ...shorthands.borderRadius(theme.borderRadiusSmall), })), medium: createCustomFocusIndicatorStyle(theme => ({ ...shorthands.borderRadius(theme.borderRadiusMedium), })), large: createCustomFocusIndicatorStyle(theme => ({ ...shorthands.borderRadius(theme.borderRadiusLarge), })), }); const useRootIconOnlyStyles = makeStyles({ // Size variations small: { ...shorthands.padding(buttonSpacing.smaller), minWidth: '28px', maxWidth: '28px', }, medium: { ...shorthands.padding(buttonSpacing.smaller), minWidth: '32px', maxWidth: '32px', }, large: { ...shorthands.padding(buttonSpacing.small), minWidth: '40px', maxWidth: '40px', }, }); const useIconStyles = makeStyles({ // Base styles base: { alignItems: 'center', display: 'inline-flex', justifyContent: 'center', }, // Size variations small: { fontSize: '20px', height: '20px', width: '20px', }, medium: { fontSize: '20px', height: '20px', width: '20px', }, large: { fontSize: '24px', height: '24px', width: '24px', }, }); export const useButtonStyles = (state: ButtonState): ButtonState => { const rootStyles = useRootStyles(); const rootDisabledStyles = useRootDisabledStyles(); const rootFocusStyles = useRootFocusStyles(); const rootIconOnlyStyles = useRootIconOnlyStyles(); const iconStyles = useIconStyles(); const { appearance, block, disabled, disabledFocusable, iconOnly, shape, size } = state; state.root.className = mergeClasses( buttonClassName, // Root styles rootStyles.base, block && rootStyles.block, appearance && rootStyles[appearance], rootStyles[size], rootStyles[shape], // Disabled styles (disabled || disabledFocusable) && rootDisabledStyles.base, appearance && (disabled || disabledFocusable) && rootDisabledStyles[appearance], // Focus styles rootFocusStyles.base, appearance === 'primary' && rootFocusStyles.primary, rootFocusStyles[size], rootFocusStyles[shape], // Icon-only styles iconOnly && rootIconOnlyStyles[size], // User provided class name state.root.className, ); if (state.icon) { state.icon.className = mergeClasses(iconStyles.base, iconStyles[size], state.icon.className); } return state; };
the_stack
import * as assert from 'assert'; import * as json from 'vs/base/common/json'; import { KeyCode } from 'vs/base/common/keyCodes'; import { ChordKeybinding, SimpleKeybinding } from 'vs/base/common/keybindings'; import { OS } from 'vs/base/common/platform'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { IEnvironmentService } from 'vs/platform/environment/common/environment'; import { IFileService } from 'vs/platform/files/common/files'; import { TestInstantiationService } from 'vs/platform/instantiation/test/common/instantiationServiceMock'; import { IUserFriendlyKeybinding } from 'vs/platform/keybinding/common/keybinding'; import { ResolvedKeybindingItem } from 'vs/platform/keybinding/common/resolvedKeybindingItem'; import { USLayoutResolvedKeybinding } from 'vs/platform/keybinding/common/usLayoutResolvedKeybinding'; import { NullLogService } from 'vs/platform/log/common/log'; import { KeybindingsEditingService } from 'vs/workbench/services/keybinding/common/keybindingEditing'; import { ITextFileService } from 'vs/workbench/services/textfile/common/textfiles'; import { TestEnvironmentService, workbenchInstantiationService } from 'vs/workbench/test/browser/workbenchTestServices'; import { FileService } from 'vs/platform/files/common/fileService'; import { Schemas } from 'vs/base/common/network'; import { URI } from 'vs/base/common/uri'; import { FileUserDataProvider } from 'vs/platform/userData/common/fileUserDataProvider'; import { TestConfigurationService } from 'vs/platform/configuration/test/common/testConfigurationService'; import { joinPath } from 'vs/base/common/resources'; import { InMemoryFileSystemProvider } from 'vs/platform/files/common/inMemoryFilesystemProvider'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { VSBuffer } from 'vs/base/common/buffer'; interface Modifiers { metaKey?: boolean; ctrlKey?: boolean; altKey?: boolean; shiftKey?: boolean; } const ROOT = URI.file('tests').with({ scheme: 'vscode-tests' }); suite('KeybindingsEditing', () => { const disposables = new DisposableStore(); let instantiationService: TestInstantiationService; let fileService: IFileService; let environmentService: IEnvironmentService; let testObject: KeybindingsEditingService; setup(async () => { environmentService = TestEnvironmentService; const logService = new NullLogService(); fileService = disposables.add(new FileService(logService)); const fileSystemProvider = disposables.add(new InMemoryFileSystemProvider()); disposables.add(fileService.registerProvider(ROOT.scheme, fileSystemProvider)); disposables.add(fileService.registerProvider(Schemas.vscodeUserData, disposables.add(new FileUserDataProvider(ROOT.scheme, fileSystemProvider, Schemas.vscodeUserData, new NullLogService())))); const userFolder = joinPath(ROOT, 'User'); await fileService.createFolder(userFolder); const configService = new TestConfigurationService(); configService.setUserConfiguration('files', { 'eol': '\n' }); instantiationService = workbenchInstantiationService({ fileService: () => fileService, configurationService: () => configService, environmentService: () => environmentService }, disposables); testObject = disposables.add(instantiationService.createInstance(KeybindingsEditingService)); }); teardown(() => disposables.clear()); test('errors cases - parse errors', async () => { await fileService.writeFile(environmentService.keybindingsResource, VSBuffer.fromString(',,,,,,,,,,,,,,')); try { await testObject.editKeybinding(aResolvedKeybindingItem({ firstPart: { keyCode: KeyCode.Escape } }), 'alt+c', undefined); assert.fail('Should fail with parse errors'); } catch (error) { assert.strictEqual(error.message, 'Unable to write to the keybindings configuration file. Please open it to correct errors/warnings in the file and try again.'); } }); test('errors cases - parse errors 2', async () => { await fileService.writeFile(environmentService.keybindingsResource, VSBuffer.fromString('[{"key": }]')); try { await testObject.editKeybinding(aResolvedKeybindingItem({ firstPart: { keyCode: KeyCode.Escape } }), 'alt+c', undefined); assert.fail('Should fail with parse errors'); } catch (error) { assert.strictEqual(error.message, 'Unable to write to the keybindings configuration file. Please open it to correct errors/warnings in the file and try again.'); } }); test('errors cases - dirty', () => { instantiationService.stub(ITextFileService, 'isDirty', true); return testObject.editKeybinding(aResolvedKeybindingItem({ firstPart: { keyCode: KeyCode.Escape } }), 'alt+c', undefined) .then(() => assert.fail('Should fail with dirty error'), error => assert.strictEqual(error.message, 'Unable to write because the keybindings configuration file has unsaved changes. Please save it first and then try again.')); }); test('errors cases - did not find an array', async () => { await fileService.writeFile(environmentService.keybindingsResource, VSBuffer.fromString('{"key": "alt+c", "command": "hello"}')); try { await testObject.editKeybinding(aResolvedKeybindingItem({ firstPart: { keyCode: KeyCode.Escape } }), 'alt+c', undefined); assert.fail('Should fail'); } catch (error) { assert.strictEqual(error.message, 'Unable to write to the keybindings configuration file. It has an object which is not of type Array. Please open the file to clean up and try again.'); } }); test('edit a default keybinding to an empty file', async () => { await fileService.writeFile(environmentService.keybindingsResource, VSBuffer.fromString('')); const expected: IUserFriendlyKeybinding[] = [{ key: 'alt+c', command: 'a' }, { key: 'escape', command: '-a' }]; await testObject.editKeybinding(aResolvedKeybindingItem({ firstPart: { keyCode: KeyCode.Escape }, command: 'a' }), 'alt+c', undefined); assert.deepStrictEqual(await getUserKeybindings(), expected); }); test('edit a default keybinding to an empty array', async () => { await writeToKeybindingsFile(); const expected: IUserFriendlyKeybinding[] = [{ key: 'alt+c', command: 'a' }, { key: 'escape', command: '-a' }]; await testObject.editKeybinding(aResolvedKeybindingItem({ firstPart: { keyCode: KeyCode.Escape }, command: 'a' }), 'alt+c', undefined); return assert.deepStrictEqual(await getUserKeybindings(), expected); }); test('edit a default keybinding in an existing array', async () => { await writeToKeybindingsFile({ command: 'b', key: 'shift+c' }); const expected: IUserFriendlyKeybinding[] = [{ key: 'shift+c', command: 'b' }, { key: 'alt+c', command: 'a' }, { key: 'escape', command: '-a' }]; await testObject.editKeybinding(aResolvedKeybindingItem({ firstPart: { keyCode: KeyCode.Escape }, command: 'a' }), 'alt+c', undefined); return assert.deepStrictEqual(await getUserKeybindings(), expected); }); test('add another keybinding', async () => { const expected: IUserFriendlyKeybinding[] = [{ key: 'alt+c', command: 'a' }]; await testObject.addKeybinding(aResolvedKeybindingItem({ firstPart: { keyCode: KeyCode.Escape }, command: 'a' }), 'alt+c', undefined); return assert.deepStrictEqual(await getUserKeybindings(), expected); }); test('add a new default keybinding', async () => { const expected: IUserFriendlyKeybinding[] = [{ key: 'alt+c', command: 'a' }]; await testObject.addKeybinding(aResolvedKeybindingItem({ command: 'a' }), 'alt+c', undefined); return assert.deepStrictEqual(await getUserKeybindings(), expected); }); test('add a new default keybinding using edit', async () => { const expected: IUserFriendlyKeybinding[] = [{ key: 'alt+c', command: 'a' }]; await testObject.editKeybinding(aResolvedKeybindingItem({ command: 'a' }), 'alt+c', undefined); assert.deepStrictEqual(await getUserKeybindings(), expected); }); test('edit an user keybinding', async () => { await writeToKeybindingsFile({ key: 'escape', command: 'b' }); const expected: IUserFriendlyKeybinding[] = [{ key: 'alt+c', command: 'b' }]; await testObject.editKeybinding(aResolvedKeybindingItem({ firstPart: { keyCode: KeyCode.Escape }, command: 'b', isDefault: false }), 'alt+c', undefined); assert.deepStrictEqual(await getUserKeybindings(), expected); }); test('edit an user keybinding with more than one element', async () => { await writeToKeybindingsFile({ key: 'escape', command: 'b' }, { key: 'alt+shift+g', command: 'c' }); const expected: IUserFriendlyKeybinding[] = [{ key: 'alt+c', command: 'b' }, { key: 'alt+shift+g', command: 'c' }]; await testObject.editKeybinding(aResolvedKeybindingItem({ firstPart: { keyCode: KeyCode.Escape }, command: 'b', isDefault: false }), 'alt+c', undefined); assert.deepStrictEqual(await getUserKeybindings(), expected); }); test('remove a default keybinding', async () => { const expected: IUserFriendlyKeybinding[] = [{ key: 'alt+c', command: '-a' }]; await testObject.removeKeybinding(aResolvedKeybindingItem({ command: 'a', firstPart: { keyCode: KeyCode.KeyC, modifiers: { altKey: true } } })); assert.deepStrictEqual(await getUserKeybindings(), expected); }); test('remove a default keybinding should not ad duplicate entries', async () => { const expected: IUserFriendlyKeybinding[] = [{ key: 'alt+c', command: '-a' }]; await testObject.removeKeybinding(aResolvedKeybindingItem({ command: 'a', firstPart: { keyCode: KeyCode.KeyC, modifiers: { altKey: true } } })); await testObject.removeKeybinding(aResolvedKeybindingItem({ command: 'a', firstPart: { keyCode: KeyCode.KeyC, modifiers: { altKey: true } } })); await testObject.removeKeybinding(aResolvedKeybindingItem({ command: 'a', firstPart: { keyCode: KeyCode.KeyC, modifiers: { altKey: true } } })); await testObject.removeKeybinding(aResolvedKeybindingItem({ command: 'a', firstPart: { keyCode: KeyCode.KeyC, modifiers: { altKey: true } } })); await testObject.removeKeybinding(aResolvedKeybindingItem({ command: 'a', firstPart: { keyCode: KeyCode.KeyC, modifiers: { altKey: true } } })); assert.deepStrictEqual(await getUserKeybindings(), expected); }); test('remove a user keybinding', async () => { await writeToKeybindingsFile({ key: 'alt+c', command: 'b' }); await testObject.removeKeybinding(aResolvedKeybindingItem({ command: 'b', firstPart: { keyCode: KeyCode.KeyC, modifiers: { altKey: true } }, isDefault: false })); assert.deepStrictEqual(await getUserKeybindings(), []); }); test('reset an edited keybinding', async () => { await writeToKeybindingsFile({ key: 'alt+c', command: 'b' }); await testObject.resetKeybinding(aResolvedKeybindingItem({ command: 'b', firstPart: { keyCode: KeyCode.KeyC, modifiers: { altKey: true } }, isDefault: false })); assert.deepStrictEqual(await getUserKeybindings(), []); }); test('reset a removed keybinding', async () => { await writeToKeybindingsFile({ key: 'alt+c', command: '-b' }); await testObject.resetKeybinding(aResolvedKeybindingItem({ command: 'b', isDefault: false })); assert.deepStrictEqual(await getUserKeybindings(), []); }); test('reset multiple removed keybindings', async () => { await writeToKeybindingsFile({ key: 'alt+c', command: '-b' }); await writeToKeybindingsFile({ key: 'alt+shift+c', command: '-b' }); await writeToKeybindingsFile({ key: 'escape', command: '-b' }); await testObject.resetKeybinding(aResolvedKeybindingItem({ command: 'b', isDefault: false })); assert.deepStrictEqual(await getUserKeybindings(), []); }); test('add a new keybinding to unassigned keybinding', async () => { await writeToKeybindingsFile({ key: 'alt+c', command: '-a' }); const expected: IUserFriendlyKeybinding[] = [{ key: 'alt+c', command: '-a' }, { key: 'shift+alt+c', command: 'a' }]; await testObject.editKeybinding(aResolvedKeybindingItem({ command: 'a', isDefault: false }), 'shift+alt+c', undefined); assert.deepStrictEqual(await getUserKeybindings(), expected); }); test('add when expression', async () => { await writeToKeybindingsFile({ key: 'alt+c', command: '-a' }); const expected: IUserFriendlyKeybinding[] = [{ key: 'alt+c', command: '-a' }, { key: 'shift+alt+c', command: 'a', when: 'editorTextFocus' }]; await testObject.editKeybinding(aResolvedKeybindingItem({ command: 'a', isDefault: false }), 'shift+alt+c', 'editorTextFocus'); assert.deepStrictEqual(await getUserKeybindings(), expected); }); test('update command and when expression', async () => { await writeToKeybindingsFile({ key: 'alt+c', command: '-a', when: 'editorTextFocus && !editorReadonly' }); const expected: IUserFriendlyKeybinding[] = [{ key: 'alt+c', command: '-a', when: 'editorTextFocus && !editorReadonly' }, { key: 'shift+alt+c', command: 'a', when: 'editorTextFocus' }]; await testObject.editKeybinding(aResolvedKeybindingItem({ command: 'a', isDefault: false }), 'shift+alt+c', 'editorTextFocus'); assert.deepStrictEqual(await getUserKeybindings(), expected); }); test('update when expression', async () => { await writeToKeybindingsFile({ key: 'alt+c', command: '-a', when: 'editorTextFocus && !editorReadonly' }, { key: 'shift+alt+c', command: 'a', when: 'editorTextFocus && !editorReadonly' }); const expected: IUserFriendlyKeybinding[] = [{ key: 'alt+c', command: '-a', when: 'editorTextFocus && !editorReadonly' }, { key: 'shift+alt+c', command: 'a', when: 'editorTextFocus' }]; await testObject.editKeybinding(aResolvedKeybindingItem({ command: 'a', isDefault: false, when: 'editorTextFocus && !editorReadonly' }), 'shift+alt+c', 'editorTextFocus'); assert.deepStrictEqual(await getUserKeybindings(), expected); }); test('remove when expression', async () => { await writeToKeybindingsFile({ key: 'alt+c', command: '-a', when: 'editorTextFocus && !editorReadonly' }); const expected: IUserFriendlyKeybinding[] = [{ key: 'alt+c', command: '-a', when: 'editorTextFocus && !editorReadonly' }, { key: 'shift+alt+c', command: 'a' }]; await testObject.editKeybinding(aResolvedKeybindingItem({ command: 'a', isDefault: false }), 'shift+alt+c', undefined); assert.deepStrictEqual(await getUserKeybindings(), expected); }); async function writeToKeybindingsFile(...keybindings: IUserFriendlyKeybinding[]): Promise<void> { await fileService.writeFile(environmentService.keybindingsResource, VSBuffer.fromString(JSON.stringify(keybindings || []))); } async function getUserKeybindings(): Promise<IUserFriendlyKeybinding[]> { return json.parse((await fileService.readFile(environmentService.keybindingsResource)).value.toString()); } function aResolvedKeybindingItem({ command, when, isDefault, firstPart, chordPart }: { command?: string; when?: string; isDefault?: boolean; firstPart?: { keyCode: KeyCode; modifiers?: Modifiers }; chordPart?: { keyCode: KeyCode; modifiers?: Modifiers } }): ResolvedKeybindingItem { const aSimpleKeybinding = function (part: { keyCode: KeyCode; modifiers?: Modifiers }): SimpleKeybinding { const { ctrlKey, shiftKey, altKey, metaKey } = part.modifiers || { ctrlKey: false, shiftKey: false, altKey: false, metaKey: false }; return new SimpleKeybinding(ctrlKey!, shiftKey!, altKey!, metaKey!, part.keyCode); }; let parts: SimpleKeybinding[] = []; if (firstPart) { parts.push(aSimpleKeybinding(firstPart)); if (chordPart) { parts.push(aSimpleKeybinding(chordPart)); } } const keybinding = parts.length > 0 ? new USLayoutResolvedKeybinding(new ChordKeybinding(parts), OS) : undefined; return new ResolvedKeybindingItem(keybinding, command || 'some command', null, when ? ContextKeyExpr.deserialize(when) : undefined, isDefault === undefined ? true : isDefault, null, false); } });
the_stack
import AlbumForEditContract from '@DataContracts/Album/AlbumForEditContract'; import ArtistContract from '@DataContracts/Artist/ArtistContract'; import SongApiContract from '@DataContracts/Song/SongApiContract'; import SongInAlbumEditContract from '@DataContracts/Song/SongInAlbumEditContract'; import TranslatedEnumField from '@DataContracts/TranslatedEnumField'; import UrlMapper from '@Shared/UrlMapper'; import AlbumEditViewModel, { TrackArtistSelectionViewModel, } from '@ViewModels/Album/AlbumEditViewModel'; import { TrackPropertiesViewModel } from '@ViewModels/Album/AlbumEditViewModel'; import SongInAlbumEditViewModel from '@ViewModels/SongInAlbumEditViewModel'; import _ from 'lodash'; import FakeAlbumRepository from '../TestSupport/FakeAlbumRepository'; import FakeArtistRepository from '../TestSupport/FakeArtistRepository'; import FakeSongRepository from '../TestSupport/FakeSongRepository'; import FakeUserRepository from '../TestSupport/FakeUserRepository'; var rep = new FakeAlbumRepository(); var songRep: FakeSongRepository; var artistRep: FakeArtistRepository; var userRepo = new FakeUserRepository(); var pvRep: any = null; var urlMapper = new UrlMapper(''); var song: SongApiContract; var categories: TranslatedEnumField[] = [ { id: 'Official', name: 'Official' }, { id: 'Commercial', name: 'Commercial' }, ]; var producer: ArtistContract = { id: 1, name: 'Tripshots', additionalNames: '', artistType: 'Producer', }; var vocalist: ArtistContract = { id: 2, name: 'Hatsune Miku', additionalNames: '初音ミク', artistType: 'Vocalist', }; var label: ArtistContract = { id: 3, name: 'KarenT', additionalNames: '', artistType: 'Label', }; var producerArtistLink = { artist: producer, id: 39, isSupport: false, name: '', roles: 'Default', }; var vocalistArtistLink = { artist: vocalist, id: 40, isSupport: false, name: '', roles: 'Default', }; var labelArtistLink = { artist: label, id: 41, isSupport: false, name: '', roles: 'Default', }; var customArtistLink: any = { artist: null, id: 42, isSupport: false, name: 'xxJulexx', roles: 'Default', }; var songInAlbum: SongInAlbumEditContract; var customTrack: SongInAlbumEditContract; var roles: { [key: string]: string } = { Default: 'Default', VoiceManipulator: 'Voice manipulator', }; var webLinkData = { category: 'Official', description: 'Youtube Channel', id: 123, url: 'http://www.youtube.com/user/tripshots', disabled: false, }; var data: AlbumForEditContract; vdb.resources = { album: {}, albumDetails: { download: '' }, albumEdit: { addExtraArtist: '' }, entryEdit: {}, shared: null, song: null, }; beforeEach(() => { songRep = new FakeSongRepository(); song = { additionalNames: '', artistString: 'Tripshots', artists: [ { id: 0, artist: producer, isSupport: false, name: null!, roles: null!, }, ], id: 2, lengthSeconds: 0, name: 'Anger', pvServices: 'Nothing', ratingScore: 0, songType: 'Original', createDate: null!, status: 'Finished', }; songRep.song = song; artistRep = new FakeArtistRepository(); songInAlbum = { artists: [producer], artistString: 'Tripshots', discNumber: 1, songAdditionalNames: '', songId: 3, songInAlbumId: 1, songName: 'Nebula', trackNumber: 1, }; customTrack = { artists: [], artistString: '', discNumber: 1, songAdditionalNames: '', songId: 0, songInAlbumId: 2, songName: 'Bonus Track', trackNumber: 2, isCustomTrack: true, }; data = { artistLinks: [ producerArtistLink, vocalistArtistLink, labelArtistLink, customArtistLink, ], coverPictureMime: 'image/jpeg', defaultNameLanguage: 'English', description: { original: '', english: '', }, discType: 'Album', discs: [], id: 0, identifiers: [], names: [], originalRelease: { catNum: '', releaseEvent: null!, releaseDate: {}, }, pictures: [], pvs: [], songs: [songInAlbum, customTrack], status: 'Draft', webLinks: [webLinkData], }; }); function createViewModel(): AlbumEditViewModel { return new AlbumEditViewModel( vdb.values, rep, songRep, artistRep, pvRep, userRepo, null!, urlMapper, roles, categories, data, true, false, null!, ); } function createTrackPropertiesViewModel(): TrackPropertiesViewModel { var songVm = new SongInAlbumEditViewModel(songInAlbum); return new TrackPropertiesViewModel([producer, vocalist], songVm); } function findArtistSelection( target: TrackPropertiesViewModel, artist: ArtistContract, ): TrackArtistSelectionViewModel { return _.find(target.artistSelections, (a) => a.artist === artist)!; } test('constructor', () => { var target = createViewModel(); expect(target.artistLinks().length, 'artistLinks.length').toBe(4); expect(target.artistLinks()[0].id, 'artistLinks[0].id').toBe(39); expect(target.artistLinks()[0].artist, 'artistLinks[0].artist').toBeTruthy(); expect(target.artistLinks()[0].artist, 'artistLinks[0].artist').toBe( producer, ); expect(target.tracks().length, 'tracks.length').toBe(2); expect(target.tracks()[0].songId, 'tracks[0].songId').toBe(3); expect(target.tracks()[0].songName, 'tracks[0].songName').toBe('Nebula'); expect(target.tracks()[0].selected(), 'tracks[0].selected').toBe(false); expect(target.tracks()[0].trackNumber(), 'tracks[0].trackNumber').toBe(1); expect(target.webLinks.items().length, 'webLinks.length').toBe(1); expect(target.webLinks.items()[0].id, 'webLinks[0].id').toBe(123); }); test('acceptTrackSelection existing', () => { var target = createViewModel(); target.tracks.removeAll(); target.acceptTrackSelection(2, null!); expect(target.tracks().length, 'tracks.length').toBe(1); expect(target.tracks()[0].songId, 'tracks[0].songId').toBe(2); expect(target.tracks()[0].songName, 'tracks[0].songName').toBe('Anger'); }); test('acceptTrackSelection new', () => { var target = createViewModel(); target.tracks.removeAll(); target.acceptTrackSelection(null!, 'Anger RMX'); expect(target.tracks().length, 'tracks.length').toBe(1); expect(target.tracks()[0].songId, 'tracks[0].songId').toBe(0); expect(target.tracks()[0].songName, 'tracks[0].songName').toBe('Anger RMX'); }); test('acceptTrackSelection add a second track', () => { var target = createViewModel(); target.acceptTrackSelection(2, null!); expect(target.tracks().length, 'tracks.length').toBe(3); expect(_.last(target.tracks())!.trackNumber(), 'tracks[2].trackNumber').toBe( 3, ); }); test('addArtist existing', () => { var newVocalist: ArtistContract = { id: 4, name: 'Kagamine Rin', additionalNames: '', artistType: 'Vocaloid', }; artistRep.result = newVocalist; var target = createViewModel(); target.addArtist(4); expect(target.artistLinks().length, 'artistLinks().length').toBe(5); expect( _.some(target.artistLinks(), (a) => a.artist === newVocalist), 'New vocalist was added', ).toBe(true); }); test('addArtist custom', () => { var target = createViewModel(); target.addArtist(null!, 'Custom artist'); expect(target.artistLinks().length, 'artistLinks().length').toBe(5); expect( _.some(target.artistLinks(), (a) => a.name() === 'Custom artist'), 'Custom artist was added', ).toBe(true); }); test('allTracksSelected', () => { var target = createViewModel(); target.allTracksSelected(true); expect(target.tracks()[0].selected(), 'tracks[0].selected').toBe(true); expect(target.tracks()[1].selected(), 'tracks[1].selected').toBe(false); // Custom tracks won't be selected }); test('editTrackProperties', () => { var target = createViewModel(); var track = target.tracks()[0]; target.editTrackProperties(track); var edited = target.editedSong()!; expect(edited, 'editedSong').toBeTruthy(); expect(edited.song, 'editedSong.song').toBe(track); expect(edited.artistSelections, 'editedSong.artistSelections').toBeTruthy(); expect( edited.artistSelections.length, 'editedSong.artistSelections.length', ).toBe(2); // Label or custom artist are not included. expect( edited.artistSelections[0].artist, 'editedSong.artistSelections[0].artist', ).toBe(producer); expect( edited.artistSelections[0].selected(), 'editedSong.artistSelections[0].selected', ).toBe(true); // Selected, because added to song expect( edited.artistSelections[0].visible(), 'artistSelections[0].visible', ).toBe(true); // No filter expect( edited.artistSelections[1].artist, 'editedSong.artistSelections[1].artist', ).toBe(vocalist); expect( edited.artistSelections[1].selected(), 'editedSong.artistSelections[1].selected', ).toBe(false); // Not seleted, because not added yet expect( edited.artistSelections[1].visible(), 'artistSelections[1].visible', ).toBe(true); // No filter }); test('saveTrackProperties not changed', () => { var target = createViewModel(); var track = target.tracks()[0]; target.editTrackProperties(track); target.saveTrackProperties(); expect(track.artists().length, 'track.artists.length').toBe(1); expect(track.artists()[0], 'track.artists[0]').toBe(producer); }); test('saveTrackProperties changed', () => { var target = createViewModel(); var track = target.tracks()[0]; target.editTrackProperties(track); target.editedSong()!.artistSelections[0].selected(false); target.saveTrackProperties(); expect(track.artists().length, 'track.artists.length').toBe(0); }); test('filter displayName', () => { var target = createViewModel(); var track = target.tracks()[0]; target.editTrackProperties(track); var edited = target.editedSong()!; edited.filter('tri'); expect( edited.artistSelections[0].visible(), 'artistSelections[0].visible', ).toBe(true); // Producer (Tripshots) expect( edited.artistSelections[1].visible(), 'artistSelections[1].visible', ).toBe(false); // Vocalist (Hatsune Miku) }); test('filter additionalName', () => { var target = createViewModel(); var track = target.tracks()[0]; target.editTrackProperties(track); var edited = target.editedSong()!; edited.filter('初音ミク'); expect( edited.artistSelections[0].visible(), 'artistSelections[0].visible', ).toBe(false); // Producer (Tripshots) expect( edited.artistSelections[1].visible(), 'artistSelections[1].visible', ).toBe(true); // Vocalist (Hatsune Miku) }); test('editMultipleTrackProperties', () => { var target = createViewModel(); target.editMultipleTrackProperties(); expect(target.editedSong(), 'editedSong').toBeTruthy(); expect( target.editedSong()!.artistSelections, 'editedSong.artistSelections', ).toBeTruthy(); expect( target.editedSong()!.artistSelections.length, 'editedSong.artistSelections.length', ).toBe(2); // Label or custom artist are not included. expect( target.editedSong()!.artistSelections[0].selected(), 'editedSong.artistSelections[0].selected', ).toBe(false); expect( target.editedSong()!.artistSelections[1].selected(), 'editedSong.artistSelections[1].selected', ).toBe(false); }); // Add an artist to a track that was not added before test('addArtistsToSelectedTracks add new artists', () => { var target = createViewModel(); var track = target.tracks()[0]; track.selected(true); target.editMultipleTrackProperties(); target.editedSong()!.artistSelections[1].selected(true); // Select vocalist, which is not added yet target.addArtistsToSelectedTracks(); expect(track.artists().length, 'target.tracks[0].artists.length').toBe(2); expect(track.artists()[0], 'target.tracks[0].artists[0]').toBe(producer); expect(track.artists()[1], 'target.tracks[0].artists[1]').toBe(vocalist); }); test('addArtistsToSelectedTracks not changed', () => { var target = createViewModel(); var track = target.tracks()[0]; track.selected(true); target.editMultipleTrackProperties(); target.editedSong()!.artistSelections[0].selected(true); // Select producer, who is added already target.addArtistsToSelectedTracks(); expect(track.artists().length, 'target.tracks[0].artists.length').toBe(1); expect(track.artists()[0], 'target.tracks[0].artists[0]').toBe(producer); }); test('removeArtistsFromSelectedTracks remove artist', () => { var target = createViewModel(); var track = target.tracks()[0]; track.selected(true); target.editMultipleTrackProperties(); target.editedSong()!.artistSelections[0].selected(true); // Select producer, who is added already target.removeArtistsFromSelectedTracks(); expect(track.artists().length, 'target.tracks[0].artists.length').toBe(0); }); test('removeArtistsFromSelectedTracks not changed', () => { var target = createViewModel(); var track = target.tracks()[0]; track.selected(true); target.editMultipleTrackProperties(); target.editedSong()!.artistSelections[1].selected(true); // Select vocalist, who isn't added target.removeArtistsFromSelectedTracks(); expect(track.artists().length, 'target.tracks[0].artists.length').toBe(1); expect(track.artists()[0], 'target.tracks[0].artists[0]').toBe(producer); }); test('getArtistLink found', () => { var target = createViewModel(); var result = target.getArtistLink(39); expect(result, 'result').toBeTruthy(); expect(result.id, 'result.id').toBe(39); }); test('getArtistLink not found', () => { var target = createViewModel(); var result = target.getArtistLink(123); expect(!result, 'result').toBeTruthy(); }); test('translateArtistRole', () => { var target = createViewModel(); var result = target.translateArtistRole('VoiceManipulator'); expect(result, 'result').toBe('Voice manipulator'); }); test('updateTrackNumbers updated by setting isNextDisc', () => { var target = createViewModel(); target.acceptTrackSelection(3, null!); // Adds a new track target.tracks()[0].isNextDisc(true); expect(target.tracks()[0].discNumber(), 'tracks[0].discNumber').toBe(2); expect(target.tracks()[0].trackNumber(), 'tracks[0].trackNumber').toBe(1); expect(target.tracks()[1].trackNumber(), 'tracks[1].trackNumber').toBe(2); expect(target.tracks()[2].trackNumber(), 'tracks[2].trackNumber').toBe(3); }); test('TrackPropertiesViewModel constructor', () => { var target = createTrackPropertiesViewModel(); expect(target.artistSelections, 'artistSelections').toBeTruthy(); expect(target.somethingSelected(), 'somethingSelected').toBe(true); expect(target.somethingSelectable(), 'somethingSelectable').toBe(true); expect(target.artistSelections.length, 'artistSelections.length').toBe(2); var producerSelection = findArtistSelection(target, producer); expect(producerSelection, 'producerSelection').toBeTruthy(); expect(producerSelection.selected(), 'producerSelection.selected').toBe(true); expect(producerSelection.visible(), 'producerSelection.visible').toBe(true); var vocalistSelection = findArtistSelection(target, vocalist); expect(vocalistSelection, 'vocalistSelection').toBeTruthy(); expect(vocalistSelection.selected(), 'vocalistSelection.selected').toBe( false, ); expect(vocalistSelection.visible(), 'vocalistSelection.visible').toBe(true); }); test('TrackPropertiesViewModel filter matches artist', () => { var target = createTrackPropertiesViewModel(); target.filter('miku'); var vocalistSelection = findArtistSelection(target, vocalist); expect(vocalistSelection.visible(), 'vocalistSelection.visible').toBe(true); }); test('TrackPropertiesViewModel filter does not match artist', () => { var target = createTrackPropertiesViewModel(); target.filter('luka'); var vocalistSelection = findArtistSelection(target, vocalist); expect(vocalistSelection.visible(), 'vocalistSelection.visible').toBe(false); });
the_stack
import {uniqueId, parseCacheControl} from '../util/util'; import {deserialize as deserializeBucket} from '../data/bucket'; import '../data/feature_index'; import type FeatureIndex from '../data/feature_index'; import GeoJSONFeature from '../util/vectortile_to_geojson'; import featureFilter from '../style-spec/feature_filter'; import SymbolBucket from '../data/bucket/symbol_bucket'; import {CollisionBoxArray} from '../data/array_types.g'; import Texture from '../render/texture'; import browser from '../util/browser'; import toEvaluationFeature from '../data/evaluation_feature'; import EvaluationParameters from '../style/evaluation_parameters'; import SourceFeatureState from '../source/source_state'; import {lazyLoadRTLTextPlugin} from './rtl_text_plugin'; const CLOCK_SKEW_RETRY_TIMEOUT = 30000; import type {Bucket} from '../data/bucket'; import type StyleLayer from '../style/style_layer'; import type {WorkerTileResult} from './worker_source'; import type Actor from '../util/actor'; import type DEMData from '../data/dem_data'; import type {AlphaImage} from '../util/image'; import type ImageAtlas from '../render/image_atlas'; import type ImageManager from '../render/image_manager'; import type Context from '../gl/context'; import type {OverscaledTileID} from './tile_id'; import type Framebuffer from '../gl/framebuffer'; import type Transform from '../geo/transform'; import type {LayerFeatureStates} from './source_state'; import type {Cancelable} from '../types/cancelable'; import type {FilterSpecification} from '../style-spec/types.g'; import type Point from '@mapbox/point-geometry'; import {mat4} from 'gl-matrix'; import type {VectorTileLayer} from '@mapbox/vector-tile'; import {ExpiryData} from '../util/ajax'; export type TileState = // Tile data is in the process of loading. 'loading' | // Tile data has been loaded. Tile can be rendered. 'loaded' | // Tile data has been loaded and is being updated. Tile can be rendered. 'reloading' | // Tile data has been deleted. 'unloaded' | // Tile data was not loaded because of an error. 'errored' | 'expired'; /* Tile data was previously loaded, but has expired per its * HTTP headers and is in the process of refreshing. */ /** * A tile object is the combination of a Coordinate, which defines * its place, as well as a unique ID and data tracking for its content * * @private */ class Tile { tileID: OverscaledTileID; uid: number; uses: number; tileSize: number; buckets: {[_: string]: Bucket}; latestFeatureIndex: FeatureIndex; latestRawTileData: ArrayBuffer; imageAtlas: ImageAtlas; imageAtlasTexture: Texture; glyphAtlasImage: AlphaImage; glyphAtlasTexture: Texture; expirationTime: any; expiredRequestCount: number; state: TileState; timeAdded: any; timeLoaded: any; fadeEndTime: any; collisionBoxArray: CollisionBoxArray; redoWhenDone: boolean; showCollisionBoxes: boolean; placementSource: any; actor: Actor; vtLayers: {[_: string]: VectorTileLayer}; neighboringTiles: any; dem: DEMData; demMatrix: mat4; aborted: boolean; needsHillshadePrepare: boolean; needsTerrainPrepare: boolean; request: Cancelable; texture: any; fbo: Framebuffer; demTexture: Texture; refreshedUponExpiration: boolean; reloadCallback: any; resourceTiming: Array<PerformanceResourceTiming>; queryPadding: number; symbolFadeHoldUntil: number; hasSymbolBuckets: boolean; hasRTLText: boolean; dependencies: any; textures: Array<Texture>; textureCoords: {[_: string]: string}; // remeber all coords rendered to textures /** * @param {OverscaledTileID} tileID * @param size * @private */ constructor(tileID: OverscaledTileID, size: number) { this.tileID = tileID; this.uid = uniqueId(); this.uses = 0; this.tileSize = size; this.buckets = {}; this.expirationTime = null; this.queryPadding = 0; this.hasSymbolBuckets = false; this.hasRTLText = false; this.dependencies = {}; this.textures = []; this.textureCoords = {}; // Counts the number of times a response was already expired when // received. We're using this to add a delay when making a new request // so we don't have to keep retrying immediately in case of a server // serving expired tiles. this.expiredRequestCount = 0; this.state = 'loading'; } registerFadeDuration(duration: number) { const fadeEndTime = duration + this.timeAdded; if (fadeEndTime < browser.now()) return; if (this.fadeEndTime && fadeEndTime < this.fadeEndTime) return; this.fadeEndTime = fadeEndTime; } wasRequested() { return this.state === 'errored' || this.state === 'loaded' || this.state === 'reloading'; } clearTextures(painter: any) { if (this.demTexture) painter.saveTileTexture(this.demTexture); this.textures.forEach(t => painter.saveTileTexture(t)); this.demTexture = null; this.textures = []; this.textureCoords = {}; } /** * Given a data object with a 'buffers' property, load it into * this tile's elementGroups and buffers properties and set loaded * to true. If the data is null, like in the case of an empty * GeoJSON tile, no-op but still set loaded to true. * @param {Object} data * @param painter * @returns {undefined} * @private */ loadVectorData(data: WorkerTileResult, painter: any, justReloaded?: boolean | null) { if (this.hasData()) { this.unloadVectorData(); } this.state = 'loaded'; // empty GeoJSON tile if (!data) { this.collisionBoxArray = new CollisionBoxArray(); return; } if (data.featureIndex) { this.latestFeatureIndex = data.featureIndex; if (data.rawTileData) { // Only vector tiles have rawTileData, and they won't update it for // 'reloadTile' this.latestRawTileData = data.rawTileData; this.latestFeatureIndex.rawTileData = data.rawTileData; } else if (this.latestRawTileData) { // If rawTileData hasn't updated, hold onto a pointer to the last // one we received this.latestFeatureIndex.rawTileData = this.latestRawTileData; } } this.collisionBoxArray = data.collisionBoxArray; this.buckets = deserializeBucket(data.buckets, painter.style); this.hasSymbolBuckets = false; for (const id in this.buckets) { const bucket = this.buckets[id]; if (bucket instanceof SymbolBucket) { this.hasSymbolBuckets = true; if (justReloaded) { bucket.justReloaded = true; } else { break; } } } this.hasRTLText = false; if (this.hasSymbolBuckets) { for (const id in this.buckets) { const bucket = this.buckets[id]; if (bucket instanceof SymbolBucket) { if (bucket.hasRTLText) { this.hasRTLText = true; lazyLoadRTLTextPlugin(); break; } } } } this.queryPadding = 0; for (const id in this.buckets) { const bucket = this.buckets[id]; this.queryPadding = Math.max(this.queryPadding, painter.style.getLayer(id).queryRadius(bucket)); } if (data.imageAtlas) { this.imageAtlas = data.imageAtlas; } if (data.glyphAtlasImage) { this.glyphAtlasImage = data.glyphAtlasImage; } } /** * Release any data or WebGL resources referenced by this tile. * @returns {undefined} * @private */ unloadVectorData() { for (const id in this.buckets) { this.buckets[id].destroy(); } this.buckets = {}; if (this.imageAtlasTexture) { this.imageAtlasTexture.destroy(); } if (this.imageAtlas) { this.imageAtlas = null; } if (this.glyphAtlasTexture) { this.glyphAtlasTexture.destroy(); } this.latestFeatureIndex = null; this.state = 'unloaded'; } getBucket(layer: StyleLayer) { return this.buckets[layer.id]; } upload(context: Context) { for (const id in this.buckets) { const bucket = this.buckets[id]; if (bucket.uploadPending()) { bucket.upload(context); } } const gl = context.gl; if (this.imageAtlas && !this.imageAtlas.uploaded) { this.imageAtlasTexture = new Texture(context, this.imageAtlas.image, gl.RGBA); this.imageAtlas.uploaded = true; } if (this.glyphAtlasImage) { this.glyphAtlasTexture = new Texture(context, this.glyphAtlasImage, gl.ALPHA); this.glyphAtlasImage = null; } } prepare(imageManager: ImageManager) { if (this.imageAtlas) { this.imageAtlas.patchUpdatedImages(imageManager, this.imageAtlasTexture); } } // Queries non-symbol features rendered for this tile. // Symbol features are queried globally queryRenderedFeatures( layers: {[_: string]: StyleLayer}, serializedLayers: {[_: string]: any}, sourceFeatureState: SourceFeatureState, queryGeometry: Array<Point>, cameraQueryGeometry: Array<Point>, scale: number, params: { filter: FilterSpecification; layers: Array<string>; availableImages: Array<string>; }, transform: Transform, maxPitchScaleFactor: number, pixelPosMatrix: mat4 ): {[_: string]: Array<{featureIndex: number; feature: GeoJSONFeature}>} { if (!this.latestFeatureIndex || !this.latestFeatureIndex.rawTileData) return {}; return this.latestFeatureIndex.query({ queryGeometry, cameraQueryGeometry, scale, tileSize: this.tileSize, pixelPosMatrix, transform, params, queryPadding: this.queryPadding * maxPitchScaleFactor }, layers, serializedLayers, sourceFeatureState); } querySourceFeatures(result: Array<GeoJSONFeature>, params?: { sourceLayer: string; filter: Array<any>; validate?: boolean; }) { const featureIndex = this.latestFeatureIndex; if (!featureIndex || !featureIndex.rawTileData) return; const vtLayers = featureIndex.loadVTLayers(); const sourceLayer = params ? params.sourceLayer : ''; const layer = vtLayers._geojsonTileLayer || vtLayers[sourceLayer]; if (!layer) return; const filter = featureFilter(params && params.filter); const {z, x, y} = this.tileID.canonical; const coord = {z, x, y}; for (let i = 0; i < layer.length; i++) { const feature = layer.feature(i); if (filter.needGeometry) { const evaluationFeature = toEvaluationFeature(feature, true); if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) continue; } else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) { continue; } const id = featureIndex.getId(feature, sourceLayer); const geojsonFeature = new GeoJSONFeature(feature, z, x, y, id); (geojsonFeature as any).tile = coord; result.push(geojsonFeature); } } hasData() { return this.state === 'loaded' || this.state === 'reloading' || this.state === 'expired'; } patternsLoaded() { return this.imageAtlas && !!Object.keys(this.imageAtlas.patternPositions).length; } setExpiryData(data: ExpiryData) { const prior = this.expirationTime; if (data.cacheControl) { const parsedCC = parseCacheControl(data.cacheControl); if (parsedCC['max-age']) this.expirationTime = Date.now() + parsedCC['max-age'] * 1000; } else if (data.expires) { this.expirationTime = new Date(data.expires).getTime(); } if (this.expirationTime) { const now = Date.now(); let isExpired = false; if (this.expirationTime > now) { isExpired = false; } else if (!prior) { isExpired = true; } else if (this.expirationTime < prior) { // Expiring date is going backwards: // fall back to exponential backoff isExpired = true; } else { const delta = this.expirationTime - prior; if (!delta) { // Server is serving the same expired resource over and over: fall // back to exponential backoff. isExpired = true; } else { // Assume that either the client or the server clock is wrong and // try to interpolate a valid expiration date (from the client POV) // observing a minimum timeout. this.expirationTime = now + Math.max(delta, CLOCK_SKEW_RETRY_TIMEOUT); } } if (isExpired) { this.expiredRequestCount++; this.state = 'expired'; } else { this.expiredRequestCount = 0; } } } getExpiryTimeout() { if (this.expirationTime) { if (this.expiredRequestCount) { return 1000 * (1 << Math.min(this.expiredRequestCount - 1, 31)); } else { // Max value for `setTimeout` implementations is a 32 bit integer; cap this accordingly return Math.min(this.expirationTime - new Date().getTime(), Math.pow(2, 31) - 1); } } } setFeatureState(states: LayerFeatureStates, painter: any) { if (!this.latestFeatureIndex || !this.latestFeatureIndex.rawTileData || Object.keys(states).length === 0) { return; } const vtLayers = this.latestFeatureIndex.loadVTLayers(); for (const id in this.buckets) { if (!painter.style.hasLayer(id)) continue; const bucket = this.buckets[id]; // Buckets are grouped by common source-layer const sourceLayerId = bucket.layers[0]['sourceLayer'] || '_geojsonTileLayer'; const sourceLayer = vtLayers[sourceLayerId]; const sourceLayerStates = states[sourceLayerId]; if (!sourceLayer || !sourceLayerStates || Object.keys(sourceLayerStates).length === 0) continue; bucket.update(sourceLayerStates, sourceLayer, this.imageAtlas && this.imageAtlas.patternPositions || {}); const layer = painter && painter.style && painter.style.getLayer(id); if (layer) { this.queryPadding = Math.max(this.queryPadding, layer.queryRadius(bucket)); } } } holdingForFade(): boolean { return this.symbolFadeHoldUntil !== undefined; } symbolFadeFinished(): boolean { return !this.symbolFadeHoldUntil || this.symbolFadeHoldUntil < browser.now(); } clearFadeHold() { this.symbolFadeHoldUntil = undefined; } setHoldDuration(duration: number) { this.symbolFadeHoldUntil = browser.now() + duration; } setDependencies(namespace: string, dependencies: Array<string>) { const index = {}; for (const dep of dependencies) { index[dep] = true; } this.dependencies[namespace] = index; } hasDependency(namespaces: Array<string>, keys: Array<string>) { for (const namespace of namespaces) { const dependencies = this.dependencies[namespace]; if (dependencies) { for (const key of keys) { if (dependencies[key]) { return true; } } } } return false; } } export default Tile;
the_stack
import { StyleBuilder, DefinitionKebabCase } from "./builder"; describe("Test style builder", () => { const builder = new StyleBuilder({ custom: { test: { fontSize: 20, }, test2: { fontSize: 22, }, }, colors: { primary: "#FFFFFF", secondary: "#AAAAAA", "secondary-200": "#222222", }, widths: { "10": 10, full: "100%", }, heights: { "50": 50, full: "100%", }, paddingSizes: { "10": 1, small: "2", }, marginSizes: { "1": 3, medium: "4", }, borderWidths: { "1": 1, small: 10, }, borderRadiuses: { "123": 123, big: 1000, }, opacities: { "10": 0.1, "100": 1, }, }); test("Test Kebab case definition", () => { const definition = new DefinitionKebabCase("test1-test2-test3-test4"); for (let i = 0; i < 4; i++) { // Read method should return the segment of the kebab case string and don't move forward to the next segment. expect(definition.peek()).toBe(`test${i + 1}`); // Read method should return the segment of the kebab case string and move forward to the next segment. expect(definition.read()).toBe(`test${i + 1}`); } // If defintion doesn't have remaining segment, just return empty string expect(definition.peek()).toBe(""); expect(definition.read()).toBe(""); definition.reset(); // Flush method should return the remaining string without considering the segment and move forward to the end. expect(definition.flush()).toBe("test1-test2-test3-test4"); expect(definition.read()).toBe(""); definition.reset(); expect(definition.read()).toBe("test1"); // Flush method should return the remaining string without considering the segment and move forward to the end. expect(definition.flush()).toBe("test2-test3-test4"); expect(definition.read()).toBe(""); }); test("Throw an error if config has the reserved word", () => { expect(() => { new StyleBuilder({ custom: {}, colors: { primary: "#FFFFFF", secondary: "#AAAAAA", secondary200: "#222222", // Reserved word color: "should throw error", }, widths: { "10": 10, full: "100%", }, heights: { "50": 50, full: "100%", }, paddingSizes: { "10": "1", small: "2", }, marginSizes: { "1": "3", medium: "4", }, borderWidths: { "1": 1, small: 10, }, borderRadiuses: { "123": 123, big: 1000, }, opacities: { "10": 0.1, "100": 1, }, }); }).toThrow(); expect(() => { new StyleBuilder({ custom: {}, colors: { primary: "#FFFFFF", secondary: "#AAAAAA", secondary200: "#222222", // Reserved word ["asdf-solid"]: "should throw error", }, widths: { "10": 10, full: "100%", }, heights: { "50": 50, full: "100%", }, paddingSizes: { "10": "1", small: "2", }, marginSizes: { "1": "3", medium: "4", }, borderWidths: { "1": 1, small: 10, }, borderRadiuses: { "123": 123, big: 1000, }, opacities: { "10": 0.1, "100": 1, }, }); }).toThrow(); }); test("Test Custom", () => { expect(builder.get("test")).toStrictEqual({ fontSize: 20, }); }); test("Test Flatten", () => { expect(builder.flatten(["test", "flex"])).toStrictEqual({ fontSize: 20, display: "flex", }); }); test("Test Conditional Flatten", () => { expect(builder.flatten(["test"], [false])).toStrictEqual({ fontSize: 20, }); expect( builder.flatten( ["test", "absolute", "test2"], [null, undefined, false, true] ) ).toStrictEqual({ position: "absolute", fontSize: 22, }); expect( builder.flatten(["test", "absolute"], ["test2", undefined, false, true]) ).toStrictEqual({ position: "absolute", fontSize: 22, }); expect( builder.flatten(["test", "absolute"], [null, undefined, "test2", true]) ).toStrictEqual({ position: "absolute", fontSize: 22, }); expect( builder.flatten(["absolute"], [null, undefined, "test2", true]) ).toStrictEqual({ position: "absolute", fontSize: 22, }); expect( builder.flatten(["absolute"], ["test", undefined, "test2", true]) ).toStrictEqual({ position: "absolute", fontSize: 22, }); }); test("Test Display", () => { expect(builder.get("flex")).toStrictEqual({ display: "flex", }); expect(builder.get("display-none")).toStrictEqual({ display: "none", }); }); test("Test Position", () => { expect(builder.get("absolute")).toStrictEqual({ position: "absolute", }); expect(builder.get("absolute-fill")).toStrictEqual({ position: "absolute", left: 0, right: 0, top: 0, bottom: 0, }); expect(builder.get("relative")).toStrictEqual({ position: "relative", }); for (let i = 0; i <= 10; i++) { expect(builder.get(`flex-${i}` as any)).toStrictEqual({ flex: i, }); } expect(builder.get("flex-row")).toStrictEqual({ flexDirection: "row", }); expect(builder.get("flex-column")).toStrictEqual({ flexDirection: "column", }); expect(builder.get("flex-row-reverse")).toStrictEqual({ flexDirection: "row-reverse", }); expect(builder.get("flex-wrap")).toStrictEqual({ flexWrap: "wrap", }); expect(builder.get("flex-wrap-reverse")).toStrictEqual({ flexWrap: "wrap-reverse", }); expect(builder.get("flex-nowrap")).toStrictEqual({ flexWrap: "nowrap", }); expect(builder.get("flex-column-reverse")).toStrictEqual({ flexDirection: "column-reverse", }); expect(builder.get("content-start")).toStrictEqual({ alignContent: "flex-start", }); expect(builder.get("content-center")).toStrictEqual({ alignContent: "center", }); expect(builder.get("content-end")).toStrictEqual({ alignContent: "flex-end", }); expect(builder.get("content-stretch")).toStrictEqual({ alignContent: "stretch", }); expect(builder.get("content-between")).toStrictEqual({ alignContent: "space-between", }); expect(builder.get("content-around")).toStrictEqual({ alignContent: "space-around", }); expect(builder.get("items-start")).toStrictEqual({ alignItems: "flex-start", }); expect(builder.get("items-center")).toStrictEqual({ alignItems: "center", }); expect(builder.get("items-end")).toStrictEqual({ alignItems: "flex-end", }); expect(builder.get("items-stretch")).toStrictEqual({ alignItems: "stretch", }); expect(builder.get("items-baseline")).toStrictEqual({ alignItems: "baseline", }); expect(builder.get("self-auto")).toStrictEqual({ alignSelf: "auto", }); expect(builder.get("self-start")).toStrictEqual({ alignSelf: "flex-start", }); expect(builder.get("self-center")).toStrictEqual({ alignSelf: "center", }); expect(builder.get("self-end")).toStrictEqual({ alignSelf: "flex-end", }); expect(builder.get("self-stretch")).toStrictEqual({ alignSelf: "stretch", }); expect(builder.get("self-baseline")).toStrictEqual({ alignSelf: "baseline", }); expect(builder.get("justify-start")).toStrictEqual({ justifyContent: "flex-start", }); expect(builder.get("justify-center")).toStrictEqual({ justifyContent: "center", }); expect(builder.get("justify-end")).toStrictEqual({ justifyContent: "flex-end", }); expect(builder.get("justify-between")).toStrictEqual({ justifyContent: "space-between", }); expect(builder.get("justify-around")).toStrictEqual({ justifyContent: "space-around", }); expect(builder.get("justify-evenly")).toStrictEqual({ justifyContent: "space-evenly", }); expect(builder.get("overflow-visible")).toStrictEqual({ overflow: "visible", }); expect(builder.get("overflow-hidden")).toStrictEqual({ overflow: "hidden", }); expect(builder.get("overflow-scroll")).toStrictEqual({ overflow: "scroll", }); }); test("Test Color", () => { expect(builder.get("color-primary")).toStrictEqual({ color: "#FFFFFF", }); expect(builder.get("color-secondary")).toStrictEqual({ color: "#AAAAAA", }); expect(builder.get("color-secondary-200")).toStrictEqual({ color: "#222222", }); expect(builder.get("background-color-primary")).toStrictEqual({ backgroundColor: "#FFFFFF", }); expect(builder.get("background-color-secondary")).toStrictEqual({ backgroundColor: "#AAAAAA", }); expect(builder.get("background-color-secondary-200")).toStrictEqual({ backgroundColor: "#222222", }); expect(builder.get("border-color-primary")).toStrictEqual({ borderColor: "#FFFFFF", }); expect(builder.get("border-color-secondary")).toStrictEqual({ borderColor: "#AAAAAA", }); expect(builder.get("border-color-secondary-200")).toStrictEqual({ borderColor: "#222222", }); }); test("Test Sizing", () => { expect(builder.get("width-10")).toStrictEqual({ width: 10, }); expect(builder.get("min-width-10")).toStrictEqual({ minWidth: 10, }); expect(builder.get("max-width-10")).toStrictEqual({ maxWidth: 10, }); expect(builder.get("width-full")).toStrictEqual({ width: "100%", }); expect(builder.get("min-width-full")).toStrictEqual({ minWidth: "100%", }); expect(builder.get("max-width-full")).toStrictEqual({ maxWidth: "100%", }); expect(builder.get("height-50")).toStrictEqual({ height: 50, }); expect(builder.get("min-height-50")).toStrictEqual({ minHeight: 50, }); expect(builder.get("max-height-50")).toStrictEqual({ maxHeight: 50, }); expect(builder.get("height-full")).toStrictEqual({ height: "100%", }); expect(builder.get("min-height-full")).toStrictEqual({ minHeight: "100%", }); expect(builder.get("max-height-full")).toStrictEqual({ maxHeight: "100%", }); }); test("Test Border Style", () => { expect(builder.get("border-solid")).toStrictEqual({ borderStyle: "solid", }); expect(builder.get("border-dashed")).toStrictEqual({ borderStyle: "dashed", }); expect(builder.get("border-dotted")).toStrictEqual({ borderStyle: "dotted", }); }); test("Test Border Width", () => { expect(builder.get("border-width-1")).toStrictEqual({ borderWidth: 1, }); expect(builder.get("border-width-small")).toStrictEqual({ borderWidth: 10, }); expect(builder.get("border-width-left-1")).toStrictEqual({ borderLeftWidth: 1, }); expect(builder.get("border-width-left-small")).toStrictEqual({ borderLeftWidth: 10, }); expect(builder.get("border-width-right-1")).toStrictEqual({ borderRightWidth: 1, }); expect(builder.get("border-width-right-small")).toStrictEqual({ borderRightWidth: 10, }); expect(builder.get("border-width-top-1")).toStrictEqual({ borderTopWidth: 1, }); expect(builder.get("border-width-top-small")).toStrictEqual({ borderTopWidth: 10, }); expect(builder.get("border-width-bottom-1")).toStrictEqual({ borderBottomWidth: 1, }); expect(builder.get("border-width-bottom-small")).toStrictEqual({ borderBottomWidth: 10, }); }); test("Test Border Radius", () => { expect(builder.get("border-radius-123")).toStrictEqual({ borderRadius: 123, }); expect(builder.get("border-radius-big")).toStrictEqual({ borderRadius: 1000, }); expect(builder.get("border-radius-top-left-123")).toStrictEqual({ borderTopLeftRadius: 123, }); expect(builder.get("border-radius-top-left-big")).toStrictEqual({ borderTopLeftRadius: 1000, }); expect(builder.get("border-radius-top-right-123")).toStrictEqual({ borderTopRightRadius: 123, }); expect(builder.get("border-radius-top-right-big")).toStrictEqual({ borderTopRightRadius: 1000, }); expect(builder.get("border-radius-bottom-left-123")).toStrictEqual({ borderBottomLeftRadius: 123, }); expect(builder.get("border-radius-bottom-left-big")).toStrictEqual({ borderBottomLeftRadius: 1000, }); expect(builder.get("border-radius-bottom-right-123")).toStrictEqual({ borderBottomRightRadius: 123, }); expect(builder.get("border-radius-bottom-right-big")).toStrictEqual({ borderBottomRightRadius: 1000, }); }); test("Test Padding", () => { expect(builder.get("padding-10")).toStrictEqual({ paddingTop: 1, paddingBottom: 1, paddingLeft: 1, paddingRight: 1, }); expect(builder.get("padding-small")).toStrictEqual({ paddingTop: "2", paddingBottom: "2", paddingLeft: "2", paddingRight: "2", }); expect(builder.get("padding-left-10")).toStrictEqual({ paddingLeft: 1, }); expect(builder.get("padding-left-small")).toStrictEqual({ paddingLeft: "2", }); expect(builder.get("padding-right-10")).toStrictEqual({ paddingRight: 1, }); expect(builder.get("padding-right-small")).toStrictEqual({ paddingRight: "2", }); expect(builder.get("padding-top-10")).toStrictEqual({ paddingTop: 1, }); expect(builder.get("padding-top-small")).toStrictEqual({ paddingTop: "2", }); expect(builder.get("padding-bottom-10")).toStrictEqual({ paddingBottom: 1, }); expect(builder.get("padding-bottom-small")).toStrictEqual({ paddingBottom: "2", }); expect(builder.get("padding-x-10")).toStrictEqual({ paddingLeft: 1, paddingRight: 1, }); expect(builder.get("padding-x-small")).toStrictEqual({ paddingLeft: "2", paddingRight: "2", }); expect(builder.get("padding-y-10")).toStrictEqual({ paddingTop: 1, paddingBottom: 1, }); expect(builder.get("padding-y-small")).toStrictEqual({ paddingTop: "2", paddingBottom: "2", }); }); test("Test Margin", () => { expect(builder.get("margin-1")).toStrictEqual({ marginTop: 3, marginBottom: 3, marginLeft: 3, marginRight: 3, }); expect(builder.get("margin-medium")).toStrictEqual({ marginTop: "4", marginBottom: "4", marginLeft: "4", marginRight: "4", }); expect(builder.get("margin-left-1")).toStrictEqual({ marginLeft: 3, }); expect(builder.get("margin-left-medium")).toStrictEqual({ marginLeft: "4", }); expect(builder.get("margin-right-1")).toStrictEqual({ marginRight: 3, }); expect(builder.get("margin-right-medium")).toStrictEqual({ marginRight: "4", }); expect(builder.get("margin-top-1")).toStrictEqual({ marginTop: 3, }); expect(builder.get("margin-top-medium")).toStrictEqual({ marginTop: "4", }); expect(builder.get("margin-bottom-1")).toStrictEqual({ marginBottom: 3, }); expect(builder.get("margin-bottom-medium")).toStrictEqual({ marginBottom: "4", }); expect(builder.get("margin-x-1")).toStrictEqual({ marginLeft: 3, marginRight: 3, }); expect(builder.get("margin-x-medium")).toStrictEqual({ marginLeft: "4", marginRight: "4", }); expect(builder.get("margin-y-1")).toStrictEqual({ marginTop: 3, marginBottom: 3, }); expect(builder.get("margin-y-medium")).toStrictEqual({ marginTop: "4", marginBottom: "4", }); }); test("Test Opacity", () => { expect(builder.get("opacity-10")).toStrictEqual({ opacity: 0.1, }); expect(builder.get("opacity-100")).toStrictEqual({ opacity: 1, }); }); test("Test Resize mode", () => { expect(builder.get("resize-cover")).toStrictEqual({ resizeMode: "cover", }); expect(builder.get("resize-contain")).toStrictEqual({ resizeMode: "contain", }); expect(builder.get("resize-stretch")).toStrictEqual({ resizeMode: "stretch", }); expect(builder.get("resize-repeat")).toStrictEqual({ resizeMode: "repeat", }); expect(builder.get("resize-center")).toStrictEqual({ resizeMode: "center", }); }); test("Test Text static style", () => { expect(builder.get("italic")).toStrictEqual({ fontStyle: "italic", }); expect(builder.get("not-italic")).toStrictEqual({ fontStyle: "normal", }); const weights = [ "font-thin", "font-extralight", "font-light", "font-normal", "font-medium", "font-semibold", "font-bold", "font-extrabold", "font-black", ]; for (let i = 0; i < weights.length; i++) { const weight = weights[i]; expect(builder.get(weight as any)).toStrictEqual({ fontWeight: ((i + 1) * 100).toString(), }); } expect(builder.get("uppercase")).toStrictEqual({ textTransform: "uppercase", }); expect(builder.get("lowercase")).toStrictEqual({ textTransform: "lowercase", }); expect(builder.get("capitalize")).toStrictEqual({ textTransform: "capitalize", }); expect(builder.get("normal-case")).toStrictEqual({ textTransform: "none", }); expect(builder.get("text-auto")).toStrictEqual({ textAlign: "auto", }); expect(builder.get("text-left")).toStrictEqual({ textAlign: "left", }); expect(builder.get("text-right")).toStrictEqual({ textAlign: "right", }); expect(builder.get("text-center")).toStrictEqual({ textAlign: "center", }); expect(builder.get("text-justify")).toStrictEqual({ textAlign: "justify", }); }); });
the_stack
import { Component, ViewChild, OnInit, Input } from '@angular/core'; import { Location } from '@angular/common'; import { CodeshareService } from './codeshare.service'; import { BookingService } from '../shared/booking.service'; import { ActivatedRoute } from '@angular/router'; import { Settings } from './settings'; import { AdalService } from 'ng2-adal/core'; import { Network, DataSet, Node, Edge, IdType } from 'vis'; import { Popup } from 'ng2-opd-popup'; interface Metadata { properties?: any; outE?: any; inE?: any; to?: string; from?: string; type?: string; id?: string; label?: string; _displayLabel?: string; } enum PropertyPanelMode { Text, Json } @Component({ providers: [CodeshareService], templateUrl: './codeshare.component.html' }) export class CodeshareComponent implements OnInit { @Input('graphInMetatdata') graphInMetatdata: (Metadata)[]; private networkContainer: HTMLElement; private network: Network; private graphMetadata: Metadata; private graphMetadataOriginal: Metadata; private searchString: string; private jsonPropertyContent: any; private flightId: string; private serviceName: string; codeshare: any; name: string; price: number; letters: string[]; BookingReady: boolean; PurchaseReady: boolean; LoaderVisibility: boolean; physics = Settings.physicsSettings; iconGroups = Settings.defaultIconGroups; shapes = Settings.defaultShapes; sizableShapes = Settings.sizableShapes; selectedShape = this.shapes[0]; selectedPhysics = 'forceAtlas2Based'; constructor(private codeshareService: CodeshareService, private bookingService: BookingService, private adalService: AdalService, private route: ActivatedRoute, private _prevLocation: Location) { this.BookingReady = true; this.PurchaseReady = false; this.adalService.getUser().subscribe( res => { this.name = res.profile.name; }, err => { console.log(err); } ); } graphData: any; nodes: any; edges: any; nodeSize = "25"; edgeSize = "1"; iconSize = "25"; collections: Array<string>; selectedCollection: string; collectionTitle: string; labelMappings: { [label: string]: string } = {}; edgeColors: { [label: string]: string } = {}; selectedLabelProperty: string; defaultLabelConstant = '__originalLabel__'; noLabelConstant = '__noLabel__'; PanelMode: PropertyPanelMode; //to show popup of node details @ViewChild('nodedetails') nodedetails: Popup; ngOnInit() { var container = document.getElementById('network'); var serviceData = this.bookingService.codeshareSoloServiceData; if (typeof serviceData.serviceName != 'undefined' && serviceData.serviceName == "soloservice") { this.serviceName = "Solo Services"; } else if (typeof serviceData.serviceName != 'undefined' && serviceData.serviceName == "codeshare") { this.serviceName = "Code Share Partners"; } setTimeout(() => { this.codeshareService.get(serviceData.flightId, serviceData.serviceName).subscribe( res => { this.graphData = res; this.renderGraphNetwork(this.graphData); }, err => { console.log(err); } ); }, 2500); } graphMetadataItems: any[]; graphMetadataProperties: any[]; private GoBackToFlightView() { this._prevLocation.back(); } private click(params) { if (this.LoaderVisibility == true) { this.LoaderVisibility = false; } this.PanelMode = PropertyPanelMode.Text; //create empty object this.graphMetadata = {}; if (params.nodes && params.nodes.length === 1) { var node = this.nodes.get(params.nodes[0]); var nodeDetails = node.data; this.jsonPropertyContent = nodeDetails; if (nodeDetails) { //this assign will take care of id, label, properties in a node Object.assign(this.graphMetadata, nodeDetails); this.graphMetadata._displayLabel = node.label; this.selectedLabelProperty = this.labelMappings[node._gLabel] || null; //this.setSelectedNodeSettings(nodeDetails.label); //flatten the properties from nodes - instead of xxxx: Array(1), made it xxxx: yyyyy if (nodeDetails.properties != null) { this.graphMetadata.properties = {}; for (var kk in nodeDetails.properties) { this.graphMetadata.properties[kk] = nodeDetails.properties[kk][0].value; } } this.graphMetadata.type = "Vertex"; } } else if (params.edges && params.edges.length === 1) { var edgeDetails = this.edges.get(params.edges[0]); this.jsonPropertyContent = edgeDetails.data; if (edgeDetails) { //this assign will take care of id, label in an edge Object.assign(this.graphMetadata, edgeDetails); //we need to move data.properties to properties if (edgeDetails.data && edgeDetails.data.properties) { this.graphMetadata.properties = {}; for (var i in edgeDetails.data.properties) { this.graphMetadata.properties[i] = edgeDetails.data.properties[i]; } } this.graphMetadata.from = this.nodes.get(edgeDetails.from).label; this.graphMetadata.to = this.nodes.get(edgeDetails.to).label; this.graphMetadata.type = "Edge"; } } else { return; } if (Object.keys(this.graphMetadata).length === 0) { this.graphMetadata = null; } else { //copy graphMetadata object to an original one, graphMetadata will be modified on search and we need to keep a copy of the base one. this.graphMetadataOriginal = {}; Object.assign(this.graphMetadataOriginal, this.graphMetadata); } this.searchString = ''; this.nodedetails.options = { header: "Details", color: "#28aae1", // red, blue.... widthProsentage: 40, // The with of the popou measured by browser width animationDuration: 1, // in seconds, 0 = no animation showButtons: true, // You can hide this in case you want to use custom buttons confirmBtnContent: "", // The text on your confirm button cancleBtnContent: "OK", // the text on your cancel button confirmBtnClass: "sr-only", // your class for styling the confirm button cancleBtnClass: "btn btn-md btn-primary", // you class for styling the cancel button animation: "fadeInDown" // 'fadeInLeft', 'fadeInRight', 'fadeInUp', 'bounceIn','bounceInDown' }; this.graphMetadataItems = [this.graphMetadata]; this.graphMetadataProperties = [this.graphMetadata.properties]; this.nodedetails.show(this.nodedetails.options); } //fetch label value of node private getLabelValue(node, property) { var label; switch (property) { case this.defaultLabelConstant: label = node.data.label; break; case this.noLabelConstant: label = ''; break; default: label = node.data.properties[property][0].value; break; } return label; } //Render the network graph of Solo service and Codeshare renderGraphNetwork(data) { this.LoaderVisibility = true; this.nodes = new DataSet(); this.edges = new DataSet(); var container = document.getElementById('network'); for (let obj of data) { if (obj.type == 'vertex' && !this.nodes.get(obj.id)) { var node = obj; //do not change _gLabel anywhere, this is the base gremlin node type let visNode = { id: node.id, label: node.label, _gLabel: node.label, data: node }; if (this.iconGroups[node.label]) { (visNode as any).group = node.label; } if (this.labelMappings[node.label]) { visNode.label = this.getLabelValue(visNode, this.labelMappings[node.label]); } this.nodes.add(visNode); } else if (obj.type == 'edge' && !this.edges.get(obj.id)) { var edge = obj; var visEdge = { from: edge.outV, to: edge.inV, data: edge }; (visEdge as any).hiddenLabel = edge.label; //uncomment if done with settings part //if (this.showEdgeLabel) { // (visEdge as any).label = edge.label; //} if (this.edgeColors[edge.label]) { (visEdge as any).color = { color: this.edgeColors[edge.label] }; } this.edges.add(visEdge); } } var options = Settings.defaultGraphOptions; options.groups = this.iconGroups; options.nodes.shape = this.selectedShape; options.physics = this.physics[this.selectedPhysics]; options.physics.stabilization = { iterations: 1250, updateInterval: 1 }; options.physics.minVelocity = 5; this.network = new Network(container, { nodes: this.nodes, edges: this.edges }, options); this.network.on('click', this.click.bind(this)); } }
the_stack
import { WindowPostMessageProxy } from 'window-post-message-proxy'; import { HttpPostMessage } from 'http-post-message'; import { spyApp, setupEmbedMockApp } from './utility/mockEmbed'; import { hpmFactory, routerFactory, wpmpFactory } from '../src/factories'; import { iframeSrc, logMessages } from './constsants'; import * as models from 'powerbi-models'; describe('Protocol', function () { let hpm: HttpPostMessage; let wpmp: WindowPostMessageProxy; let iframe: HTMLIFrameElement; let iframeHpm: HttpPostMessage; let spyHandler: { test: jasmine.Spy; handle: jasmine.Spy; }; beforeEach(async function () { iframe = document.createElement('iframe'); iframe.id = 'protocol'; iframe.src = iframeSrc; document.body.appendChild(iframe); await new Promise(resolve => iframe.addEventListener('load', () => resolve(null))); // Register Iframe side iframeHpm = setupEmbedMockApp(iframe.contentWindow, window, logMessages, 'ProtocolMockAppWpmp'); // Register SDK side WPMP wpmp = wpmpFactory('HostProxyDefaultNoHandlers', logMessages, iframe.contentWindow); hpm = hpmFactory(wpmp, iframe.contentWindow, 'testVersion'); const router = routerFactory(wpmp); spyHandler = { test: jasmine.createSpy("testSpy").and.returnValue(true), handle: jasmine.createSpy("handleSpy").and.callFake(function (message: any) { message.handled = true; return message; }) }; router.post('/reports/:uniqueId/events/:eventName', (req, res) => { spyHandler.handle(req); res.send(202); }); router.post('/reports/:uniqueId/pages/:pageName/events/:eventName', (req, res) => { spyHandler.handle(req); res.send(202); }); router.post('/reports/:uniqueId/pages/:pageName/visuals/:visualName/events/:eventName', (req, res) => { spyHandler.handle(req); res.send(202); }); }); afterEach(function () { iframe.remove(); wpmp.stop(); spyHandler.test.calls.reset(); spyHandler.handle.calls.reset(); spyApp.reset(); }); describe('HPM-to-MockApp', function () { describe('notfound', function () { it('GET request to uknown url returns 404 Not Found', async function () { try { await hpm.get<any>('route/that/does/not/exist'); } catch (response) { expect(response.statusCode).toEqual(404); } }); it('POST request to uknown url returns 404 Not Found', async function () { try { await hpm.post<any>('route/that/does/not/exist', null); } catch (response) { expect(response.statusCode).toEqual(404); } }); it('PUT request to uknown url returns 404 Not Found', async function () { try { await hpm.put<any>('route/that/does/not/exist', null); } catch (response) { expect(response.statusCode).toEqual(404); } }); it('PATCH request to uknown url returns 404 Not Found', async function () { try { await hpm.patch<any>('route/that/does/not/exist', null); } catch (response) { expect(response.statusCode).toEqual(404); } }); it('DELETE request to uknown url returns 404 Not Found', async function () { try { await hpm.delete<any>('route/that/does/not/exist'); } catch (response) { expect(response.statusCode).toEqual(404); } }); }); describe('create', function () { describe('report', function () { it('POST /report/create returns 400 if the request is invalid', async function () { // Arrange const testData = { uniqueId: 'uniqueId', create: { datasetId: "fakeId", accessToken: "fakeToken", } }; spyApp.validateCreateReport.and.callFake(() => Promise.reject(null)); // Act try { await hpm.post<models.IError>('/report/create', testData.create, { uid: testData.uniqueId }); fail("POST to /report/create should fail"); } catch (response) { // Assert expect(spyApp.validateCreateReport).toHaveBeenCalledWith(testData.create); expect(response.statusCode).toEqual(400); } }); }); it('POST /report/create returns 202 if the request is valid', async function () { // Arrange const testData = { create: { datasetId: "fakeId", accessToken: "fakeToken", } }; spyApp.validateCreateReport.and.returnValue(Promise.resolve(null)); // Act try { const response = await hpm.post<void>('/report/create', testData.create); // Assert expect(spyApp.validateCreateReport).toHaveBeenCalledWith(testData.create); expect(response.statusCode).toEqual(202); } catch (error) { console.log("hpm.post failed with", error); fail("hpm.post"); } }); }); }); describe('load & prepare', function () { describe('report', function () { for (let action of ['load', 'prepare']) { it(`POST /report/${action} returns 400 if the request is invalid`, async function () { // Arrange const testData = { uniqueId: 'uniqueId', load: { reportId: "fakeId", accessToken: "fakeToken", options: { } } }; spyApp.validateReportLoad.and.callFake(() => Promise.reject(null)); // Act try { await hpm.post<models.IError>(`/report/${action}`, testData.load, { uid: testData.uniqueId }); fail(`Post to /report/${action} should fail`); } catch (response) { // Assert expect(spyApp.validateReportLoad).toHaveBeenCalledWith(testData.load); expect(spyApp.reportLoad).not.toHaveBeenCalledWith(testData.load); expect(response.statusCode).toEqual(400); } }); it(`POST /report/${action} returns 202 if the request is valid`, async function () { // Arrange const testData = { load: { reportId: "fakeId", accessToken: "fakeToken", options: { } } }; spyApp.validateReportLoad.and.callFake(() => Promise.resolve({})); try { const response = await hpm.post<void>(`/report/${action}`, testData.load); // Assert expect(spyApp.validateReportLoad).toHaveBeenCalledWith(testData.load); expect(spyApp.reportLoad).toHaveBeenCalledWith(testData.load); expect(response.statusCode).toEqual(202); } catch (error) { console.error(error); fail(error); } }); it(`POST /report/${action} causes POST /reports/:uniqueId/events/loaded`, async function () { // Arrange const testData = { uniqueId: 'uniqueId', load: { reportId: "fakeId", accessToken: "fakeToken", options: { navContentPaneEnabled: false } }, }; const testExpectedEvent = { method: 'POST', url: `/reports/${testData.uniqueId}/events/loaded`, body: { initiator: 'sdk' } }; try { // Act await hpm.post<void>(`/report/${action}`, testData.load, { uid: testData.uniqueId }); // Assert expect(spyApp.validateReportLoad).toHaveBeenCalledWith(testData.load); expect(spyApp.reportLoad).toHaveBeenCalledWith(testData.load); expect(spyHandler.handle).toHaveBeenCalledWith(jasmine.objectContaining(testExpectedEvent)); } catch (error) { console.log("hpm.post failed with", error); fail("hpm.post failed"); } }); it(`POST /report/${action} causes POST /reports/:uniqueId/events/error`, async function () { // Arrange const testData = { uniqueId: 'uniqueId', load: { reportId: "fakeId", accessToken: "fakeToken", options: { navContentPaneEnabled: false } }, error: { message: "error message" } }; const testExpectedEvent = { method: 'POST', url: `/reports/${testData.uniqueId}/events/error`, body: testData.error }; spyApp.reportLoad.and.callFake(() => Promise.reject(testData.error)); try { // Act await hpm.post<void>(`/report/${action}`, testData.load, { uid: testData.uniqueId }); expect(spyApp.validateReportLoad).toHaveBeenCalledWith(testData.load); expect(spyApp.reportLoad).toHaveBeenCalledWith(testData.load); expect(spyHandler.handle).toHaveBeenCalledWith(jasmine.objectContaining(testExpectedEvent)); } catch (error) { console.log("hpm pody failed with", error); fail("hpm pody failed"); } }); } }); describe('dashboard', function () { it('POST /dashboard/load returns 202 if the request is valid', async function () { // Arrange const testData = { load: { dashboardId: "fakeId", accessToken: "fakeToken", options: { } } }; spyApp.validateDashboardLoad.and.returnValue(Promise.resolve(null)); try { // Act const response = await hpm.post<void>('/dashboard/load', testData.load); // Assert expect(spyApp.validateDashboardLoad).toHaveBeenCalledWith(testData.load); expect(spyApp.dashboardLoad).toHaveBeenCalledWith(testData.load); expect(response.statusCode).toEqual(202); } catch (error) { console.error(error); fail(error); } }); it('POST /dashboard/load returns 400 if the request is invalid', async function () { // Arrange const testData = { uniqueId: 'uniqueId', load: { dashboardId: "fakeId", accessToken: "fakeToken", options: { } } }; spyApp.validateDashboardLoad.and.callFake(() => Promise.reject(null)); try { // Act await hpm.post<models.IError>('/dashboard/load', testData.load, { uid: testData.uniqueId }); fail("POST to /dashboard/load should fail"); } catch (response) { // Assert expect(spyApp.validateDashboardLoad).toHaveBeenCalledWith(testData.load); expect(spyApp.dashboardLoad).not.toHaveBeenCalledWith(testData.load); expect(response.statusCode).toEqual(400); } }); }); }); describe('render', function () { it('POST /report/render returns 202 if the request is valid', async function () { // Arrange spyApp.render.and.returnValue(Promise.resolve(null)); // Act const response = await hpm.post<void>('/report/render', null); // Assert expect(spyApp.render).toHaveBeenCalled(); expect(response.statusCode).toEqual(202); }); }); describe('pages', function () { it('GET /report/pages returns 200 with body as array of pages', async function () { // Arrange const testData = { expectedPages: [ { name: "a" }, { name: "b" } ] }; spyApp.getPages.and.returnValue(Promise.resolve(testData.expectedPages)); // Act const response = await hpm.get<models.IPage[]>('/report/pages'); // Assert expect(spyApp.getPages).toHaveBeenCalled(); const pages = response.body; // @ts-ignore as testData is not of type IFilter expect(pages).toEqual(testData.expectedPages); }); it('GET /report/pages returns 500 with body as error', async function () { // Arrange const testData = { expectedError: { message: "could not query pages" } }; spyApp.getPages.and.callFake(() => Promise.reject(testData.expectedError)); try { // Act await hpm.get<models.IPage[]>('/report/pages'); fail("Get /report/pages should fail"); } catch (response) { // Assert expect(spyApp.getPages).toHaveBeenCalled(); const error = response.body; expect(error).toEqual(testData.expectedError); } }); it('PUT /report/pages/active returns 400 if request is invalid', async function () { // Arrange const testData = { page: { name: "fakeName" } }; spyApp.validatePage.and.callFake(() => Promise.reject(null)); try { // Act await hpm.put<void>('/report/pages/active', testData.page); fail("put to /report/pages/active should fail"); } catch (response) { // Assert expect(spyApp.validatePage).toHaveBeenCalledWith(testData.page); expect(spyApp.setPage).not.toHaveBeenCalled(); expect(response.statusCode).toEqual(400); } }); it('PUT /report/pages/active returns 202 if request is valid', async function () { // Arrange const testData = { page: { name: "fakeName" } }; spyApp.validatePage.and.returnValue(Promise.resolve(null)); // Act const response = await hpm.put<void>('/report/pages/active', testData.page); // Assert expect(spyApp.validatePage).toHaveBeenCalledWith(testData.page); expect(spyApp.setPage).toHaveBeenCalledWith(testData.page); expect(response.statusCode).toEqual(202); }); it('PUT /report/pages/active causes POST /reports/:uniqueId/events/pageChanged', async function () { // Arrange const testData = { uniqueId: 'uniqueId', reportId: 'fakeReportId', page: { name: "fakeName" } }; const expectedEvent = { method: 'POST', url: `/reports/${testData.uniqueId}/events/pageChanged`, body: jasmine.objectContaining({ initiator: 'sdk' }) }; spyApp.validatePage.and.returnValue(Promise.resolve(null)); spyHandler.handle.calls.reset(); // Act const response = await hpm.put<void>('/report/pages/active', testData.page, { uid: testData.uniqueId }); // Assert expect(spyApp.validatePage).toHaveBeenCalledWith(testData.page); expect(spyApp.setPage).toHaveBeenCalledWith(testData.page); expect(response.statusCode).toEqual(202); expect(spyHandler.handle).toHaveBeenCalledWith(jasmine.objectContaining(expectedEvent)); }); it('PUT /report/pages/active causes POST /reports/:uniqueId/events/error', async function () { // Arrange const testData = { uniqueId: 'uniqueId', reportId: 'fakeReportId', page: { name: "fakeName" }, error: { message: "error" } }; const expectedEvent = { method: 'POST', url: `/reports/${testData.uniqueId}/events/error`, body: testData.error }; spyApp.validatePage.and.returnValue(Promise.resolve(null)); spyApp.setPage.and.callFake(() => Promise.reject(testData.error)); // Act const response = await hpm.put<void>('/report/pages/active', testData.page, { uid: testData.uniqueId }); // Assert expect(spyApp.validatePage).toHaveBeenCalledWith(testData.page); expect(spyApp.setPage).toHaveBeenCalledWith(testData.page); expect(response.statusCode).toEqual(202); expect(spyHandler.handle).toHaveBeenCalledWith(jasmine.objectContaining(expectedEvent)); }); describe('refresh', function () { it('POST /report/refresh returns 202 if the request is valid', async function () { // Arrange spyApp.refreshData.and.returnValue(Promise.resolve(null)); // Act const response = await hpm.post<void>('/report/refresh', null); // Assert expect(spyApp.refreshData).toHaveBeenCalled(); expect(response.statusCode).toEqual(202); }); }); describe('print', function () { it('POST /report/print returns 202 if the request is valid', async function () { // Arrange spyApp.print.and.returnValue(Promise.resolve(null)); // Act const response = await hpm.post<void>('/report/print', null); // Assert expect(spyApp.print).toHaveBeenCalled(); expect(response.statusCode).toEqual(202); }); }); describe('switchMode', function () { it('POST /report/switchMode returns 202 if the request is valid', async function () { // Arrange spyApp.switchMode.and.returnValue(Promise.resolve(null)); // Act const response = await hpm.post<void>('/report/switchMode/Edit', null); // Assert expect(spyApp.switchMode).toHaveBeenCalled(); expect(response.statusCode).toEqual(202); }); }); describe('save', function () { it('POST /report/save returns 202 if the request is valid', async function () { // Arrange spyApp.save.and.returnValue(Promise.resolve(null)); // Act const response = await hpm.post<void>('/report/save', null); // Assert expect(spyApp.save).toHaveBeenCalled(); expect(response.statusCode).toEqual(202); }); }); }); describe('saveAs', function () { it('POST /report/saveAs returns 202 if the request is valid', async function () { // Arrange let saveAsParameters: models.ISaveAsParameters = { name: "reportName" }; spyApp.saveAs.and.returnValue(Promise.resolve(null)); // Act const response = await hpm.post<void>('/report/saveAs', saveAsParameters); // Assert expect(spyApp.saveAs).toHaveBeenCalled(); expect(spyApp.saveAs).toHaveBeenCalledWith(saveAsParameters); expect(response.statusCode).toEqual(202); }); }); describe('setAccessToken', function () { it('POST /report/token returns 202 if the request is valid', async function () { // Arrange let accessToken: string = "fakeToken"; spyApp.setAccessToken.and.returnValue(Promise.resolve(null)); // Act const response = await hpm.post<void>('/report/token', accessToken); // Assert expect(spyApp.setAccessToken).toHaveBeenCalled(); expect(spyApp.setAccessToken).toHaveBeenCalledWith(accessToken); expect(response.statusCode).toEqual(202); }); }); describe('filters (report level)', function () { it('GET /report/filters returns 200 with body as array of filters', async function () { // Arrange const testData = { filters: [ { name: "fakeFilter1" }, { name: "fakeFilter2" } ] }; spyApp.getFilters.and.returnValue(Promise.resolve(testData.filters)); // Act const response = await hpm.get<models.IFilter[]>('/report/filters'); // Assert expect(spyApp.getFilters).toHaveBeenCalled(); expect(response.statusCode).toEqual(200); // @ts-ignore as testData is not of type IFilter expect(response.body).toEqual(testData.filters); }); it('GET /report/filters returns 500 with body as error', async function () { // Arrange const testData = { error: { message: "internal error" } }; spyApp.getFilters.and.callFake(() => Promise.reject(testData.error)); // Act try { await hpm.get<models.IFilter[]>('/report/filters'); } catch (response) { // Assert expect(spyApp.getFilters).toHaveBeenCalled(); expect(response.statusCode).toEqual(500); expect(response.body).toEqual(testData.error); } }); it('PUT /report/filters returns 400 if request is invalid', async function () { // Arrange const testData = { filters: [ { name: "fakeFilter" } ] }; spyApp.validateFilter.and.callFake(() => Promise.reject(null)); // Act try { await hpm.put<models.IError>('/report/filters', testData.filters); } catch (response) { // Assert expect(spyApp.validateFilter).toHaveBeenCalledWith(testData.filters[0]); expect(spyApp.setFilters).not.toHaveBeenCalled(); expect(response.statusCode).toEqual(400); } }); it('PUT /report/filters returns 202 if request is valid', async function () { // Arrange const testData = { filters: [ { name: "fakeFilter" } ] }; spyApp.validateFilter.and.returnValue(Promise.resolve(null)); // Act const response = await hpm.put<void>('/report/filters', testData.filters); // Assert expect(spyApp.validateFilter).toHaveBeenCalledWith(testData.filters[0]); expect(spyApp.setFilters).toHaveBeenCalledWith(testData.filters); expect(response.statusCode).toEqual(202); }); it('PUT /report/filters will cause POST /reports/:uniqueId/events/filtersApplied', async function () { // Arrange const testData = { uniqueId: 'uniqueId', reportId: 'fakeReportId', filters: [ { name: "fakeFilter" } ] }; const testExpectedEvent = { method: 'POST', url: `/reports/${testData.uniqueId}/events/filtersApplied` }; spyApp.validateFilter.and.returnValue(Promise.resolve(null)); // Act const response = await hpm.put<void>('/report/filters', testData.filters, { uid: testData.uniqueId }); // Assert expect(spyApp.validateFilter).toHaveBeenCalledWith(testData.filters[0]); expect(spyApp.setFilters).toHaveBeenCalledWith(testData.filters); expect(response.statusCode).toEqual(202); expect(spyHandler.handle).toHaveBeenCalledWith(jasmine.objectContaining(testExpectedEvent)); }); }); describe('filters (page level)', function () { beforeEach(() => { spyApp.validatePage.and.returnValue(Promise.resolve(null)); spyApp.validateFilter.and.returnValue(Promise.resolve(null)); }); it('GET /report/pages/xyz/filters returns 200 with body as array of filters', async function () { // Arrange const testData = { filters: [ { name: "fakeFilter1" }, { name: "fakeFilter2" } ] }; spyApp.getFilters.and.returnValue(Promise.resolve(testData.filters)); // Act const response = await hpm.get<models.IFilter[]>('/report/pages/xyz/filters'); // Assert expect(spyApp.getFilters).toHaveBeenCalled(); expect(response.statusCode).toEqual(200); // @ts-ignore as testData is not of type IFilter expect(response.body).toEqual(testData.filters); }); it('GET /report/pages/xyz/filters returns 500 with body as error', async function () { // Arrange const testData = { error: { message: "internal error" } }; spyApp.getFilters.and.callFake(() => Promise.reject(testData.error)); // Act try { await hpm.get<models.IFilter[]>('/report/pages/xyz/filters'); } catch (response) { // Assert expect(spyApp.getFilters).toHaveBeenCalled(); expect(response.statusCode).toEqual(500); expect(response.body).toEqual(testData.error); } }); it('PUT /report/pages/xyz/filters returns 400 if request is invalid', async function () { // Arrange const testData = { filters: [ { name: "fakeFilter" } ] }; spyApp.validateFilter.and.callFake(() => Promise.reject(null)); // Act try { await hpm.put<models.IError>('/report/pages/xyz/filters', testData.filters); } catch (response) { // Assert expect(spyApp.validateFilter).toHaveBeenCalledWith(testData.filters[0]); expect(spyApp.setFilters).not.toHaveBeenCalled(); expect(response.statusCode).toEqual(400); } }); it('PUT /report/pages/xyz/filters returns 202 if request is valid', async function () { // Arrange const testData = { filters: [ { name: "fakeFilter" } ], }; spyApp.validateFilter.and.returnValue(Promise.resolve(null)); // Act const response = await hpm.put<void>('/report/pages/xyz/filters', testData.filters); // Assert expect(spyApp.validateFilter).toHaveBeenCalledWith(testData.filters[0]); expect(spyApp.setFilters).toHaveBeenCalledWith(testData.filters); expect(response.statusCode).toEqual(202); }); it('PUT /report/pages/xyz/filters will cause POST /reports/:uniqueId/pages/xyz/events/filtersApplied', async function () { // Arrange const testData = { uniqueId: 'uniqueId', reportId: 'fakeReportId', filters: [ { name: "fakeFilter" } ] }; const testExpectedEvent = { method: 'POST', url: `/reports/${testData.uniqueId}/pages/xyz/events/filtersApplied` }; spyApp.validateFilter.and.returnValue(Promise.resolve(null)); // Act const response = await hpm.put<void>('/report/pages/xyz/filters', testData.filters, { uid: testData.uniqueId }); // Assert expect(spyApp.validateFilter).toHaveBeenCalledWith(testData.filters[0]); expect(spyApp.setFilters).toHaveBeenCalledWith(testData.filters); expect(response.statusCode).toEqual(202); expect(spyHandler.handle).toHaveBeenCalledWith(jasmine.objectContaining(testExpectedEvent)); }); }); describe('filters (visual level)', function () { it('GET /report/pages/xyz/visuals/uvw/filters returns 200 with body as array of filters', async function () { // Arrange const testData = { filters: [ { name: "fakeFilter1" }, { name: "fakeFilter2" } ] }; spyApp.getFilters.and.returnValue(Promise.resolve(testData.filters)); // Act try { const response = await hpm.get<models.IFilter[]>('/report/pages/xyz/visuals/uvw/filters'); // Assert expect(spyApp.getFilters).toHaveBeenCalled(); expect(response.statusCode).toEqual(200); // @ts-ignore as testData is not of type IFilter expect(response.body).toEqual(testData.filters); } catch (error) { console.log("get filter shouldn't fail"); } }); it('GET /report/pages/xyz/visuals/uvw/filters returns 500 with body as error', async function () { // Arrange const testData = { error: { message: "internal error" } }; spyApp.getFilters.and.callFake(() => Promise.reject(testData.error)); // Act try { await hpm.get<models.IFilter[]>('/report/pages/xyz/visuals/uvw/filters'); } catch (response) { // Assert expect(spyApp.getFilters).toHaveBeenCalled(); expect(response.statusCode).toEqual(500); expect(response.body).toEqual(testData.error); } }); it('PUT /report/pages/xyz/visuals/uvw/filters returns 400 if request is invalid', async function () { // Arrange const testData = { uniqueId: 'uniqueId', filters: [ { name: "fakeFilter" } ] }; spyApp.validateFilter.and.callFake(() => Promise.reject(null)); // Act try { await hpm.put<models.IError>('/report/pages/xyz/visuals/uvw/filters', testData.filters, { uid: testData.uniqueId }); } catch (response) { // Assert expect(spyApp.validateFilter).toHaveBeenCalledWith(testData.filters[0]); expect(spyApp.setFilters).not.toHaveBeenCalled(); expect(response.statusCode).toEqual(400); } }); it('PUT /report/pages/xyz/visuals/uvw/filters returns 202 if request is valid', async function () { // Arrange const testData = { uniqueId: 'uniqueId', filters: [ { name: "fakeFilter" } ], }; spyApp.validateFilter.and.returnValue(Promise.resolve(null)); // Act const response = await hpm.put<void>('/report/pages/xyz/visuals/uvw/filters', testData.filters, { uid: testData.uniqueId }); // Assert expect(spyApp.validateFilter).toHaveBeenCalledWith(testData.filters[0]); expect(spyApp.setFilters).toHaveBeenCalledWith(testData.filters); expect(response.statusCode).toEqual(202); }); it('PUT /report/:uniqueId/pages/xyz/visuals/uvw/filters will cause POST /reports/:uniqueId/pages/xyz/visuals/uvw/events/filtersApplied', async function () { // Arrange const testData = { uniqueId: 'uniqueId', filters: [ { name: "fakeFilter" } ] }; const testExpectedEvent = { method: 'POST', url: `/reports/${testData.uniqueId}/pages/xyz/visuals/uvw/events/filtersApplied` }; // Act try { const response = await hpm.put<void>('/report/pages/xyz/visuals/uvw/filters', testData.filters, { uid: testData.uniqueId }); // Assert expect(spyApp.validateFilter).toHaveBeenCalledWith(testData.filters[0]); expect(spyApp.setFilters).toHaveBeenCalledWith(testData.filters); expect(response.statusCode).toEqual(202); expect(spyHandler.handle).toHaveBeenCalledWith(jasmine.objectContaining(testExpectedEvent)); } catch (error) { console.log("hpm.put failed with", error); fail("hpm.put failed"); } }); }); describe('settings', function () { it('PATCH /report/settings returns 400 if request is invalid', async function () { // Arrange const testData = { settings: { filterPaneEnabled: false, navContentPaneEnabled: false } }; spyApp.validateSettings.and.callFake(() => Promise.reject(null)); // Act try { await hpm.patch<models.IError[]>('/report/settings', testData.settings); } catch (response) { // Assert expect(spyApp.validateSettings).toHaveBeenCalledWith(testData.settings); expect(spyApp.updateSettings).not.toHaveBeenCalled(); expect(response.statusCode).toEqual(400); } }); it('PATCH /report/settings returns 202 if request is valid', async function () { // Arrange const testData = { settings: { filterPaneEnabled: false, navContentPaneEnabled: false } }; spyApp.validateSettings.and.returnValue(Promise.resolve(null)); // Act const response = await hpm.patch<void>('/report/settings', testData.settings); // Assert expect(spyApp.validateSettings).toHaveBeenCalledWith(testData.settings); expect(spyApp.updateSettings).toHaveBeenCalledWith(testData.settings); expect(response.statusCode).toEqual(202); }); it('PATCH /report/settings causes POST /reports/:uniqueId/events/settingsUpdated', async function () { // Arrange const testData = { uniqueId: 'uniqueId', reportId: 'fakeReportId', settings: { filterPaneEnabled: false } }; const testExpectedEvent = { method: 'POST', url: `/reports/${testData.uniqueId}/events/settingsUpdated`, body: { initiator: 'sdk', settings: { filterPaneEnabled: false, navContentPaneEnabled: false } } }; spyApp.validateSettings.and.returnValue(Promise.resolve(null)); spyApp.updateSettings.and.returnValue(Promise.resolve(testExpectedEvent.body.settings)); // Act const response = await hpm.patch<void>('/report/settings', testData.settings, { uid: testData.uniqueId }); // Assert expect(spyApp.validateSettings).toHaveBeenCalledWith(testData.settings); expect(spyApp.updateSettings).toHaveBeenCalledWith(testData.settings); expect(response.statusCode).toEqual(202); expect(spyHandler.handle).toHaveBeenCalledWith(jasmine.objectContaining(testExpectedEvent)); }); }); describe('MockApp-to-HPM', function () { describe('pages', function () { it('POST /reports/:uniqueId/events/pageChanged when user changes page', async function () { // Arrange const testData = { uniqueId: 'uniqueId', reportId: 'fakeReportId', event: { initiator: 'user', newPage: { name: "fakePageName" } } }; const testExpectedRequest = { method: 'POST', url: `/reports/${testData.uniqueId}/events/pageChanged`, body: testData.event }; // Act const response = await iframeHpm.post<void>(testExpectedRequest.url, testData.event); // Assert expect(response.statusCode).toBe(202); expect(spyHandler.handle).toHaveBeenCalledWith(jasmine.objectContaining(testExpectedRequest)); }); }); describe('filters (report level)', function () { it('POST /reports/:uniqueId/events/filtersApplied when user changes filter', async function () { // Arrange const testData = { uniqueId: 'uniqueId', reportId: 'fakeReportId', event: { initiator: 'user', filters: [ { name: "fakeFilter" } ] } }; const testExpectedRequest = { method: 'POST', url: `/reports/${testData.uniqueId}/events/filtersApplied`, body: testData.event }; // Act const response = await iframeHpm.post(testExpectedRequest.url, testData.event); // Assert expect(response.statusCode).toBe(202); expect(spyHandler.handle).toHaveBeenCalledWith(jasmine.objectContaining(testExpectedRequest)); }); describe('filters (page level)', function () { it('POST /reports/:uniqueId/pages/xyz/events/filtersApplied when user changes filter', async function () { // Arrange const testData = { uniqueId: 'uniqueId', reportId: 'fakeReportId', event: { initiator: 'user', filters: [ { name: "fakeFilter" } ] } }; const testExpectedRequest = { method: 'POST', url: `/reports/${testData.uniqueId}/pages/xyz/events/filtersApplied`, body: testData.event }; // Act const response = await iframeHpm.post(testExpectedRequest.url, testData.event); // Assert expect(response.statusCode).toBe(202); expect(spyHandler.handle).toHaveBeenCalledWith(jasmine.objectContaining(testExpectedRequest)); }); }); describe('filters (visual level)', function () { it('POST /reports/:uniqueId/pages/xyz/visuals/uvw/events/filtersApplied when user changes filter', async function () { // Arrange const testData = { uniqueId: 'uniqueId', reportId: 'fakeReportId', event: { initiator: 'user', filters: [ { name: "fakeFilter" } ] } }; const testExpectedRequest = { method: 'POST', url: `/reports/${testData.uniqueId}/pages/xyz/visuals/uvw/events/filtersApplied`, body: testData.event }; // Act const response = await iframeHpm.post(testExpectedRequest.url, testData.event); // Assert expect(response.statusCode).toBe(202); expect(spyHandler.handle).toHaveBeenCalledWith(jasmine.objectContaining(testExpectedRequest)); }); }); describe('settings', function () { it('POST /reports/:uniqueId/events/settingsUpdated when user changes settings', async function () { // Arrange const testData = { uniqueId: 'uniqueId', reportId: 'fakeReportId', event: { initiator: 'user', settings: { navContentPaneEnabled: true } } }; const testExpectedRequest = { method: 'POST', url: `/reports/${testData.uniqueId}/events/settingsUpdated`, body: testData.event }; // Act const response = await iframeHpm.post(testExpectedRequest.url, testData.event); // Assert expect(response.statusCode).toBe(202); expect(spyHandler.handle).toHaveBeenCalledWith(jasmine.objectContaining(testExpectedRequest)); }); }); describe('data selection', function () { it('POST /reports/:uniqueId/events/dataSelected when user selects data', async function () { // Arrange const testData = { uniqueId: 'uniqueId', reportId: 'fakeReportId', event: { initiator: 'user', selection: { data: true } } }; const testExpectedRequest = { method: 'POST', url: `/reports/${testData.uniqueId}/events/dataSelected`, body: testData.event }; // Act const response = await iframeHpm.post(testExpectedRequest.url, testData.event); // Assert expect(response.statusCode).toBe(202); expect(spyHandler.handle).toHaveBeenCalledWith(jasmine.objectContaining(testExpectedRequest)); }); }); }); }); });
the_stack
import React, { ChangeEvent, HTMLAttributes, useCallback, useLayoutEffect, useMemo, useRef, useState, } from 'react' import styled, { css } from 'styled-components' import { Theme, useTheme } from '../../hooks/useTheme' import { useOuterClick } from '../../hooks/useOuterClick' import { hasParentElementByClassName } from './multiComboBoxHelper' import { useClassNames } from './useClassNames' import { FaCaretDownIcon } from '../Icon' import { useListBox } from './useListBox' import { MultiSelectedItem } from './MultiSelectedItem' import { convertMatchableString } from './comboBoxHelper' import { Item } from './types' type Props<T> = { /** * 選択可能なアイテムのリスト */ items: Array<Item<T>> /** * 選択されているアイテムのリスト */ selectedItems: Array<Item<T> & { deletable?: boolean }> /** * input 要素の `name` 属性の値 */ name?: string /** * input 要素の `disabled` 属性の値 */ disabled?: boolean /** * `true` のとき、コンポーネントの外枠が `DANGER` カラーになる */ error?: boolean /** * `true` のとき、 `items` 内に存在しないアイテムを新しく追加できるようになる */ creatable?: boolean /** * input 要素の `placeholder` 属性の値 */ placeholder?: string /** * `true` のとき、ドロップダウンリスト内にローダーを表示する */ isLoading?: boolean /** * 選択されているアイテムのラベルを省略表示するかどうか */ selectedItemEllipsis?: boolean /** * input 要素の `width` スタイルに適用する値 */ width?: number | string /** * テキストボックスの `value` 属性の値。 * `onChangeInput` と併せて設定することで、テキストボックスの挙動が制御可能になる。 */ inputValue?: string /** * コンポーネント内の一番外側の要素に適用するクラス名 */ className?: string /** * input 要素の `value` が変わった時に発火するコールバック関数 * @deprecated `onChange` は非推奨なため、代わりに `onChangeInput` を使用してください。 */ onChange?: (e: ChangeEvent<HTMLInputElement>) => void /** * input 要素の `value` が変わった時に発火するコールバック関数 */ onChangeInput?: (e: ChangeEvent<HTMLInputElement>) => void /** * `items` 内に存在しないアイテムが追加されたときに発火するコールバック関数 */ onAdd?: (label: string) => void /** * 選択されているアイテムの削除ボタンがクリックされた時に発火するコールバック関数 */ onDelete?: (item: Item<T>) => void /** * アイテムが選択された時に発火するコールバック関数 */ onSelect?: (item: Item<T>) => void /** * 選択されているアイテムのリストが変わった時に発火するコールバック関数 */ onChangeSelected?: (selectedItems: Array<Item<T>>) => void /** * コンポーネントがフォーカスされたときに発火するコールバック関数 */ onFocus?: () => void /** * コンポーネントからフォーカスが外れた時に発火するコールバック関数 */ onBlur?: () => void } type ElementProps<T> = Omit<HTMLAttributes<HTMLDivElement>, keyof Props<T>> export function MultiComboBox<T>({ items, selectedItems, name, disabled = false, error = false, creatable = false, placeholder = '', isLoading, selectedItemEllipsis, width = 'auto', inputValue: controlledInputValue, className = '', onChange, onChangeInput, onAdd, onDelete, onSelect, onChangeSelected, onFocus, onBlur, ...props }: Props<T> & ElementProps<T>) { const theme = useTheme() const classNames = useClassNames().multi const outerRef = useRef<HTMLDivElement>(null) const inputRef = useRef<HTMLInputElement>(null) const [isFocused, setIsFocused] = useState(false) const isInputControlled = useMemo( () => controlledInputValue !== undefined, [controlledInputValue], ) const [uncontrolledInputValue, setUncontrolledInputValue] = useState('') const inputValue = isInputControlled ? controlledInputValue : uncontrolledInputValue const [isComposing, setIsComposing] = useState(false) const selectedLabels = selectedItems.map(({ label }) => label) const filteredItems = items.filter(({ label }) => { if (selectedLabels.includes(label)) return false if (!inputValue) return true return convertMatchableString(label).includes(convertMatchableString(inputValue)) }) const isDuplicate = items.some((item) => item.label === inputValue) const hasSelectableExactMatch = filteredItems.some((item) => item.label === inputValue) const { renderListBox, calculateDropdownRect, resetActiveOptionIndex, handleInputKeyDown, listBoxRef, aria, } = useListBox({ items: filteredItems, inputValue, onAdd, onSelect: (selected) => { onSelect && onSelect(selected) onChangeSelected && onChangeSelected(selectedItems.concat(selected)) }, isExpanded: isFocused, isAddable: creatable && !!inputValue && !isDuplicate, isDuplicate: creatable && !!inputValue && isDuplicate && !hasSelectableExactMatch, hasNoMatch: (!creatable && filteredItems.length === 0) || (creatable && filteredItems.length === 0 && !inputValue), isLoading, classNames: classNames.listBox, }) const focus = useCallback(() => { onFocus && onFocus() setIsFocused(true) resetActiveOptionIndex() }, [onFocus, resetActiveOptionIndex]) const blur = useCallback(() => { if (!isFocused) return onBlur && onBlur() setIsFocused(false) }, [isFocused, onBlur]) const caretIconColor = useMemo(() => { if (isFocused) return theme.color.TEXT_BLACK if (disabled) return theme.color.TEXT_DISABLED return theme.color.TEXT_GREY }, [disabled, isFocused, theme]) useOuterClick( [outerRef, listBoxRef], useCallback(() => { blur() }, [blur]), ) useLayoutEffect(() => { if (!isInputControlled) { setUncontrolledInputValue('') } if (isFocused && inputRef.current) { inputRef.current.focus() } }, [isFocused, isInputControlled, selectedItems]) useLayoutEffect(() => { // ドロップダウン表示時に位置を計算する if (outerRef.current && isFocused) { calculateDropdownRect(outerRef.current) } // 選択済みアイテムによってコンボボックスの高さが変わりうるので selectedItems を依存に含める }, [calculateDropdownRect, isFocused, selectedItems]) return ( <Container {...props} themes={theme} width={width} ref={outerRef} className={`${className} ${classNames.wrapper}`} onClick={(e) => { if ( !hasParentElementByClassName(e.target as HTMLElement, classNames.deleteButton) && !disabled && !isFocused ) { focus() } }} onKeyDown={(e) => { if (e.key === 'Escape' || e.key === 'Esc') { e.stopPropagation() blur() } }} role="combobox" aria-owns={aria.listBoxId} aria-haspopup="listbox" aria-expanded={isFocused} aria-invalid={error || undefined} aria-disabled={disabled} > <InputArea themes={theme}> <List themes={theme}> {selectedItems.map((selectedItem) => ( <li key={selectedItem.label}> <MultiSelectedItem item={selectedItem} disabled={disabled} onDelete={() => { onDelete && onDelete(selectedItem) onChangeSelected && onChangeSelected( selectedItems.filter( (selected) => selected.label !== selectedItem.label || selected.value !== selectedItem.value, ), ) }} enableEllipsis={selectedItemEllipsis} /> </li> ))} <InputWrapper className={isFocused ? undefined : 'hidden'}> <Input type="text" name={name} value={inputValue} disabled={disabled} ref={inputRef} themes={theme} onChange={(e) => { if (onChange) onChange(e) if (onChangeInput) onChangeInput(e) if (!isInputControlled) { setUncontrolledInputValue(e.currentTarget.value) } }} onFocus={() => { if (!isFocused) { focus() } }} onCompositionStart={() => setIsComposing(true)} onCompositionEnd={() => setIsComposing(false)} onKeyDown={(e) => { if (isComposing) { return } if (e.key === 'Tab') { blur() return } handleInputKeyDown(e) }} autoComplete="off" aria-activedescendant={aria.activeDescendant} aria-autocomplete="list" aria-controls={aria.listBoxId} className={classNames.input} /> </InputWrapper> {selectedItems.length === 0 && placeholder && !isFocused && ( <li> <Placeholder themes={theme} className={classNames.placeholder}> {placeholder} </Placeholder> </li> )} </List> </InputArea> <Suffix themes={theme}> <FaCaretDownIcon color={caretIconColor} /> </Suffix> {renderListBox()} </Container> ) } const Container = styled.div<{ themes: Theme; width: number | string }>` ${({ themes, width }) => { const { border, radius, color, shadow, spacingByChar } = themes return css` display: inline-flex; min-width: calc(62px + 32px + ${spacingByChar(0.5)} * 2); width: ${typeof width === 'number' ? `${width}px` : width}; min-height: 40px; border-radius: ${radius.m}; border: ${border.shorthand}; box-sizing: border-box; background-color: ${color.WHITE}; cursor: text; &[aria-expanded='true'] { box-shadow: ${shadow.OUTLINE}; } &[aria-invalid='true'] { border-color: ${color.DANGER}; } &[aria-disabled='true'] { background-color: ${color.COLUMN}; cursor: not-allowed; } ` }} ` const InputArea = styled.div<{ themes: Theme }>` ${({ themes: { spacingByChar } }) => css` flex: 1; overflow-y: auto; max-height: 300px; padding-left: ${spacingByChar(0.5)}; `} ` const smallMargin = 6.5 const borderWidth = 1 const List = styled.ul<{ themes: Theme }>` ${({ themes }) => { const { fontSize: { pxToRem }, spacingByChar, } = themes return css` display: flex; flex-wrap: wrap; margin: ${pxToRem(smallMargin - borderWidth)} 0 0; padding: 0; list-style: none; > li { min-height: 27px; max-width: calc(100% - ${spacingByChar(0.5)}); margin-right: ${spacingByChar(0.5)}; margin-bottom: ${pxToRem(smallMargin - borderWidth)}; } ` }} ` const InputWrapper = styled.li` &.hidden { position: absolute; opacity: 0; pointer-events: none; } flex: 1; ` const Input = styled.input<{ themes: Theme }>` ${({ themes }) => { const { fontSize } = themes return css` min-width: 80px; width: 100%; border: none; font-size: ${fontSize.M}; box-sizing: border-box; outline: none; &[disabled] { display: none; } ` }} ` const Placeholder = styled.p<{ themes: Theme }>` ${({ themes }) => { const { color, fontSize } = themes return css` margin: 0; color: ${color.TEXT_GREY}; font-size: ${fontSize.M}; line-height: 25px; ` }} ` const Suffix = styled.div<{ themes: Theme }>` ${({ themes: { spacingByChar, border } }) => css` display: flex; justify-content: center; align-items: center; margin: ${spacingByChar(0.5)} 0; padding: 0 ${spacingByChar(0.5)}; border-left: ${border.shorthand}; box-sizing: border-box; `} `
the_stack
import { codec } from '@liskhq/lisk-codec'; import { getRandomBytes } from '@liskhq/lisk-cryptography'; import { KVStore, NotFoundError } from '@liskhq/lisk-db'; import { EventEmitter } from 'events'; import * as liskP2P from '@liskhq/lisk-p2p'; import { APP_EVENT_NETWORK_READY, APP_EVENT_NETWORK_EVENT, EVENT_POST_BLOCK, EVENT_POST_NODE_INFO, EVENT_POST_TRANSACTION_ANNOUNCEMENT, } from '../../constants'; import { InMemoryChannel } from '../../controller/channels'; import { lookupPeersIPs } from './utils'; import { Logger } from '../../logger'; import { NetworkConfig } from '../../types'; import { customNodeInfoSchema } from './schema'; const { P2P, events: { EVENT_NETWORK_READY, EVENT_NEW_INBOUND_PEER, EVENT_CLOSE_INBOUND, EVENT_CLOSE_OUTBOUND, EVENT_CONNECT_OUTBOUND, EVENT_DISCOVERED_PEER, EVENT_FAILED_TO_FETCH_PEER_INFO, EVENT_FAILED_TO_PUSH_NODE_INFO, EVENT_OUTBOUND_SOCKET_ERROR, EVENT_INBOUND_SOCKET_ERROR, EVENT_UPDATED_PEER_INFO, EVENT_FAILED_PEER_INFO_UPDATE, EVENT_REQUEST_RECEIVED, EVENT_MESSAGE_RECEIVED, EVENT_BAN_PEER, }, } = liskP2P; const DB_KEY_NETWORK_NODE_SECRET = 'network:nodeSecret'; const DB_KEY_NETWORK_TRIED_PEERS_LIST = 'network:triedPeersList'; const DEFAULT_PEER_SAVE_INTERVAL = 10 * 60 * 1000; // 10min in ms const REMOTE_EVENTS_WHITE_LIST = [ EVENT_POST_BLOCK, EVENT_POST_NODE_INFO, EVENT_POST_TRANSACTION_ANNOUNCEMENT, ]; interface NodeInfoOptions { [key: string]: unknown; readonly lastBlockID: Buffer; readonly height: number; readonly maxHeightPrevoted: number; readonly blockVersion: number; } interface NetworkConstructor { readonly options: NetworkConfig; readonly channel: InMemoryChannel; readonly logger: Logger; readonly nodeDB: KVStore; readonly networkVersion: string; } interface P2PRequestPacket extends liskP2P.p2pTypes.P2PRequestPacket { readonly peerId: string; } interface P2PMessagePacket extends liskP2P.p2pTypes.P2PMessagePacket { readonly peerId: string; } interface P2PRequest { readonly procedure: string; readonly wasResponseSent: boolean; readonly data: object; readonly peerId: string; readonly end: (result: object) => void; readonly error: (result: object) => void; } type P2PRPCEndpointHandler = (input: { data: unknown; peerId: string }) => unknown; interface P2PRPCEndpoints { [key: string]: P2PRPCEndpointHandler; } export class Network { public readonly events: EventEmitter; private readonly _options: NetworkConfig; private readonly _channel: InMemoryChannel; private readonly _logger: Logger; private readonly _nodeDB: KVStore; private readonly _networkVersion: string; private _networkID!: string; private _secret: number | undefined; private _p2p!: liskP2P.P2P; private _endpoints: P2PRPCEndpoints; public constructor({ options, channel, logger, nodeDB, networkVersion }: NetworkConstructor) { this._options = options; this._channel = channel; this._logger = logger; this._nodeDB = nodeDB; this._networkVersion = networkVersion; this._endpoints = {}; this._secret = undefined; this.events = new EventEmitter(); } public async bootstrap(networkIdentifier: Buffer): Promise<void> { this._networkID = networkIdentifier.toString('hex'); let previousPeers: ReadonlyArray<liskP2P.p2pTypes.ProtocolPeerInfo> = []; try { // Load peers from the database that were tried or connected the last time node was running const previousPeersBuffer = await this._nodeDB.get(DB_KEY_NETWORK_TRIED_PEERS_LIST); // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment previousPeers = JSON.parse(previousPeersBuffer.toString('utf8')); } catch (error) { if (!(error instanceof NotFoundError)) { this._logger.error({ err: error as Error }, 'Error while querying nodeDB'); } } // Get previous secret if exists let secret: Buffer | undefined; try { secret = await this._nodeDB.get(DB_KEY_NETWORK_NODE_SECRET); } catch (error) { if (!(error instanceof NotFoundError)) { this._logger.error({ err: error as Error }, 'Error while querying nodeDB'); } } if (!secret) { secret = getRandomBytes(4); await this._nodeDB.put(DB_KEY_NETWORK_NODE_SECRET, secret); } this._secret = secret?.readUInt32BE(0); const initialNodeInfo = { networkIdentifier: this._networkID, networkVersion: this._networkVersion, // Nonce is required in type, but it is overwritten nonce: '', advertiseAddress: this._options.advertiseAddress ?? true, options: { lastBlockID: Buffer.alloc(0), blockVersion: 0, height: 0, maxHeightPrevoted: 0, }, }; const seedPeers = await lookupPeersIPs(this._options.seedPeers, true); // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition const blacklistedIPs = this._options.blacklistedIPs ?? []; // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition const fixedPeers = this._options.fixedPeers ? this._options.fixedPeers.map(peer => ({ ipAddress: peer.ip, port: peer.port, })) : []; // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition const whitelistedPeers = this._options.whitelistedPeers ? this._options.whitelistedPeers.map(peer => ({ ipAddress: peer.ip, port: peer.port, })) : []; const p2pConfig: liskP2P.p2pTypes.P2PConfig = { port: this._options.port, nodeInfo: initialNodeInfo, hostIp: this._options.hostIp, blacklistedIPs, fixedPeers, whitelistedPeers, seedPeers: seedPeers.map(peer => ({ ipAddress: peer.ip, port: peer.port, })), previousPeers, maxOutboundConnections: this._options.maxOutboundConnections, maxInboundConnections: this._options.maxInboundConnections, peerBanTime: this._options.peerBanTime, sendPeerLimit: this._options.sendPeerLimit, maxPeerDiscoveryResponseLength: this._options.maxPeerDiscoveryResponseLength, maxPeerInfoSize: this._options.maxPeerInfoSize, wsMaxPayload: this._options.wsMaxPayload, secret: this._secret, customNodeInfoSchema, }; this._p2p = new P2P(p2pConfig); // ---- START: Bind event handlers ---- this._p2p.on(EVENT_NETWORK_READY, () => { this._logger.debug('Node connected to the network'); this.events.emit(APP_EVENT_NETWORK_READY); this._channel.publish(APP_EVENT_NETWORK_READY); }); this._p2p.on( EVENT_CLOSE_OUTBOUND, ({ peerInfo, code, reason }: liskP2P.p2pTypes.P2PClosePacket) => { this._logger.debug( { ...peerInfo, code, reason, }, 'EVENT_CLOSE_OUTBOUND: Close outbound peer connection', ); }, ); this._p2p.on( EVENT_CLOSE_INBOUND, ({ peerInfo, code, reason }: liskP2P.p2pTypes.P2PClosePacket) => { this._logger.debug( { ...peerInfo, code, reason, }, 'EVENT_CLOSE_INBOUND: Close inbound peer connection', ); }, ); this._p2p.on(EVENT_CONNECT_OUTBOUND, peerInfo => { this._logger.debug( { ...peerInfo, }, 'EVENT_CONNECT_OUTBOUND: Outbound peer connection', ); }); this._p2p.on(EVENT_DISCOVERED_PEER, peerInfo => { this._logger.trace( { ...peerInfo, }, 'EVENT_DISCOVERED_PEER: Discovered peer connection', ); }); this._p2p.on(EVENT_NEW_INBOUND_PEER, peerInfo => { this._logger.debug( { ...peerInfo, }, 'EVENT_NEW_INBOUND_PEER: Inbound peer connection', ); }); this._p2p.on(EVENT_FAILED_TO_FETCH_PEER_INFO, (error: Error) => { this._logger.error( { err: error }, 'EVENT_FAILED_TO_FETCH_PEER_INFO: Failed to fetch peer info', ); }); this._p2p.on(EVENT_FAILED_TO_PUSH_NODE_INFO, (error: Error) => { this._logger.trace( { err: error }, 'EVENT_FAILED_TO_PUSH_NODE_INFO: Failed to push node info', ); }); this._p2p.on(EVENT_OUTBOUND_SOCKET_ERROR, (error: Error) => { this._logger.debug({ err: error }, 'EVENT_OUTBOUND_SOCKET_ERROR: Outbound socket error'); }); this._p2p.on(EVENT_INBOUND_SOCKET_ERROR, (error: Error) => { this._logger.debug({ err: error }, 'EVENT_INBOUND_SOCKET_ERROR: Inbound socket error'); }); this._p2p.on(EVENT_UPDATED_PEER_INFO, peerInfo => { this._logger.trace( { ...peerInfo, }, 'EVENT_UPDATED_PEER_INFO: Update peer info', ); }); this._p2p.on(EVENT_FAILED_PEER_INFO_UPDATE, (error: Error) => { this._logger.error({ err: error }, 'EVENT_FAILED_PEER_INFO_UPDATE: Failed peer update'); }); // eslint-disable-next-line @typescript-eslint/no-misused-promises this._p2p.on(EVENT_REQUEST_RECEIVED, async (request: P2PRequest) => { this._logger.trace( { procedure: request.procedure }, 'EVENT_REQUEST_RECEIVED: Received inbound request for procedure', ); // If the request has already been handled internally by the P2P library, we ignore. if (request.wasResponseSent) { return; } if (!Object.keys(this._endpoints).includes(request.procedure)) { const error = new Error(`Requested procedure "${request.procedure}" is not permitted.`); this._logger.error( { err: error, procedure: request.procedure }, 'Peer request not fulfilled event: Requested procedure is not permitted.', ); // Ban peer on if non-permitted procedure is requested this._p2p.applyPenalty({ peerId: request.peerId, penalty: 100 }); // Send an error back to the peer. request.error(error); return; } try { const result = await this._endpoints[request.procedure]({ data: request.data, peerId: request.peerId, }); this._logger.trace( { procedure: request.procedure }, 'Peer request fulfilled event: Responded to peer request', ); request.end(result as object); // Send the response back to the peer. } catch (error) { this._logger.error( { err: error as Error, procedure: request.procedure }, 'Peer request not fulfilled event: Could not respond to peer request', ); request.error(error); // Send an error back to the peer. } }); this._p2p.on( EVENT_MESSAGE_RECEIVED, (packet: { readonly peerId: string; readonly event: string; readonly data: Buffer | undefined; }) => { if (!REMOTE_EVENTS_WHITE_LIST.includes(packet.event)) { const error = new Error(`Sent event "${packet.event}" is not permitted.`); this._logger.error( { err: error, event: packet.event }, 'Peer request not fulfilled. Sent event is not permitted.', ); // Ban peer on if non-permitted procedure is requested this._p2p.applyPenalty({ peerId: packet.peerId, penalty: 100 }); return; } this._logger.trace( { peerId: packet.peerId, event: packet.event, }, 'EVENT_MESSAGE_RECEIVED: Received inbound message', ); this.events.emit(APP_EVENT_NETWORK_EVENT, packet); }, ); this._p2p.on(EVENT_BAN_PEER, (peerId: string) => { this._logger.error({ peerId }, 'EVENT_MESSAGE_RECEIVED: Peer has been banned temporarily'); }); // eslint-disable-next-line @typescript-eslint/no-misused-promises setInterval(async () => { const triedPeers = this._p2p.getTriedPeers(); if (triedPeers.length) { await this._nodeDB.put( DB_KEY_NETWORK_TRIED_PEERS_LIST, Buffer.from(JSON.stringify(triedPeers), 'utf8'), ); } }, DEFAULT_PEER_SAVE_INTERVAL); // ---- END: Bind event handlers ---- try { await this._p2p.start(); } catch (error) { this._logger.fatal( { message: (error as Error).message, stack: (error as Error).stack, }, 'Failed to initialize network', ); throw error; } } public registerEndpoint(endpoint: string, handler: P2PRPCEndpointHandler): void { if (this._endpoints[endpoint]) { throw new Error(`Endpoint ${endpoint} has already been registered.`); } this._endpoints[endpoint] = handler; } public async request( requestPacket: liskP2P.p2pTypes.P2PRequestPacket, ): Promise<liskP2P.p2pTypes.P2PResponsePacket> { return this._p2p.request({ procedure: requestPacket.procedure, data: requestPacket.data, }); } public send(sendPacket: liskP2P.p2pTypes.P2PMessagePacket): void { return this._p2p.send({ event: sendPacket.event, data: sendPacket.data, }); } public async requestFromPeer( requestPacket: P2PRequestPacket, ): Promise<liskP2P.p2pTypes.P2PResponsePacket> { return this._p2p.requestFromPeer( { procedure: requestPacket.procedure, data: requestPacket.data, }, requestPacket.peerId, ); } public sendToPeer(sendPacket: P2PMessagePacket): void { return this._p2p.sendToPeer( { event: sendPacket.event, data: sendPacket.data, }, sendPacket.peerId, ); } public broadcast(broadcastPacket: liskP2P.p2pTypes.P2PMessagePacket): void { return this._p2p.broadcast({ event: broadcastPacket.event, data: broadcastPacket.data, }); } public getConnectedPeers(): ReadonlyArray<liskP2P.p2pTypes.PeerInfo> { const peers = this._p2p.getConnectedPeers(); return peers.map(peer => { const parsedPeer = { ...peer, }; if (parsedPeer.options) { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment parsedPeer.options = codec.toJSON(customNodeInfoSchema, parsedPeer.options); } return parsedPeer; }); } public getNetworkStats(): liskP2P.p2pTypes.NetworkStats { return this._p2p.getNetworkStats(); } public getDisconnectedPeers(): ReadonlyArray<liskP2P.p2pTypes.PeerInfo> { const peers = this._p2p.getDisconnectedPeers(); return peers.map(peer => { const parsedPeer = { ...peer, }; if (parsedPeer.options) { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment parsedPeer.options = codec.toJSON(customNodeInfoSchema, parsedPeer.options); } return parsedPeer; }); } public applyPenaltyOnPeer(penaltyPacket: liskP2P.p2pTypes.P2PPenalty): void { return this._p2p.applyPenalty({ peerId: penaltyPacket.peerId, penalty: penaltyPacket.penalty, }); } public applyNodeInfo(data: NodeInfoOptions): void { const newNodeInfo = { networkIdentifier: this._networkID, networkVersion: this._networkVersion, advertiseAddress: this._options.advertiseAddress ?? true, options: data, }; try { this._p2p.applyNodeInfo(newNodeInfo); } catch (error) { this._logger.error({ err: error as Error }, 'Applying NodeInfo failed because of error'); } } public async cleanup(): Promise<void> { this._logger.info('Network cleanup started'); await this._p2p.stop(); this._logger.info('Network cleanup completed'); } }
the_stack
import { HttpClientTestingModule, HttpTestingController, } from '@angular/common/http/testing'; import { Type } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { BaseOccUrlProperties, CartModification, ConverterService, DynamicAttributes, OccEndpointsService, TranslationService, } from '@spartacus/core'; import { CommonConfigurator, CommonConfiguratorUtilsService, ConfiguratorModelUtils, ConfiguratorType, } from '@spartacus/product-configurator/common'; import { CART_MODIFICATION_NORMALIZER } from 'projects/core/src/cart'; import { of } from 'rxjs'; import { VARIANT_CONFIGURATOR_PRICE_NORMALIZER, VariantConfiguratorOccAdapter, } from '.'; import { Configurator } from '../../core/model/configurator.model'; import { ConfiguratorTestUtils } from '../../testing/configurator-test-utils'; import { OccConfiguratorTestUtils } from '../../testing/occ-configurator-test-utils'; import { OccConfiguratorVariantNormalizer } from './converters/occ-configurator-variant-normalizer'; import { OccConfiguratorVariantOverviewNormalizer } from './converters/occ-configurator-variant-overview-normalizer'; import { VARIANT_CONFIGURATOR_NORMALIZER, VARIANT_CONFIGURATOR_OVERVIEW_NORMALIZER, VARIANT_CONFIGURATOR_SERIALIZER, } from './variant-configurator-occ.converters'; import { OccConfigurator } from './variant-configurator-occ.models'; import { OccConfiguratorVariantPriceNormalizer } from './converters/occ-configurator-variant-price-normalizer'; class MockOccEndpointsService { buildUrl( endpoint: string, _attributes?: DynamicAttributes, _propertiesToOmit?: BaseOccUrlProperties ) { return this.getEndpoint(endpoint); } getEndpoint(url: string) { return url; } } class MockTranslationService { translate(text: string) { return text; } } const productCode = 'CONF_LAPTOP'; const cartEntryNo = '1'; const configId = '1234-56-7890'; const groupId = 'GROUP1'; const documentEntryNumber = '3'; const userId = 'Anony'; const documentId = '82736353'; //const mockProductConfiguration: Configurator.Configuration = productConfiguration; const configuration: Configurator.Configuration = { ...ConfiguratorTestUtils.createConfiguration( configId, ConfiguratorModelUtils.createOwner( CommonConfigurator.OwnerType.PRODUCT, productCode ) ), productCode: productCode, }; const productConfigurationOcc: OccConfigurator.Configuration = { configId: configId, }; const pricesOcc: OccConfigurator.Prices = OccConfiguratorTestUtils.createOccConfiguratorPrices(false, 1, 0, 3, 3); const productConfigurationForCartEntry: Configurator.Configuration = { ...ConfiguratorTestUtils.createConfiguration( configId, ConfiguratorModelUtils.createOwner( CommonConfigurator.OwnerType.CART_ENTRY, cartEntryNo ) ), productCode: productCode, }; const overviewOcc: OccConfigurator.Overview = { id: configId }; const cartModification: CartModification = { quantity: 1 }; describe('OccConfigurationVariantAdapter', () => { let occConfiguratorVariantAdapter: VariantConfiguratorOccAdapter; let httpMock: HttpTestingController; let converterService: ConverterService; let occEndpointsService: OccEndpointsService; let configuratorUtils: CommonConfiguratorUtilsService; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ VariantConfiguratorOccAdapter, { provide: OccEndpointsService, useClass: MockOccEndpointsService }, { provide: TranslationService, useClass: MockTranslationService }, { provide: VARIANT_CONFIGURATOR_NORMALIZER, useExisting: OccConfiguratorVariantNormalizer, multi: true, }, { provide: VARIANT_CONFIGURATOR_OVERVIEW_NORMALIZER, useExisting: OccConfiguratorVariantOverviewNormalizer, multi: true, }, { provide: VARIANT_CONFIGURATOR_PRICE_NORMALIZER, useExisting: OccConfiguratorVariantPriceNormalizer, multi: true, }, ], }); httpMock = TestBed.inject( HttpTestingController as Type<HttpTestingController> ); converterService = TestBed.inject( ConverterService as Type<ConverterService> ); occEndpointsService = TestBed.inject( OccEndpointsService as Type<OccEndpointsService> ); occConfiguratorVariantAdapter = TestBed.inject( VariantConfiguratorOccAdapter as Type<VariantConfiguratorOccAdapter> ); configuratorUtils = TestBed.inject( CommonConfiguratorUtilsService as Type<CommonConfiguratorUtilsService> ); configuratorUtils.setOwnerKey(configuration.owner); spyOn(converterService, 'convert').and.callThrough(); spyOn(occEndpointsService, 'buildUrl').and.callThrough(); }); afterEach(() => { httpMock.verify(); }); it('should call createConfiguration endpoint', (done) => { spyOn(converterService, 'pipeable').and.callThrough(); occConfiguratorVariantAdapter .createConfiguration(configuration.owner) .subscribe((resultConfiguration) => { expect(resultConfiguration.configId).toEqual(configId); done(); }); //this call doesn't do the actual mapping but retrieves the map function, //therefore expectation is valid here outside the subscribe expect(converterService.pipeable).toHaveBeenCalledWith( VARIANT_CONFIGURATOR_NORMALIZER ); const mockReq = httpMock.expectOne((req) => { return req.method === 'GET' && req.url === 'createVariantConfiguration'; }); expect(occEndpointsService.buildUrl).toHaveBeenCalledWith( 'createVariantConfiguration', { urlParams: { productCode, }, } ); expect(mockReq.cancelled).toBeFalsy(); expect(mockReq.request.responseType).toEqual('json'); mockReq.flush(productConfigurationOcc); }); it('should call readConfiguration endpoint', (done) => { spyOn(converterService, 'pipeable').and.callThrough(); occConfiguratorVariantAdapter .readConfiguration(configId, groupId, configuration.owner) .subscribe((resultConfiguration) => { expect(resultConfiguration.configId).toEqual(configId); done(); }); const mockReq = httpMock.expectOne((req) => { return req.method === 'GET' && req.url === 'readVariantConfiguration'; }); expect(occEndpointsService.buildUrl).toHaveBeenCalledWith( 'readVariantConfiguration', { urlParams: { configId }, queryParams: { groupId }, } ); expect(mockReq.cancelled).toBeFalsy(); expect(mockReq.request.responseType).toEqual('json'); expect(converterService.pipeable).toHaveBeenCalledWith( VARIANT_CONFIGURATOR_NORMALIZER ); mockReq.flush(productConfigurationOcc); }); it('should call updateConfiguration endpoint', (done) => { spyOn(converterService, 'pipeable').and.callThrough(); occConfiguratorVariantAdapter .updateConfiguration(configuration) .subscribe((resultConfiguration) => { expect(resultConfiguration.configId).toEqual(configId); done(); }); const mockReq = httpMock.expectOne((req) => { return req.method === 'PATCH' && req.url === 'updateVariantConfiguration'; }); expect(occEndpointsService.buildUrl).toHaveBeenCalledWith( 'updateVariantConfiguration', { urlParams: { configId, }, } ); expect(mockReq.cancelled).toBeFalsy(); expect(mockReq.request.responseType).toEqual('json'); expect(converterService.pipeable).toHaveBeenCalledWith( VARIANT_CONFIGURATOR_NORMALIZER ); expect(converterService.convert).toHaveBeenCalledWith( configuration, VARIANT_CONFIGURATOR_SERIALIZER ); mockReq.flush(productConfigurationOcc); }); it('should call readPriceSummary endpoint', (done) => { spyOn(converterService, 'pipeable').and.callThrough(); occConfiguratorVariantAdapter .readPriceSummary(configuration) .subscribe((resultConfiguration) => { expect(resultConfiguration.priceSummary?.basePrice?.currencyIso).toBe( pricesOcc.priceSummary?.basePrice?.currencyIso ); expect(resultConfiguration.priceSupplements.length).toBe(3); expect(resultConfiguration.priceSupplements[0].attributeUiKey).toBe( 'group1@attribute_1_1' ); expect( resultConfiguration.priceSupplements[0].valueSupplements.length ).toBe(3); expect( resultConfiguration.priceSupplements[0].valueSupplements[0] .attributeValueKey ).toBe('value_1_1'); expect( resultConfiguration.priceSupplements[0].valueSupplements[1] .attributeValueKey ).toBe('value_1_2'); expect( resultConfiguration.priceSupplements[0].valueSupplements[2] .attributeValueKey ).toBe('value_1_3'); expect(resultConfiguration.priceSupplements[1].attributeUiKey).toBe( 'group1@attribute_1_2' ); expect( resultConfiguration.priceSupplements[1].valueSupplements.length ).toBe(3); expect( resultConfiguration.priceSupplements[1].valueSupplements[0] .attributeValueKey ).toBe('value_2_1'); expect( resultConfiguration.priceSupplements[1].valueSupplements[1] .attributeValueKey ).toBe('value_2_2'); expect( resultConfiguration.priceSupplements[1].valueSupplements[2] .attributeValueKey ).toBe('value_2_3'); expect(resultConfiguration.priceSupplements[2].attributeUiKey).toBe( 'group1@attribute_1_3' ); expect( resultConfiguration.priceSupplements[2].valueSupplements.length ).toBe(3); expect( resultConfiguration.priceSupplements[2].valueSupplements[0] .attributeValueKey ).toBe('value_3_1'); expect( resultConfiguration.priceSupplements[2].valueSupplements[1] .attributeValueKey ).toBe('value_3_2'); expect( resultConfiguration.priceSupplements[2].valueSupplements[2] .attributeValueKey ).toBe('value_3_3'); done(); }); const mockReq = httpMock.expectOne((req) => { return ( req.method === 'GET' && req.url === 'readVariantConfigurationPriceSummary' ); }); expect(occEndpointsService.buildUrl).toHaveBeenCalledWith( 'readVariantConfigurationPriceSummary', { urlParams: { configId, }, queryParams: { groupId: configuration?.interactionState?.currentGroup }, } ); expect(mockReq.cancelled).toBeFalsy(); expect(mockReq.request.responseType).toEqual('json'); expect(converterService.pipeable).toHaveBeenCalledWith( VARIANT_CONFIGURATOR_PRICE_NORMALIZER ); mockReq.flush(pricesOcc); }); it('should call readConfigurationForCartEntry endpoint', (done) => { spyOn(converterService, 'pipeable').and.callThrough(); const params: CommonConfigurator.ReadConfigurationFromCartEntryParameters = { owner: configuration.owner, userId: userId, cartId: documentId, cartEntryNumber: documentEntryNumber, }; occConfiguratorVariantAdapter .readConfigurationForCartEntry(params) .subscribe((resultConfiguration) => { expect(resultConfiguration.configId).toEqual(configId); done(); }); const mockReq = httpMock.expectOne((req) => { return ( req.method === 'GET' && req.url === 'readVariantConfigurationForCartEntry' ); }); expect(occEndpointsService.buildUrl).toHaveBeenCalledWith( 'readVariantConfigurationForCartEntry', { urlParams: { userId, cartId: documentId, cartEntryNumber: documentEntryNumber, }, } ); expect(mockReq.cancelled).toBeFalsy(); expect(mockReq.request.responseType).toEqual('json'); expect(converterService.pipeable).toHaveBeenCalledWith( VARIANT_CONFIGURATOR_NORMALIZER ); mockReq.flush(productConfigurationOcc); }); it('should call readVariantConfigurationOverviewForOrderEntry endpoint', (done) => { spyOn(converterService, 'pipeable').and.callThrough(); const params: CommonConfigurator.ReadConfigurationFromOrderEntryParameters = { owner: configuration.owner, userId: userId, orderId: documentId, orderEntryNumber: documentEntryNumber, }; occConfiguratorVariantAdapter .readConfigurationForOrderEntry(params) .subscribe((resultConfiguration) => { expect(resultConfiguration.configId).toEqual(configId); done(); }); const mockReq = httpMock.expectOne((req) => { return ( req.method === 'GET' && req.url === 'readVariantConfigurationOverviewForOrderEntry' ); }); expect(occEndpointsService.buildUrl).toHaveBeenCalledWith( 'readVariantConfigurationOverviewForOrderEntry', { urlParams: { userId, orderId: documentId, orderEntryNumber: documentEntryNumber, }, } ); expect(mockReq.cancelled).toBeFalsy(); expect(mockReq.request.responseType).toEqual('json'); expect(converterService.pipeable).toHaveBeenCalledWith( VARIANT_CONFIGURATOR_OVERVIEW_NORMALIZER ); mockReq.flush(overviewOcc); }); it('should call updateVariantConfigurationForCartEntry endpoint', (done) => { spyOn(converterService, 'pipeable').and.callThrough(); const params: Configurator.UpdateConfigurationForCartEntryParameters = { configuration: configuration, userId: userId, cartId: documentId, cartEntryNumber: documentEntryNumber, }; occConfiguratorVariantAdapter .updateConfigurationForCartEntry(params) .subscribe((cartModificationResult) => { expect(cartModificationResult.quantity).toEqual( cartModification.quantity ); done(); }); const mockReq = httpMock.expectOne((req) => { return ( req.method === 'PUT' && req.url === 'updateVariantConfigurationForCartEntry' ); }); expect(occEndpointsService.buildUrl).toHaveBeenCalledWith( 'updateVariantConfigurationForCartEntry', { urlParams: { userId, cartId: documentId, cartEntryNumber: documentEntryNumber, }, } ); expect(mockReq.cancelled).toBeFalsy(); expect(mockReq.request.responseType).toEqual('json'); expect(converterService.pipeable).toHaveBeenCalledWith( CART_MODIFICATION_NORMALIZER ); mockReq.flush(cartModification); }); it('should call addToCart endpoint', (done) => { spyOn(converterService, 'pipeable').and.callThrough(); const params: Configurator.AddToCartParameters = { productCode: 'Product', quantity: 1, configId: configId, owner: configuration.owner, userId: userId, cartId: documentId, }; occConfiguratorVariantAdapter .addToCart(params) .subscribe((cartModificationResult) => { expect(cartModificationResult.quantity).toEqual( cartModification.quantity ); done(); }); const mockReq = httpMock.expectOne((req) => { return ( req.method === 'POST' && req.url === 'addVariantConfigurationToCart' ); }); expect(mockReq.cancelled).toBeFalsy(); expect(mockReq.request.responseType).toEqual('json'); expect(converterService.pipeable).toHaveBeenCalledWith( CART_MODIFICATION_NORMALIZER ); mockReq.flush(cartModification); }); it('should set owner on readVariantConfigurationForCartEntry according to parameters', (done) => { const params: CommonConfigurator.ReadConfigurationFromCartEntryParameters = { owner: productConfigurationForCartEntry.owner, userId: userId, cartId: documentId, cartEntryNumber: documentEntryNumber, }; spyOn(converterService, 'pipeable').and.returnValue(() => of(configuration) ); occConfiguratorVariantAdapter .readConfigurationForCartEntry(params) .subscribe((result) => { const owner = result.owner; expect(owner).toBeDefined(); expect(owner.type).toBe(CommonConfigurator.OwnerType.CART_ENTRY); expect(owner.id).toBe(cartEntryNo); done(); }); }); it('should call getVariantConfigurationOverview endpoint', (done) => { spyOn(converterService, 'pipeable').and.callThrough(); occConfiguratorVariantAdapter .getConfigurationOverview(configuration.configId) .subscribe((productConfigurationResult) => { expect(productConfigurationResult.configId).toBe(configId); done(); }); const mockReq = httpMock.expectOne((req) => { return ( req.method === 'GET' && req.url === 'getVariantConfigurationOverview' ); }); expect(occEndpointsService.buildUrl).toHaveBeenCalledWith( 'getVariantConfigurationOverview', { urlParams: { configId, }, } ); expect(mockReq.cancelled).toBeFalsy(); expect(mockReq.request.responseType).toEqual('json'); expect(converterService.pipeable).toHaveBeenCalledWith( VARIANT_CONFIGURATOR_OVERVIEW_NORMALIZER ); mockReq.flush(overviewOcc); }); it('should return configurator type', () => { expect(occConfiguratorVariantAdapter.getConfiguratorType()).toEqual( ConfiguratorType.VARIANT ); }); });
the_stack
import debounce from 'lodash/debounce'; import {ChunkManager} from 'neuroglancer/chunk_manager/frontend'; import {CredentialsProvider, makeCredentialsGetter} from 'neuroglancer/credentials_provider'; import {fetchWithCredentials} from 'neuroglancer/credentials_provider/http_request'; import {CompleteUrlOptions, CompletionResult, DataSource, DataSourceProvider, DataSubsourceEntry, GetDataSourceOptions} from 'neuroglancer/datasource'; import {Credentials, NggraphCredentialsProvider} from 'neuroglancer/datasource/nggraph/credentials_provider'; import {VisibleSegmentsState} from 'neuroglancer/segmentation_display_state/base'; import {ComputedSplit, isBaseSegmentId, SegmentationGraphSource, SegmentationGraphSourceConnection, UNKNOWN_NEW_SEGMENT_ID} from 'neuroglancer/segmentation_graph/source'; import {StatusMessage} from 'neuroglancer/status'; import {Uint64Set} from 'neuroglancer/uint64_set'; import {CancellationToken, uncancelableToken} from 'neuroglancer/util/cancellation'; import {getPrefixMatchesWithDescriptions} from 'neuroglancer/util/completion'; import {DisjointUint64Sets} from 'neuroglancer/util/disjoint_sets'; import {responseJson} from 'neuroglancer/util/http_request'; import {parseArray, verifyFiniteFloat, verifyInt, verifyObject, verifyObjectProperty, verifyString, verifyStringArray} from 'neuroglancer/util/json'; import {Uint64} from 'neuroglancer/util/uint64'; const urlPattern = '^(https?://[^/]+)/(.*)$'; interface GraphSegmentInfo { id: Uint64; baseSegments: Uint64[]; baseSegmentParents: Uint64[]; name: string, tags: string[], numVoxels: number, bounds: number[], lastLogId: Uint64|null, } function parseGraphSegmentInfo(obj: any): GraphSegmentInfo { verifyObject(obj); return { id: verifyObjectProperty(obj, 'id', x => Uint64.parseString(verifyString(x))), baseSegments: verifyObjectProperty( obj, 'base_segment_ids', x => parseArray(x, y => Uint64.parseString(verifyString(y)))), baseSegmentParents: verifyObjectProperty( obj, 'base_segment_parent_ids', x => parseArray(x, y => Uint64.parseString(verifyString(y)))), name: verifyObjectProperty(obj, 'name', verifyString), tags: verifyObjectProperty(obj, 'tags', verifyStringArray), numVoxels: verifyObjectProperty(obj, 'num_voxels', verifyInt), bounds: verifyObjectProperty(obj, 'bounds', x => parseArray(x, y => verifyFiniteFloat(y))), lastLogId: verifyObjectProperty( obj, 'last_log_id', x => x == null ? null : Uint64.parseString(verifyString(x))), }; } /// Base-10 string representation of a segment id, used as map key. type SegmentIdString = string; interface ActiveSegmentQuery { id: Uint64; current: GraphSegmentInfo|undefined; addedEquivalences: boolean; seenGeneration: number; disposer: () => void; } type GraphSegmentUpdate = GraphSegmentInfo|'invalid'|'error'; // Generation used for checking if segments have been seen. let updateGeneration = 0; class GraphConnection extends SegmentationGraphSourceConnection { graph: NggraphSegmentationGraphSource; constructor(graph: NggraphSegmentationGraphSource, segmentsState: VisibleSegmentsState) { super(graph, segmentsState); const visibleSegmentsChanged = () => { if (!this.ignoreVisibleSegmentsChanged) { this.debouncedVisibleSegmentsChanged(); } }; this.registerDisposer(segmentsState.visibleSegments.changed.add(visibleSegmentsChanged)); this.registerDisposer( segmentsState.temporaryVisibleSegments.changed.add(visibleSegmentsChanged)); this.visibleSegmentsChanged(); } computeSplit(include: Uint64, exclude: Uint64): ComputedSplit|undefined { const {segmentEquivalences} = this.segmentsState; const graphSegment = segmentEquivalences.get(include); if (isBaseSegmentId(graphSegment)) return undefined; if (!Uint64.equal(segmentEquivalences.get(exclude), graphSegment)) return undefined; const query = this.segmentQueries.get(graphSegment.toString()); if (query === undefined) return undefined; const {current} = query; if (current === undefined) return undefined; const {baseSegments, baseSegmentParents} = current; let length = baseSegmentParents.length; const ds = new DisjointUint64Sets(); for (let i = 0; i < length; ++i) { let baseSegment = baseSegments[i]; let parent = baseSegmentParents[i]; if (Uint64.equal(baseSegment, exclude) || Uint64.equal(parent, exclude)) continue; ds.link(baseSegment, parent); console.log(`Linking ${baseSegment} - ${parent} == ${include}? ${ Uint64.equal( include, baseSegment)} ${Uint64.equal(include, parent)} :: unioned with include = ${ Uint64.equal( include, ds.get(baseSegment))}, with exclude = ${Uint64.equal(exclude, ds.get(baseSegment))}`); } const includeSegments: Uint64[] = []; const excludeSegments: Uint64[] = []; const includeRep = ds.get(include); for (const segment of baseSegments) { if (Uint64.equal(ds.get(segment), includeRep)) { includeSegments.push(segment); } else { excludeSegments.push(segment); } } console.log('include = ' + includeSegments.map(x => x.toString()).join(',')); console.log('exclude = ' + excludeSegments.map(x => x.toString()).join(',')); return { includeRepresentative: graphSegment, includeBaseSegments: includeSegments, excludeRepresentative: UNKNOWN_NEW_SEGMENT_ID, excludeBaseSegments: excludeSegments }; } private debouncedVisibleSegmentsChanged = this.registerCancellable(debounce(() => this.visibleSegmentsChanged(), 0)); private segmentQueries = new Map<SegmentIdString, ActiveSegmentQuery>(); private ignoreVisibleSegmentsChanged = false; private segmentEquivalencesChanged = this.registerCancellable(debounce(() => { this.debouncedVisibleSegmentsChanged.flush(); this.segmentEquivalencesChanged.cancel(); const {segmentQueries} = this; const {segmentEquivalences} = this.segmentsState; segmentEquivalences.clear(); for (const [segmentIdString, query] of segmentQueries) { segmentIdString; if (query.current === undefined || isBaseSegmentId(query.id)) continue; const {id, baseSegments} = query.current; if (baseSegments.length > 0) { for (const segmentId of baseSegments) { segmentEquivalences.link(segmentId, id); } query.addedEquivalences = true; } else { query.addedEquivalences = false; } } }, 0)); private registerVisibleSegment(segmentId: Uint64) { const query: ActiveSegmentQuery = { id: segmentId, current: undefined, addedEquivalences: false, seenGeneration: updateGeneration, disposer: this.graph.watchSegment( segmentId, info => this.handleSegmentUpdate(query.id.toString(), info)), }; const segmentIdString = segmentId.toString(); this.segmentQueries.set(segmentIdString, query); console.log(`adding to segmentQueries: ${segmentIdString}`); } private handleSegmentUpdate(segmentIdString: SegmentIdString, update: GraphSegmentUpdate) { console.log(`handleSegmentUpdate: ${segmentIdString}`); const query = this.segmentQueries.get(segmentIdString)!; if (update === 'invalid') { query.disposer(); console.log(`removing from segmentQueries: ${segmentIdString} due to invalid`); this.segmentQueries.delete(segmentIdString); try { this.ignoreVisibleSegmentsChanged = true; this.segmentsState.visibleSegments.delete(query.id); this.segmentsState.temporaryVisibleSegments.delete(query.id); } finally { this.ignoreVisibleSegmentsChanged = false; } if (query.addedEquivalences) { this.segmentEquivalencesChanged(); } return; } if (update === 'error') { query.current = undefined; if (query.addedEquivalences) { this.segmentEquivalencesChanged(); } console.log( `Error from ${this.graph.serverUrl}/${this.graph.entityName}` + ` watching segment ${segmentIdString}`); return; } query.current = update; const oldId = query.id; const newId = update.id; if (!Uint64.equal(newId, oldId)) { query.id = newId; let newSegmentIdString = newId.toString(); let newQuery = this.segmentQueries.get(newSegmentIdString); console.log(`removing from segmentQueries: ${segmentIdString} due to rename -> ${newId}`); this.segmentQueries.delete(segmentIdString); try { this.ignoreVisibleSegmentsChanged = true; if (this.segmentsState.visibleSegments.has(oldId)) { this.segmentsState.visibleSegments.delete(oldId); this.segmentsState.visibleSegments.add(newId); } if (this.segmentsState.temporaryVisibleSegments.has(oldId)) { this.segmentsState.temporaryVisibleSegments.delete(oldId); this.segmentsState.temporaryVisibleSegments.add(newId); } } finally { this.ignoreVisibleSegmentsChanged = false; } if (newQuery === undefined) { console.log(`adding to segmentQueries due to rename -> ${newId}`); this.segmentQueries.set(newSegmentIdString, query); this.segmentEquivalencesChanged(); } else { if (update.lastLogId !== null && (typeof newQuery.current !== 'object' || newQuery.current.lastLogId === null || Uint64.less(newQuery.current.lastLogId, update.lastLogId))) { newQuery.current = update; this.segmentEquivalencesChanged(); } query.disposer(); } } else { query.current = update; if (!isBaseSegmentId(query.id)) { this.segmentEquivalencesChanged(); } } } private visibleSegmentsChanged() { const {segmentsState} = this; const {segmentQueries} = this; const generation = ++updateGeneration; const processVisibleSegments = (visibleSegments: Uint64Set) => { for (const segmentId of visibleSegments) { if (Uint64.equal(segmentId, UNKNOWN_NEW_SEGMENT_ID)) continue; const segmentIdString = segmentId.toString(); const existingQuery = segmentQueries.get(segmentIdString); if (existingQuery !== undefined) { existingQuery.seenGeneration = generation; continue; } this.registerVisibleSegment(segmentId.clone()); } }; processVisibleSegments(segmentsState.visibleSegments); processVisibleSegments(segmentsState.temporaryVisibleSegments); for (const [segmentIdString, query] of segmentQueries) { if (query.seenGeneration !== generation) { console.log(`removing from segmentQueries due to seenGeneration: ${segmentIdString}`); segmentQueries.delete(segmentIdString); query.disposer(); if (query.addedEquivalences) { this.segmentEquivalencesChanged(); } } } } } type GraphSegmentUpdateCallback = (info: GraphSegmentUpdate) => void; interface WatchInfo { callback: GraphSegmentUpdateCallback; segment: Uint64; watchId: number; } export class NggraphSegmentationGraphSource extends SegmentationGraphSource { private startingWebsocket = false; private websocket: WebSocket|undefined = undefined; private watchesById = new Map<number, WatchInfo>(); private watches = new Set<WatchInfo>(); private nextWatchId = 0; private numOpenFailures = 0; constructor( public chunkManager: ChunkManager, public serverUrl: string, public entityName: string) { super(); } get highBitRepresentative() { return true; } private startWebsocket() { if (this.startingWebsocket) return; if (this.watches.size === 0) return; this.startingWebsocket = true; let status: StatusMessage|undefined = new StatusMessage(this.numOpenFailures ? false : true); status.setText( `Opening websocket connection for nggraph://${this.serverUrl}/${this.entityName}`); (async () => { const {numOpenFailures} = this; if (numOpenFailures > 1) { const delay = 1000 * Math.min(16, 2 ** numOpenFailures); await new Promise(resolve => setTimeout(resolve, delay)); } const credentials = (await getEntityCredentialsProvider(this.chunkManager, this.serverUrl, this.entityName) .get()) .credentials; let url = new URL('/graph/watch/' + encodeURIComponent(credentials.token), this.serverUrl); url.protocol = url.protocol.replace('http', 'ws'); const websocket = new WebSocket(url.href); websocket.onclose = () => { if (status !== undefined) { status.dispose(); status = undefined; } ++this.numOpenFailures; this.websocket = undefined; this.startingWebsocket = false; this.watchesById.clear(); this.startWebsocket(); }; websocket.onopen = () => { if (status !== undefined) { status.dispose(); status = undefined; } this.numOpenFailures = 0; this.websocket = websocket; this.nextWatchId = 0; try { for (const watchInfo of this.watches) { websocket.send(JSON.stringify({'watch': {'segment_id': watchInfo.segment.toString()}})); let watchId = this.nextWatchId++; watchInfo.watchId = watchId; this.watchesById.set(watchId, watchInfo); } } catch { // Ignore send error, which indicates the connection has been closed. The close handler // already deals with this case. } }; websocket.onmessage = ev => { let update: GraphSegmentUpdate; let watchInfo: WatchInfo; try { const msg = JSON.parse(ev.data); verifyObject(msg); const watchId = verifyObjectProperty(msg, 'watch_id', verifyInt); const w = this.watchesById.get(watchId); if (w === undefined) { // Watch has already been cancelled. return; } watchInfo = w; const state = verifyObjectProperty(msg, 'state', verifyString); if (state === 'invalid' || state === 'error') { update = state; } else { update = verifyObjectProperty(msg, 'info', parseGraphSegmentInfo); } } catch (e) { console.log(`Received unexpected websocket message from ${this.serverUrl}:`, ev.data, e); return; } console.log('got update', update); watchInfo.callback(update); }; })(); } connect(segmentsState: VisibleSegmentsState) { return new GraphConnection(this, segmentsState); } trackSegment(id: Uint64, callback: (id: Uint64|null) => void): () => void { return this.watchSegment(id, (info: GraphSegmentUpdate) => { if (info === 'invalid') { callback(null); } else if (info === 'error') { // Ignore errors. return; } else { callback(info.id); } }); } watchSegment(segment: Uint64, callback: GraphSegmentUpdateCallback): () => void { let watchInfo = { callback, segment, watchId: -1, }; this.watches.add(watchInfo); const {websocket} = this; if (websocket !== undefined) { try { websocket.send(JSON.stringify({'watch': {'segment_id': segment.toString()}})); let watchId = this.nextWatchId++; watchInfo.watchId = watchId; this.watchesById.set(watchId, watchInfo); } catch { // Ignore send error, which indicates the connection has been closed. The close handler // already deals with this case. } } else { this.startWebsocket(); } const disposer = () => { const {websocket} = this; if (websocket !== undefined && websocket.readyState === WebSocket.OPEN) { const watchId = watchInfo.watchId; this.watchesById.delete(watchId); try { websocket.send(JSON.stringify({'unwatch': {'watch_id': watchId}})); } catch { // Ignore send error, which indicates the connection has been closed. The close handler // already deals with this case. } } this.watches.delete(watchInfo); }; return disposer; } async merge(a: Uint64, b: Uint64): Promise<Uint64> { let response = await nggraphGraphFetch( this.chunkManager, this.serverUrl, this.entityName, '/graph/mutate', { body: JSON.stringify({ merge: {anchor: a.toString(), other: b.toString()}, }), headers: {'Content-Type': 'application/json'}, method: 'POST', }); verifyObject(response); return verifyObjectProperty(response, 'merged', x => Uint64.parseString(x)); } async split(include: Uint64, exclude: Uint64): Promise<{include: Uint64, exclude: Uint64}> { let response = await nggraphGraphFetch( this.chunkManager, this.serverUrl, this.entityName, '/graph/mutate', { body: JSON.stringify({ split: {include: include.toString(), exclude: exclude.toString()}, }), headers: {'Content-Type': 'application/json'}, method: 'POST', }); verifyObject(response); return { include: verifyObjectProperty(response, 'include', x => Uint64.parseString(x)), exclude: verifyObjectProperty(response, 'exclude', x => Uint64.parseString(x)), }; } } function parseNggraphUrl(providerUrl: string) { const m = providerUrl.match(urlPattern); if (m === null) { throw new Error(`Invalid nggraph url: ${JSON.stringify(providerUrl)}`) } return {serverUrl: m[1], id: m[2]}; } function fetchWithNggraphCredentials( credentialsProvider: CredentialsProvider<Credentials>, serverUrl: string, path: string, init: RequestInit, cancellationToken: CancellationToken = uncancelableToken): Promise<any> { return fetchWithCredentials( credentialsProvider, `${serverUrl}${path}`, init, responseJson, (credentials, init) => { const headers = new Headers(init.headers); headers.set('Authorization', credentials.token); return {...init, headers}; }, error => { const {status} = error; if (status === 401) return 'refresh'; throw error; }, cancellationToken); } interface EntityCredentials extends Credentials { role: string; entityType: string; } function nggraphServerFetch( chunkManager: ChunkManager, serverUrl: string, path: string, init: RequestInit, cancellationToken: CancellationToken = uncancelableToken): Promise<any> { return fetchWithNggraphCredentials( getCredentialsProvider(chunkManager, serverUrl), serverUrl, path, init, cancellationToken); } class NggraphEntityCredentialsProvider extends CredentialsProvider<EntityCredentials> { constructor( public parentCredentialsProvider: CredentialsProvider<Credentials>, public serverUrl: string, public entityName: string) { super(); } get = makeCredentialsGetter(async () => { let response = await fetchWithNggraphCredentials( this.parentCredentialsProvider, this.serverUrl, '/entity_token', { body: JSON.stringify({entity: this.entityName}), headers: {'Content-Type': 'application/json'}, method: 'POST', }); return {token: response['token'], entityType: response['entity_type'], role: response['role']}; }); } function getCredentialsProvider(chunkManager: ChunkManager, serverUrl: string) { return chunkManager.memoize.getUncounted( {'type': 'nggraph:credentialsProvider', serverUrl}, () => new NggraphCredentialsProvider(serverUrl)); } function getEntityCredentialsProvider( chunkManager: ChunkManager, serverUrl: string, entityName: string) { return chunkManager.memoize.getUncounted( {'type': 'nggraph:entityCredentialsProvider', serverUrl, entityName}, () => new NggraphEntityCredentialsProvider( getCredentialsProvider(chunkManager, serverUrl), serverUrl, entityName)); } function nggraphGraphFetch( chunkManager: ChunkManager, serverUrl: string, entityName: string, path: string, init: RequestInit, cancellationToken: CancellationToken = uncancelableToken): Promise<any> { return fetchWithNggraphCredentials( getEntityCredentialsProvider(chunkManager, serverUrl, entityName), serverUrl, path, init, cancellationToken); } function parseListResponse(response: any) { verifyObject(response); return verifyObjectProperty( response, 'entities', entries => parseArray(entries, entry => { verifyObject(entry); const id = verifyObjectProperty(entry, 'entity', verifyString); const entityType = verifyObjectProperty(entry, 'entity_type', verifyString); const accessRole = verifyObjectProperty(entry, 'access_role', verifyString); return {id, entityType, accessRole}; })); } export class NggraphDataSource extends DataSourceProvider { get description() { return 'nggraph data source'; } get(options: GetDataSourceOptions): Promise<DataSource> { const {serverUrl, id} = parseNggraphUrl(options.providerUrl); return options.chunkManager.memoize.getUncounted( {'type': 'nggraph:get', serverUrl, id}, async(): Promise<DataSource> => { let entityCredentialsProvider = getEntityCredentialsProvider(options.chunkManager, serverUrl, id); const {entityType} = (await entityCredentialsProvider.get()).credentials; if (entityType != 'graph') { throw new Error(`Unsupported entity type: ${JSON.stringify(entityType)}`); } const {datasource_url: baseSegmentation} = await nggraphGraphFetch( options.chunkManager, serverUrl, id, '/graph/config', {method: 'POST'}); let baseSegmentationDataSource = await options.registry.get({...options, url: baseSegmentation}); const segmentationGraph = new NggraphSegmentationGraphSource(options.chunkManager, serverUrl, id); const subsources: DataSubsourceEntry[] = [ ...baseSegmentationDataSource.subsources, { id: 'graph', default: true, subsource: {segmentationGraph}, }, ]; const dataSource: DataSource = { modelTransform: baseSegmentationDataSource.modelTransform, subsources, }; return dataSource; }); } async completeUrl(options: CompleteUrlOptions): Promise<CompletionResult> { const {serverUrl, id} = parseNggraphUrl(options.providerUrl); const list = await options.chunkManager.memoize.getUncounted( {'type': 'nggraph:list', serverUrl}, async () => { return parseListResponse( await nggraphServerFetch(options.chunkManager, serverUrl, '/list', {method: 'POST'})); }); return { offset: serverUrl.length + 1, completions: getPrefixMatchesWithDescriptions( id, list, entry => entry.id, entry => `${entry.entityType} (${entry.accessRole})`), }; } }
the_stack
import { EcmaVersion } from "./ecma-versions" import { Reader } from "./reader" import { RegExpSyntaxError } from "./regexp-syntax-error" import { Asterisk, Backspace, CarriageReturn, CharacterTabulation, CircumflexAccent, Colon, Comma, DigitNine, DigitOne, digitToInt, DigitZero, DollarSign, EqualsSign, ExclamationMark, FormFeed, FullStop, GreaterThanSign, HyphenMinus, LatinCapitalLetterB, LatinCapitalLetterD, LatinCapitalLetterP, LatinCapitalLetterS, LatinCapitalLetterW, LatinSmallLetterB, LatinSmallLetterC, LatinSmallLetterD, LatinSmallLetterF, LatinSmallLetterG, LatinSmallLetterI, LatinSmallLetterK, LatinSmallLetterM, LatinSmallLetterN, LatinSmallLetterP, LatinSmallLetterR, LatinSmallLetterS, LatinSmallLetterT, LatinSmallLetterU, LatinSmallLetterV, LatinSmallLetterW, LatinSmallLetterX, LatinSmallLetterY, LeftCurlyBracket, LeftParenthesis, LeftSquareBracket, LessThanSign, LineFeed, LineTabulation, LowLine, PlusSign, QuestionMark, ReverseSolidus, RightCurlyBracket, RightParenthesis, RightSquareBracket, Solidus, VerticalLine, ZeroWidthJoiner, ZeroWidthNonJoiner, combineSurrogatePair, isDecimalDigit, isHexDigit, isIdContinue, isIdStart, isLatinLetter, isLeadSurrogate, isLineTerminator, isOctalDigit, isTrailSurrogate, isValidLoneUnicodeProperty, isValidUnicodeProperty, isValidUnicode, } from "./unicode" function isSyntaxCharacter(cp: number): boolean { return ( cp === CircumflexAccent || cp === DollarSign || cp === ReverseSolidus || cp === FullStop || cp === Asterisk || cp === PlusSign || cp === QuestionMark || cp === LeftParenthesis || cp === RightParenthesis || cp === LeftSquareBracket || cp === RightSquareBracket || cp === LeftCurlyBracket || cp === RightCurlyBracket || cp === VerticalLine ) } function isRegExpIdentifierStart(cp: number): boolean { return isIdStart(cp) || cp === DollarSign || cp === LowLine } function isRegExpIdentifierPart(cp: number): boolean { return ( isIdContinue(cp) || cp === DollarSign || cp === LowLine || cp === ZeroWidthNonJoiner || cp === ZeroWidthJoiner ) } function isUnicodePropertyNameCharacter(cp: number): boolean { return isLatinLetter(cp) || cp === LowLine } function isUnicodePropertyValueCharacter(cp: number): boolean { return isUnicodePropertyNameCharacter(cp) || isDecimalDigit(cp) } export namespace RegExpValidator { /** * The options for RegExpValidator construction. */ export interface Options { /** * The flag to disable Annex B syntax. Default is `false`. */ strict?: boolean /** * ECMAScript version. Default is `2022`. * - `2015` added `u` and `y` flags. * - `2018` added `s` flag, Named Capturing Group, Lookbehind Assertion, * and Unicode Property Escape. * - `2019`, `2020`, and `2021` added more valid Unicode Property Escapes. * - `2022` added `d` flag. */ ecmaVersion?: EcmaVersion /** * A function that is called when the validator entered a RegExp literal. * @param start The 0-based index of the first character. */ onLiteralEnter?(start: number): void /** * A function that is called when the validator left a RegExp literal. * @param start The 0-based index of the first character. * @param end The next 0-based index of the last character. */ onLiteralLeave?(start: number, end: number): void /** * A function that is called when the validator found flags. * @param start The 0-based index of the first character. * @param end The next 0-based index of the last character. * @param global `g` flag. * @param ignoreCase `i` flag. * @param multiline `m` flag. * @param unicode `u` flag. * @param sticky `y` flag. * @param dotAll `s` flag. * @param hasIndices `d` flag. */ onFlags?( start: number, end: number, global: boolean, ignoreCase: boolean, multiline: boolean, unicode: boolean, sticky: boolean, dotAll: boolean, hasIndices: boolean, ): void /** * A function that is called when the validator entered a pattern. * @param start The 0-based index of the first character. */ onPatternEnter?(start: number): void /** * A function that is called when the validator left a pattern. * @param start The 0-based index of the first character. * @param end The next 0-based index of the last character. */ onPatternLeave?(start: number, end: number): void /** * A function that is called when the validator entered a disjunction. * @param start The 0-based index of the first character. */ onDisjunctionEnter?(start: number): void /** * A function that is called when the validator left a disjunction. * @param start The 0-based index of the first character. * @param end The next 0-based index of the last character. */ onDisjunctionLeave?(start: number, end: number): void /** * A function that is called when the validator entered an alternative. * @param start The 0-based index of the first character. * @param index The 0-based index of alternatives in a disjunction. */ onAlternativeEnter?(start: number, index: number): void /** * A function that is called when the validator left an alternative. * @param start The 0-based index of the first character. * @param end The next 0-based index of the last character. * @param index The 0-based index of alternatives in a disjunction. */ onAlternativeLeave?(start: number, end: number, index: number): void /** * A function that is called when the validator entered an uncapturing group. * @param start The 0-based index of the first character. */ onGroupEnter?(start: number): void /** * A function that is called when the validator left an uncapturing group. * @param start The 0-based index of the first character. * @param end The next 0-based index of the last character. */ onGroupLeave?(start: number, end: number): void /** * A function that is called when the validator entered a capturing group. * @param start The 0-based index of the first character. * @param name The group name. */ onCapturingGroupEnter?(start: number, name: string | null): void /** * A function that is called when the validator left a capturing group. * @param start The 0-based index of the first character. * @param end The next 0-based index of the last character. * @param name The group name. */ onCapturingGroupLeave?( start: number, end: number, name: string | null, ): void /** * A function that is called when the validator found a quantifier. * @param start The 0-based index of the first character. * @param end The next 0-based index of the last character. * @param min The minimum number of repeating. * @param max The maximum number of repeating. * @param greedy The flag to choose the longest matching. */ onQuantifier?( start: number, end: number, min: number, max: number, greedy: boolean, ): void /** * A function that is called when the validator entered a lookahead/lookbehind assertion. * @param start The 0-based index of the first character. * @param kind The kind of the assertion. * @param negate The flag which represents that the assertion is negative. */ onLookaroundAssertionEnter?( start: number, kind: "lookahead" | "lookbehind", negate: boolean, ): void /** * A function that is called when the validator left a lookahead/lookbehind assertion. * @param start The 0-based index of the first character. * @param end The next 0-based index of the last character. * @param kind The kind of the assertion. * @param negate The flag which represents that the assertion is negative. */ onLookaroundAssertionLeave?( start: number, end: number, kind: "lookahead" | "lookbehind", negate: boolean, ): void /** * A function that is called when the validator found an edge boundary assertion. * @param start The 0-based index of the first character. * @param end The next 0-based index of the last character. * @param kind The kind of the assertion. */ onEdgeAssertion?( start: number, end: number, kind: "start" | "end", ): void /** * A function that is called when the validator found a word boundary assertion. * @param start The 0-based index of the first character. * @param end The next 0-based index of the last character. * @param kind The kind of the assertion. * @param negate The flag which represents that the assertion is negative. */ onWordBoundaryAssertion?( start: number, end: number, kind: "word", negate: boolean, ): void /** * A function that is called when the validator found a dot. * @param start The 0-based index of the first character. * @param end The next 0-based index of the last character. * @param kind The kind of the character set. */ onAnyCharacterSet?(start: number, end: number, kind: "any"): void /** * A function that is called when the validator found a character set escape. * @param start The 0-based index of the first character. * @param end The next 0-based index of the last character. * @param kind The kind of the character set. * @param negate The flag which represents that the character set is negative. */ onEscapeCharacterSet?( start: number, end: number, kind: "digit" | "space" | "word", negate: boolean, ): void /** * A function that is called when the validator found a Unicode proerty escape. * @param start The 0-based index of the first character. * @param end The next 0-based index of the last character. * @param kind The kind of the character set. * @param key The property name. * @param value The property value. * @param negate The flag which represents that the character set is negative. */ onUnicodePropertyCharacterSet?( start: number, end: number, kind: "property", key: string, value: string | null, negate: boolean, ): void /** * A function that is called when the validator found a character. * @param start The 0-based index of the first character. * @param end The next 0-based index of the last character. * @param value The code point of the character. */ onCharacter?(start: number, end: number, value: number): void /** * A function that is called when the validator found a backreference. * @param start The 0-based index of the first character. * @param end The next 0-based index of the last character. * @param ref The key of the referred capturing group. */ onBackreference?(start: number, end: number, ref: number | string): void /** * A function that is called when the validator entered a character class. * @param start The 0-based index of the first character. * @param negate The flag which represents that the character class is negative. */ onCharacterClassEnter?(start: number, negate: boolean): void /** * A function that is called when the validator left a character class. * @param start The 0-based index of the first character. * @param end The next 0-based index of the last character. * @param negate The flag which represents that the character class is negative. */ onCharacterClassLeave?( start: number, end: number, negate: boolean, ): void /** * A function that is called when the validator found a character class range. * @param start The 0-based index of the first character. * @param end The next 0-based index of the last character. * @param min The minimum code point of the range. * @param max The maximum code point of the range. */ onCharacterClassRange?( start: number, end: number, min: number, max: number, ): void } } /** * The regular expression validator. */ export class RegExpValidator { private readonly _options: RegExpValidator.Options private readonly _reader = new Reader() private _uFlag = false private _nFlag = false private _lastIntValue = 0 private _lastMinValue = 0 private _lastMaxValue = 0 private _lastStrValue = "" private _lastKeyValue = "" private _lastValValue = "" private _lastAssertionIsQuantifiable = false private _numCapturingParens = 0 private _groupNames = new Set<string>() private _backreferenceNames = new Set<string>() /** * Initialize this validator. * @param options The options of validator. */ public constructor(options?: RegExpValidator.Options) { this._options = options || {} } /** * Validate a regular expression literal. E.g. "/abc/g" * @param source The source code to validate. * @param start The start index in the source code. * @param end The end index in the source code. */ public validateLiteral( source: string, start = 0, end: number = source.length, ): void { this._uFlag = this._nFlag = false this.reset(source, start, end) this.onLiteralEnter(start) if (this.eat(Solidus) && this.eatRegExpBody() && this.eat(Solidus)) { const flagStart = this.index const uFlag = source.includes("u", flagStart) this.validateFlags(source, flagStart, end) this.validatePattern(source, start + 1, flagStart - 1, uFlag) } else if (start >= end) { this.raise("Empty") } else { const c = String.fromCodePoint(this.currentCodePoint) this.raise(`Unexpected character '${c}'`) } this.onLiteralLeave(start, end) } /** * Validate a regular expression flags. E.g. "gim" * @param source The source code to validate. * @param start The start index in the source code. * @param end The end index in the source code. */ public validateFlags( source: string, start = 0, end: number = source.length, ): void { const existingFlags = new Set<number>() let global = false let ignoreCase = false let multiline = false let sticky = false let unicode = false let dotAll = false let hasIndices = false for (let i = start; i < end; ++i) { const flag = source.charCodeAt(i) if (existingFlags.has(flag)) { this.raise(`Duplicated flag '${source[i]}'`) } existingFlags.add(flag) if (flag === LatinSmallLetterG) { global = true } else if (flag === LatinSmallLetterI) { ignoreCase = true } else if (flag === LatinSmallLetterM) { multiline = true } else if (flag === LatinSmallLetterU && this.ecmaVersion >= 2015) { unicode = true } else if (flag === LatinSmallLetterY && this.ecmaVersion >= 2015) { sticky = true } else if (flag === LatinSmallLetterS && this.ecmaVersion >= 2018) { dotAll = true } else if (flag === LatinSmallLetterD && this.ecmaVersion >= 2022) { hasIndices = true } else { this.raise(`Invalid flag '${source[i]}'`) } } this.onFlags( start, end, global, ignoreCase, multiline, unicode, sticky, dotAll, hasIndices, ) } /** * Validate a regular expression pattern. E.g. "abc" * @param source The source code to validate. * @param start The start index in the source code. * @param end The end index in the source code. * @param uFlag The flag to set unicode mode. */ public validatePattern( source: string, start = 0, end: number = source.length, uFlag = false, ): void { this._uFlag = uFlag && this.ecmaVersion >= 2015 this._nFlag = uFlag && this.ecmaVersion >= 2018 this.reset(source, start, end) this.consumePattern() if ( !this._nFlag && this.ecmaVersion >= 2018 && this._groupNames.size > 0 ) { this._nFlag = true this.rewind(start) this.consumePattern() } } // #region Delegate for Options private get strict() { return Boolean(this._options.strict || this._uFlag) } private get ecmaVersion() { return this._options.ecmaVersion || 2022 } private onLiteralEnter(start: number): void { if (this._options.onLiteralEnter) { this._options.onLiteralEnter(start) } } private onLiteralLeave(start: number, end: number): void { if (this._options.onLiteralLeave) { this._options.onLiteralLeave(start, end) } } private onFlags( start: number, end: number, global: boolean, ignoreCase: boolean, multiline: boolean, unicode: boolean, sticky: boolean, dotAll: boolean, hasIndices: boolean, ): void { if (this._options.onFlags) { this._options.onFlags( start, end, global, ignoreCase, multiline, unicode, sticky, dotAll, hasIndices, ) } } private onPatternEnter(start: number): void { if (this._options.onPatternEnter) { this._options.onPatternEnter(start) } } private onPatternLeave(start: number, end: number): void { if (this._options.onPatternLeave) { this._options.onPatternLeave(start, end) } } private onDisjunctionEnter(start: number): void { if (this._options.onDisjunctionEnter) { this._options.onDisjunctionEnter(start) } } private onDisjunctionLeave(start: number, end: number): void { if (this._options.onDisjunctionLeave) { this._options.onDisjunctionLeave(start, end) } } private onAlternativeEnter(start: number, index: number): void { if (this._options.onAlternativeEnter) { this._options.onAlternativeEnter(start, index) } } private onAlternativeLeave( start: number, end: number, index: number, ): void { if (this._options.onAlternativeLeave) { this._options.onAlternativeLeave(start, end, index) } } private onGroupEnter(start: number): void { if (this._options.onGroupEnter) { this._options.onGroupEnter(start) } } private onGroupLeave(start: number, end: number): void { if (this._options.onGroupLeave) { this._options.onGroupLeave(start, end) } } private onCapturingGroupEnter(start: number, name: string | null): void { if (this._options.onCapturingGroupEnter) { this._options.onCapturingGroupEnter(start, name) } } private onCapturingGroupLeave( start: number, end: number, name: string | null, ): void { if (this._options.onCapturingGroupLeave) { this._options.onCapturingGroupLeave(start, end, name) } } private onQuantifier( start: number, end: number, min: number, max: number, greedy: boolean, ): void { if (this._options.onQuantifier) { this._options.onQuantifier(start, end, min, max, greedy) } } private onLookaroundAssertionEnter( start: number, kind: "lookahead" | "lookbehind", negate: boolean, ): void { if (this._options.onLookaroundAssertionEnter) { this._options.onLookaroundAssertionEnter(start, kind, negate) } } private onLookaroundAssertionLeave( start: number, end: number, kind: "lookahead" | "lookbehind", negate: boolean, ): void { if (this._options.onLookaroundAssertionLeave) { this._options.onLookaroundAssertionLeave(start, end, kind, negate) } } private onEdgeAssertion( start: number, end: number, kind: "start" | "end", ): void { if (this._options.onEdgeAssertion) { this._options.onEdgeAssertion(start, end, kind) } } private onWordBoundaryAssertion( start: number, end: number, kind: "word", negate: boolean, ): void { if (this._options.onWordBoundaryAssertion) { this._options.onWordBoundaryAssertion(start, end, kind, negate) } } private onAnyCharacterSet(start: number, end: number, kind: "any"): void { if (this._options.onAnyCharacterSet) { this._options.onAnyCharacterSet(start, end, kind) } } private onEscapeCharacterSet( start: number, end: number, kind: "digit" | "space" | "word", negate: boolean, ): void { if (this._options.onEscapeCharacterSet) { this._options.onEscapeCharacterSet(start, end, kind, negate) } } private onUnicodePropertyCharacterSet( start: number, end: number, kind: "property", key: string, value: string | null, negate: boolean, ): void { if (this._options.onUnicodePropertyCharacterSet) { this._options.onUnicodePropertyCharacterSet( start, end, kind, key, value, negate, ) } } private onCharacter(start: number, end: number, value: number): void { if (this._options.onCharacter) { this._options.onCharacter(start, end, value) } } private onBackreference( start: number, end: number, ref: number | string, ): void { if (this._options.onBackreference) { this._options.onBackreference(start, end, ref) } } private onCharacterClassEnter(start: number, negate: boolean): void { if (this._options.onCharacterClassEnter) { this._options.onCharacterClassEnter(start, negate) } } private onCharacterClassLeave( start: number, end: number, negate: boolean, ): void { if (this._options.onCharacterClassLeave) { this._options.onCharacterClassLeave(start, end, negate) } } private onCharacterClassRange( start: number, end: number, min: number, max: number, ): void { if (this._options.onCharacterClassRange) { this._options.onCharacterClassRange(start, end, min, max) } } // #endregion // #region Delegate for Reader private get source(): string { return this._reader.source } private get index(): number { return this._reader.index } private get currentCodePoint(): number { return this._reader.currentCodePoint } private get nextCodePoint(): number { return this._reader.nextCodePoint } private get nextCodePoint2(): number { return this._reader.nextCodePoint2 } private get nextCodePoint3(): number { return this._reader.nextCodePoint3 } private reset(source: string, start: number, end: number): void { this._reader.reset(source, start, end, this._uFlag) } private rewind(index: number): void { this._reader.rewind(index) } private advance(): void { this._reader.advance() } private eat(cp: number): boolean { return this._reader.eat(cp) } private eat2(cp1: number, cp2: number): boolean { return this._reader.eat2(cp1, cp2) } private eat3(cp1: number, cp2: number, cp3: number): boolean { return this._reader.eat3(cp1, cp2, cp3) } // #endregion private raise(message: string): never { throw new RegExpSyntaxError( this.source, this._uFlag, this.index, message, ) } // https://www.ecma-international.org/ecma-262/8.0/#prod-RegularExpressionBody private eatRegExpBody(): boolean { const start = this.index let inClass = false let escaped = false for (;;) { const cp = this.currentCodePoint if (cp === -1 || isLineTerminator(cp)) { const kind = inClass ? "character class" : "regular expression" this.raise(`Unterminated ${kind}`) } if (escaped) { escaped = false } else if (cp === ReverseSolidus) { escaped = true } else if (cp === LeftSquareBracket) { inClass = true } else if (cp === RightSquareBracket) { inClass = false } else if ( (cp === Solidus && !inClass) || (cp === Asterisk && this.index === start) ) { break } this.advance() } return this.index !== start } /** * Validate the next characters as a RegExp `Pattern` production. * ``` * Pattern[U, N]:: * Disjunction[?U, ?N] * ``` */ private consumePattern(): void { const start = this.index this._numCapturingParens = this.countCapturingParens() this._groupNames.clear() this._backreferenceNames.clear() this.onPatternEnter(start) this.consumeDisjunction() const cp = this.currentCodePoint if (this.currentCodePoint !== -1) { if (cp === RightParenthesis) { this.raise("Unmatched ')'") } if (cp === ReverseSolidus) { this.raise("\\ at end of pattern") } if (cp === RightSquareBracket || cp === RightCurlyBracket) { this.raise("Lone quantifier brackets") } const c = String.fromCodePoint(cp) this.raise(`Unexpected character '${c}'`) } for (const name of this._backreferenceNames) { if (!this._groupNames.has(name)) { this.raise("Invalid named capture referenced") } } this.onPatternLeave(start, this.index) } /** * Count capturing groups in the current source code. * @returns The number of capturing groups. */ private countCapturingParens(): number { const start = this.index let inClass = false let escaped = false let count = 0 let cp = 0 while ((cp = this.currentCodePoint) !== -1) { if (escaped) { escaped = false } else if (cp === ReverseSolidus) { escaped = true } else if (cp === LeftSquareBracket) { inClass = true } else if (cp === RightSquareBracket) { inClass = false } else if ( cp === LeftParenthesis && !inClass && (this.nextCodePoint !== QuestionMark || (this.nextCodePoint2 === LessThanSign && this.nextCodePoint3 !== EqualsSign && this.nextCodePoint3 !== ExclamationMark)) ) { count += 1 } this.advance() } this.rewind(start) return count } /** * Validate the next characters as a RegExp `Disjunction` production. * ``` * Disjunction[U, N]:: * Alternative[?U, ?N] * Alternative[?U, ?N] `|` Disjunction[?U, ?N] * ``` */ private consumeDisjunction(): void { const start = this.index let i = 0 this.onDisjunctionEnter(start) do { this.consumeAlternative(i++) } while (this.eat(VerticalLine)) if (this.consumeQuantifier(true)) { this.raise("Nothing to repeat") } if (this.eat(LeftCurlyBracket)) { this.raise("Lone quantifier brackets") } this.onDisjunctionLeave(start, this.index) } /** * Validate the next characters as a RegExp `Alternative` production. * ``` * Alternative[U, N]:: * ε * Alternative[?U, ?N] Term[?U, ?N] * ``` */ private consumeAlternative(i: number): void { const start = this.index this.onAlternativeEnter(start, i) while (this.currentCodePoint !== -1 && this.consumeTerm()) { // do nothing. } this.onAlternativeLeave(start, this.index, i) } /** * Validate the next characters as a RegExp `Term` production if possible. * ``` * Term[U, N]:: * [strict] Assertion[+U, ?N] * [strict] Atom[+U, ?N] * [strict] Atom[+U, ?N] Quantifier * [annexB][+U] Assertion[+U, ?N] * [annexB][+U] Atom[+U, ?N] * [annexB][+U] Atom[+U, ?N] Quantifier * [annexB][~U] QuantifiableAssertion[?N] Quantifier * [annexB][~U] Assertion[~U, ?N] * [annexB][~U] ExtendedAtom[?N] Quantifier * [annexB][~U] ExtendedAtom[?N] * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeTerm(): boolean { if (this._uFlag || this.strict) { return ( this.consumeAssertion() || (this.consumeAtom() && this.consumeOptionalQuantifier()) ) } return ( (this.consumeAssertion() && (!this._lastAssertionIsQuantifiable || this.consumeOptionalQuantifier())) || (this.consumeExtendedAtom() && this.consumeOptionalQuantifier()) ) } private consumeOptionalQuantifier(): boolean { this.consumeQuantifier() return true } /** * Validate the next characters as a RegExp `Term` production if possible. * Set `this._lastAssertionIsQuantifiable` if the consumed assertion was a * `QuantifiableAssertion` production. * ``` * Assertion[U, N]:: * `^` * `$` * `\b` * `\B` * [strict] `(?=` Disjunction[+U, ?N] `)` * [strict] `(?!` Disjunction[+U, ?N] `)` * [annexB][+U] `(?=` Disjunction[+U, ?N] `)` * [annexB][+U] `(?!` Disjunction[+U, ?N] `)` * [annexB][~U] QuantifiableAssertion[?N] * `(?<=` Disjunction[?U, ?N] `)` * `(?<!` Disjunction[?U, ?N] `)` * QuantifiableAssertion[N]:: * `(?=` Disjunction[~U, ?N] `)` * `(?!` Disjunction[~U, ?N] `)` * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeAssertion(): boolean { const start = this.index this._lastAssertionIsQuantifiable = false // ^, $, \B \b if (this.eat(CircumflexAccent)) { this.onEdgeAssertion(start, this.index, "start") return true } if (this.eat(DollarSign)) { this.onEdgeAssertion(start, this.index, "end") return true } if (this.eat2(ReverseSolidus, LatinCapitalLetterB)) { this.onWordBoundaryAssertion(start, this.index, "word", true) return true } if (this.eat2(ReverseSolidus, LatinSmallLetterB)) { this.onWordBoundaryAssertion(start, this.index, "word", false) return true } // Lookahead / Lookbehind if (this.eat2(LeftParenthesis, QuestionMark)) { const lookbehind = this.ecmaVersion >= 2018 && this.eat(LessThanSign) let negate = false if (this.eat(EqualsSign) || (negate = this.eat(ExclamationMark))) { const kind = lookbehind ? "lookbehind" : "lookahead" this.onLookaroundAssertionEnter(start, kind, negate) this.consumeDisjunction() if (!this.eat(RightParenthesis)) { this.raise("Unterminated group") } this._lastAssertionIsQuantifiable = !lookbehind && !this.strict this.onLookaroundAssertionLeave(start, this.index, kind, negate) return true } this.rewind(start) } return false } /** * Validate the next characters as a RegExp `Quantifier` production if * possible. * ``` * Quantifier:: * QuantifierPrefix * QuantifierPrefix `?` * QuantifierPrefix:: * `*` * `+` * `?` * `{` DecimalDigits `}` * `{` DecimalDigits `,}` * `{` DecimalDigits `,` DecimalDigits `}` * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeQuantifier(noConsume = false): boolean { const start = this.index let min = 0 let max = 0 let greedy = false // QuantifierPrefix if (this.eat(Asterisk)) { min = 0 max = Number.POSITIVE_INFINITY } else if (this.eat(PlusSign)) { min = 1 max = Number.POSITIVE_INFINITY } else if (this.eat(QuestionMark)) { min = 0 max = 1 } else if (this.eatBracedQuantifier(noConsume)) { min = this._lastMinValue max = this._lastMaxValue } else { return false } // `?` greedy = !this.eat(QuestionMark) if (!noConsume) { this.onQuantifier(start, this.index, min, max, greedy) } return true } /** * Eat the next characters as the following alternatives if possible. * Set `this._lastMinValue` and `this._lastMaxValue` if it consumed the next * characters successfully. * ``` * `{` DecimalDigits `}` * `{` DecimalDigits `,}` * `{` DecimalDigits `,` DecimalDigits `}` * ``` * @returns `true` if it consumed the next characters successfully. */ private eatBracedQuantifier(noError: boolean): boolean { const start = this.index if (this.eat(LeftCurlyBracket)) { this._lastMinValue = 0 this._lastMaxValue = Number.POSITIVE_INFINITY if (this.eatDecimalDigits()) { this._lastMinValue = this._lastMaxValue = this._lastIntValue if (this.eat(Comma)) { this._lastMaxValue = this.eatDecimalDigits() ? this._lastIntValue : Number.POSITIVE_INFINITY } if (this.eat(RightCurlyBracket)) { if (!noError && this._lastMaxValue < this._lastMinValue) { this.raise("numbers out of order in {} quantifier") } return true } } if (!noError && (this._uFlag || this.strict)) { this.raise("Incomplete quantifier") } this.rewind(start) } return false } /** * Validate the next characters as a RegExp `Atom` production if possible. * ``` * Atom[U, N]:: * PatternCharacter * `.` * `\\` AtomEscape[?U, ?N] * CharacterClass[?U] * `(?:` Disjunction[?U, ?N] ) * `(` GroupSpecifier[?U] Disjunction[?U, ?N] `)` * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeAtom(): boolean { return ( this.consumePatternCharacter() || this.consumeDot() || this.consumeReverseSolidusAtomEscape() || this.consumeCharacterClass() || this.consumeUncapturingGroup() || this.consumeCapturingGroup() ) } /** * Validate the next characters as the following alternatives if possible. * ``` * `.` * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeDot(): boolean { if (this.eat(FullStop)) { this.onAnyCharacterSet(this.index - 1, this.index, "any") return true } return false } /** * Validate the next characters as the following alternatives if possible. * ``` * `\\` AtomEscape[?U, ?N] * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeReverseSolidusAtomEscape(): boolean { const start = this.index if (this.eat(ReverseSolidus)) { if (this.consumeAtomEscape()) { return true } this.rewind(start) } return false } /** * Validate the next characters as the following alternatives if possible. * ``` * `(?:` Disjunction[?U, ?N] ) * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeUncapturingGroup(): boolean { const start = this.index if (this.eat3(LeftParenthesis, QuestionMark, Colon)) { this.onGroupEnter(start) this.consumeDisjunction() if (!this.eat(RightParenthesis)) { this.raise("Unterminated group") } this.onGroupLeave(start, this.index) return true } return false } /** * Validate the next characters as the following alternatives if possible. * ``` * `(` GroupSpecifier[?U] Disjunction[?U, ?N] `)` * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeCapturingGroup(): boolean { const start = this.index if (this.eat(LeftParenthesis)) { let name: string | null = null if (this.ecmaVersion >= 2018) { if (this.consumeGroupSpecifier()) { name = this._lastStrValue } } else if (this.currentCodePoint === QuestionMark) { this.raise("Invalid group") } this.onCapturingGroupEnter(start, name) this.consumeDisjunction() if (!this.eat(RightParenthesis)) { this.raise("Unterminated group") } this.onCapturingGroupLeave(start, this.index, name) return true } return false } /** * Validate the next characters as a RegExp `ExtendedAtom` production if * possible. * ``` * ExtendedAtom[N]:: * `.` * `\` AtomEscape[~U, ?N] * `\` [lookahead = c] * CharacterClass[~U] * `(?:` Disjunction[~U, ?N] `)` * `(` Disjunction[~U, ?N] `)` * InvalidBracedQuantifier * ExtendedPatternCharacter * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeExtendedAtom(): boolean { return ( this.consumeDot() || this.consumeReverseSolidusAtomEscape() || this.consumeReverseSolidusFollowedByC() || this.consumeCharacterClass() || this.consumeUncapturingGroup() || this.consumeCapturingGroup() || this.consumeInvalidBracedQuantifier() || this.consumeExtendedPatternCharacter() ) } /** * Validate the next characters as the following alternatives if possible. * ``` * `\` [lookahead = c] * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeReverseSolidusFollowedByC(): boolean { const start = this.index if ( this.currentCodePoint === ReverseSolidus && this.nextCodePoint === LatinSmallLetterC ) { this._lastIntValue = this.currentCodePoint this.advance() this.onCharacter(start, this.index, ReverseSolidus) return true } return false } /** * Validate the next characters as a RegExp `InvalidBracedQuantifier` * production if possible. * ``` * InvalidBracedQuantifier:: * `{` DecimalDigits `}` * `{` DecimalDigits `,}` * `{` DecimalDigits `,` DecimalDigits `}` * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeInvalidBracedQuantifier(): boolean { if (this.eatBracedQuantifier(/* noError= */ true)) { this.raise("Nothing to repeat") } return false } /** * Validate the next characters as a RegExp `PatternCharacter` production if * possible. * ``` * PatternCharacter:: * SourceCharacter but not SyntaxCharacter * ``` * @returns `true` if it consumed the next characters successfully. */ private consumePatternCharacter(): boolean { const start = this.index const cp = this.currentCodePoint if (cp !== -1 && !isSyntaxCharacter(cp)) { this.advance() this.onCharacter(start, this.index, cp) return true } return false } /** * Validate the next characters as a RegExp `ExtendedPatternCharacter` * production if possible. * ``` * ExtendedPatternCharacter:: * SourceCharacter but not one of ^ $ \ . * + ? ( ) [ | * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeExtendedPatternCharacter(): boolean { const start = this.index const cp = this.currentCodePoint if ( cp !== -1 && cp !== CircumflexAccent && cp !== DollarSign && cp !== ReverseSolidus && cp !== FullStop && cp !== Asterisk && cp !== PlusSign && cp !== QuestionMark && cp !== LeftParenthesis && cp !== RightParenthesis && cp !== LeftSquareBracket && cp !== VerticalLine ) { this.advance() this.onCharacter(start, this.index, cp) return true } return false } /** * Validate the next characters as a RegExp `GroupSpecifier` production. * Set `this._lastStrValue` if the group name existed. * ``` * GroupSpecifier[U]:: * ε * `?` GroupName[?U] * ``` * @returns `true` if the group name existed. */ private consumeGroupSpecifier(): boolean { if (this.eat(QuestionMark)) { if (this.eatGroupName()) { if (!this._groupNames.has(this._lastStrValue)) { this._groupNames.add(this._lastStrValue) return true } this.raise("Duplicate capture group name") } this.raise("Invalid group") } return false } /** * Validate the next characters as a RegExp `AtomEscape` production if * possible. * ``` * AtomEscape[U, N]:: * [strict] DecimalEscape * [annexB][+U] DecimalEscape * [annexB][~U] DecimalEscape but only if the CapturingGroupNumber of DecimalEscape is <= NcapturingParens * CharacterClassEscape[?U] * [strict] CharacterEscape[?U] * [annexB] CharacterEscape[?U, ?N] * [+N] `k` GroupName[?U] * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeAtomEscape(): boolean { if ( this.consumeBackreference() || this.consumeCharacterClassEscape() || this.consumeCharacterEscape() || (this._nFlag && this.consumeKGroupName()) ) { return true } if (this.strict || this._uFlag) { this.raise("Invalid escape") } return false } /** * Validate the next characters as the follwoing alternatives if possible. * ``` * [strict] DecimalEscape * [annexB][+U] DecimalEscape * [annexB][~U] DecimalEscape but only if the CapturingGroupNumber of DecimalEscape is <= NcapturingParens * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeBackreference(): boolean { const start = this.index if (this.eatDecimalEscape()) { const n = this._lastIntValue if (n <= this._numCapturingParens) { this.onBackreference(start - 1, this.index, n) return true } if (this.strict || this._uFlag) { this.raise("Invalid escape") } this.rewind(start) } return false } /** * Validate the next characters as a RegExp `DecimalEscape` production if * possible. * Set `-1` to `this._lastIntValue` as meaning of a character set if it ate * the next characters successfully. * ``` * CharacterClassEscape[U]:: * `d` * `D` * `s` * `S` * `w` * `W` * [+U] `p{` UnicodePropertyValueExpression `}` * [+U] `P{` UnicodePropertyValueExpression `}` * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeCharacterClassEscape(): boolean { const start = this.index if (this.eat(LatinSmallLetterD)) { this._lastIntValue = -1 this.onEscapeCharacterSet(start - 1, this.index, "digit", false) return true } if (this.eat(LatinCapitalLetterD)) { this._lastIntValue = -1 this.onEscapeCharacterSet(start - 1, this.index, "digit", true) return true } if (this.eat(LatinSmallLetterS)) { this._lastIntValue = -1 this.onEscapeCharacterSet(start - 1, this.index, "space", false) return true } if (this.eat(LatinCapitalLetterS)) { this._lastIntValue = -1 this.onEscapeCharacterSet(start - 1, this.index, "space", true) return true } if (this.eat(LatinSmallLetterW)) { this._lastIntValue = -1 this.onEscapeCharacterSet(start - 1, this.index, "word", false) return true } if (this.eat(LatinCapitalLetterW)) { this._lastIntValue = -1 this.onEscapeCharacterSet(start - 1, this.index, "word", true) return true } let negate = false if ( this._uFlag && this.ecmaVersion >= 2018 && (this.eat(LatinSmallLetterP) || (negate = this.eat(LatinCapitalLetterP))) ) { this._lastIntValue = -1 if ( this.eat(LeftCurlyBracket) && this.eatUnicodePropertyValueExpression() && this.eat(RightCurlyBracket) ) { this.onUnicodePropertyCharacterSet( start - 1, this.index, "property", this._lastKeyValue, this._lastValValue || null, negate, ) return true } this.raise("Invalid property name") } return false } /** * Validate the next characters as a RegExp `CharacterEscape` production if * possible. * ``` * CharacterEscape[U, N]:: * ControlEscape * `c` ControlLetter * `0` [lookahead ∉ DecimalDigit] * HexEscapeSequence * RegExpUnicodeEscapeSequence[?U] * [annexB][~U] LegacyOctalEscapeSequence * IdentityEscape[?U, ?N] * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeCharacterEscape(): boolean { const start = this.index if ( this.eatControlEscape() || this.eatCControlLetter() || this.eatZero() || this.eatHexEscapeSequence() || this.eatRegExpUnicodeEscapeSequence() || (!this.strict && !this._uFlag && this.eatLegacyOctalEscapeSequence()) || this.eatIdentityEscape() ) { this.onCharacter(start - 1, this.index, this._lastIntValue) return true } return false } /** * Validate the next characters as the follwoing alternatives if possible. * ``` * `k` GroupName[?U] * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeKGroupName(): boolean { const start = this.index if (this.eat(LatinSmallLetterK)) { if (this.eatGroupName()) { const groupName = this._lastStrValue this._backreferenceNames.add(groupName) this.onBackreference(start - 1, this.index, groupName) return true } this.raise("Invalid named reference") } return false } /** * Validate the next characters as a RegExp `CharacterClass` production if * possible. * ``` * CharacterClass[U]:: * `[` [lookahead ≠ ^] ClassRanges[?U] `]` * `[^` ClassRanges[?U] `]` * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeCharacterClass(): boolean { const start = this.index if (this.eat(LeftSquareBracket)) { const negate = this.eat(CircumflexAccent) this.onCharacterClassEnter(start, negate) this.consumeClassRanges() if (!this.eat(RightSquareBracket)) { this.raise("Unterminated character class") } this.onCharacterClassLeave(start, this.index, negate) return true } return false } /** * Validate the next characters as a RegExp `ClassRanges` production. * ``` * ClassRanges[U]:: * ε * NonemptyClassRanges[?U] * NonemptyClassRanges[U]:: * ClassAtom[?U] * ClassAtom[?U] NonemptyClassRangesNoDash[?U] * ClassAtom[?U] `-` ClassAtom[?U] ClassRanges[?U] * NonemptyClassRangesNoDash[U]:: * ClassAtom[?U] * ClassAtomNoDash[?U] NonemptyClassRangesNoDash[?U] * ClassAtomNoDash[?U] `-` ClassAtom[?U] ClassRanges[?U] * ``` */ private consumeClassRanges(): void { const strict = this.strict || this._uFlag for (;;) { // Consume the first ClassAtom const rangeStart = this.index if (!this.consumeClassAtom()) { break } const min = this._lastIntValue // Consume `-` if (!this.eat(HyphenMinus)) { continue } this.onCharacter(this.index - 1, this.index, HyphenMinus) // Consume the second ClassAtom if (!this.consumeClassAtom()) { break } const max = this._lastIntValue // Validate if (min === -1 || max === -1) { if (strict) { this.raise("Invalid character class") } continue } if (min > max) { this.raise("Range out of order in character class") } this.onCharacterClassRange(rangeStart, this.index, min, max) } } /** * Validate the next characters as a RegExp `ClassAtom` production if * possible. * Set `this._lastIntValue` if it consumed the next characters successfully. * ``` * ClassAtom[U, N]:: * `-` * ClassAtomNoDash[?U, ?N] * ClassAtomNoDash[U, N]:: * SourceCharacter but not one of \ ] - * `\` ClassEscape[?U, ?N] * [annexB] `\` [lookahead = c] * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeClassAtom(): boolean { const start = this.index const cp = this.currentCodePoint if (cp !== -1 && cp !== ReverseSolidus && cp !== RightSquareBracket) { this.advance() this._lastIntValue = cp this.onCharacter(start, this.index, this._lastIntValue) return true } if (this.eat(ReverseSolidus)) { if (this.consumeClassEscape()) { return true } if (!this.strict && this.currentCodePoint === LatinSmallLetterC) { this._lastIntValue = ReverseSolidus this.onCharacter(start, this.index, this._lastIntValue) return true } if (this.strict || this._uFlag) { this.raise("Invalid escape") } this.rewind(start) } return false } /** * Validate the next characters as a RegExp `ClassEscape` production if * possible. * Set `this._lastIntValue` if it consumed the next characters successfully. * ``` * ClassEscape[U, N]:: * `b` * [+U] `-` * [annexB][~U] `c` ClassControlLetter * CharacterClassEscape[?U] * CharacterEscape[?U, ?N] * ClassControlLetter:: * DecimalDigit * `_` * ``` * @returns `true` if it consumed the next characters successfully. */ private consumeClassEscape(): boolean { const start = this.index // `b` if (this.eat(LatinSmallLetterB)) { this._lastIntValue = Backspace this.onCharacter(start - 1, this.index, this._lastIntValue) return true } // [+U] `-` if (this._uFlag && this.eat(HyphenMinus)) { this._lastIntValue = HyphenMinus this.onCharacter(start - 1, this.index, this._lastIntValue) return true } // [annexB][~U] `c` ClassControlLetter let cp = 0 if ( !this.strict && !this._uFlag && this.currentCodePoint === LatinSmallLetterC && (isDecimalDigit((cp = this.nextCodePoint)) || cp === LowLine) ) { this.advance() this.advance() this._lastIntValue = cp % 0x20 this.onCharacter(start - 1, this.index, this._lastIntValue) return true } return ( this.consumeCharacterClassEscape() || this.consumeCharacterEscape() ) } /** * Eat the next characters as a RegExp `GroupName` production if possible. * Set `this._lastStrValue` if the group name existed. * ``` * GroupName[U]:: * `<` RegExpIdentifierName[?U] `>` * ``` * @returns `true` if it ate the next characters successfully. */ private eatGroupName(): boolean { if (this.eat(LessThanSign)) { if (this.eatRegExpIdentifierName() && this.eat(GreaterThanSign)) { return true } this.raise("Invalid capture group name") } return false } /** * Eat the next characters as a RegExp `RegExpIdentifierName` production if * possible. * Set `this._lastStrValue` if the identifier name existed. * ``` * RegExpIdentifierName[U]:: * RegExpIdentifierStart[?U] * RegExpIdentifierName[?U] RegExpIdentifierPart[?U] * ``` * @returns `true` if it ate the next characters successfully. */ private eatRegExpIdentifierName(): boolean { if (this.eatRegExpIdentifierStart()) { this._lastStrValue = String.fromCodePoint(this._lastIntValue) while (this.eatRegExpIdentifierPart()) { this._lastStrValue += String.fromCodePoint(this._lastIntValue) } return true } return false } /** * Eat the next characters as a RegExp `RegExpIdentifierStart` production if * possible. * Set `this._lastIntValue` if the identifier start existed. * ``` * RegExpIdentifierStart[U] :: * UnicodeIDStart * `$` * `_` * `\` RegExpUnicodeEscapeSequence[+U] * [~U] UnicodeLeadSurrogate UnicodeTrailSurrogate * ``` * @returns `true` if it ate the next characters successfully. */ private eatRegExpIdentifierStart(): boolean { const start = this.index const forceUFlag = !this._uFlag && this.ecmaVersion >= 2020 let cp = this.currentCodePoint this.advance() if ( cp === ReverseSolidus && this.eatRegExpUnicodeEscapeSequence(forceUFlag) ) { cp = this._lastIntValue } else if ( forceUFlag && isLeadSurrogate(cp) && isTrailSurrogate(this.currentCodePoint) ) { cp = combineSurrogatePair(cp, this.currentCodePoint) this.advance() } if (isRegExpIdentifierStart(cp)) { this._lastIntValue = cp return true } if (this.index !== start) { this.rewind(start) } return false } /** * Eat the next characters as a RegExp `RegExpIdentifierPart` production if * possible. * Set `this._lastIntValue` if the identifier part existed. * ``` * RegExpIdentifierPart[U] :: * UnicodeIDContinue * `$` * `_` * `\` RegExpUnicodeEscapeSequence[+U] * [~U] UnicodeLeadSurrogate UnicodeTrailSurrogate * <ZWNJ> * <ZWJ> * ``` * @returns `true` if it ate the next characters successfully. */ private eatRegExpIdentifierPart(): boolean { const start = this.index const forceUFlag = !this._uFlag && this.ecmaVersion >= 2020 let cp = this.currentCodePoint this.advance() if ( cp === ReverseSolidus && this.eatRegExpUnicodeEscapeSequence(forceUFlag) ) { cp = this._lastIntValue } else if ( forceUFlag && isLeadSurrogate(cp) && isTrailSurrogate(this.currentCodePoint) ) { cp = combineSurrogatePair(cp, this.currentCodePoint) this.advance() } if (isRegExpIdentifierPart(cp)) { this._lastIntValue = cp return true } if (this.index !== start) { this.rewind(start) } return false } /** * Eat the next characters as the follwoing alternatives if possible. * Set `this._lastIntValue` if it ate the next characters successfully. * ``` * `c` ControlLetter * ``` * @returns `true` if it ate the next characters successfully. */ private eatCControlLetter(): boolean { const start = this.index if (this.eat(LatinSmallLetterC)) { if (this.eatControlLetter()) { return true } this.rewind(start) } return false } /** * Eat the next characters as the follwoing alternatives if possible. * Set `this._lastIntValue` if it ate the next characters successfully. * ``` * `0` [lookahead ∉ DecimalDigit] * ``` * @returns `true` if it ate the next characters successfully. */ private eatZero(): boolean { if ( this.currentCodePoint === DigitZero && !isDecimalDigit(this.nextCodePoint) ) { this._lastIntValue = 0 this.advance() return true } return false } /** * Eat the next characters as a RegExp `ControlEscape` production if * possible. * Set `this._lastIntValue` if it ate the next characters successfully. * ``` * ControlEscape:: one of * f n r t v * ``` * @returns `true` if it ate the next characters successfully. */ private eatControlEscape(): boolean { if (this.eat(LatinSmallLetterF)) { this._lastIntValue = FormFeed return true } if (this.eat(LatinSmallLetterN)) { this._lastIntValue = LineFeed return true } if (this.eat(LatinSmallLetterR)) { this._lastIntValue = CarriageReturn return true } if (this.eat(LatinSmallLetterT)) { this._lastIntValue = CharacterTabulation return true } if (this.eat(LatinSmallLetterV)) { this._lastIntValue = LineTabulation return true } return false } /** * Eat the next characters as a RegExp `ControlLetter` production if * possible. * Set `this._lastIntValue` if it ate the next characters successfully. * ``` * ControlLetter:: one of * 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 * 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 * ``` * @returns `true` if it ate the next characters successfully. */ private eatControlLetter(): boolean { const cp = this.currentCodePoint if (isLatinLetter(cp)) { this.advance() this._lastIntValue = cp % 0x20 return true } return false } /** * Eat the next characters as a RegExp `RegExpUnicodeEscapeSequence` * production if possible. * Set `this._lastIntValue` if it ate the next characters successfully. * ``` * RegExpUnicodeEscapeSequence[U]:: * [+U] `u` LeadSurrogate `\u` TrailSurrogate * [+U] `u` LeadSurrogate * [+U] `u` TrailSurrogate * [+U] `u` NonSurrogate * [~U] `u` Hex4Digits * [+U] `u{` CodePoint `}` * ``` * @returns `true` if it ate the next characters successfully. */ private eatRegExpUnicodeEscapeSequence(forceUFlag = false): boolean { const start = this.index const uFlag = forceUFlag || this._uFlag if (this.eat(LatinSmallLetterU)) { if ( (uFlag && this.eatRegExpUnicodeSurrogatePairEscape()) || this.eatFixedHexDigits(4) || (uFlag && this.eatRegExpUnicodeCodePointEscape()) ) { return true } if (this.strict || uFlag) { this.raise("Invalid unicode escape") } this.rewind(start) } return false } /** * Eat the next characters as the following alternatives if possible. * Set `this._lastIntValue` if it ate the next characters successfully. * ``` * LeadSurrogate `\u` TrailSurrogate * ``` * @returns `true` if it ate the next characters successfully. */ private eatRegExpUnicodeSurrogatePairEscape(): boolean { const start = this.index if (this.eatFixedHexDigits(4)) { const lead = this._lastIntValue if ( isLeadSurrogate(lead) && this.eat(ReverseSolidus) && this.eat(LatinSmallLetterU) && this.eatFixedHexDigits(4) ) { const trail = this._lastIntValue if (isTrailSurrogate(trail)) { this._lastIntValue = combineSurrogatePair(lead, trail) return true } } this.rewind(start) } return false } /** * Eat the next characters as the following alternatives if possible. * Set `this._lastIntValue` if it ate the next characters successfully. * ``` * `{` CodePoint `}` * ``` * @returns `true` if it ate the next characters successfully. */ private eatRegExpUnicodeCodePointEscape(): boolean { const start = this.index if ( this.eat(LeftCurlyBracket) && this.eatHexDigits() && this.eat(RightCurlyBracket) && isValidUnicode(this._lastIntValue) ) { return true } this.rewind(start) return false } /** * Eat the next characters as a RegExp `IdentityEscape` production if * possible. * Set `this._lastIntValue` if it ate the next characters successfully. * ``` * IdentityEscape[U, N]:: * [+U] SyntaxCharacter * [+U] `/` * [strict][~U] SourceCharacter but not UnicodeIDContinue * [annexB][~U] SourceCharacterIdentityEscape[?N] * SourceCharacterIdentityEscape[N]:: * [~N] SourceCharacter but not c * [+N] SourceCharacter but not one of c k * ``` * @returns `true` if it ate the next characters successfully. */ private eatIdentityEscape(): boolean { const cp = this.currentCodePoint if (this.isValidIdentityEscape(cp)) { this._lastIntValue = cp this.advance() return true } return false } private isValidIdentityEscape(cp: number): boolean { if (cp === -1) { return false } if (this._uFlag) { return isSyntaxCharacter(cp) || cp === Solidus } if (this.strict) { return !isIdContinue(cp) } if (this._nFlag) { return !(cp === LatinSmallLetterC || cp === LatinSmallLetterK) } return cp !== LatinSmallLetterC } /** * Eat the next characters as a RegExp `DecimalEscape` production if * possible. * Set `this._lastIntValue` if it ate the next characters successfully. * ``` * DecimalEscape:: * NonZeroDigit DecimalDigits(opt) [lookahead ∉ DecimalDigit] * ``` * @returns `true` if it ate the next characters successfully. */ private eatDecimalEscape(): boolean { this._lastIntValue = 0 let cp = this.currentCodePoint if (cp >= DigitOne && cp <= DigitNine) { do { this._lastIntValue = 10 * this._lastIntValue + (cp - DigitZero) this.advance() } while ( (cp = this.currentCodePoint) >= DigitZero && cp <= DigitNine ) return true } return false } /** * Eat the next characters as a RegExp `UnicodePropertyValueExpression` * production if possible. * Set `this._lastKeyValue` and `this._lastValValue` if it ate the next * characters successfully. * ``` * UnicodePropertyValueExpression:: * UnicodePropertyName `=` UnicodePropertyValue * LoneUnicodePropertyNameOrValue * ``` * @returns `true` if it ate the next characters successfully. */ private eatUnicodePropertyValueExpression(): boolean { const start = this.index // UnicodePropertyName `=` UnicodePropertyValue if (this.eatUnicodePropertyName() && this.eat(EqualsSign)) { this._lastKeyValue = this._lastStrValue if (this.eatUnicodePropertyValue()) { this._lastValValue = this._lastStrValue if ( isValidUnicodeProperty( this.ecmaVersion, this._lastKeyValue, this._lastValValue, ) ) { return true } this.raise("Invalid property name") } } this.rewind(start) // LoneUnicodePropertyNameOrValue if (this.eatLoneUnicodePropertyNameOrValue()) { const nameOrValue = this._lastStrValue if ( isValidUnicodeProperty( this.ecmaVersion, "General_Category", nameOrValue, ) ) { this._lastKeyValue = "General_Category" this._lastValValue = nameOrValue return true } if (isValidLoneUnicodeProperty(this.ecmaVersion, nameOrValue)) { this._lastKeyValue = nameOrValue this._lastValValue = "" return true } this.raise("Invalid property name") } return false } /** * Eat the next characters as a RegExp `UnicodePropertyName` production if * possible. * Set `this._lastStrValue` if it ate the next characters successfully. * ``` * UnicodePropertyName:: * UnicodePropertyNameCharacters * ``` * @returns `true` if it ate the next characters successfully. */ private eatUnicodePropertyName(): boolean { this._lastStrValue = "" while (isUnicodePropertyNameCharacter(this.currentCodePoint)) { this._lastStrValue += String.fromCodePoint(this.currentCodePoint) this.advance() } return this._lastStrValue !== "" } /** * Eat the next characters as a RegExp `UnicodePropertyValue` production if * possible. * Set `this._lastStrValue` if it ate the next characters successfully. * ``` * UnicodePropertyValue:: * UnicodePropertyValueCharacters * ``` * @returns `true` if it ate the next characters successfully. */ private eatUnicodePropertyValue(): boolean { this._lastStrValue = "" while (isUnicodePropertyValueCharacter(this.currentCodePoint)) { this._lastStrValue += String.fromCodePoint(this.currentCodePoint) this.advance() } return this._lastStrValue !== "" } /** * Eat the next characters as a RegExp `UnicodePropertyValue` production if * possible. * Set `this._lastStrValue` if it ate the next characters successfully. * ``` * LoneUnicodePropertyNameOrValue:: * UnicodePropertyValueCharacters * ``` * @returns `true` if it ate the next characters successfully. */ private eatLoneUnicodePropertyNameOrValue(): boolean { return this.eatUnicodePropertyValue() } /** * Eat the next characters as a `HexEscapeSequence` production if possible. * Set `this._lastIntValue` if it ate the next characters successfully. * ``` * HexEscapeSequence:: * `x` HexDigit HexDigit * HexDigit:: one of * 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F * ``` * @returns `true` if it ate the next characters successfully. */ private eatHexEscapeSequence(): boolean { const start = this.index if (this.eat(LatinSmallLetterX)) { if (this.eatFixedHexDigits(2)) { return true } if (this._uFlag || this.strict) { this.raise("Invalid escape") } this.rewind(start) } return false } /** * Eat the next characters as a `DecimalDigits` production if possible. * Set `this._lastIntValue` if it ate the next characters successfully. * ``` * DecimalDigits:: * DecimalDigit * DecimalDigits DecimalDigit * DecimalDigit:: one of * 0 1 2 3 4 5 6 7 8 9 * ``` * @returns `true` if it ate the next characters successfully. */ private eatDecimalDigits(): boolean { const start = this.index this._lastIntValue = 0 while (isDecimalDigit(this.currentCodePoint)) { this._lastIntValue = 10 * this._lastIntValue + digitToInt(this.currentCodePoint) this.advance() } return this.index !== start } /** * Eat the next characters as a `HexDigits` production if possible. * Set `this._lastIntValue` if it ate the next characters successfully. * ``` * HexDigits:: * HexDigit * HexDigits HexDigit * HexDigit:: one of * 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F * ``` * @returns `true` if it ate the next characters successfully. */ private eatHexDigits(): boolean { const start = this.index this._lastIntValue = 0 while (isHexDigit(this.currentCodePoint)) { this._lastIntValue = 16 * this._lastIntValue + digitToInt(this.currentCodePoint) this.advance() } return this.index !== start } /** * Eat the next characters as a `HexDigits` production if possible. * Set `this._lastIntValue` if it ate the next characters successfully. * ``` * LegacyOctalEscapeSequence:: * OctalDigit [lookahead ∉ OctalDigit] * ZeroToThree OctalDigit [lookahead ∉ OctalDigit] * FourToSeven OctalDigit * ZeroToThree OctalDigit OctalDigit * OctalDigit:: one of * 0 1 2 3 4 5 6 7 * ZeroToThree:: one of * 0 1 2 3 * FourToSeven:: one of * 4 5 6 7 * ``` * @returns `true` if it ate the next characters successfully. */ private eatLegacyOctalEscapeSequence(): boolean { if (this.eatOctalDigit()) { const n1 = this._lastIntValue if (this.eatOctalDigit()) { const n2 = this._lastIntValue if (n1 <= 3 && this.eatOctalDigit()) { this._lastIntValue = n1 * 64 + n2 * 8 + this._lastIntValue } else { this._lastIntValue = n1 * 8 + n2 } } else { this._lastIntValue = n1 } return true } return false } /** * Eat the next characters as a `OctalDigit` production if possible. * Set `this._lastIntValue` if it ate the next characters successfully. * ``` * OctalDigit:: one of * 0 1 2 3 4 5 6 7 * ``` * @returns `true` if it ate the next characters successfully. */ private eatOctalDigit(): boolean { const cp = this.currentCodePoint if (isOctalDigit(cp)) { this.advance() this._lastIntValue = cp - DigitZero return true } this._lastIntValue = 0 return false } /** * Eat the next characters as the given number of `HexDigit` productions if * possible. * Set `this._lastIntValue` if it ate the next characters successfully. * ``` * HexDigit:: one of * 0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F * ``` * @returns `true` if it ate the next characters successfully. */ private eatFixedHexDigits(length: number): boolean { const start = this.index this._lastIntValue = 0 for (let i = 0; i < length; ++i) { const cp = this.currentCodePoint if (!isHexDigit(cp)) { this.rewind(start) return false } this._lastIntValue = 16 * this._lastIntValue + digitToInt(cp) this.advance() } return true } }
the_stack
import { ChangeDetectionStrategy, Component, Input, ChangeDetectorRef, ElementRef, Self, Optional, DoCheck } from '@angular/core'; import { ControlValueAccessor, NgControl, NgForm, FormGroupDirective, FormControl } from '@angular/forms'; import { NxCodeInputIntl } from './code-input-intl'; import { ErrorStateMatcher } from '@aposin/ng-aquila/utils'; import { BACKSPACE, LEFT_ARROW, RIGHT_ARROW, SPACE, DOWN_ARROW, UP_ARROW } from '@angular/cdk/keycodes'; import { coerceBooleanProperty, BooleanInput } from '@angular/cdk/coercion'; const DEFAULT_INPUT_LENGTH = 6; const TAG_NAME_INPUT = 'INPUT'; const AUTO_UPPERCASE = 'upper'; const AUTO_LOWERCASE = 'lower'; const INPUT_FIELD_GAP = 'nx-code-input--field-with-gap'; export type NxConversionTypes = 'lower' | 'upper'; @Component({ selector: 'nx-code-input', templateUrl: 'code-input.component.html', styleUrls: [ 'code-input.scss' ], host: { '[class.nx-code-input]': 'true', '[class.has-error]': 'errorState', '[class.is-negative]': 'negative', '[class.is-disabled]': 'disabled', '[attr.tabindex]': '-1' }, changeDetection: ChangeDetectionStrategy.OnPush }) export class NxCodeInputComponent implements ControlValueAccessor, DoCheck { /** Whether the current input of the component has an error. */ errorState: boolean = false; /** The length of the code input. Default: 6. */ @Input('length') set codeLength(value: number) { this._codeLength = value; this.setInputLength(); this._changeDetectorRef.markForCheck(); } get codeLength() { return this._codeLength; } private _codeLength: number = DEFAULT_INPUT_LENGTH; /** The type of HTML input */ @Input() set type(value: string) { this._type = value; this._changeDetectorRef.markForCheck(); } get type() { return this._type; } private _type: string = 'text'; private _isUpDown: boolean = false; /** Sets the tabindex of the contained input elements. */ @Input() set tabindex(value: number) { this._tabindex = value; this._changeDetectorRef.markForCheck(); } get tabindex(): number { return this._tabindex; } private _tabindex: number = 0; /** Whether the form should auto capitalize or lowercase (optional). */ @Input('nxConvertTo') set convertTo(value: NxConversionTypes) { this._convertTo = value; this._changeDetectorRef.markForCheck(); } get convertTo() { return this._convertTo!; } private _convertTo?: NxConversionTypes; /** The user input in array form */ _keyCode: string[] = new Array(DEFAULT_INPUT_LENGTH); private _focused: boolean = false; /** Whether the code input uses the negative set of styling. */ @Input() set negative(value: boolean) { const newValue = coerceBooleanProperty(value); if (this._negative !== newValue) { this._negative = newValue; this._changeDetectorRef.markForCheck(); } } get negative() { return this._negative; } private _negative: boolean = false; /** Whether the code input is disabled. */ @Input() set disabled(value: boolean) { const newValue = coerceBooleanProperty(value); if (this._disabled !== newValue) { this._disabled = newValue; this._changeDetectorRef.markForCheck(); } } get disabled() { return this._disabled; } private _disabled: boolean = false; constructor( private _changeDetectorRef: ChangeDetectorRef, private _el: ElementRef, @Self() @Optional() public _control: NgControl, public _intl: NxCodeInputIntl, private _errorStateMatcher: ErrorStateMatcher, @Optional() private _parentForm: NgForm, @Optional() private _parentFormGroup: FormGroupDirective) { if (this._control) { // Note: we provide the value accessor through here, instead of // the `providers` to avoid running into a circular import. this._control.valueAccessor = this; } } ngDoCheck() { if (this._control) { // We need to re-evaluate this on every change detection cycle, because there are some // error triggers that we can't subscribe to (e.g. parent form submissions). This means // that whatever logic is in here has to be super lean or we risk destroying the performance. this.updateErrorState(); } } /** Sets the length of the input fields. */ setInputLength(): void { if (this.codeLength) { this._keyCode = new Array(this.codeLength); } else { this._keyCode = new Array(DEFAULT_INPUT_LENGTH); } } /** Converts to upper or lowercase when enabled. */ _convertLetterSize(value: any): string | undefined { if (value === 'ß') { return value; } if (typeof value === 'string') { if (this.convertTo === AUTO_UPPERCASE) { return value.toUpperCase(); } else if (this.convertTo === AUTO_LOWERCASE) { return value.toLowerCase(); } return value; } } /** Reacts to keydown event. */ _keydownAction(event: KeyboardEvent): void | false { const targetElement: HTMLInputElement = event.target as HTMLInputElement; const previousInputField: HTMLInputElement = targetElement.previousElementSibling as HTMLInputElement; const nextInputField: HTMLInputElement = targetElement.nextElementSibling as HTMLInputElement; switch (event.keyCode) { case SPACE: return false; case BACKSPACE: if (targetElement.value === '') { if (previousInputField && previousInputField.tagName === TAG_NAME_INPUT) { this.selectInput(previousInputField); } } break; case LEFT_ARROW: if (previousInputField && previousInputField.tagName === TAG_NAME_INPUT) { event.preventDefault(); this.selectInput(previousInputField); } break; case RIGHT_ARROW: if (nextInputField && nextInputField.tagName === TAG_NAME_INPUT) { this.selectInput(nextInputField); } event.preventDefault(); break; case DOWN_ARROW: this._isUpDown = true; if (this._type === 'number' && (targetElement.value === '' || targetElement.value === '0')) { event.preventDefault(); } break; case UP_ARROW: this._isUpDown = true; if (this._type === 'number' && targetElement.value === '9') { event.preventDefault(); } break; default: break; } } /** Selects the value on click of an input field. */ _selectText(event: Event): void { this.selectInput(event.target as HTMLInputElement); } /** Automatically focuses and selects the next input on key input. */ _selectNextInput(event: Event): void { const eventTarget: HTMLInputElement = event.target as HTMLInputElement; eventTarget.value = this._convertLetterSize(eventTarget.value.slice(0, 1)) as string; const currentIndex: number = Number(this._getFocusedInputIndex(event)); // save in model with uppercase if needed this._keyCode[currentIndex] = eventTarget.value; this.propagateChange(this._keyCode.join('')); // don't jump to next input if the user uses UP/DOWn arrow (native behaviour) const focusNextInput = !(this._isUpDown && this.type === 'number'); if (eventTarget.value && focusNextInput) { const nextInputField = eventTarget.nextSibling as HTMLInputElement; if (nextInputField !== null && nextInputField.tagName === TAG_NAME_INPUT) { nextInputField.focus(); if (nextInputField.value !== '') { this.selectInput(nextInputField); } } } this._isUpDown = false; } /** Paste event to distribute content in input fields. */ _pasteClipboard(event: ClipboardEvent): void { let copiedText = (event.clipboardData || (window as any).clipboardData).getData('text'); let copiedTextIndex = 0; const inputIndex: number = Number(this._getFocusedInputIndex(event)); copiedText = this.type === 'number' ? this._formatNumberInput(copiedText) : copiedText; for (let i: number = inputIndex; i < this.codeLength; i++) { this._keyCode[i] = this._convertLetterSize(copiedText[copiedTextIndex]) as string; copiedTextIndex++; } this.propagateChange(this._keyCode.join('')); if (inputIndex + copiedText.length < this.codeLength) { this._el.nativeElement.children.item(inputIndex + copiedText.length).focus(); } else { this._el.nativeElement.children.item(this.codeLength - 1).focus(); } event.preventDefault(); } /** Returns the index of the code input, which is currently focused. */ private _getFocusedInputIndex(event: Event) { let inputIndex; for (let i = 0; i < this._el.nativeElement.children.length; i++) { if (event.srcElement === this._el.nativeElement.children.item(i)) { inputIndex = i; } } return inputIndex; } /** Removes all characters from the input except for numbers [0-9]. */ private _formatNumberInput(copiedText: string) { let formattedInput = ''; for (let i = 0; i < copiedText.length; i++) { if (copiedText[i].match(/[0-9]{1}$/)) { formattedInput += copiedText[i]; } } return formattedInput; } /** Triggers when an input field is blurred. */ _onBlur(): void { this._focused = false; setTimeout(() => { if (!this._focused) { this.propagateTouch(this._keyCode.join('')); } this._changeDetectorRef.markForCheck(); }); } /** Sets _focused state and makes valid. */ _setFocusState(): void { this._focused = true; } /** * Disables the code input. Part of the ControlValueAccessor interface required * to integrate with Angular's core forms API. * * @param isDisabled Sets whether the component is disabled. */ setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; this._changeDetectorRef.markForCheck(); } /** Sets initial value, used by ControlValueAccessor. */ writeValue(value: string): void { if (value) { const valueAsArray = value.split('').slice(0, this.codeLength); for (let i = 0; i < this.codeLength; i++) { this._keyCode[i] = valueAsArray[i]; } } else { this.setInputLength(); } this._changeDetectorRef.markForCheck(); } _trackByKeyCode(index: number, item: string): number { return index; } /** Adds a gap to input fields when appropriate. */ _inputGap(index: number): string { switch (this.codeLength) { case 4: case 6: case 8: if (index === this.codeLength / 2) { return INPUT_FIELD_GAP; } else { return ''; } default: return ''; } } /** @docs-private */ propagateChange = (_: any) => { } /** @docs-private */ propagateTouch = (_: any) => { } registerOnChange(fn: any) { this.propagateChange = fn; } registerOnTouched(fn: any) { this.propagateTouch = fn; } /** @docs-private */ updateErrorState() { const oldState = this.errorState; const parent = this._parentFormGroup || this._parentForm; const control = this._control ? this._control.control as FormControl : null; const newState = this._errorStateMatcher.isErrorState(control, parent); if (newState !== oldState) { this.errorState = newState; } } getAriaLabel(keyIndex: number) { return `${this._intl.inputFieldAriaLabel} ${keyIndex + 1} ${this._intl.ofLabel} ${this._keyCode.length}`; } /** @docs-private * Workaround preventing the selection error because the `setSelectionRange` is not supported on input['type=number'] * */ selectInput(input: HTMLInputElement) { input.focus(); try { input.setSelectionRange(0, input.value.length); } catch (err) { if (err instanceof DOMException && err.name === 'InvalidStateError') { // setSelectionRange does not apply } else { throw err; } } } static ngAcceptInputType_negative: BooleanInput; static ngAcceptInputType_disabled: BooleanInput; }
the_stack
function id(d: any[]): any { return d[0]; } interface NearleyToken { value: any; [key: string]: any; } interface NearleyLexer { reset: (chunk: string, info: any) => void; next: () => NearleyToken | undefined; save: () => any; formatError: (token: NearleyToken) => string; has: (tokenType: string) => boolean; } interface NearleyRule { name: string; symbols: NearleySymbol[]; postprocess?: (d: any[], loc?: number, reject?: {}) => any; } type NearleySymbol = | string | { literal: any } | { test: (token: any) => boolean }; interface Grammar { Lexer: NearleyLexer | undefined; ParserRules: NearleyRule[]; ParserStart: string; } const grammar: Grammar = { Lexer: undefined, ParserRules: [ { name: "_$ebnf$1", symbols: [] }, { name: "_$ebnf$1", symbols: ["_$ebnf$1", "wschar"], postprocess: (d) => d[0].concat([d[1]]), }, { name: "_", symbols: ["_$ebnf$1"], postprocess(d) { return null; }, }, { name: "__$ebnf$1", symbols: ["wschar"] }, { name: "__$ebnf$1", symbols: ["__$ebnf$1", "wschar"], postprocess: (d) => d[0].concat([d[1]]), }, { name: "__", symbols: ["__$ebnf$1"], postprocess(d) { return null; }, }, { name: "wschar", symbols: [/[ \t\n\v\f]/], postprocess: id }, { name: "clause_database_or_schema$subexpression$1", symbols: [/[dD]/, /[aA]/, /[tT]/, /[aA]/, /[bB]/, /[aA]/, /[sS]/, /[eE]/], postprocess(d) { return d.join(""); }, }, { name: "clause_database_or_schema", symbols: ["clause_database_or_schema$subexpression$1", "__"], }, { name: "clause_database_or_schema$subexpression$2", symbols: [/[sS]/, /[cC]/, /[hH]/, /[eE]/, /[mM]/, /[aA]/], postprocess(d) { return d.join(""); }, }, { name: "clause_database_or_schema", symbols: ["clause_database_or_schema$subexpression$2", "__"], }, { name: "clause_if_exists", symbols: [] }, { name: "clause_if_exists$subexpression$1", symbols: [/[iI]/, /[fF]/], postprocess(d) { return d.join(""); }, }, { name: "clause_if_exists$subexpression$2", symbols: [/[eE]/, /[xX]/, /[iI]/, /[sS]/, /[tT]/, /[sS]/], postprocess(d) { return d.join(""); }, }, { name: "clause_if_exists", symbols: [ "clause_if_exists$subexpression$1", "__", "clause_if_exists$subexpression$2", "__", ], }, { name: "clause_if_not_exists", symbols: [] }, { name: "clause_if_not_exists$subexpression$1", symbols: [/[iI]/, /[fF]/], postprocess(d) { return d.join(""); }, }, { name: "clause_if_not_exists$subexpression$2", symbols: [/[nN]/, /[oO]/, /[tT]/], postprocess(d) { return d.join(""); }, }, { name: "clause_if_not_exists$subexpression$3", symbols: [/[eE]/, /[xX]/, /[iI]/, /[sS]/, /[tT]/, /[sS]/], postprocess(d) { return d.join(""); }, }, { name: "clause_if_not_exists", symbols: [ "clause_if_not_exists$subexpression$1", "__", "clause_if_not_exists$subexpression$2", "__", "clause_if_not_exists$subexpression$3", "__", ], }, { name: "name$ebnf$1", symbols: [/[a-z]/] }, { name: "name$ebnf$1", symbols: ["name$ebnf$1", /[a-z]/], postprocess: (d) => d[0].concat([d[1]]), }, { name: "name", symbols: ["name$ebnf$1"], postprocess: (word) => word[0].join(""), }, { name: "name_list", symbols: ["name"] }, { name: "name_list", symbols: ["name_list", "__", { literal: "," }, "name_list", "_"], }, { name: "terminator", symbols: [{ literal: ";" }] }, { name: "equals", symbols: [{ literal: "=" }] }, { name: "optional_equals", symbols: [] }, { name: "optional_equals", symbols: ["equals"] }, { name: "yes", symbols: [{ literal: "Y" }] }, { name: "no", symbols: [{ literal: "N" }] }, { name: "yes_or_no", symbols: ["yes"] }, { name: "yes_or_no", symbols: ["no"] }, { name: "trigger$subexpression$1", symbols: [/[tT]/, /[rR]/, /[iI]/, /[gG]/, /[gG]/, /[eE]/, /[rR]/], postprocess(d) { return d.join(""); }, }, { name: "trigger", symbols: ["trigger$subexpression$1", "__"] }, { name: "statement", symbols: ["drop_statements", "_", "terminator"] }, { name: "drop_statements", symbols: ["drop_table"] }, { name: "drop_statements", symbols: ["drop_database"] }, { name: "drop_statements", symbols: ["drop_function"] }, { name: "drop_statements", symbols: ["drop_procedure"] }, { name: "drop_statements", symbols: ["drop_event"] }, { name: "drop_statements", symbols: ["drop_view"] }, { name: "drop_statements", symbols: ["drop_server"] }, { name: "drop_statements", symbols: ["drop_spatial_reference_system"] }, { name: "drop_statements", symbols: ["drop_logfile_group"] }, { name: "drop_statements", symbols: ["drop_trigger"] }, { name: "drop_table", symbols: [ "keyword", "temporary", "table", "clause_if_exists", "name_list", "clause_end_options", ], }, { name: "drop_database", symbols: [ "keyword", "clause_database_or_schema", "_", "clause_if_exists", "name", ], }, { name: "drop_event", symbols: ["keyword", "event", "clause_if_exists", "name"], }, { name: "drop_function", symbols: ["keyword", "function", "clause_if_exists", "name"], }, { name: "drop_procedure", symbols: ["keyword", "procedure", "clause_if_exists", "name"], }, { name: "drop_view", symbols: [ "keyword", "view", "clause_if_exists", "name_list", "clause_end_options", ], }, { name: "drop_server", symbols: ["keyword", "server", "clause_if_exists", "name"], }, { name: "drop_spatial_reference_system", symbols: [ "keyword", "spatial_reference_system", "clause_if_exists", "name", ], }, { name: "drop_trigger", symbols: ["keyword", "trigger", "clause_if_exists", "name"], postprocess(statement) { return { statement_type: statement[0], trigger: statement[3], }; }, }, { name: "drop_logfile_group", symbols: [ "keyword", "logfile", "group", "name", "__", "engine", "optional_equals", "_", "name", ], postprocess(statement) { return { statement_type: statement[0], logfile: statement[3], engine: statement[8], }; }, }, { name: "keyword$subexpression$1", symbols: [/[dD]/, /[rR]/, /[oO]/, /[pP]/], postprocess(d) { return d.join(""); }, }, { name: "keyword", symbols: ["keyword$subexpression$1", "__"], postprocess: (word) => word.join(""), }, { name: "engine$subexpression$1", symbols: [/[eE]/, /[nN]/, /[gG]/, /[iI]/, /[nN]/, /[eE]/], postprocess(d) { return d.join(""); }, }, { name: "engine", symbols: ["engine$subexpression$1", "__"] }, { name: "logfile$subexpression$1", symbols: [/[lL]/, /[oO]/, /[gG]/, /[fF]/, /[iI]/, /[lL]/, /[eE]/], postprocess(d) { return d.join(""); }, }, { name: "logfile", symbols: ["logfile$subexpression$1", "__"] }, { name: "group$subexpression$1", symbols: [/[gG]/, /[rR]/, /[oO]/, /[uU]/, /[pP]/], postprocess(d) { return d.join(""); }, }, { name: "group", symbols: ["group$subexpression$1", "__"] }, { name: "temporary", symbols: [] }, { name: "temporary$subexpression$1", symbols: [ /[tT]/, /[eE]/, /[mM]/, /[pP]/, /[oO]/, /[rR]/, /[aA]/, /[rR]/, /[yY]/, ], postprocess(d) { return d.join(""); }, }, { name: "temporary", symbols: ["temporary$subexpression$1", "__"] }, { name: "table$subexpression$1", symbols: [/[tT]/, /[aA]/, /[bB]/, /[lL]/, /[eE]/], postprocess(d) { return d.join(""); }, }, { name: "table", symbols: ["table$subexpression$1", "__"] }, { name: "event$subexpression$1", symbols: [/[eE]/, /[vV]/, /[eE]/, /[nN]/, /[tT]/], postprocess(d) { return d.join(""); }, }, { name: "event", symbols: ["event$subexpression$1", "__"] }, { name: "function$subexpression$1", symbols: [/[fF]/, /[uU]/, /[nN]/, /[cC]/, /[tT]/, /[iI]/, /[oO]/, /[nN]/], postprocess(d) { return d.join(""); }, }, { name: "function", symbols: ["function$subexpression$1", "__"] }, { name: "procedure$subexpression$1", symbols: [ /[pP]/, /[rR]/, /[oO]/, /[cC]/, /[eE]/, /[dD]/, /[uU]/, /[rR]/, /[eE]/, ], postprocess(d) { return d.join(""); }, }, { name: "procedure", symbols: ["procedure$subexpression$1", "__"], postprocess: (word) => word.join(""), }, { name: "view$subexpression$1", symbols: [/[vV]/, /[iI]/, /[eE]/, /[wW]/], postprocess(d) { return d.join(""); }, }, { name: "view", symbols: ["view$subexpression$1", "__"] }, { name: "server$subexpression$1", symbols: [/[sS]/, /[eE]/, /[rR]/, /[vV]/, /[eE]/, /[rR]/], postprocess(d) { return d.join(""); }, }, { name: "server", symbols: ["server$subexpression$1", "__"] }, { name: "spatial_reference_system$subexpression$1", symbols: [/[sS]/, /[pP]/, /[aA]/, /[tT]/, /[iI]/, /[aA]/, /[lL]/], postprocess(d) { return d.join(""); }, }, { name: "spatial_reference_system$subexpression$2", symbols: [ /[rR]/, /[eE]/, /[fF]/, /[eE]/, /[rR]/, /[eE]/, /[nN]/, /[cC]/, /[eE]/, ], postprocess(d) { return d.join(""); }, }, { name: "spatial_reference_system$subexpression$3", symbols: [/[sS]/, /[yY]/, /[sS]/, /[tT]/, /[eE]/, /[mM]/], postprocess(d) { return d.join(""); }, }, { name: "spatial_reference_system", symbols: [ "spatial_reference_system$subexpression$1", "__", "spatial_reference_system$subexpression$2", "__", "spatial_reference_system$subexpression$3", "__", ], }, { name: "clause_end_options", symbols: [] }, { name: "clause_end_options$subexpression$1", symbols: [/[rR]/, /[eE]/, /[sS]/, /[tT]/, /[rR]/, /[iI]/, /[cC]/, /[tT]/], postprocess(d) { return d.join(""); }, }, { name: "clause_end_options", symbols: ["__", "clause_end_options$subexpression$1", "__"], }, { name: "clause_end_options$subexpression$2", symbols: [/[cC]/, /[aA]/, /[sS]/, /[cC]/, /[aA]/, /[dD]/, /[eE]/], postprocess(d) { return d.join(""); }, }, { name: "clause_end_options", symbols: ["clause_end_options$subexpression$2", "__"], }, ], ParserStart: "statement", }; export default grammar;
the_stack
import TurmsClient from '../turms-client'; import RequestUtil from '../util/request-util'; import {ParsedModel} from '../model/parsed-model'; import NotificationUtil from '../util/notification-util'; import MessageAddition from '../model/message/message-addition'; import TurmsBusinessError from '../model/turms-business-error'; import BuiltinSystemMessageType from '../model/message/builtin-system-message-type'; import * as Long from 'long' import {UserLocation} from '../model/proto/model/user/user_location'; import {AudioFile} from '../model/proto/model/file/audio_file'; import {VideoFile} from '../model/proto/model/file/video_file'; import {ImageFile} from '../model/proto/model/file/image_file'; import {File} from '../model/proto/model/file/file'; export default class MessageService { /** * Format: "@{userId}" * Example: "@{123}", "I need to talk with @{123} and @{321}" */ private static readonly DEFAULT_MENTIONED_USER_IDS_PARSER = function (message: ParsedModel.Message): string[] { const regex = /@{(\d+?)}/g; if (message.text) { const userIds = []; let matches; while ((matches = regex.exec(message.text))) { userIds.push(matches[1]); } return userIds; } return []; }; private _turmsClient: TurmsClient; private _mentionedUserIdsParser?: (message: ParsedModel.Message) => string[]; private _messageListeners: ((message: ParsedModel.Message, messageAddition: MessageAddition) => void)[] = []; constructor(turmsClient: TurmsClient) { this._turmsClient = turmsClient; this._turmsClient.driver .addNotificationListener(notification => { if (this._messageListeners.length && notification.relayedRequest) { const request = notification.relayedRequest.createMessageRequest; if (request) { const message = MessageService._createMessageRequest2Message(notification.requesterId, request); const addition = this._parseMessageAddition(message); this._messageListeners.forEach(listener => listener(message, addition)); } } return null; }); } addMessageListener(listener: (message: ParsedModel.Message, messageAddition: MessageAddition) => void): void { this._messageListeners.push(listener); } removeMessageListener(listener: (message: ParsedModel.Message, messageAddition: MessageAddition) => void): void { this._messageListeners = this._messageListeners.filter(cur => cur !== listener); } sendMessage( isGroupMessage: boolean, targetId: string, deliveryDate?: Date, text?: string, records?: Uint8Array[], burnAfter?: number): Promise<string> { if (RequestUtil.isFalsy(targetId)) { return TurmsBusinessError.notFalsyPromise('targetId'); } if (RequestUtil.isFalsy(text) && RequestUtil.isFalsy(records)) { return TurmsBusinessError.illegalParamPromise('text and records must not all be null'); } if (!deliveryDate) { deliveryDate = new Date(); } return this._turmsClient.driver.send({ createMessageRequest: { groupId: isGroupMessage ? targetId : undefined, recipientId: !isGroupMessage ? targetId : undefined, deliveryDate: RequestUtil.getDateTimeStr(deliveryDate), text, records: records || [], burnAfter } }).then(n => NotificationUtil.getFirstIdOrThrow(n)); } forwardMessage( messageId: string, isGroupMessage: boolean, targetId: string): Promise<string> { if (RequestUtil.isFalsy(messageId)) { return TurmsBusinessError.notFalsyPromise('messageId'); } if (RequestUtil.isFalsy(targetId)) { return TurmsBusinessError.notFalsyPromise('targetId'); } return this._turmsClient.driver.send({ createMessageRequest: { messageId, groupId: isGroupMessage ? targetId : undefined, recipientId: !isGroupMessage ? targetId : undefined, records: [] } }).then(n => NotificationUtil.getFirstIdOrThrow(n)); } updateSentMessage( messageId: string, text?: string, records?: Uint8Array[]): Promise<void> { if (RequestUtil.isFalsy(messageId)) { return TurmsBusinessError.notFalsyPromise('messageId'); } if (RequestUtil.areAllFalsy(text, records)) { return Promise.resolve(); } return this._turmsClient.driver.send({ updateMessageRequest: { messageId, text, records: records || [] } }).then(() => null); } queryMessages( ids?: string[], areGroupMessages?: boolean, areSystemMessages?: boolean, fromId?: string, deliveryDateAfter?: Date, deliveryDateBefore?: Date, size = 50): Promise<ParsedModel.Message[]> { return this._turmsClient.driver.send({ queryMessagesRequest: { ids: ids || [], areGroupMessages, areSystemMessages, fromId, deliveryDateAfter: RequestUtil.getDateTimeStr(deliveryDateAfter), deliveryDateBefore: RequestUtil.getDateTimeStr(deliveryDateBefore), size, withTotal: false } }).then(n => NotificationUtil.transformOrEmpty(n.data?.messages?.messages)); } queryMessagesWithTotal( ids?: string[], areGroupMessages?: boolean, areSystemMessages?: boolean, fromId?: string, deliveryDateAfter?: Date, deliveryDateBefore?: Date, size = 1): Promise<ParsedModel.MessagesWithTotal[]> { return this._turmsClient.driver.send({ queryMessagesRequest: { ids: ids || [], areGroupMessages, areSystemMessages, fromId, deliveryDateAfter: RequestUtil.getDateTimeStr(deliveryDateAfter), deliveryDateBefore: RequestUtil.getDateTimeStr(deliveryDateBefore), size, withTotal: true } }).then(n => NotificationUtil.transformOrEmpty(n.data?.messagesWithTotalList?.messagesWithTotalList)); } recallMessage(messageId: string, recallDate = new Date()): Promise<void> { if (RequestUtil.isFalsy(messageId)) { return TurmsBusinessError.notFalsyPromise('messageId'); } return this._turmsClient.driver.send({ updateMessageRequest: { messageId, recallDate: RequestUtil.getDateTimeStr(recallDate), records: [] } }).then(() => null); } isMentionEnabled(): boolean { return this._mentionedUserIdsParser != null; } enableMention(mentionedUserIdsParser?: (message: ParsedModel.Message) => string[]): void { if (mentionedUserIdsParser) { this._mentionedUserIdsParser = mentionedUserIdsParser; } else if (!this._mentionedUserIdsParser) { this._mentionedUserIdsParser = MessageService.DEFAULT_MENTIONED_USER_IDS_PARSER; } } static generateLocationRecord( latitude: number, longitude: number, locationName?: string, address?: string ): Uint8Array { RequestUtil.throwIfAnyFalsy(latitude, longitude); return UserLocation.encode({ latitude, longitude, address, name: locationName }).finish(); } static generateAudioRecordByDescription(url: string, duration?: number, format?: string, size?: number): Uint8Array { RequestUtil.throwIfAnyFalsy(url); return AudioFile.encode({ description: { url, duration, format, size, } }).finish(); } static generateAudioRecordByData(data: ArrayBuffer): Uint8Array { RequestUtil.throwIfAnyFalsy(data); return AudioFile.encode({ data: new Uint8Array(data) }).finish(); } static generateVideoRecordByDescription(url: string, duration?: number, format?: string, size?: number): Uint8Array { RequestUtil.throwIfAnyFalsy(url); return VideoFile.encode({ description: { url, duration, format, size, } }).finish(); } static generateVideoRecordByData(data: ArrayBuffer): Uint8Array { RequestUtil.throwIfAnyFalsy(data); return VideoFile.encode({ data: new Uint8Array(data) }).finish(); } public static generateImageRecordByData(data: ArrayBuffer): Uint8Array { RequestUtil.throwIfAnyFalsy(data); return ImageFile.encode({ data: new Uint8Array(data) }).finish(); } static generateImageRecordByDescription(url: string, fileSize?: number, imageSize?: number, original?: boolean): Uint8Array { RequestUtil.throwIfAnyFalsy(url); return ImageFile.encode({ description: { url, fileSize, imageSize, original } }).finish(); } static generateFileRecordByDate(data: ArrayBuffer): Uint8Array { RequestUtil.throwIfAnyFalsy(data); return File.encode({ data: new Uint8Array(data) }).finish(); } static generateFileRecordByDescription(url: string, format?: string, size?: number): Uint8Array { RequestUtil.throwIfAnyFalsy(url); return File.encode({ description: { url, format, size } }).finish(); } private _parseMessageAddition(message: ParsedModel.Message): MessageAddition { const mentionedUserIds = this._mentionedUserIdsParser ? this._mentionedUserIdsParser(message) : []; const isMentioned = mentionedUserIds.indexOf(this._turmsClient.userService.userInfo.userId) >= 0; const systemMessageType = message.isSystemMessage && message.records[0]?.[0]; const recalledMessageIds = []; if (systemMessageType === BuiltinSystemMessageType.RECALL_MESSAGE) { const size = message.records.length; for (let i = 1; i < size; i++) { const id = Long.fromBytes(message.records[i] as any); recalledMessageIds.push(id); } } return new MessageAddition(isMentioned, mentionedUserIds, recalledMessageIds); } /** * @param request should be a parsed im.turms.proto.ICreateMessageRequest */ private static _createMessageRequest2Message(requesterId: string, request: any): ParsedModel.Message { return { id: request.messageId, isSystemMessage: request.isSystemMessage, deliveryDate: request.deliveryDate, text: request.text, records: request.records, senderId: requesterId, groupId: request.groupId, recipientId: request.recipientId } } }
the_stack
import {Cloneable} from './Cloneable'; import {TCModelError} from './errors'; import {GVL} from './GVL'; import {ConsentLanguages, IntMap, PurposeRestrictionVector, Vector} from './model'; import {Purpose} from './model/gvl'; type StringOrNumber = number | string; export type TCModelPropType = number | Date | string | boolean | Vector | PurposeRestrictionVector; export class TCModel extends Cloneable<TCModel> { /** * Set of available consent languages published by the IAB */ public static readonly consentLanguages: ConsentLanguages = GVL.consentLanguages; private isServiceSpecific_ = false; private supportOOB_ = true; private useNonStandardStacks_ = false; private purposeOneTreatment_ = false; private publisherCountryCode_ = 'AA'; private version_ = 2; private consentScreen_: StringOrNumber = 0; private policyVersion_: StringOrNumber = 2; private consentLanguage_ = 'EN'; private cmpId_: StringOrNumber = 0; private cmpVersion_: StringOrNumber = 0; private vendorListVersion_: StringOrNumber = 0; private numCustomPurposes_ = 0; // Member Variable for GVL private gvl_: GVL; public created: Date; public lastUpdated: Date; /** * The TCF designates certain Features as special, that is, a CMP must afford * the user a means to opt in to their use. These Special Features are * published and numbered in the GVL separately from normal Features. * Provides for up to 12 special features. */ public readonly specialFeatureOptins: Vector = new Vector(); /** * Renamed from `PurposesAllowed` in TCF v1.1 * The user’s consent value for each Purpose established on the legal basis * of consent. Purposes are published in the Global Vendor List (see. [[GVL]]). */ public readonly purposeConsents: Vector = new Vector(); /** * The user’s permission for each Purpose established on the legal basis of * legitimate interest. If the user has exercised right-to-object for a * purpose. */ public readonly purposeLegitimateInterests: Vector = new Vector(); /** * The user’s consent value for each Purpose established on the legal basis * of consent, for the publisher. Purposes are published in the Global * Vendor List. */ public readonly publisherConsents: Vector = new Vector(); /** * The user’s permission for each Purpose established on the legal basis of * legitimate interest. If the user has exercised right-to-object for a * purpose. */ public readonly publisherLegitimateInterests: Vector = new Vector(); /** * The user’s consent value for each Purpose established on the legal basis * of consent, for the publisher. Purposes are published in the Global * Vendor List. */ public readonly publisherCustomConsents: Vector = new Vector(); /** * The user’s permission for each Purpose established on the legal basis of * legitimate interest. If the user has exercised right-to-object for a * purpose that is established in the publisher's custom purposes. */ public readonly publisherCustomLegitimateInterests: Vector = new Vector(); /** * set by a publisher if they wish to collect consent and LI Transparency for * purposes outside of the TCF */ public customPurposes: IntMap<Purpose>; /** * Each [[Vendor]] is keyed by id. Their consent value is true if it is in * the Vector */ public readonly vendorConsents: Vector = new Vector(); /** * Each [[Vendor]] is keyed by id. Whether their Legitimate Interests * Disclosures have been established is stored as boolean. * see: [[Vector]] */ public readonly vendorLegitimateInterests: Vector = new Vector(); /** * The value included for disclosed vendors signals which vendors have been * disclosed to the user in the interface surfaced by the CMP. This section * content is required when writing a TC string to the global (consensu) * scope. When a CMP has read from and is updating a TC string from the * global consensu.org storage, the CMP MUST retain the existing disclosure * information and only add information for vendors that it has disclosed * that had not been disclosed by other CMPs in prior interactions with this * device/user agent. */ public readonly vendorsDisclosed: Vector = new Vector(); /** * Signals which vendors the publisher permits to use OOB legal bases. */ public readonly vendorsAllowed: Vector = new Vector(); public readonly publisherRestrictions: PurposeRestrictionVector = new PurposeRestrictionVector(); /** * Constructs the TCModel. Passing a [[GVL]] is optional when constructing * as this TCModel may be constructed from decoding an existing encoded * TCString. * * @param {GVL} [gvl] */ public constructor(gvl?: GVL) { super(); if (gvl) { this.gvl = gvl; } this.created = new Date(); this.updated(); } /** * sets the [[GVL]] with side effects of also setting the `vendorListVersion`, `policyVersion`, and `consentLanguage` * @param {GVL} gvl */ public set gvl(gvl: GVL) { /** * set the reference, but make sure it's our GVL wrapper class. */ if (!(GVL.isInstanceOf(gvl))) { gvl = new GVL(gvl); } this.gvl_ = gvl; this.publisherRestrictions.gvl = gvl; } /** * @return {GVL} the gvl instance set on this TCModel instance */ public get gvl(): GVL { return this.gvl_; } /** * @param {number} integer - A unique ID will be assigned to each Consent * Manager Provider (CMP) from the iab. * * @throws {TCModelError} if the value is not an integer greater than 1 as those are not valid. */ public set cmpId(integer: StringOrNumber) { if (Number.isInteger(+integer) && integer > 1) { this.cmpId_ = +integer; } else { throw new TCModelError('cmpId', integer); } } public get cmpId(): StringOrNumber { return this.cmpId_; } /** * Each change to an operating CMP should receive a * new version number, for logging proof of consent. CmpVersion defined by * each CMP. * * @param {number} integer * * @throws {TCModelError} if the value is not an integer greater than 1 as those are not valid. */ public set cmpVersion(integer: StringOrNumber) { if (Number.isInteger(+integer) && integer > -1) { this.cmpVersion_ = +integer; } else { throw new TCModelError('cmpVersion', integer); } } public get cmpVersion(): StringOrNumber { return this.cmpVersion_; } /** * The screen number is CMP and CmpVersion * specific, and is for logging proof of consent.(For example, a CMP could * keep records so that a publisher can request information about the context * in which consent was gathered.) * * @param {number} integer * * @throws {TCModelError} if the value is not an integer greater than 0 as those are not valid. */ public set consentScreen(integer: StringOrNumber) { if (Number.isInteger(+integer) && integer > -1) { this.consentScreen_ = +integer; } else { throw new TCModelError('consentScreen', integer); } } public get consentScreen(): StringOrNumber { return this.consentScreen_; } /** * @param {string} lang - [two-letter ISO 639-1 language * code](http://www.loc.gov/standards/iso639-2/php/code_list.php) in which * the CMP UI was presented * * @throws {TCModelError} if the value is not a length-2 string of alpha characters */ public set consentLanguage(lang: string) { this.consentLanguage_ = lang; } public get consentLanguage(): string { return this.consentLanguage_; } /** * @param {string} countryCode - [two-letter ISO 3166-1 alpha-2 country * code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the publisher, * determined by the CMP-settings of the publisher. * * @throws {TCModelError} if the value is not a length-2 string of alpha characters */ public set publisherCountryCode(countryCode: string) { if (/^([A-z]){2}$/.test(countryCode)) { this.publisherCountryCode_ = countryCode.toUpperCase(); } else { throw new TCModelError('publisherCountryCode', countryCode); } } public get publisherCountryCode(): string { return this.publisherCountryCode_; } /** * Version of the GVL used to create this TCModel. Global * Vendor List versions will be released periodically. * * @param {number} integer * * @throws {TCModelError} if the value is not an integer greater than 0 as those are not valid. */ public set vendorListVersion(integer: StringOrNumber) { /** * first coerce to a number via leading '+' then take the integer value by * bitshifting to the right. This works on all types in JavaScript and if * it's not valid then value will be 0. */ integer = +integer>>0; if (integer < 0) { throw new TCModelError('vendorListVersion', integer); } else { this.vendorListVersion_ = integer; } } public get vendorListVersion(): StringOrNumber { if (this.gvl) { return this.gvl.vendorListVersion; } else { return this.vendorListVersion_; } } /** * From the corresponding field in the GVL that was * used for obtaining consent. A new policy version invalidates existing * strings and requires CMPs to re-establish transparency and consent from * users. * * If a TCF policy version number is different from the one from the latest * GVL, the CMP must re-establish transparency and consent. * * @param {number} num - You do not need to set this. This comes * directly from the [[GVL]]. * */ public set policyVersion(num: StringOrNumber) { this.policyVersion_ = parseInt(num as string, 10); if (this.policyVersion_ < 0) { throw new TCModelError('policyVersion', num); } } public get policyVersion(): StringOrNumber { if (this.gvl) { return this.gvl.tcfPolicyVersion; } else { return this.policyVersion_; } } public set version(num: StringOrNumber) { this.version_ = parseInt(num as string, 10); } public get version(): StringOrNumber { return this.version_; } /** * Whether the signals encoded in this TC String were from site-specific * storage `true` versus ‘global’ consensu.org shared storage `false`. A * string intended to be stored in global/shared scope but the CMP is unable * to store due to a user agent not accepting third-party cookies would be * considered site-specific `true`. * * @param {boolean} bool - value to set. Some changes to other fields in this * model will automatically change this value like adding publisher * restrictions. */ public set isServiceSpecific(bool: boolean) { this.isServiceSpecific_ = bool; }; public get isServiceSpecific(): boolean { return this.isServiceSpecific_; }; /** * Non-standard stacks means that a CMP is using publisher-customized stack * descriptions. Stacks (in terms of purposes in a stack) are pre-set by the * IAB. As are titles. Descriptions are pre-set, but publishers can customize * them. If they do, they need to set this bit to indicate that they've * customized descriptions. * * @param {boolean} bool - value to set */ public set useNonStandardStacks(bool: boolean) { this.useNonStandardStacks_ = bool; }; public get useNonStandardStacks(): boolean { return this.useNonStandardStacks_; }; /** * Whether or not this publisher supports OOB signaling. On Global TC String * OOB Vendors Disclosed will be included if the publish wishes to no allow * these vendors they should set this to false. * @param {boolean} bool - value to set */ public set supportOOB(bool: boolean) { this.supportOOB_ = bool; }; public get supportOOB(): boolean { return this.supportOOB_; }; /** * `false` There is no special Purpose 1 status. * Purpose 1 was disclosed normally (consent) as expected by Policy. `true` * Purpose 1 not disclosed at all. CMPs use PublisherCC to indicate the * publisher’s country of establishment to help Vendors determine whether the * vendor requires Purpose 1 consent. In global scope TC strings, this field * must always have a value of `false`. When a CMP encounters a global scope * string with `purposeOneTreatment=true` then that string should be * considered invalid and the CMP must re-establish transparency and consent. * * @param {boolean} bool */ public set purposeOneTreatment(bool: boolean) { this.purposeOneTreatment_ = bool; }; public get purposeOneTreatment(): boolean { return this.purposeOneTreatment_; }; /** * setAllVendorConsents - sets all vendors on the GVL Consent (true) * * @return {void} */ public setAllVendorConsents(): void { this.vendorConsents.set(this.gvl.vendors); } /** * unsetAllVendorConsents - unsets all vendors on the GVL Consent (false) * * @return {void} */ public unsetAllVendorConsents(): void { this.vendorConsents.empty(); } /** * setAllVendorsDisclosed - sets all vendors on the GVL Vendors Disclosed (true) * * @return {void} */ public setAllVendorsDisclosed(): void { this.vendorsDisclosed.set(this.gvl.vendors); } /** * unsetAllVendorsDisclosed - unsets all vendors on the GVL Consent (false) * * @return {void} */ public unsetAllVendorsDisclosed(): void { this.vendorsDisclosed.empty(); } /** * setAllVendorsAllowed - sets all vendors on the GVL Consent (true) * * @return {void} */ public setAllVendorsAllowed(): void { this.vendorsAllowed.set(this.gvl.vendors); } /** * unsetAllVendorsAllowed - unsets all vendors on the GVL Consent (false) * * @return {void} */ public unsetAllVendorsAllowed(): void { this.vendorsAllowed.empty(); } /** * setAllVendorLegitimateInterests - sets all vendors on the GVL LegitimateInterests (true) * * @return {void} */ public setAllVendorLegitimateInterests(): void { this.vendorLegitimateInterests.set(this.gvl.vendors); } /** * unsetAllVendorLegitimateInterests - unsets all vendors on the GVL LegitimateInterests (false) * * @return {void} */ public unsetAllVendorLegitimateInterests(): void { this.vendorLegitimateInterests.empty(); } /** * setAllPurposeConsents - sets all purposes on the GVL Consent (true) * * @return {void} */ public setAllPurposeConsents(): void { this.purposeConsents.set(this.gvl.purposes); } /** * unsetAllPurposeConsents - unsets all purposes on the GVL Consent (false) * * @return {void} */ public unsetAllPurposeConsents(): void { this.purposeConsents.empty(); } /** * setAllPurposeLegitimateInterests - sets all purposes on the GVL LI Transparency (true) * * @return {void} */ public setAllPurposeLegitimateInterests(): void { this.purposeLegitimateInterests.set(this.gvl.purposes); } /** * unsetAllPurposeLegitimateInterests - unsets all purposes on the GVL LI Transparency (false) * * @return {void} */ public unsetAllPurposeLegitimateInterests(): void { this.purposeLegitimateInterests.empty(); } /** * setAllSpecialFeatureOptins - sets all special featuresOptins on the GVL (true) * * @return {void} */ public setAllSpecialFeatureOptins(): void { this.specialFeatureOptins.set(this.gvl.specialFeatures); } /** * unsetAllSpecialFeatureOptins - unsets all special featuresOptins on the GVL (true) * * @return {void} */ public unsetAllSpecialFeatureOptins(): void { this.specialFeatureOptins.empty(); } public setAll(): void { this.setAllVendorConsents(); this.setAllPurposeLegitimateInterests(); this.setAllSpecialFeatureOptins(); this.setAllPurposeConsents(); this.setAllVendorLegitimateInterests(); } public unsetAll(): void { this.unsetAllVendorConsents(); this.unsetAllPurposeLegitimateInterests(); this.unsetAllSpecialFeatureOptins(); this.unsetAllPurposeConsents(); this.unsetAllVendorLegitimateInterests(); } public get numCustomPurposes(): StringOrNumber { let len = this.numCustomPurposes_; if (typeof this.customPurposes === 'object') { /** * Keys are not guaranteed to be in order and likewise there is no * requirement that the customPurposes be non-sparse. So we have to sort * and take the highest value. Even if the set only contains 3 purposes * but goes to ID 6 we need to set the number to 6 for the encoding to * work properly since it's positional. */ const purposeIds: string[] = Object.keys(this.customPurposes) .sort((a: string, b: string): number => +a - +b); len = parseInt(purposeIds.pop(), 10); } return len; } public set numCustomPurposes(num: StringOrNumber) { this.numCustomPurposes_ = parseInt(num as string, 10); if (this.numCustomPurposes_ < 0) { throw new TCModelError('numCustomPurposes', num); } } /** * updated - updates the lastUpdatedDate with a 'now' timestamp * * @return {void} */ public updated(): void { this.lastUpdated = new Date(); } }
the_stack
import assert from 'assert'; import { Changes, Connection, isRethinkDBError, r, RCursor, RethinkDBErrorType, } from '../src'; import { RethinkDBConnection } from '../src/connection/connection'; import config from './config'; import { uuid } from './util/common'; function isAsyncIterable(val: any): boolean { if (val === null || val === undefined) { return false; } const isIterable = typeof val[Symbol.iterator] === 'function'; const isAsync = typeof val[Symbol.asyncIterator] === 'function'; return isAsync || isIterable; } describe('cursor', () => { let connection: Connection; let dbName: string; let tableName: string; let tableName2: string; let cursor: RCursor; let result: any; let feed: RCursor; const numDocs = 100; // Number of documents in the "big table" used to test the SUCCESS_PARTIAL const smallNumDocs = 5; // Number of documents in the "small table" before(async () => { await r.connectPool(config); dbName = uuid(); tableName = uuid(); // Big table to test partial sequence tableName2 = uuid(); // small table to test success sequence // delete all but the system dbs await r .dbList() .filter((db) => r.expr(['rethinkdb', 'test']).contains(db).not()) .forEach((db) => r.dbDrop(db)) .run(connection); result = await r.dbCreate(dbName).run(); assert.equal(result.dbs_created, 1); result = await r.db(dbName).tableCreate(tableName).run(); assert.equal(result.tables_created, 1); result = await r.db(dbName).tableCreate(tableName2).run(); assert.equal(result.tables_created, 1); }); after(async () => { await r.getPoolMaster().drain(); }); it('Inserting batch - table 1', async () => { result = await r .db(dbName) .table(tableName) .insert(r.expr(Array(numDocs).fill({}))) .run(); assert.equal(result.inserted, numDocs); }); it('Inserting batch - table 2', async () => { result = await r .db(dbName) .table(tableName2) .insert(r.expr(Array(smallNumDocs).fill({}))) .run(); assert.equal(result.inserted, smallNumDocs); }); it('Updating batch', async () => { result = await r .db(dbName) .table(tableName) .update( { date: r.now().sub(r.random().mul(1000000)), value: r.random(), }, { nonAtomic: true }, ) .run(); assert.equal(result.replaced, 100); }); it('`table` should return a cursor', async () => { cursor = await r.db(dbName).table(tableName).getCursor(); assert(cursor); assert.equal(cursor.toString(), '[object Cursor]'); }); it('`next` should return a document', async () => { result = await cursor.next(); assert(result); assert(result.id); }); it('`each` should work', async () => { cursor = await r.db(dbName).table(tableName).getCursor(); assert(cursor); await new Promise((resolve, reject) => { let count = 0; cursor.each((err) => { if (err) { reject(err); } count++; if (count === numDocs) { resolve(); } }); }); }); it('`each` should work - onFinish - reach end', async () => { cursor = await r.db(dbName).table(tableName).getCursor(); assert(cursor); await new Promise((resolve, reject) => { let count = 0; cursor.each( (err) => { if (err) { reject(err); } count++; }, () => { if (count !== numDocs) { reject( new Error( `expected count (${count}) to equal numDocs (${numDocs})`, ), ); } assert.equal(count, numDocs); resolve(); }, ); }); }); it('`each` should work - onFinish - return false', async () => { cursor = await r.db(dbName).table(tableName).getCursor(); assert(cursor); await new Promise((resolve, reject) => { let count = 0; cursor.each( (err) => { if (err) { reject(err); } count++; return false; }, () => { count === 1 ? resolve() : reject(new Error('expected count to not equal 1')); }, ); }); }); it('`eachAsync` should work', async () => { cursor = await r.db(dbName).table(tableName).getCursor(); assert(cursor); const history = []; let count = 0; let promisesWait = 0; // TODO cleanup await cursor.eachAsync(async () => { history.push(count); count++; await new Promise((resolve, reject) => { setTimeout(() => { history.push(promisesWait); promisesWait--; if (count === numDocs) { const expected = []; for (let i = 0; i < numDocs; i++) { expected.push(i); expected.push(-1 * i); } assert.deepEqual(history, expected); } if (count > numDocs) { reject(new Error(`eachAsync exceeded ${numDocs} iterations`)); } else { resolve(); } }, 1); }); }); }); it('`eachAsync` should work - callback style', async () => { cursor = await r.db(dbName).table(tableName).getCursor(); assert(cursor); let count = 0; const now = Date.now(); const timeout = 10; await cursor.eachAsync((_, onRowFinished) => { count++; setTimeout(onRowFinished, timeout); }); assert.equal(count, 100); const elapsed = Date.now() - now; assert(elapsed >= timeout * count); }); it('`toArray` should work', async () => { cursor = await r.db(dbName).table(tableName).getCursor(); result = await cursor.toArray(); assert.equal(result.length, numDocs); }); it('`toArray` should work - 2', async () => { cursor = await r.db(dbName).table(tableName2).getCursor(); result = await cursor.toArray(); assert.equal(result.length, smallNumDocs); }); it('`toArray` should work -- with a profile', async () => { cursor = await r.db(dbName).table(tableName).getCursor({ profile: true }); result = await cursor.toArray(); assert(Array.isArray(result)); assert.equal(result.length, numDocs); }); it('`toArray` should work with a datum', async () => { cursor = await r.expr([1, 2, 3]).getCursor(); result = await cursor.toArray(); assert(Array.isArray(result)); assert.deepEqual(result, [1, 2, 3]); }); it('`table` should return a cursor - 2', async () => { cursor = await r.db(dbName).table(tableName2).getCursor(); assert(cursor); }); it('`next` should return a document - 2', async () => { result = await cursor.next(); assert(result); assert(result.id); }); it('`next` should work -- testing common pattern', async () => { cursor = await r.db(dbName).table(tableName2).getCursor(); assert(cursor); let i = 0; try { while (true) { result = await cursor.next(); assert(result); i++; } } catch (e) { assert.equal(e.message, 'No more rows in the cursor.'); assert.equal(smallNumDocs, i); } }); it('`cursor.close` should return a promise', async () => { const cursor1 = await r.db(dbName).table(tableName2).getCursor(); await cursor1.close(); }); it('`cursor.close` should still return a promise if the cursor was closed', async () => { cursor = await r.db(dbName).table(tableName2).changes().run(); await cursor.close(); result = cursor.close(); try { result.then(() => undefined); // Promise's contract is to have a `then` method } catch (e) { assert.fail(e); } }); it('cursor should throw if the user try to serialize it in JSON', async () => { cursor = await r.db(dbName).table(tableName).getCursor(); try { // @ts-ignore cursor.toJSON(); } catch (err) { assert.equal(err.message, 'cursor.toJSON is not a function'); } }); it('Remove the field `val` in some docs - 1', async () => { result = await r.db(dbName).table(tableName).update({ val: 1 }).run(); assert.equal(result.replaced, numDocs); result = await r .db(dbName) .table(tableName) .sample(5) .replace((row) => row.without('val')) .run(); assert.equal(result.replaced, 5); }); it('Remove the field `val` in some docs - 2', async () => { result = await r.db(dbName).table(tableName).update({ val: 1 }).run(); result = await r .db(dbName) .table(tableName) .orderBy({ index: r.desc('id') }) .limit(5) .replace((row) => row.without('val')) .run(); assert.equal(result.replaced, 5); }); it('`toArray` with multiple batches - testing empty SUCCESS_COMPLETE', async () => { connection = await r.connect({ host: config.host, port: config.port, user: config.user, password: config.password, }); assert(connection.open); cursor = await r .db(dbName) .table(tableName) .getCursor(connection, { maxBatchRows: 1 }); assert(cursor); result = await cursor.toArray(); assert(Array.isArray(result)); assert.equal(result.length, 100); await connection.close(); assert(!connection.open); }); it('Automatic coercion from cursor to table with multiple batches', async () => { connection = await r.connect({ host: config.host, port: config.port, user: config.user, password: config.password, }); assert(connection.open); result = await r .db(dbName) .table(tableName) .run(connection, { maxBatchRows: 1 }); assert(result.length > 0); await connection.close(); assert(!connection.open); }); it('`next` with multiple batches', async () => { connection = await r.connect({ host: config.host, port: config.port, user: config.user, password: config.password, }); assert(connection.open); cursor = await r .db(dbName) .table(tableName) .getCursor(connection, { maxBatchRows: 1 }); assert(cursor); let i = 0; try { while (true) { result = await cursor.next(); i++; } } catch (e) { if (i > 0 && e.message === 'No more rows in the cursor.') { await connection.close(); assert(!connection.open); } else { assert.fail(e); } } }); it('`next` should error when hitting an error -- not on the first batch', async () => { connection = await r.connect({ host: config.host, port: config.port, user: config.user, password: config.password, }); assert(connection); cursor = await r .db(dbName) .table(tableName) .orderBy({ index: 'id' }) .map((row) => row('val').add(1)) .getCursor(connection, { maxBatchRows: 10 }); assert(cursor); let i = 0; try { while (true) { result = await cursor.next(); i++; } } catch (e) { if (i > 0 && e.message.match(/^No attribute `val` in object/)) { await connection.close(); assert(!connection.open); } else { assert.fail(e); } } }); it('`changes` should return a feed', async () => { feed = await r.db(dbName).table(tableName).changes().run(); assert(feed); assert.equal(feed.toString(), '[object Feed]'); await feed.close(); }); it('`changes` should work with squash: true', async () => { feed = await r.db(dbName).table(tableName).changes({ squash: true }).run(); assert(feed); assert.equal(feed.toString(), '[object Feed]'); await feed.close(); }); it('`get.changes` should return a feed', async () => { feed = await r.db(dbName).table(tableName).get(1).changes().run(); assert(feed); assert.equal(feed.toString(), '[object AtomFeed]'); await feed.close(); }); it('`orderBy.limit.changes` should return a feed', async () => { feed = await r .db(dbName) .table(tableName) .orderBy({ index: 'id' }) .limit(2) .changes() .run(); assert(feed); assert.equal(feed.toString(), '[object OrderByLimitFeed]'); await feed.close(); }); it('`changes` with `includeOffsets` should work', async () => { feed = await r .db(dbName) .table(tableName) .orderBy({ index: 'id' }) .limit(2) .changes({ includeOffsets: true, includeInitial: true, }) .run(); let counter = 0; const promise = new Promise<void>((resolve, reject) => { feed.each((error, change) => { if (error) { reject(error); } assert(typeof change.new_offset === 'number'); if (counter >= 2) { assert(typeof change.old_offset === 'number'); feed.close().then(resolve).catch(reject); } counter++; }); }); await r.db(dbName).table(tableName).insert({ id: 0 }).run(); await promise; }); it('`changes` with `includeTypes` should work', async () => { feed = await r .db(dbName) .table(tableName) .orderBy({ index: 'id' }) .limit(2) .changes({ includeTypes: true, includeInitial: true, }) .run(); let counter = 0; const promise = new Promise<void>((resolve, reject) => { feed.each((error, change) => { if (error) { reject(error); } assert(typeof change.type === 'string'); if (counter > 0) { feed.close().then(resolve).catch(reject); } counter++; }); }); result = await r.db(dbName).table(tableName).insert({ id: 0 }).run(); assert.equal(result.errors, 1); // Duplicate primary key (depends on previous test case) await promise; }); it('`next` should work on a feed', async () => { feed = await r.db(dbName).table(tableName2).changes().run(); assert(feed); const promise = new Promise((resolve, reject) => { let i = 0; while (true) { feed .next() .then(assert) .catch((err) => { if ( isRethinkDBError(err) && err.type === RethinkDBErrorType.CANCEL ) { resolve(); } }); i++; if (i === smallNumDocs) { return feed.close().catch(reject); } } }); await r.db(dbName).table(tableName2).update({ foo: r.now() }).run(); await promise; }); it('`next` should work on an atom feed', async () => { const idValue = uuid(); feed = await r .db(dbName) .table(tableName2) .get(idValue) .changes({ includeInitial: true }) .run(); assert(feed); const promise = new Promise<void>((resolve, reject) => { feed .next() .then((res) => assert.deepEqual(res, { new_val: null })) .then(() => feed.next()) .then((res) => assert.deepEqual(res, { new_val: { id: idValue }, old_val: null }), ) .then(resolve) .catch(reject); }); await r.db(dbName).table(tableName2).insert({ id: idValue }).run(); await promise; await feed.close(); }); it('`close` should work on feed', async () => { feed = await r.db(dbName).table(tableName2).changes().run(); assert(feed); await feed.close(); }); it('`close` should work on feed with events', async () => { feed = await r.db(dbName).table(tableName2).changes().run(); const promise = new Promise((resolve, reject) => { feed.on('error', reject); feed.on('data', () => null).on('end', resolve); }); await feed.close(); await promise; }); it('`on` should work on feed', async () => { feed = await r.db(dbName).table(tableName2).changes().run(); assert(feed); const promise = new Promise<void>((resolve, reject) => { let i = 0; feed.on('data', () => { i++; if (i === smallNumDocs) { feed.close().then(resolve).catch(reject); } }); feed.on('error', reject); }); await r.db(dbName).table(tableName2).update({ foo: r.now() }).run(); await promise; }); it('`on` should work on cursor - a `end` event shoul be eventually emitted on a cursor', async () => { cursor = await r.db(dbName).table(tableName2).getCursor(); assert(cursor); const promise = new Promise((resolve, reject) => { cursor.on('data', () => null).on('end', resolve); cursor.on('error', reject); }); await r.db(dbName).table(tableName2).update({ foo: r.now() }).run(); await promise; }); it('`next`, `each`, `toArray` should be deactivated if the EventEmitter interface is used', async () => { feed = await r.db(dbName).table(tableName2).changes().run(); feed.on('data', () => undefined); feed.on('error', assert.fail); try { await feed.next(); assert.fail('should throw'); } catch (e) { assert( e.message === 'You cannot call `next` once you have bound listeners on the Feed.', ); await feed.close(); } }); it('`each` should not return an error if the feed is closed - 1', async () => { feed = await r.db(dbName).table(tableName2).changes().run(); assert(feed); const promise = new Promise<void>((resolve, reject) => { let count = 0; feed.each((err, res) => { if (err) { reject(err); } if (res.new_val.foo instanceof Date) { count++; } if (count === 1) { setTimeout(() => { feed.close().then(resolve).catch(reject); }, 100); } }); }); await r .db(dbName) .table(tableName2) .limit(2) .update({ foo: r.now() }) .run(); await promise; }); it('`each` should not return an error if the feed is closed - 2', async () => { feed = await r.db(dbName).table(tableName2).changes().run(); assert(feed); const promise = new Promise<void>((resolve, reject) => { let count = 0; feed.each((err, res) => { if (err) { reject(err); } if (res.new_val.foo instanceof Date) { count++; } if (count === 2) { setTimeout(() => { feed.close().then(resolve).catch(reject); }, 100); } }); }); await r .db(dbName) .table(tableName2) .limit(2) .update({ foo: r.now() }) .run(); await promise; }); it('events should not return an error if the feed is closed - 1', async () => { feed = await r.db(dbName).table(tableName2).get(1).changes().run(); assert(feed); const promise = new Promise<void>((resolve, reject) => { feed.each((err, res) => { if (err) { reject(err); } if (res.new_val != null && res.new_val.id === 1) { feed.close().then(resolve).catch(reject); } }); }); await r.db(dbName).table(tableName2).insert({ id: 1 }).run(); await promise; }); it('events should not return an error if the feed is closed - 2', async () => { feed = await r.db(dbName).table(tableName2).changes().run(); assert(feed); const promise = new Promise<void>((resolve, reject) => { let count = 0; feed.on('data', (res) => { if (res.new_val.foo instanceof Date) { count++; } if (count === 1) { setTimeout(() => { feed.close().then(resolve).catch(reject); }, 100); } }); }); await r .db(dbName) .table(tableName2) .limit(2) .update({ foo: r.now() }) .run(); await promise; }); it('`includeStates` should work', async () => { feed = await r .db(dbName) .table(tableName) .orderBy({ index: 'id' }) .limit(10) .changes({ includeStates: true, includeInitial: true }) .run(); let i = 0; await new Promise<void>((resolve, reject) => { feed.each((err) => { if (err) { reject(err); } i++; if (i === 10) { feed.close().then(resolve).catch(reject); } }); }); }); it('`each` should return an error if the connection dies', async () => { connection = await r.connect({ host: config.host, port: config.port, user: config.user, password: config.password, }); assert(connection); const feed1 = await r.db(dbName).table(tableName).changes().run(connection); const promise = feed1.each((err) => { assert( err.message.startsWith( 'The connection was closed before the query could be completed', ), ); }); // Kill the TCP connection const { socket } = (connection as RethinkDBConnection).socket; if (socket) { socket.destroy(); } return promise; }); it('`eachAsync` should return an error if the connection dies', async () => { connection = await r.connect({ host: config.host, port: config.port, user: config.user, password: config.password, }); assert(connection); const feed1 = await r.db(dbName).table(tableName).changes().run(connection); const promise = feed1 .eachAsync(() => undefined) .catch((err) => { assert( err.message.startsWith( 'The connection was closed before the query could be completed', ), ); }); // Kill the TCP connection const { socket } = (connection as RethinkDBConnection).socket; if (socket) { socket.destroy(); } return promise; }); it('cursor should be an async iterator', async () => { connection = await r.connect({ host: config.host, port: config.port, user: config.user, password: config.password, }); assert(connection.open); const feed1 = await r.db(dbName).table(tableName).changes().run(connection); assert(feed1); const iterator = feed1; assert(isAsyncIterable(iterator)); // Kill the TCP connection const { socket } = (connection as RethinkDBConnection).socket; if (socket) { socket.destroy(); } }); it('`asyncIterator` should work', async () => { const feed1 = await r.db(dbName).table(tableName2).changes().run(); assert(feed1); const value = 1; const promise = (async () => { let res: any; for await (const row of feed1 as AsyncIterableIterator<Changes<any>>) { res = row; feed1.close(); } return res; })(); await r.db(dbName).table(tableName2).insert({ foo: value }).run(); result = await promise; assert(result.new_val.foo === value); }); });
the_stack
import { Command } from "commander"; import { log } from "console"; import { IdentityManagementClient, IdentityManagementModels } from "../../api/sdk"; import { throwError } from "../../api/utils"; import { adjustColor, errorLog, getColor, getSdk, homeDirLog, proxyLog, serviceCredentialLog, verboseLog, } from "./command-utils"; let color = getColor("magenta"); let cyan = getColor("cyan"); let yellow = getColor("yellow"); export default (program: Command) => { program .command("identity-management") .alias("iam") .option( "-m, --mode [list|create|assign|remove|delete]", "Mode can be list | create | assign | remove | delete", "list" ) .option("-u, --user [user]", "user name") .option("-g, --group [group]", "user group") .option("-m, --membergroup [membergroup]", "member group") .option("-r, --raw", "don't automatically preceed group names with mdsp_usergroup") .option("-k, --passkey <passkey>", "passkey") .option("-v, --verbose", "verbose output") .description(color("manage mindsphere users and groups *")) .action((options) => { (async () => { try { checkRequiredParameters(options); const sdk = getSdk(options); color = adjustColor(color, options); homeDirLog(options.verbose, color); proxyLog(options.verbose, color); const iam = sdk.GetIdentityManagementClient(); options.mode === "list" && options.user && (await listUsers(iam, options)); options.mode === "list" && options.group && (await listGroups(iam, options)); options.mode === "create" && options.user && (await createUser(iam, options)); options.mode === "create" && options.group && (await createGroup(iam, options)); options.mode === "delete" && options.user && (await deleteUser(iam, options)); options.mode === "delete" && options.group && (await deleteGroup(iam, options)); options.mode === "assign" && (await assign(iam, options)); options.mode === "remove" && (await remove(iam, options)); } catch (err) { errorLog(err, options.verbose); } })(); }) .on("--help", () => { log(`\n Example:\n`); log(` mc iam --mode list --user \t\t list all users`); log(` mc iam --mode list --user prefix \t list all users which start with "prefix"`); log(` mc iam --mode list --group \t\t list all groups`); log(` mc iam --mode list --group prefix \t list all groups which start with "prefix"`); log(`\n mc iam --mode create|delete --group groupName \t create or delete group`); log(` mc iam --mode create|delete --user userName \t create or delete user`); log(`\n mc iam --mode assign --group groupName --user userName \t\t Assign userName to groupName`); log( ` mc iam --mode assign --group groupName --membergroup memberGroupName \t Assign memberGroupName to groupName` ); log(` mc iam --mode remove --group groupName --user userName \t\t Delete userName from groupName`); log( ` mc iam --mode remove --group groupName --membergroup memberGroupName \t Delete memberGroupName from groupName` ); serviceCredentialLog(); }); }; async function listUsers(iam: IdentityManagementClient, options: any) { let startIndex = 0; // for users the startIndex starts at 0 let userCount = 0; let adminCount = 0; let nonAdminCount = 0; do { const filter: any = { attributes: "userName,groups,name", startIndex: startIndex, sortBy: "userName" }; if (options.user !== true) { filter.filter! = `userName sw "${options.user}"`; } const users = await iam.GetUsers(filter); users.resources?.forEach((user) => { userCount++; const groups = user.groups?.filter((x) => x.display === "mdsp:core:TenantAdmin"); const userColor = groups && groups.length ? color : cyan; const admin = groups && groups.length > 0 ? color(`*`) : `-`; groups && groups.length > 0 ? adminCount++ : nonAdminCount++; console.log(`${admin} ${userColor(user.userName)} [${user.groups?.length} groups]`); options.verbose && user.groups?.forEach((grp) => { console.log(`\t - ${grp.display}`); }); }); startIndex = startIndex + users.itemsPerPage! + 1; if (users.totalResults === undefined || startIndex > users.totalResults) break; } while (true); console.log( `Found: ${userCount} users. [${color(adminCount)} tenant admins and ${cyan(nonAdminCount)} non-admin users]` ); } async function listGroups(iam: IdentityManagementClient, options: any) { let startIndex = 1; //for groups start index starts at 1 for some reason let totalGroups = 0; let userGroups = 0; let coreRoles = 0; let otherRoles = 0; do { const filter: any = { startIndex: startIndex, sortBy: "displayName" }; if (options.group !== true) { filter.filter! = `displayName sw "${normalizeGroupName(options.group, options)}"`; } const groups = await iam.GetGroups(filter); for await (const group of groups.resources || []) { const userCount = options.verbose ? `[${group.members?.length} users]` : ""; let displayName = group.displayName || ""; if (displayName.startsWith("mdsp_usergroup:")) { displayName = cyan(group.displayName); userGroups++; } else if (displayName.startsWith("mdsp:core:")) { displayName = color(group.displayName); coreRoles++; } else { displayName = yellow(group.displayName); otherRoles++; } console.log(`${displayName} ${userCount}`); if (options.verbose) { for await (const member of group.members!) { if (member.type === IdentityManagementModels.ScimGroupMember.TypeEnum.USER) { const user = await iam.GetUser(member.value); console.log(`\t ${user.userName}`); } else { const group = await iam.GetGroup(member.value); console.log(`\t ${group.displayName}`); } } } } // console.log(groups); totalGroups = groups.totalResults || 0; startIndex = startIndex + groups.itemsPerPage!; // console.log(startIndex, groups.startIndex, groups.totalResults); if (startIndex > groups.totalResults!) break; } while (true); console.log( `Found: ${totalGroups} groups. [${cyan(userGroups)} user groups, ${color(coreRoles)} core roles and ${yellow( otherRoles )} other roles]` ); } async function createUser(iam: IdentityManagementClient, options: any) { const user = await iam.PostUser({ userName: options.user }); console.log(`user with username ${color(user.userName)} created`); verboseLog(JSON.stringify(user, null, 2), options.verbose); } async function createGroup(iam: IdentityManagementClient, options: any) { const name = normalizeGroupName(options.group, options); const group = await iam.PostGroup({ displayName: name, description: `created using CLI` }); console.log(`group with displayName ${color(group.displayName)} created`); verboseLog(JSON.stringify(group, null, 2), options.verbose); } function normalizeGroupName(name: string, options: any) { if (name === undefined) { return name; } if (!options.raw && !name.startsWith("mdsp_usergroup:")) { name = `mdsp_usergroup:${name}`; } return name; } async function deleteUser(iam: IdentityManagementClient, options: any) { const users = await iam.GetUsers({ filter: `userName eq "${options.user}"` }); if (users.totalResults === 1) { const deletedUser = await iam.DeleteUser(users.resources![0].id!); console.log(`user with username ${color(users.resources![0].userName!)} deleted`); verboseLog(JSON.stringify(deletedUser, null, 2), options.verbose); } else { throwError(`found ${color(users.totalResults)} users users but expected 1 `); } } async function deleteGroup(iam: IdentityManagementClient, options: any) { const groups = await iam.GetGroups({ filter: `displayName eq "${normalizeGroupName(options.group, options)}"` }); if (groups.totalResults === 1) { const deletedGroup = await iam.DeleteGroup(groups.resources![0].id!); console.log(`group ${color(groups.resources![0].displayName!)} deleted`); verboseLog(JSON.stringify(deletedGroup, null, 2), options.verbose); } else { throwError(`found ${color(groups.totalResults)} groups but expected 1 `); } } async function assign(iam: IdentityManagementClient, options: any) { const users = await iam.GetUsers({ filter: `userName eq "${options.user}"` }); const groups = await iam.GetGroups({ filter: `displayName eq "${normalizeGroupName(options.group, options)}"` }); const membergroups = await iam.GetGroups({ filter: `displayName eq "${normalizeGroupName(options.membergroup, options)}"`, }); if (options.user && users.totalResults === 1 && groups.totalResults === 1) { const assigned = await iam.PostGroupMember(groups.resources![0].id!, { type: IdentityManagementModels.ScimGroupMember.TypeEnum.USER, value: users.resources![0].id!, }); console.log(`assigned user ${color(options.user)} to ${color(normalizeGroupName(options.group, options))}`); verboseLog(JSON.stringify(assigned, null, 2), options.verbose); } else if (options.user) { throwError( `found ${color(users.totalResults)} users and ${color(groups.totalResults)} groups but expected 1 of each` ); } else if (options.membergroup && membergroups.totalResults === 1 && groups.totalResults === 1) { const assigned = await iam.PostGroupMember(groups.resources![0].id!, { type: IdentityManagementModels.ScimGroupMember.TypeEnum.GROUP, value: membergroups.resources![0].id!, }); console.log( `assigned member ${color(options.membergroup)} to ${color(normalizeGroupName(options.group, options))}` ); verboseLog(JSON.stringify(assigned, null, 2), options.verbose); } else if (options.membergroup) { throwError( `found ${color(membergroups.totalResults)} membergroups && ${color( groups.totalResults )} groups but expected 1 of each` ); } } async function remove(iam: IdentityManagementClient, options: any) { const users = await iam.GetUsers({ filter: `userName eq "${options.user}"` }); const groups = await iam.GetGroups({ filter: `displayName eq "${normalizeGroupName(options.group, options)}"` }); const membergroups = await iam.GetGroups({ filter: `displayName eq "${normalizeGroupName(options.membergroup, options)}"`, }); if (options.user && users.totalResults === 1 && groups.totalResults === 1) { const assigned = await iam.DeleteGroupMember(groups.resources![0].id!, users.resources![0].id!); console.log(`deleted user ${color(options.user)} from ${color(normalizeGroupName(options.group, options))}`); verboseLog(JSON.stringify(assigned, null, 2), options.verbose); } else if (options.user) { throwError( `found ${color(users.totalResults)} users and ${color(groups.totalResults)} groups but expected 1 of each` ); } else if (options.membergroup && membergroups.totalResults === 1 && groups.totalResults === 1) { const assigned = await iam.DeleteGroupMember(groups.resources![0].id!, membergroups.resources![0].id!); console.log( `deleted member ${color(options.membergroup)} from ${color(normalizeGroupName(options.group, options))}` ); verboseLog(JSON.stringify(assigned, null, 2), options.verbose); } else if (options.membergroup) { throwError( `found ${color(membergroups.totalResults)} membergroups && ${color( groups.totalResults )} groups but expected 1 of each` ); } } function checkRequiredParameters(options: any) { !(["list", "create", "assign", "remove", "delete"].indexOf(options.mode) >= 0) && throwError(`invalid mode ${options.mode} (must be config, list, select or add)`); ["list", "create", "delete"].forEach((x) => { options.mode === x && !options.user && !options.group && throwError(`you have to specify either --user [user] or --group [group] for mc iam --mode ${x} command`); options.mode === x && options.user && options.group && throwError( `you have to specify either --user [user] or --group [group] for mc iam --mode ${x} command but not both` ); }); ["create", "delete", "assign", "remove"].forEach((x) => { options.mode === x && options.user && options.user === true && throwError(`you have to specify full user name for iam --mode ${x} command`); options.mode === x && options.group && options.group === true && throwError(`you have to specify full user name for iam --mode ${x} command`); }); ["assign", "remove"].forEach((x) => { options.mode === x && (options.group === true || !options.group) && throwError(`you have to specify --group [group] iam --mode ${x} command`); options.mode === x && options.user && options.membergroup && throwError( `you have to specify --user [user] or --membergroup [membergroup] iam --mode ${x} command but not both` ); options.mode === x && !options.user && !options.membergroup && throwError( `you have to specify either --user [user] or --membergroup [membergroup] iam --mode ${x} command ` ); options.mode === x && (options.user === true || options.membergroup === true) && throwError( `you have to specify either --user [user] or --membergroup [membergroup] iam --mode ${x} command (no empty parameters)` ); }); }
the_stack
import React from 'react'; import { AuthType, IAuthData } from 'matrix-js-sdk/src/interactive-auth'; import { logger } from "matrix-js-sdk/src/logger"; import Analytics from '../../../Analytics'; import { MatrixClientPeg } from '../../../MatrixClientPeg'; import * as Lifecycle from '../../../Lifecycle'; import { _t } from '../../../languageHandler'; import InteractiveAuth, { ERROR_USER_CANCELLED } from "../../structures/InteractiveAuth"; import { DEFAULT_PHASE, PasswordAuthEntry, SSOAuthEntry } from "../auth/InteractiveAuthEntryComponents"; import StyledCheckbox from "../elements/StyledCheckbox"; import { replaceableComponent } from "../../../utils/replaceableComponent"; import BaseDialog from "./BaseDialog"; interface IProps { onFinished: (success: boolean) => void; } interface IState { shouldErase: boolean; errStr: string; authData: any; // for UIA authEnabled: boolean; // see usages for information // A few strings that are passed to InteractiveAuth for design or are displayed // next to the InteractiveAuth component. bodyText: string; continueText: string; continueKind: string; } @replaceableComponent("views.dialogs.DeactivateAccountDialog") export default class DeactivateAccountDialog extends React.Component<IProps, IState> { constructor(props) { super(props); this.state = { shouldErase: false, errStr: null, authData: null, // for UIA authEnabled: true, // see usages for information // A few strings that are passed to InteractiveAuth for design or are displayed // next to the InteractiveAuth component. bodyText: null, continueText: null, continueKind: null, }; this.initAuth(/* shouldErase= */false); } private onStagePhaseChange = (stage: AuthType, phase: string): void => { const dialogAesthetics = { [SSOAuthEntry.PHASE_PREAUTH]: { body: _t("Confirm your account deactivation by using Single Sign On to prove your identity."), continueText: _t("Single Sign On"), continueKind: "danger", }, [SSOAuthEntry.PHASE_POSTAUTH]: { body: _t("Are you sure you want to deactivate your account? This is irreversible."), continueText: _t("Confirm account deactivation"), continueKind: "danger", }, }; // This is the same as aestheticsForStagePhases in InteractiveAuthDialog minus the `title` const DEACTIVATE_AESTHETICS = { [SSOAuthEntry.LOGIN_TYPE]: dialogAesthetics, [SSOAuthEntry.UNSTABLE_LOGIN_TYPE]: dialogAesthetics, [PasswordAuthEntry.LOGIN_TYPE]: { [DEFAULT_PHASE]: { body: _t("To continue, please enter your password:"), }, }, }; const aesthetics = DEACTIVATE_AESTHETICS[stage]; let bodyText = null; let continueText = null; let continueKind = null; if (aesthetics) { const phaseAesthetics = aesthetics[phase]; if (phaseAesthetics && phaseAesthetics.body) bodyText = phaseAesthetics.body; if (phaseAesthetics && phaseAesthetics.continueText) continueText = phaseAesthetics.continueText; if (phaseAesthetics && phaseAesthetics.continueKind) continueKind = phaseAesthetics.continueKind; } this.setState({ bodyText, continueText, continueKind }); }; private onUIAuthFinished = (success: boolean, result: Error) => { if (success) return; // great! makeRequest() will be called too. if (result === ERROR_USER_CANCELLED) { this.onCancel(); return; } logger.error("Error during UI Auth:", { result }); this.setState({ errStr: _t("There was a problem communicating with the server. Please try again.") }); }; private onUIAuthComplete = (auth: IAuthData): void => { // XXX: this should be returning a promise to maintain the state inside the state machine correct // but given that a deactivation is followed by a local logout and all object instances being thrown away // this isn't done. MatrixClientPeg.get().deactivateAccount(auth, this.state.shouldErase).then(r => { // Deactivation worked - logout & close this dialog Analytics.trackEvent('Account', 'Deactivate Account'); Lifecycle.onLoggedOut(); this.props.onFinished(true); }).catch(e => { logger.error(e); this.setState({ errStr: _t("There was a problem communicating with the server. Please try again.") }); }); }; private onEraseFieldChange = (ev: React.FormEvent<HTMLInputElement>): void => { this.setState({ shouldErase: ev.currentTarget.checked, // Disable the auth form because we're going to have to reinitialize the auth // information. We do this because we can't modify the parameters in the UIA // session, and the user will have selected something which changes the request. // Therefore, we throw away the last auth session and try a new one. authEnabled: false, }); // As mentioned above, set up for auth again to get updated UIA session info this.initAuth(/* shouldErase= */ev.currentTarget.checked); }; private onCancel(): void { this.props.onFinished(false); } private initAuth(shouldErase: boolean): void { MatrixClientPeg.get().deactivateAccount(null, shouldErase).then(r => { // If we got here, oops. The server didn't require any auth. // Our application lifecycle will catch the error and do the logout bits. // We'll try to log something in an vain attempt to record what happened (storage // is also obliterated on logout). logger.warn("User's account got deactivated without confirmation: Server had no auth"); this.setState({ errStr: _t("Server did not require any authentication") }); }).catch(e => { if (e && e.httpStatus === 401 && e.data) { // Valid UIA response this.setState({ authData: e.data, authEnabled: true }); } else { this.setState({ errStr: _t("Server did not return valid authentication information.") }); } }); } public render() { let error = null; if (this.state.errStr) { error = <div className="error"> { this.state.errStr } </div>; } let auth = <div>{ _t("Loading...") }</div>; if (this.state.authData && this.state.authEnabled) { auth = ( <div> { this.state.bodyText } <InteractiveAuth matrixClient={MatrixClientPeg.get()} authData={this.state.authData} // XXX: onUIAuthComplete breaches the expected method contract, it gets away with it because it // knows the entire app is about to die as a result of the account deactivation. makeRequest={this.onUIAuthComplete as any} onAuthFinished={this.onUIAuthFinished} onStagePhaseChange={this.onStagePhaseChange} continueText={this.state.continueText} continueKind={this.state.continueKind} /> </div> ); } // this is on purpose not a <form /> to prevent Enter triggering submission, to further prevent accidents return ( <BaseDialog className="mx_DeactivateAccountDialog" onFinished={this.props.onFinished} titleClass="danger" title={_t("Deactivate Account")} > <div className="mx_Dialog_content"> <p>{ _t( "This will make your account permanently unusable. " + "You will not be able to log in, and no one will be able to re-register the same " + "user ID. " + "This will cause your account to leave all rooms it is participating in, and it " + "will remove your account details from your identity server. " + "<b>This action is irreversible.</b>", {}, { b: (sub) => <b> { sub } </b> }, ) }</p> <p>{ _t( "Deactivating your account <b>does not by default cause us to forget messages you " + "have sent.</b> " + "If you would like us to forget your messages, please tick the box below.", {}, { b: (sub) => <b> { sub } </b> }, ) }</p> <p>{ _t( "Message visibility in Matrix is similar to email. " + "Our forgetting your messages means that messages you have sent will not be shared " + "with any new or unregistered users, but registered users who already have access " + "to these messages will still have access to their copy.", ) }</p> <div className="mx_DeactivateAccountDialog_input_section"> <p> <StyledCheckbox checked={this.state.shouldErase} onChange={this.onEraseFieldChange} > { _t( "Please forget all messages I have sent when my account is deactivated " + "(<b>Warning:</b> this will cause future users to see an incomplete view " + "of conversations)", {}, { b: (sub) => <b>{ sub }</b> }, ) } </StyledCheckbox> </p> { error } { auth } </div> </div> </BaseDialog> ); } }
the_stack
import { Injectable } from '@angular/core'; import { CoreError } from '@classes/errors/error'; import { SQLiteDBRecordValues } from '@classes/sqlitedb'; import { CoreFile } from '@services/file'; import { CoreSites } from '@services/sites'; import { CoreTextUtils } from '@services/utils/text'; import { CoreTimeUtils } from '@services/utils/time'; import { makeSingleton } from '@singletons'; import { CoreText } from '@singletons/text'; import { AddonModAssignOutcomes, AddonModAssignSavePluginData } from './assign'; import { AddonModAssignSubmissionsDBRecord, AddonModAssignSubmissionsGradingDBRecord, SUBMISSIONS_GRADES_TABLE, SUBMISSIONS_TABLE, } from './database/assign'; /** * Service to handle offline assign. */ @Injectable({ providedIn: 'root' }) export class AddonModAssignOfflineProvider { /** * Delete a submission. * * @param assignId Assignment ID. * @param userId User ID. If not defined, site's current user. * @param siteId Site ID. If not defined, current site. * @return Promise resolved if deleted, rejected if failure. */ async deleteSubmission(assignId: number, userId?: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); await site.getDb().deleteRecords( SUBMISSIONS_TABLE, { assignid: assignId, userid: userId }, ); } /** * Delete a submission grade. * * @param assignId Assignment ID. * @param userId User ID. If not defined, site's current user. * @param siteId Site ID. If not defined, current site. * @return Promise resolved if deleted, rejected if failure. */ async deleteSubmissionGrade(assignId: number, userId?: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); await site.getDb().deleteRecords( SUBMISSIONS_GRADES_TABLE, { assignid: assignId, userid: userId }, ); } /** * Get all the assignments ids that have something to be synced. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved with assignments id that have something to be synced. */ async getAllAssigns(siteId?: string): Promise<number[]> { const promises: Promise<AddonModAssignSubmissionsDBRecordFormatted[] | AddonModAssignSubmissionsGradingDBRecordFormatted[]>[] = []; promises.push(this.getAllSubmissions(siteId)); promises.push(this.getAllSubmissionsGrade(siteId)); const results = await Promise.all(promises); // Flatten array. const flatten: (AddonModAssignSubmissionsDBRecord | AddonModAssignSubmissionsGradingDBRecord)[] = [].concat.apply([], results); // Get assign id. let assignIds: number[] = flatten.map((assign) => assign.assignid); // Get unique values. assignIds = assignIds.filter((id, pos) => assignIds.indexOf(id) == pos); return assignIds; } /** * Get all the stored submissions from all the assignments. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved with submissions. */ protected async getAllSubmissions(siteId?: string): Promise<AddonModAssignSubmissionsDBRecordFormatted[]> { return this.getAssignSubmissionsFormatted(undefined, siteId); } /** * Get all the stored submissions for a certain assignment. * * @param assignId Assignment ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with submissions. */ async getAssignSubmissions(assignId: number, siteId?: string): Promise<AddonModAssignSubmissionsDBRecordFormatted[]> { return this.getAssignSubmissionsFormatted({ assignid: assignId }, siteId); } /** * Convenience helper function to get stored submissions formatted. * * @param conditions Query conditions. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with submissions. */ protected async getAssignSubmissionsFormatted( conditions: SQLiteDBRecordValues = {}, siteId?: string, ): Promise<AddonModAssignSubmissionsDBRecordFormatted[]> { const db = await CoreSites.getSiteDb(siteId); const submissions: AddonModAssignSubmissionsDBRecord[] = await db.getRecords(SUBMISSIONS_TABLE, conditions); // Parse the plugin data. return submissions.map((submission) => ({ assignid: submission.assignid, userid: submission.userid, courseid: submission.courseid, plugindata: CoreTextUtils.parseJSON<AddonModAssignSavePluginData>(submission.plugindata, {}), onlinetimemodified: submission.onlinetimemodified, timecreated: submission.timecreated, timemodified: submission.timemodified, submitted: submission.submitted, submissionstatement: submission.submissionstatement, })); } /** * Get all the stored submissions grades from all the assignments. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved with submissions grades. */ protected async getAllSubmissionsGrade(siteId?: string): Promise<AddonModAssignSubmissionsGradingDBRecordFormatted[]> { return this.getAssignSubmissionsGradeFormatted(undefined, siteId); } /** * Get all the stored submissions grades for a certain assignment. * * @param assignId Assignment ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with submissions grades. */ async getAssignSubmissionsGrade( assignId: number, siteId?: string, ): Promise<AddonModAssignSubmissionsGradingDBRecordFormatted[]> { return this.getAssignSubmissionsGradeFormatted({ assignid: assignId }, siteId); } /** * Convenience helper function to get stored submissions grading formatted. * * @param conditions Query conditions. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with submissions grades. */ protected async getAssignSubmissionsGradeFormatted( conditions: SQLiteDBRecordValues = {}, siteId?: string, ): Promise<AddonModAssignSubmissionsGradingDBRecordFormatted[]> { const db = await CoreSites.getSiteDb(siteId); const submissions: AddonModAssignSubmissionsGradingDBRecord[] = await db.getRecords(SUBMISSIONS_GRADES_TABLE, conditions); // Parse the plugin data and outcomes. return submissions.map((submission) => ({ assignid: submission.assignid, userid: submission.userid, courseid: submission.courseid, grade: submission.grade, attemptnumber: submission.attemptnumber, addattempt: submission.addattempt, workflowstate: submission.workflowstate, applytoall: submission.applytoall, outcomes: CoreTextUtils.parseJSON<AddonModAssignOutcomes>(submission.outcomes, {}), plugindata: CoreTextUtils.parseJSON<AddonModAssignSavePluginData>(submission.plugindata, {}), timemodified: submission.timemodified, })); } /** * Get a stored submission. * * @param assignId Assignment ID. * @param userId User ID. If not defined, site's current user. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with submission. */ async getSubmission(assignId: number, userId?: number, siteId?: string): Promise<AddonModAssignSubmissionsDBRecordFormatted> { userId = userId || CoreSites.getCurrentSiteUserId(); const submissions = await this.getAssignSubmissionsFormatted({ assignid: assignId, userid: userId }, siteId); if (submissions.length) { return submissions[0]; } throw new CoreError('No records found.'); } /** * Get the path to the folder where to store files for an offline submission. * * @param assignId Assignment ID. * @param userId User ID. If not defined, site's current user. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the path. */ async getSubmissionFolder(assignId: number, userId?: number, siteId?: string): Promise<string> { const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); const siteFolderPath = CoreFile.getSiteFolder(site.getId()); const submissionFolderPath = 'offlineassign/' + assignId + '/' + userId; return CoreText.concatenatePaths(siteFolderPath, submissionFolderPath); } /** * Get a stored submission grade. * Submission grades are not identified using attempt number so it can retrieve the feedback for a previous attempt. * * @param assignId Assignment ID. * @param userId User ID. If not defined, site's current user. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with submission grade. */ async getSubmissionGrade( assignId: number, userId?: number, siteId?: string, ): Promise<AddonModAssignSubmissionsGradingDBRecordFormatted> { userId = userId || CoreSites.getCurrentSiteUserId(); const submissions = await this.getAssignSubmissionsGradeFormatted({ assignid: assignId, userid: userId }, siteId); if (submissions.length) { return submissions[0]; } throw new CoreError('No records found.'); } /** * Get the path to the folder where to store files for a certain plugin in an offline submission. * * @param assignId Assignment ID. * @param pluginName Name of the plugin. Must be unique (both in submission and feedback plugins). * @param userId User ID. If not defined, site's current user. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the path. */ async getSubmissionPluginFolder(assignId: number, pluginName: string, userId?: number, siteId?: string): Promise<string> { const folderPath = await this.getSubmissionFolder(assignId, userId, siteId); return CoreText.concatenatePaths(folderPath, pluginName); } /** * Check if the assignment has something to be synced. * * @param assignId Assignment ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with boolean: whether the assignment has something to be synced. */ async hasAssignOfflineData(assignId: number, siteId?: string): Promise<boolean> { const promises: Promise<AddonModAssignSubmissionsDBRecordFormatted[] | AddonModAssignSubmissionsGradingDBRecordFormatted[]>[] = []; promises.push(this.getAssignSubmissions(assignId, siteId)); promises.push(this.getAssignSubmissionsGrade(assignId, siteId)); try { const results = await Promise.all(promises); return results.some((result) => result.length); } catch { // No offline data found. return false; } } /** * Mark/Unmark a submission as being submitted. * * @param assignId Assignment ID. * @param courseId Course ID the assign belongs to. * @param submitted True to mark as submitted, false to mark as not submitted. * @param acceptStatement True to accept the submission statement, false otherwise. * @param timemodified The time the submission was last modified in online. * @param userId User ID. If not defined, site's current user. * @param siteId Site ID. If not defined, current site. * @return Promise resolved if marked, rejected if failure. */ async markSubmitted( assignId: number, courseId: number, submitted: boolean, acceptStatement: boolean, timemodified: number, userId?: number, siteId?: string, ): Promise<number> { const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); let submission: AddonModAssignSubmissionsDBRecord; try { const savedSubmission: AddonModAssignSubmissionsDBRecordFormatted = await this.getSubmission(assignId, userId, site.getId()); submission = Object.assign(savedSubmission, { plugindata: savedSubmission.plugindata ? JSON.stringify(savedSubmission.plugindata) : '{}', submitted: submitted ? 1 : 0, // Mark the submission. submissionstatement: acceptStatement ? 1 : 0, // Mark the submission. }); } catch { // No submission, create an empty one. const now = CoreTimeUtils.timestamp(); submission = { assignid: assignId, courseid: courseId, userid: userId, onlinetimemodified: timemodified, timecreated: now, timemodified: now, plugindata: '{}', submitted: submitted ? 1 : 0, // Mark the submission. submissionstatement: acceptStatement ? 1 : 0, // Mark the submission. }; } return await site.getDb().insertRecord(SUBMISSIONS_TABLE, submission); } /** * Save a submission to be sent later. * * @param assignId Assignment ID. * @param courseId Course ID the assign belongs to. * @param pluginData Data to save. * @param timemodified The time the submission was last modified in online. * @param submitted True if submission has been submitted, false otherwise. * @param userId User ID. If not defined, site's current user. * @param siteId Site ID. If not defined, current site. * @return Promise resolved if stored, rejected if failure. */ async saveSubmission( assignId: number, courseId: number, pluginData: AddonModAssignSavePluginData, timemodified: number, submitted: boolean, userId?: number, siteId?: string, ): Promise<number> { const site = await CoreSites.getSite(siteId); userId = userId || site.getUserId(); const now = CoreTimeUtils.timestamp(); const entry: AddonModAssignSubmissionsDBRecord = { assignid: assignId, courseid: courseId, plugindata: pluginData ? JSON.stringify(pluginData) : '{}', userid: userId, submitted: submitted ? 1 : 0, timecreated: now, timemodified: now, onlinetimemodified: timemodified, }; return await site.getDb().insertRecord(SUBMISSIONS_TABLE, entry); } /** * Save a grading to be sent later. * * @param assignId Assign ID. * @param userId User ID. * @param courseId Course ID the assign belongs to. * @param grade Grade to submit. * @param attemptNumber Number of the attempt being graded. * @param addAttempt Admit the user to attempt again. * @param workflowState Next workflow State. * @param applyToAll If it's a team submission, whether the grade applies to all group members. * @param outcomes Object including all outcomes values. If empty, any of them will be sent. * @param pluginData Plugin data to save. * @param siteId Site ID. If not defined, current site. * @return Promise resolved if stored, rejected if failure. */ async submitGradingForm( assignId: number, userId: number, courseId: number, grade: number, attemptNumber: number, addAttempt: boolean, workflowState: string, applyToAll: boolean, outcomes: AddonModAssignOutcomes, pluginData: AddonModAssignSavePluginData, siteId?: string, ): Promise<number> { const site = await CoreSites.getSite(siteId); const now = CoreTimeUtils.timestamp(); const entry: AddonModAssignSubmissionsGradingDBRecord = { assignid: assignId, userid: userId, courseid: courseId, grade: grade, attemptnumber: attemptNumber, addattempt: addAttempt ? 1 : 0, workflowstate: workflowState, applytoall: applyToAll ? 1 : 0, outcomes: outcomes ? JSON.stringify(outcomes) : '{}', plugindata: pluginData ? JSON.stringify(pluginData) : '{}', timemodified: now, }; return await site.getDb().insertRecord(SUBMISSIONS_GRADES_TABLE, entry); } } export const AddonModAssignOffline = makeSingleton(AddonModAssignOfflineProvider); export type AddonModAssignSubmissionsDBRecordFormatted = Omit<AddonModAssignSubmissionsDBRecord, 'plugindata'> & { plugindata: AddonModAssignSavePluginData; }; export type AddonModAssignSubmissionsGradingDBRecordFormatted = Omit<AddonModAssignSubmissionsGradingDBRecord, 'plugindata'|'outcomes'> & { plugindata: AddonModAssignSavePluginData; outcomes: AddonModAssignOutcomes; };
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement, Operator } from "../shared"; /** * Statement provider for service [lex](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonlex.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Lex extends PolicyStatement { public servicePrefix = 'lex'; /** * Statement provider for service [lex](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonlex.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Creates a new version based on the $LATEST version of the specified bot. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_CreateBotVersion.html */ public toCreateBotVersion() { return this.to('CreateBotVersion'); } /** * Creates a new version based on the $LATEST version of the specified intent. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_CreateIntentVersion.html */ public toCreateIntentVersion() { return this.to('CreateIntentVersion'); } /** * Creates a new version based on the $LATEST version of the specified slot type. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_CreateSlotTypeVersion.html */ public toCreateSlotTypeVersion() { return this.to('CreateSlotTypeVersion'); } /** * Deletes all versions of a bot. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_DeleteBot.html */ public toDeleteBot() { return this.to('DeleteBot'); } /** * Deletes an alias for a specific bot. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_DeleteBotAlias.html */ public toDeleteBotAlias() { return this.to('DeleteBotAlias'); } /** * Deletes the association between a Amazon Lex bot alias and a messaging platform. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_DeleteBotChannelAssociation.html */ public toDeleteBotChannelAssociation() { return this.to('DeleteBotChannelAssociation'); } /** * Deletes a specific version of a bot. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_DeleteBotVersion.html */ public toDeleteBotVersion() { return this.to('DeleteBotVersion'); } /** * Deletes all versions of an intent. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_DeleteIntent.html */ public toDeleteIntent() { return this.to('DeleteIntent'); } /** * Deletes a specific version of an intent. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_DeleteIntentVersion.html */ public toDeleteIntentVersion() { return this.to('DeleteIntentVersion'); } /** * Removes session information for a specified bot, alias, and user ID. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_runtime_DeleteSession.html */ public toDeleteSession() { return this.to('DeleteSession'); } /** * Deletes all versions of a slot type. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_DeleteSlotType.html */ public toDeleteSlotType() { return this.to('DeleteSlotType'); } /** * Deletes a specific version of a slot type. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_DeleteSlotTypeVersion.html */ public toDeleteSlotTypeVersion() { return this.to('DeleteSlotTypeVersion'); } /** * Deletes the information Amazon Lex maintains for utterances on a specific bot and userId. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_DeleteUtterances.html */ public toDeleteUtterances() { return this.to('DeleteUtterances'); } /** * Returns information for a specific bot. In addition to the bot name, the bot version or alias is required. * * Access Level: Read * * https://docs.aws.amazon.com/lex/latest/dg/API_GetBot.html */ public toGetBot() { return this.to('GetBot'); } /** * Returns information about a Amazon Lex bot alias. * * Access Level: Read * * https://docs.aws.amazon.com/lex/latest/dg/API_GetBotAlias.html */ public toGetBotAlias() { return this.to('GetBotAlias'); } /** * Returns a list of aliases for a given Amazon Lex bot. * * Access Level: List * * https://docs.aws.amazon.com/lex/latest/dg/API_GetBotAliases.html */ public toGetBotAliases() { return this.to('GetBotAliases'); } /** * Returns information about the association between a Amazon Lex bot and a messaging platform. * * Access Level: Read * * https://docs.aws.amazon.com/lex/latest/dg/API_GetBotChannelAssociation.html */ public toGetBotChannelAssociation() { return this.to('GetBotChannelAssociation'); } /** * Returns a list of all of the channels associated with a single bot. * * Access Level: List * * https://docs.aws.amazon.com/lex/latest/dg/API_GetBotChannelAssociations.html */ public toGetBotChannelAssociations() { return this.to('GetBotChannelAssociations'); } /** * Returns information for all versions of a specific bot. * * Access Level: List * * https://docs.aws.amazon.com/lex/latest/dg/API_GetBotVersions.html */ public toGetBotVersions() { return this.to('GetBotVersions'); } /** * Returns information for the $LATEST version of all bots, subject to filters provided by the client. * * Access Level: List * * https://docs.aws.amazon.com/lex/latest/dg/API_GetBots.html */ public toGetBots() { return this.to('GetBots'); } /** * Returns information about a built-in intent. * * Access Level: Read * * https://docs.aws.amazon.com/lex/latest/dg/API_GetBuiltinIntent.html */ public toGetBuiltinIntent() { return this.to('GetBuiltinIntent'); } /** * Gets a list of built-in intents that meet the specified criteria. * * Access Level: Read * * https://docs.aws.amazon.com/lex/latest/dg/API_GetBuiltinIntents.html */ public toGetBuiltinIntents() { return this.to('GetBuiltinIntents'); } /** * Gets a list of built-in slot types that meet the specified criteria. * * Access Level: Read * * https://docs.aws.amazon.com/lex/latest/dg/API_GetBuiltinSlotTypes.html */ public toGetBuiltinSlotTypes() { return this.to('GetBuiltinSlotTypes'); } /** * Exports Amazon Lex Resource in a requested format. * * Access Level: Read * * https://docs.aws.amazon.com/lex/latest/dg/API_GetExport.html */ public toGetExport() { return this.to('GetExport'); } /** * Gets information about an import job started with StartImport. * * Access Level: Read * * https://docs.aws.amazon.com/lex/latest/dg/API_GetImport.html */ public toGetImport() { return this.to('GetImport'); } /** * Returns information for a specific intent. In addition to the intent name, you must also specify the intent version. * * Access Level: Read * * https://docs.aws.amazon.com/lex/latest/dg/API_GetIntent.html */ public toGetIntent() { return this.to('GetIntent'); } /** * Returns information for all versions of a specific intent. * * Access Level: List * * https://docs.aws.amazon.com/lex/latest/dg/API_GetIntentVersions.html */ public toGetIntentVersions() { return this.to('GetIntentVersions'); } /** * Returns information for the $LATEST version of all intents, subject to filters provided by the client. * * Access Level: List * * https://docs.aws.amazon.com/lex/latest/dg/API_GetIntents.html */ public toGetIntents() { return this.to('GetIntents'); } /** * Grants permission to view an ongoing or completed migration * * Access Level: Read * * https://docs.aws.amazon.com/lex/latest/dg/API_GetMigration.html */ public toGetMigration() { return this.to('GetMigration'); } /** * Grants permission to view list of migrations from Amazon Lex v1 to Amazon Lex v2 * * Access Level: List * * https://docs.aws.amazon.com/lex/latest/dg/API_GetMigrations.html */ public toGetMigrations() { return this.to('GetMigrations'); } /** * Returns session information for a specified bot, alias, and user ID. * * Access Level: Read * * https://docs.aws.amazon.com/lex/latest/dg/API_runtime_GetSession.html */ public toGetSession() { return this.to('GetSession'); } /** * Returns information about a specific version of a slot type. In addition to specifying the slot type name, you must also specify the slot type version. * * Access Level: Read * * https://docs.aws.amazon.com/lex/latest/dg/API_GetSlotType.html */ public toGetSlotType() { return this.to('GetSlotType'); } /** * Returns information for all versions of a specific slot type. * * Access Level: List * * https://docs.aws.amazon.com/lex/latest/dg/API_GetSlotTypeVersions.html */ public toGetSlotTypeVersions() { return this.to('GetSlotTypeVersions'); } /** * Returns information for the $LATEST version of all slot types, subject to filters provided by the client. * * Access Level: List * * https://docs.aws.amazon.com/lex/latest/dg/API_GetSlotTypes.html */ public toGetSlotTypes() { return this.to('GetSlotTypes'); } /** * Returns a view of aggregate utterance data for versions of a bot for a recent time period. * * Access Level: List * * https://docs.aws.amazon.com/lex/latest/dg/API_GetUtterancesView.html */ public toGetUtterancesView() { return this.to('GetUtterancesView'); } /** * Lists tags for a Lex resource * * Access Level: Read * * https://docs.aws.amazon.com/lex/latest/dg/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Sends user input (text or speech) to Amazon Lex. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_runtime_PostContent.html */ public toPostContent() { return this.to('PostContent'); } /** * Sends user input (text-only) to Amazon Lex. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_runtime_PostText.html */ public toPostText() { return this.to('PostText'); } /** * Creates or updates the $LATEST version of a Amazon Lex conversational bot. * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/lex/latest/dg/API_PutBot.html */ public toPutBot() { return this.to('PutBot'); } /** * Creates or updates an alias for the specific bot. * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/lex/latest/dg/API_PutBotAlias.html */ public toPutBotAlias() { return this.to('PutBotAlias'); } /** * Creates or updates the $LATEST version of an intent. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_PutIntent.html */ public toPutIntent() { return this.to('PutIntent'); } /** * Creates a new session or modifies an existing session with an Amazon Lex bot. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_runtime_PutSession.html */ public toPutSession() { return this.to('PutSession'); } /** * Creates or updates the $LATEST version of a slot type. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_PutSlotType.html */ public toPutSlotType() { return this.to('PutSlotType'); } /** * Starts a job to import a resource to Amazon Lex. * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_StartImport.html */ public toStartImport() { return this.to('StartImport'); } /** * Grants permission to migrate a bot from Amazon Lex v1 to Amazon Lex v2 * * Access Level: Write * * https://docs.aws.amazon.com/lex/latest/dg/API_StartMigration.html */ public toStartMigration() { return this.to('StartMigration'); } /** * Adds or overwrites tags to a Lex resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/lex/latest/dg/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Removes tags from a Lex resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/lex/latest/dg/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } protected accessLevelList: AccessLevelList = { "Write": [ "CreateBotVersion", "CreateIntentVersion", "CreateSlotTypeVersion", "DeleteBot", "DeleteBotAlias", "DeleteBotChannelAssociation", "DeleteBotVersion", "DeleteIntent", "DeleteIntentVersion", "DeleteSession", "DeleteSlotType", "DeleteSlotTypeVersion", "DeleteUtterances", "PostContent", "PostText", "PutBot", "PutBotAlias", "PutIntent", "PutSession", "PutSlotType", "StartImport", "StartMigration" ], "Read": [ "GetBot", "GetBotAlias", "GetBotChannelAssociation", "GetBuiltinIntent", "GetBuiltinIntents", "GetBuiltinSlotTypes", "GetExport", "GetImport", "GetIntent", "GetMigration", "GetSession", "GetSlotType", "ListTagsForResource" ], "List": [ "GetBotAliases", "GetBotChannelAssociations", "GetBotVersions", "GetBots", "GetIntentVersions", "GetIntents", "GetMigrations", "GetSlotTypeVersions", "GetSlotTypes", "GetUtterancesView" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type bot to the statement * * https://docs.aws.amazon.com/lex/latest/dg/API_BotMetadata.html * * @param botName - Identifier for the botName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onBot(botName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:lex:${Region}:${Account}:bot:${BotName}'; arn = arn.replace('${BotName}', botName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type bot version to the statement * * https://docs.aws.amazon.com/lex/latest/dg/API_BotMetadata.html * * @param botName - Identifier for the botName. * @param botVersion - Identifier for the botVersion. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onBotVersion(botName: string, botVersion: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:lex:${Region}:${Account}:bot:${BotName}:${BotVersion}'; arn = arn.replace('${BotName}', botName); arn = arn.replace('${BotVersion}', botVersion); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type bot alias to the statement * * https://docs.aws.amazon.com/lex/latest/dg/API_BotAliasMetadata.html * * @param botName - Identifier for the botName. * @param botAlias - Identifier for the botAlias. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onBotAlias(botName: string, botAlias: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:lex:${Region}:${Account}:bot:${BotName}:${BotAlias}'; arn = arn.replace('${BotName}', botName); arn = arn.replace('${BotAlias}', botAlias); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type channel to the statement * * https://docs.aws.amazon.com/lex/latest/dg/API_BotChannelAssociation.html * * @param botName - Identifier for the botName. * @param botAlias - Identifier for the botAlias. * @param channelName - Identifier for the channelName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onChannel(botName: string, botAlias: string, channelName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:lex:${Region}:${Account}:bot-channel:${BotName}:${BotAlias}:${ChannelName}'; arn = arn.replace('${BotName}', botName); arn = arn.replace('${BotAlias}', botAlias); arn = arn.replace('${ChannelName}', channelName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type intent version to the statement * * https://docs.aws.amazon.com/lex/latest/dg/API_Intent.html * * @param intentName - Identifier for the intentName. * @param intentVersion - Identifier for the intentVersion. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onIntentVersion(intentName: string, intentVersion: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:lex:${Region}:${Account}:intent:${IntentName}:${IntentVersion}'; arn = arn.replace('${IntentName}', intentName); arn = arn.replace('${IntentVersion}', intentVersion); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type slottype version to the statement * * https://docs.aws.amazon.com/lex/latest/dg/API_SlotTypeMetadata.html * * @param slotName - Identifier for the slotName. * @param slotVersion - Identifier for the slotVersion. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onSlottypeVersion(slotName: string, slotVersion: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:lex:${Region}:${Account}:slottype:${SlotName}:${SlotVersion}'; arn = arn.replace('${SlotName}', slotName); arn = arn.replace('${SlotVersion}', slotVersion); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Enables you to control access based on the intents included in the request. * * https://docs.aws.amazon.com/lex/latest/dg/security_iam_service-with-iam.html * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifAssociatedIntents(value: string | string[], operator?: Operator | string) { return this.if(`associatedIntents`, value, operator || 'StringLike'); } /** * Enables you to control access based on the slot types included in the request. * * https://docs.aws.amazon.com/lex/latest/dg/security_iam_service-with-iam.html * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifAssociatedSlotTypes(value: string | string[], operator?: Operator | string) { return this.if(`associatedSlotTypes`, value, operator || 'StringLike'); } /** * Enables you to control access based on the channel type included in the request. * * https://docs.aws.amazon.com/lex/latest/dg/security_iam_service-with-iam.html * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifChannelType(value: string | string[], operator?: Operator | string) { return this.if(`channelType`, value, operator || 'StringLike'); } }
the_stack
import { ActionChart, translations, ObjectsTable, ObjectsTableType, actionChartController, state, GndDiscipline, MoneyDialog, BookSeriesId, Item } from ".."; /** * The action chart view API */ export const actionChartView = { /** * Fill the action chart with the player state * @param actionChart The ActionChart */ fill(actionChart: ActionChart) { document.title = translations.text( "actionChart" ); // Show endurance / combat skills. actionChartView.updateStatistics(); // Show money actionChartView.updateMoney(); // Bind drop money events actionChartView.bindDropMoneyEvents(); // Disciplines. actionChartView.fillDisciplines(actionChart); // Fill the chart objects lists actionChartView.updateObjectsLists(); // Bind event for drop meals ObjectsTable.bindTableEquipmentEvents( $("#achart-dropmeal") , ObjectsTableType.INVENTORY ); // Bind restore 20 EP (Curing) actionChartView.bindRestore20EP(); // Bind "Fight unarmed" $("#achart-fightUnarmed").click( function(e: Event) { actionChartController.setFightUnarmed( $(this).prop("checked") ? true : false ); }); // Annotations $("#achart-annotations").val( actionChart.annotations ); $("#achart-annotations").off(); $("#achart-annotations").on("input", function() { state.actionChart.annotations = $(this).val(); }); }, /** * Hide / disable the restore 20 EP button if needed */ updateRestore20EPState() { const $restoreButton = $("#achart-restore20Ep"); const restoreDiscipline = state.actionChart.get20EPRestoreDiscipline(); if (!restoreDiscipline) { $restoreButton.hide(); } else if ( restoreDiscipline === GndDiscipline.Deliverance ) { $restoreButton.html( translations.text("restore20EPGrdMasterButton") ); } else { $restoreButton.html( translations.text("restore20EPMagnakaiButton") ); } if ( !state.actionChart.canUse20EPRestoreNow() ) { $restoreButton.prop( "disabled", true ); } }, /** * Bind events to restore 20 EP (Curing) */ bindRestore20EP() { const $restoreButton = $("#achart-restore20Ep"); actionChartView.updateRestore20EPState(); $restoreButton.click( (e: Event) => { e.preventDefault(); const restoreDiscipline = state.actionChart.get20EPRestoreDiscipline(); if ( !confirm( translations.text(restoreDiscipline === GndDiscipline.Deliverance ? "confirm20EPGrdMaster" : "confirm20EP") ) ) { return; } actionChartController.use20EPRestore(); actionChartView.updateRestore20EPState(); }); }, /** * Bind events for drop money UI */ bindDropMoneyEvents() { // Bind drop money button event $("#achart-dropmoneybutton").click( (e: Event) => { e.preventDefault(); MoneyDialog.show( true ); }); }, /** * Render the disciplines table * @param {ActionChart} actionChart The action chart */ fillDisciplines(actionChart: ActionChart) { // Kai title: $("#achart-kaititle") .text( state.book.getKaiTitle( actionChart.getDisciplines().length ) ); // Lore circles: if (state.book.getBookSeries().id === BookSeriesId.Magnakai || state.actionChart.getDisciplines(BookSeriesId.Magnakai).length > 0) { // Only for Magnakai books, or if player has played some Magnakai books const circles = actionChart.getLoreCircles(); if ( circles.length === 0 ) { $("#achart-currentCircles").html( "<i>" + translations.text("noneMasculine") + "</i>" ); } else { const circlesNames: string[] = []; for ( const c of actionChart.getLoreCircles() ) { circlesNames.push( c.getDescription() ); } $("#achart-currentCircles").html( circlesNames.join( ", ") ); } } else { $("#achart-circles").hide(); } // TODO: Display the discipline "quote" tag instead the name const $displines = $("#achart-disciplines > tbody"); if ( actionChart.getDisciplines().length === 0 ) { $displines.append( "<tr><td>(" + translations.text("noneFemenine") + ")</td></tr>" ); } else { const bookDisciplines = state.book.getDisciplinesTable(); const bookSeries = state.book.getBookSeries(); // Enumerate disciplines for (const disciplineId of actionChart.getDisciplines()) { const dInfo = bookDisciplines[disciplineId]; let name = dInfo.name; if (disciplineId === bookSeries.weaponskillDiscipline) { // Show selected weapons description const weapons: string[] = []; for (const weaponSkill of actionChart.getWeaponSkill()) { weapons.push( state.mechanics.getObject( weaponSkill ).name ); } if ( weapons.length > 0 ) { name += " (" + weapons.join(", ") + ")"; } } // Unescape the HTML description: const descriptionHtml = $("<div />").html(dInfo.description).text(); $displines.append( "<tr><td>" + '<button class="btn btn-default table-op" title="' + translations.text("disciplineDescription") + '">' + '<span class="glyphicon glyphicon-question-sign"></span>' + "</button>" + "<b>" + name + `</b><br/>${dInfo.imageHtml}<i style="display:none"><small>` + descriptionHtml + "</small></i></td></tr>" ); } // Bind help button events $displines.find("button").click(function(e) { $(this).parent().find("i").toggle(); }); } }, updateMoney() { $("#achart-beltPouch").val( state.actionChart.beltPouch + " " + translations.text("goldCrowns") ); // Disable if the player has no money or it's death $("#achart-dropmoneybutton").prop( "disabled", state.actionChart.beltPouch <= 0 || state.actionChart.currentEndurance <= 0 ); }, /** * Update meals count */ updateMeals() { $("#achart-meals").val( state.actionChart.meals ); // Disable if the player has no meals or it's death $("#achart-dropmeal").prop( "disabled", state.actionChart.meals <= 0 || state.actionChart.currentEndurance <= 0 ); }, /** * Update the player statistics */ updateStatistics() { const txtCurrent = translations.text("current") + ": "; // Combat skill $("#achart-combatSkills").val( txtCurrent + state.actionChart.getCurrentCombatSkill() + " / Original: " + state.actionChart.combatSkill ); $("#achart-cs-bonuses").text( actionChartController.getBonusesText( state.actionChart.getCurrentCombatSkillBonuses() ) ); // Endurance let txtEndurance = txtCurrent + state.actionChart.currentEndurance; const max = state.actionChart.getMaxEndurance(); if ( max !== state.actionChart.endurance ) { txtEndurance += " / Max.: " + max; } txtEndurance += " / Original: " + state.actionChart.endurance; $("#achart-endurance").val( txtEndurance ); $("#achart-endurance-bonuses").text( actionChartController.getBonusesText( state.actionChart.getEnduranceBonuses() ) ); }, /** * Update weapons */ updateWeapons() { // Weapons list new ObjectsTable( state.actionChart.weapons , $("#achart-weapons > tbody") , ObjectsTableType.INVENTORY ) .renderTable(); // Current weapon: const current: Item = state.actionChart.getSelectedWeaponItem(); $("#achart-currentWeapon").html( current ? current.name : "<i>" + translations.text("noneFemenine") + "</i>" ); // Fight unarmed? const $fightUnarmed = $("#achart-fightUnarmed"); $fightUnarmed.prop( "checked" , state.actionChart.fightUnarmed ); // If the player has no weapons, or has died, disable the option "Fight unarmed" let noWeapon = ( !state.actionChart.fightUnarmed && !state.actionChart.getSelectedWeapon() ); if ( state.actionChart.currentEndurance <= 0 ) { noWeapon = true; } $fightUnarmed.prop( "disabled" , noWeapon ); }, /** * Update the chart objects lists */ updateObjectsLists() { // Weapons actionChartView.updateWeapons(); // Backpack items if ( state.actionChart.hasBackpack ) { new ObjectsTable( state.actionChart.backpackItems, $("#achart-backpack > tbody") , ObjectsTableType.INVENTORY ) .renderTable(); } else { $("#achart-backpack-content").html("<i>" + translations.text("backpackLost") + "</i>"); } // Special items new ObjectsTable( state.actionChart.specialItems, $("#achart-special > tbody") , ObjectsTableType.INVENTORY ) .renderTable(); // Meals actionChartView.updateMeals(); // Total number of backpack / special objects $("#achart-backpacktotal").text("(" + state.actionChart.getNBackpackItems() + ")"); $("#achart-specialtotal").text("(" + state.actionChart.getNSpecialItems() + ")"); }, showInventoryMsg(action: string, object: Item, msg: string) { const toastType = ( action === "pick" ? "success" : "warning" ); let html = ""; // Check if the object has an image if ( object) { const imageUrl = object.getImageUrl(); if ( imageUrl ) { html += '<img class="inventoryImg" src="' + imageUrl + '" /> '; } } html += msg; html = "<div>" + html + "</div>"; toastr[toastType]( html ); } };
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * Accounts * __NOTE__: An instance of this class is automatically created for an * instance of the LocationBasedServicesManagementClient. */ export interface Accounts { /** * Create or update a Location Based Services Account. A Location Based * Services Account holds the keys which allow access to the Location Based * Services REST APIs. * * @param {string} resourceGroupName The name of the Azure Resource Group. * * @param {string} accountName The name of the Location Based Services Account. * * @param {object} locationBasedServicesAccountCreateParameters The new or * updated parameters for the Location Based Services Account. * * @param {string} locationBasedServicesAccountCreateParameters.location The * location of the resource. * * @param {object} [locationBasedServicesAccountCreateParameters.tags] Gets or * sets a list of key value pairs that describe the resource. These tags can be * used in viewing and grouping this resource (across resource groups). A * maximum of 15 tags can be provided for a resource. Each tag must have a key * no greater than 128 characters and value no greater than 256 characters. * * @param {object} locationBasedServicesAccountCreateParameters.sku The SKU of * this account. * * @param {string} locationBasedServicesAccountCreateParameters.sku.name The * name of the SKU, in standard format (such as S0). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LocationBasedServicesAccount>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroupName: string, accountName: string, locationBasedServicesAccountCreateParameters: models.LocationBasedServicesAccountCreateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LocationBasedServicesAccount>>; /** * Create or update a Location Based Services Account. A Location Based * Services Account holds the keys which allow access to the Location Based * Services REST APIs. * * @param {string} resourceGroupName The name of the Azure Resource Group. * * @param {string} accountName The name of the Location Based Services Account. * * @param {object} locationBasedServicesAccountCreateParameters The new or * updated parameters for the Location Based Services Account. * * @param {string} locationBasedServicesAccountCreateParameters.location The * location of the resource. * * @param {object} [locationBasedServicesAccountCreateParameters.tags] Gets or * sets a list of key value pairs that describe the resource. These tags can be * used in viewing and grouping this resource (across resource groups). A * maximum of 15 tags can be provided for a resource. Each tag must have a key * no greater than 128 characters and value no greater than 256 characters. * * @param {object} locationBasedServicesAccountCreateParameters.sku The SKU of * this account. * * @param {string} locationBasedServicesAccountCreateParameters.sku.name The * name of the SKU, in standard format (such as S0). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LocationBasedServicesAccount} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LocationBasedServicesAccount} [result] - The deserialized result object if an error did not occur. * See {@link LocationBasedServicesAccount} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroupName: string, accountName: string, locationBasedServicesAccountCreateParameters: models.LocationBasedServicesAccountCreateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LocationBasedServicesAccount>; createOrUpdate(resourceGroupName: string, accountName: string, locationBasedServicesAccountCreateParameters: models.LocationBasedServicesAccountCreateParameters, callback: ServiceCallback<models.LocationBasedServicesAccount>): void; createOrUpdate(resourceGroupName: string, accountName: string, locationBasedServicesAccountCreateParameters: models.LocationBasedServicesAccountCreateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LocationBasedServicesAccount>): void; /** * Updates a Location Based Services Account. Only a subset of the parameters * may be updated after creation, such as Sku and Tags. * * @param {string} resourceGroupName The name of the Azure Resource Group. * * @param {string} accountName The name of the Location Based Services Account. * * @param {object} locationBasedServicesAccountUpdateParameters The updated * parameters for the Location Based Services Account. * * @param {object} [locationBasedServicesAccountUpdateParameters.tags] Gets or * sets a list of key value pairs that describe the resource. These tags can be * used in viewing and grouping this resource (across resource groups). A * maximum of 15 tags can be provided for a resource. Each tag must have a key * no greater than 128 characters and value no greater than 256 characters. * * @param {object} [locationBasedServicesAccountUpdateParameters.sku] The SKU * of this account. * * @param {string} locationBasedServicesAccountUpdateParameters.sku.name The * name of the SKU, in standard format (such as S0). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LocationBasedServicesAccount>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, accountName: string, locationBasedServicesAccountUpdateParameters: models.LocationBasedServicesAccountUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LocationBasedServicesAccount>>; /** * Updates a Location Based Services Account. Only a subset of the parameters * may be updated after creation, such as Sku and Tags. * * @param {string} resourceGroupName The name of the Azure Resource Group. * * @param {string} accountName The name of the Location Based Services Account. * * @param {object} locationBasedServicesAccountUpdateParameters The updated * parameters for the Location Based Services Account. * * @param {object} [locationBasedServicesAccountUpdateParameters.tags] Gets or * sets a list of key value pairs that describe the resource. These tags can be * used in viewing and grouping this resource (across resource groups). A * maximum of 15 tags can be provided for a resource. Each tag must have a key * no greater than 128 characters and value no greater than 256 characters. * * @param {object} [locationBasedServicesAccountUpdateParameters.sku] The SKU * of this account. * * @param {string} locationBasedServicesAccountUpdateParameters.sku.name The * name of the SKU, in standard format (such as S0). * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LocationBasedServicesAccount} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LocationBasedServicesAccount} [result] - The deserialized result object if an error did not occur. * See {@link LocationBasedServicesAccount} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, accountName: string, locationBasedServicesAccountUpdateParameters: models.LocationBasedServicesAccountUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LocationBasedServicesAccount>; update(resourceGroupName: string, accountName: string, locationBasedServicesAccountUpdateParameters: models.LocationBasedServicesAccountUpdateParameters, callback: ServiceCallback<models.LocationBasedServicesAccount>): void; update(resourceGroupName: string, accountName: string, locationBasedServicesAccountUpdateParameters: models.LocationBasedServicesAccountUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LocationBasedServicesAccount>): void; /** * Delete a Location Based Services Account * * @param {string} resourceGroupName The name of the Azure Resource Group. * * @param {string} accountName The name of the Location Based Services Account. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Delete a Location Based Services Account * * @param {string} resourceGroupName The name of the Azure Resource Group. * * @param {string} accountName The name of the Location Based Services Account. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, accountName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, accountName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Get a Location Based Services Account * * @param {string} resourceGroupName The name of the Azure Resource Group. * * @param {string} accountName The name of the Location Based Services Account. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LocationBasedServicesAccount>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LocationBasedServicesAccount>>; /** * Get a Location Based Services Account * * @param {string} resourceGroupName The name of the Azure Resource Group. * * @param {string} accountName The name of the Location Based Services Account. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LocationBasedServicesAccount} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LocationBasedServicesAccount} [result] - The deserialized result object if an error did not occur. * See {@link LocationBasedServicesAccount} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LocationBasedServicesAccount>; get(resourceGroupName: string, accountName: string, callback: ServiceCallback<models.LocationBasedServicesAccount>): void; get(resourceGroupName: string, accountName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LocationBasedServicesAccount>): void; /** * Get all Location Based Services Accounts in a Resource Group * * @param {string} resourceGroupName The name of the Azure Resource Group. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LocationBasedServicesAccounts>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LocationBasedServicesAccounts>>; /** * Get all Location Based Services Accounts in a Resource Group * * @param {string} resourceGroupName The name of the Azure Resource Group. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LocationBasedServicesAccounts} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LocationBasedServicesAccounts} [result] - The deserialized result object if an error did not occur. * See {@link LocationBasedServicesAccounts} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LocationBasedServicesAccounts>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.LocationBasedServicesAccounts>): void; listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LocationBasedServicesAccounts>): void; /** * Get all Location Based Services Accounts in a Subscription * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LocationBasedServicesAccounts>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listBySubscriptionWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LocationBasedServicesAccounts>>; /** * Get all Location Based Services Accounts in a Subscription * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LocationBasedServicesAccounts} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LocationBasedServicesAccounts} [result] - The deserialized result object if an error did not occur. * See {@link LocationBasedServicesAccounts} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listBySubscription(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LocationBasedServicesAccounts>; listBySubscription(callback: ServiceCallback<models.LocationBasedServicesAccounts>): void; listBySubscription(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LocationBasedServicesAccounts>): void; /** * Moves Location Based Services Accounts from one ResourceGroup (or * Subscription) to another * * @param {string} resourceGroupName The name of the resource group that * contains Location Based Services Account to move. * * @param {object} moveRequest The details of the Location Based Services * Account move. * * @param {string} moveRequest.targetResourceGroup The name of the destination * resource group. * * @param {array} moveRequest.resourceIds A list of resource names to move from * the source resource group. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ moveWithHttpOperationResponse(resourceGroupName: string, moveRequest: models.LocationBasedServicesAccountsMoveRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Moves Location Based Services Accounts from one ResourceGroup (or * Subscription) to another * * @param {string} resourceGroupName The name of the resource group that * contains Location Based Services Account to move. * * @param {object} moveRequest The details of the Location Based Services * Account move. * * @param {string} moveRequest.targetResourceGroup The name of the destination * resource group. * * @param {array} moveRequest.resourceIds A list of resource names to move from * the source resource group. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ move(resourceGroupName: string, moveRequest: models.LocationBasedServicesAccountsMoveRequest, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; move(resourceGroupName: string, moveRequest: models.LocationBasedServicesAccountsMoveRequest, callback: ServiceCallback<void>): void; move(resourceGroupName: string, moveRequest: models.LocationBasedServicesAccountsMoveRequest, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Get the keys to use with the Location Based Services APIs. A key is used to * authenticate and authorize access to the Location Based Services REST APIs. * Only one key is needed at a time; two are given to provide seamless key * regeneration. * * @param {string} resourceGroupName The name of the Azure Resource Group. * * @param {string} accountName The name of the Location Based Services Account. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LocationBasedServicesAccountKeys>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listKeysWithHttpOperationResponse(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LocationBasedServicesAccountKeys>>; /** * Get the keys to use with the Location Based Services APIs. A key is used to * authenticate and authorize access to the Location Based Services REST APIs. * Only one key is needed at a time; two are given to provide seamless key * regeneration. * * @param {string} resourceGroupName The name of the Azure Resource Group. * * @param {string} accountName The name of the Location Based Services Account. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LocationBasedServicesAccountKeys} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LocationBasedServicesAccountKeys} [result] - The deserialized result object if an error did not occur. * See {@link LocationBasedServicesAccountKeys} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listKeys(resourceGroupName: string, accountName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LocationBasedServicesAccountKeys>; listKeys(resourceGroupName: string, accountName: string, callback: ServiceCallback<models.LocationBasedServicesAccountKeys>): void; listKeys(resourceGroupName: string, accountName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LocationBasedServicesAccountKeys>): void; /** * Regenerate either the primary or secondary key for use with the Location * Based Services APIs. The old key will stop working immediately. * * @param {string} resourceGroupName The name of the Azure Resource Group. * * @param {string} accountName The name of the Location Based Services Account. * * @param {object} keySpecification Which key to regenerate: primary or * secondary. * * @param {string} keySpecification.keyType Whether the operation refers to the * primary or secondary key. Possible values include: 'primary', 'secondary' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LocationBasedServicesAccountKeys>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ regenerateKeysWithHttpOperationResponse(resourceGroupName: string, accountName: string, keySpecification: models.LocationBasedServicesKeySpecification, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LocationBasedServicesAccountKeys>>; /** * Regenerate either the primary or secondary key for use with the Location * Based Services APIs. The old key will stop working immediately. * * @param {string} resourceGroupName The name of the Azure Resource Group. * * @param {string} accountName The name of the Location Based Services Account. * * @param {object} keySpecification Which key to regenerate: primary or * secondary. * * @param {string} keySpecification.keyType Whether the operation refers to the * primary or secondary key. Possible values include: 'primary', 'secondary' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LocationBasedServicesAccountKeys} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LocationBasedServicesAccountKeys} [result] - The deserialized result object if an error did not occur. * See {@link LocationBasedServicesAccountKeys} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ regenerateKeys(resourceGroupName: string, accountName: string, keySpecification: models.LocationBasedServicesKeySpecification, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LocationBasedServicesAccountKeys>; regenerateKeys(resourceGroupName: string, accountName: string, keySpecification: models.LocationBasedServicesKeySpecification, callback: ServiceCallback<models.LocationBasedServicesAccountKeys>): void; regenerateKeys(resourceGroupName: string, accountName: string, keySpecification: models.LocationBasedServicesKeySpecification, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LocationBasedServicesAccountKeys>): void; /** * List operations available for the Location Based Services Resource Provider * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<LocationBasedServicesOperations>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listOperationsWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.LocationBasedServicesOperations>>; /** * List operations available for the Location Based Services Resource Provider * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {LocationBasedServicesOperations} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {LocationBasedServicesOperations} [result] - The deserialized result object if an error did not occur. * See {@link LocationBasedServicesOperations} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listOperations(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.LocationBasedServicesOperations>; listOperations(callback: ServiceCallback<models.LocationBasedServicesOperations>): void; listOperations(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.LocationBasedServicesOperations>): void; }
the_stack
require('module-alias/register'); import * as _ from 'lodash'; import * as ABIDecoder from 'abi-decoder'; import * as chai from 'chai'; import * as setProtocolUtils from 'set-protocol-utils'; import { BigNumber } from 'bignumber.js'; import ChaiSetup from '@utils/chaiSetup'; import { BigNumberSetup } from '@utils/bigNumberSetup'; import { CoreMockContract, RebalanceAuctionModuleContract, TWAPLiquidatorContract, RebalancingSetTokenV3Contract, } from '@utils/contracts'; import { Blockchain } from '@utils/blockchain'; import { ether } from '@utils/units'; import { DEFAULT_GAS, ONE, ONE_DAY_IN_SECONDS, ONE_HOUR_IN_SECONDS, ZERO, } from '@utils/constants'; import { getWeb3 } from '@utils/web3Helper'; import { CoreHelper } from '@utils/helpers/coreHelper'; import { ERC20Helper } from '@utils/helpers/erc20Helper'; import { LiquidatorHelper } from '@utils/helpers/liquidatorHelper'; import { OracleHelper } from 'set-protocol-oracles'; import { RebalancingSetV3Helper } from '@utils/helpers/rebalancingSetV3Helper'; import { ValuationHelper } from '@utils/helpers/valuationHelper'; import { RebalanceTestSetup, PriceUpdate } from '@utils/helpers/rebalanceTestSetup'; BigNumberSetup.configure(); ChaiSetup.configure(); const web3 = getWeb3(); const { SetProtocolUtils: SetUtils } = setProtocolUtils; const { expect } = chai; const blockchain = new Blockchain(web3); interface RebalancingSetDetails { unitShares: BigNumber; naturalUnit: BigNumber; supply: BigNumber; } interface SetDetails { components: string[]; units: BigNumber[]; naturalUnit: BigNumber; } interface ComponentSettings { component1Price: BigNumber; component2Price: BigNumber; component1Decimals: number; component2Decimals: number; } interface AuctionSettings { chunkSize: BigNumber; chunkAuctionPeriod: BigNumber; component1PriceChange: BigNumber; component2PriceChange: BigNumber; } interface ScenarioAssertions { expectedAuctions: number; } interface TWAPScenario { name: string; rebalancingSet: RebalancingSetDetails; currentSet: SetDetails; nextSet: SetDetails; components: ComponentSettings; auction: AuctionSettings; asserts: ScenarioAssertions; } interface CheckPoint { setMarketCap: BigNumber; setValue: BigNumber; unitShares: BigNumber; auctionCounter: number; timestamp: BigNumber; } const scenarios: TWAPScenario[] = [ { name: 'ETH 20 MA Set Rebalances 100% WETH to 100% USD', rebalancingSet: { unitShares: new BigNumber(2076796), naturalUnit: new BigNumber(1000000), supply: new BigNumber('20556237207015075000000'), }, currentSet: { components: ['component1'], // ETH units: [new BigNumber(1000000)], naturalUnit: new BigNumber(1000000), }, nextSet: { components: ['component2'], // USDC units: [new BigNumber(307)], naturalUnit: new BigNumber(1000000000000), }, components: { component1Price: ether(188), component2Price: ether(1), component1Decimals: 18, component2Decimals: 6, }, auction: { chunkSize: ether(2000000), chunkAuctionPeriod: new BigNumber(3600), // 1 hour component1PriceChange: new BigNumber(0.02), // 2% increase in price 1 component2PriceChange: ZERO, }, asserts: { expectedAuctions: 5, }, }, { name: 'ETHBTC Set Rebalances 100% WETH to 50% WETH/WBTC', rebalancingSet: { unitShares: new BigNumber(799797), naturalUnit: new BigNumber(100000000), supply: new BigNumber('14256596210800000000000'), }, currentSet: { components: ['component1'], // WETH units: [new BigNumber(1000000)], naturalUnit: new BigNumber(1000000), }, nextSet: { components: ['component1', 'component2'], // WETH, WBTC units: [new BigNumber(484880000000000), new BigNumber(1000)], naturalUnit: new BigNumber(10000000000000), }, components: { component1Price: ether(188), component2Price: ether(9000), component1Decimals: 18, component2Decimals: 8, }, auction: { chunkSize: ether(1000000), chunkAuctionPeriod: new BigNumber(0), component1PriceChange: new BigNumber(-0.02), // 2% decrease in ETH component2PriceChange: new BigNumber(-0.01), // 1% decrease in BTC }, asserts: { expectedAuctions: 2, }, }, { name: 'ETH RSI Yield 100% ETH to 100% cUSDC $5M - 5/13/2020', rebalancingSet: { unitShares: new BigNumber(557211), naturalUnit: new BigNumber(1000000), supply: new BigNumber('21753937919075000000000'), }, currentSet: { components: ['component1'], // WETH units: [new BigNumber(2097152)], naturalUnit: new BigNumber(1000000), }, nextSet: { components: ['component2'], // cUSDc units: [new BigNumber(16384)], naturalUnit: new BigNumber(10000000000), }, components: { component1Price: ether(200), component2Price: ether(0.021), component1Decimals: 18, component2Decimals: 8, }, auction: { chunkSize: ether(1000000), chunkAuctionPeriod: new BigNumber(0), component1PriceChange: ZERO, component2PriceChange: ZERO, }, asserts: { expectedAuctions: 6, }, }, { name: '100% cUSDC to 50/50% wBTC/cUSDC #706', rebalancingSet: { unitShares: new BigNumber(296562), naturalUnit: new BigNumber(100000000), supply: new BigNumber('37566900000000000000'), }, currentSet: { components: ['component1'], // cUSDC units: [new BigNumber(166187652)], naturalUnit: new BigNumber(1000000000000), }, nextSet: { components: ['component1', 'component2'], // cUSDC, WBTC units: [new BigNumber(41946670), new BigNumber(100)], naturalUnit: new BigNumber(1000000000000), }, components: { component1Price: ether(0.021), component2Price: ether(9000), component1Decimals: 8, component2Decimals: 8, }, auction: { chunkSize: ether(1000000), chunkAuctionPeriod: new BigNumber(0), component1PriceChange: ZERO, component2PriceChange: ZERO, }, asserts: { expectedAuctions: 1, }, }, ]; contract('RebalancingSetV3 - TWAPLiquidator Scenarios', accounts => { const [ deployerAccount, managerAccount, feeRecipient, ] = accounts; let rebalancingSetToken: RebalancingSetTokenV3Contract; let liquidator: TWAPLiquidatorContract; const name: string = 'liquidator'; const auctionPeriod: BigNumber = ONE_HOUR_IN_SECONDS.mul(4); const rangeStart: BigNumber = ether(.01); const rangeEnd: BigNumber = ether(.21); let setup: RebalanceTestSetup; let scenario: TWAPScenario; let checkPoints: CheckPoint[]; let auctionCounter: number; const coreHelper = new CoreHelper(deployerAccount, deployerAccount); const erc20Helper = new ERC20Helper(deployerAccount); const rebalancingHelper = new RebalancingSetV3Helper( deployerAccount, coreHelper, erc20Helper, blockchain ); const oracleHelper = new OracleHelper(deployerAccount); const valuationHelper = new ValuationHelper(deployerAccount, coreHelper, erc20Helper, oracleHelper); const liquidatorHelper = new LiquidatorHelper(deployerAccount, erc20Helper, valuationHelper); before(async () => { ABIDecoder.addABI(CoreMockContract.getAbi()); ABIDecoder.addABI(RebalanceAuctionModuleContract.getAbi()); }); after(async () => { ABIDecoder.removeABI(CoreMockContract.getAbi()); ABIDecoder.removeABI(RebalanceAuctionModuleContract.getAbi()); }); beforeEach(async () => { blockchain.saveSnapshotAsync(); setup = new RebalanceTestSetup(deployerAccount); checkPoints = []; auctionCounter = 1; }); afterEach(async () => { blockchain.revertAsync(); }); describe(`${scenarios[0].name}`, async () => { it('should successfully complete', async () => { await runScenario(scenarios[0]); const newRebalanceState = await setup.rebalancingSetToken.rebalanceState.callAsync(); expect(newRebalanceState).to.be.bignumber.equal(SetUtils.REBALANCING_STATE.DEFAULT); }); }); describe(`${scenarios[1].name}`, async () => { it('should successfully complete', async () => { await runScenario(scenarios[1]); }); }); describe(`${scenarios[2].name}`, async () => { it('should successfully complete', async () => { await runScenario(scenarios[2]); }); }); describe(`${scenarios[3].name}`, async () => { it('should successfully complete', async () => { await runScenario(scenarios[3]); }); }); async function runScenario(currentScenario: TWAPScenario): Promise<void> { scenario = currentScenario; await initialize(); await printContext(); await checkPoint(0); await startRebalance(); await printRebalanceDetails(); await runChunkAuctions(); await setup.rebalancingSetToken.settleRebalance.sendTransactionAsync( { from: deployerAccount, gas: DEFAULT_GAS} ); await checkPoint(1); await printResults(); await runAssertions(); } async function printContext(): Promise<void> { const { component1Price, component2Price } = scenario.components; const { set1, set2, oracleWhiteList, component1, component2 } = setup; const set1Component1Value = await valuationHelper.calculateAllocationValueAsync( set1, oracleWhiteList, component1.address, ); const set1Component2Value = await valuationHelper.calculateAllocationValueAsync( set1, oracleWhiteList, component2.address, ); const set2Component1Value = await valuationHelper.calculateAllocationValueAsync( set2, oracleWhiteList, component1.address, ); const set2Component2Value = await valuationHelper.calculateAllocationValueAsync( set2, oracleWhiteList, component2.address, ); const set1Value = set1Component1Value.plus(set1Component2Value); const set2Value = set2Component1Value.plus(set2Component2Value); const set1Component1Percent = set1Component1Value.div(set1Value).round(2, 3).mul(100); const set1Component2Percent = set1Component2Value.div(set1Value).round(2, 3).mul(100); const set2Component1Percent = set2Component1Value.div(set2Value).round(2, 3).mul(100); const set2Component2Percent = set2Component2Value.div(set2Value).round(2, 3).mul(100); const component1PercentageChange = set2Component1Percent.sub(set1Component1Percent); const component2PercentageChange = set2Component2Percent.sub(set1Component2Percent); console.log(`======================== Context ==========================`); console.log(`Component 1 Initial Price: ${deScale(component1Price).toString()}`); console.log(`Component 2 Initial Price: ${deScale(component2Price).toString()}`); console.log(`CurrentSet Value: ${deScale(set1Value).toString()}`); console.log(`CurrentSet Component 1 Percentage: ${set1Component1Percent.toString()}%`); console.log(`CurrentSet Component 2 Percentage: ${set1Component2Percent.toString()}%`); console.log(`NextSet Value: ${deScale(set2Value).toString()}`); console.log(`NextSet Component 1 Percentage: ${set2Component1Percent.toString()}%`); console.log(`NextSet Component 2 Percentage: ${set2Component2Percent.toString()}%`); console.log(`Component 1 % Change: ${component1PercentageChange}%`); console.log(`Component 2 % Change: ${component2PercentageChange}%`); } async function printRebalanceDetails(): Promise<void> { const { chunkSize } = scenario.auction; const unitShares = await setup.rebalancingSetToken.unitShares.callAsync(); const naturalUnit = await setup.rebalancingSetToken.naturalUnit.callAsync(); const currentSetQuantity = scenario.rebalancingSet.supply .mul(unitShares) .div(naturalUnit); const volume = await liquidatorHelper.calculateRebalanceVolumeAsync( setup.set1, setup.set2, setup.oracleWhiteList, currentSetQuantity, ); const orderSize = await liquidator.getOrderSize.callAsync(setup.rebalancingSetToken.address); const minimumBid = await liquidator.minimumBid.callAsync(setup.rebalancingSetToken.address); const chunkSizeCS = await liquidator.getChunkSize.callAsync(setup.rebalancingSetToken.address); console.log(`Rebalance Volume: ${deScale(volume)}`); console.log(`Rebalance $ Chunk Size: ${deScale(chunkSize)}`); console.log(`Order Size: ${orderSize}`); console.log(`Chunk Size: ${chunkSizeCS}`); console.log(`Minimum Bid: ${minimumBid}`); } async function checkPoint(num: number): Promise<void> { const setValue = await valuationHelper.calculateRebalancingSetTokenValueAsync( setup.rebalancingSetToken, setup.oracleWhiteList ); const unitShares = await setup.rebalancingSetToken.unitShares.callAsync(); const totalSupply = await setup.rebalancingSetToken.totalSupply.callAsync(); const setMarketCap = setValue.mul(totalSupply).div(10 ** 18).round(0, 3); const { timestamp } = await web3.eth.getBlock('latest'); checkPoints[num] = { setMarketCap, setValue, unitShares, auctionCounter, timestamp, }; } async function printResults(): Promise<void> { const t0 = checkPoints[0]; const tN = checkPoints[checkPoints.length - 1]; console.log(`======================== Results ==========================`); console.log(`Chunk Auctions Completed: ${auctionCounter}`); console.log(`RebalancingSet Value Before: ${deScale(t0.setValue).toString()}`); console.log(`RebalancingSet Value After: ${deScale(tN.setValue).toString()}`); console.log(`RebalancingSet MarketCap Before: ${deScale(t0.setMarketCap).toString()}`); console.log(`RebalancingSet MarketCap After: ${deScale(tN.setMarketCap).toString()}`); console.log(`unitShares Before: ${t0.unitShares}`); console.log(`unitShares After: ${tN.unitShares}`); console.log(`==================================================`); } function deScale(v1: BigNumber): BigNumber { return new BigNumber(v1).div(ether(1)).round(2, 3); } async function runAssertions(): Promise<void> { const rebalanceState = await setup.rebalancingSetToken.rebalanceState.callAsync(); expect(rebalanceState).to.be.bignumber.equal(SetUtils.REBALANCING_STATE.DEFAULT); expect(auctionCounter).to.equal(scenario.asserts.expectedAuctions); } // Sets up assets, creates and mints rebalancing set async function initialize(): Promise<void> { await setup.initializeCore(); await setup.initializeComponents(scenario.components); await setup.initializeBaseSets({ set1Components: _.map(scenario.currentSet.components, component => setup[component].address), set2Components: _.map(scenario.nextSet.components, component => setup[component].address), set1Units: scenario.currentSet.units, set2Units: scenario.nextSet.units, set1NaturalUnit: scenario.currentSet.naturalUnit, set2NaturalUnit: scenario.nextSet.naturalUnit, }); const assetPairVolumeBounds = [ { assetOne: setup.component1.address, assetTwo: setup.component2.address, bounds: {lower: ether(10 ** 4), upper: ether(10 ** 7)}, }, { assetOne: setup.component2.address, assetTwo: setup.component3.address, bounds: {lower: ZERO, upper: ether(10 ** 6)}, }, ]; liquidator = await liquidatorHelper.deployTWAPLiquidatorAsync( setup.core.address, setup.oracleWhiteList.address, auctionPeriod, rangeStart, rangeEnd, assetPairVolumeBounds, name, ); await coreHelper.addAddressToWhiteList(liquidator.address, setup.liquidatorWhitelist); const failPeriod = ONE_DAY_IN_SECONDS; const { timestamp: lastRebalanceTimestamp } = await web3.eth.getBlock('latest'); rebalancingSetToken = await rebalancingHelper.createDefaultRebalancingSetTokenV3Async( setup.core, setup.rebalancingFactory.address, managerAccount, liquidator.address, feeRecipient, setup.fixedFeeCalculator.address, setup.set1.address, failPeriod, lastRebalanceTimestamp, ZERO, // entry fee ZERO, // rebalance fee scenario.rebalancingSet.unitShares ); await setup.setRebalancingSet(rebalancingSetToken); await setup.mintRebalancingSets(scenario.rebalancingSet.supply); } async function startRebalance(): Promise<void> { const { chunkSize, chunkAuctionPeriod } = scenario.auction; const liquidatorData = liquidatorHelper.generateTWAPLiquidatorCalldata(chunkSize, chunkAuctionPeriod); await rebalancingHelper.transitionToRebalanceV2Async( setup.core, setup.rebalancingComponentWhiteList, setup.rebalancingSetToken, setup.set2, managerAccount, liquidatorData, ); } async function runChunkAuctions(): Promise<void> { const {chunkAuctionPeriod } = scenario.auction; while (await hasNextAuction()) { console.log(`==================================================`); console.log('Auction ', auctionCounter); const timeToFV = ONE_HOUR_IN_SECONDS.div(6); await blockchain.increaseTimeAsync(timeToFV); await blockchain.mineBlockAsync(); const deployerComponent1 = await setup.component1.balanceOf.callAsync(deployerAccount); const deployerComponent2 = await setup.component2.balanceOf.callAsync(deployerAccount); // Bid the entire quantity const remainingBids = await liquidator.remainingCurrentSets.callAsync(setup.rebalancingSetToken.address); await rebalancingHelper.bidAndWithdrawAsync( setup.rebalanceAuctionModule, setup.rebalancingSetToken.address, remainingBids, ); await printAuction(deployerComponent1, deployerComponent2); // If not the last auction, then iterate to next auction if (await hasNextAuction()) { await blockchain.increaseTimeAsync(chunkAuctionPeriod); await updatePrices(); await blockchain.mineBlockAsync(); await liquidator.iterateChunkAuction.sendTransactionAsync( setup.rebalancingSetToken.address, { from: deployerAccount, gas: DEFAULT_GAS } ); auctionCounter++; } } async function hasNextAuction(): Promise<boolean> { const totalRemaining = await liquidator.getTotalSetsRemaining.callAsync(setup.rebalancingSetToken.address); const minBid = await liquidator.minimumBid.callAsync(setup.rebalancingSetToken.address); return totalRemaining.gte(minBid); } async function updatePrices(): Promise<void> { const { component1PriceChange, component2PriceChange, } = scenario.auction; const priceUpdate: PriceUpdate = {}; if (!component1PriceChange.isZero()) { const existingComponent1Price = await setup.component1Oracle.read.callAsync(); priceUpdate.component1Price = existingComponent1Price.mul(ONE.plus(component1PriceChange)); } if (!component2PriceChange.isZero()) { const existingComponent2Price = await setup.component2Oracle.read.callAsync(); priceUpdate.component2Price = existingComponent2Price.mul(ONE.plus(component2PriceChange)); } await setup.jumpTimeAndUpdateOracles(ZERO, priceUpdate); } } async function printAuction(deployerComponent1: BigNumber, deployerComponent2: BigNumber): Promise<void> { const totalRemaining = await liquidator.getTotalSetsRemaining.callAsync(setup.rebalancingSetToken.address); const timestamp = await liquidator.getLastChunkAuctionEnd.callAsync(setup.rebalancingSetToken.address); const remainingCurrentSets = await liquidator.remainingCurrentSets.callAsync(setup.rebalancingSetToken.address); const deployerComponent1Post = await setup.component1.balanceOf.callAsync(deployerAccount); const deployerComponent2Post = await setup.component2.balanceOf.callAsync(deployerAccount); const existingComponent1Price = await setup.component1Oracle.read.callAsync(); const existingComponent2Price = await setup.component2Oracle.read.callAsync(); const component1ChangeUSD = await valuationHelper.computeTokenDollarAmount( existingComponent1Price, deployerComponent1Post.sub(deployerComponent1), new BigNumber(scenario.components.component1Decimals), ); const component2ChangeUSD = await valuationHelper.computeTokenDollarAmount( existingComponent2Price, deployerComponent2Post.sub(deployerComponent2), new BigNumber(scenario.components.component2Decimals), ); console.log('Component 1 Price: ', deScale(existingComponent1Price).toString()); console.log('Component 2 Price: ', deScale(existingComponent2Price).toString()); console.log('Component 1 Bidder $ Delta: ', deScale(component1ChangeUSD).toString()); console.log('Component 2 Bidder $ Delta: ', deScale(component2ChangeUSD).toString()); console.log(`Total Order Remaining: ${totalRemaining}`); console.log(`Auction Remaining Sets: ${remainingCurrentSets}`); console.log(`Completion Timestamp: ${timestamp}`); } });
the_stack
import * as _ from 'lodash'; import type { FirestoreConnectorModel } from '../model'; import type { Transaction } from '../db/transaction'; import { StatusError } from './status-error'; import { MorphReference } from '../db/morph-reference'; import { FieldOperation } from '../db/field-operation'; import { isEqualHandlingRef, Reference } from '../db/reference'; import { NormalReference } from '../db/normal-reference'; import { DeepReference } from '../db/deep-reference'; import { mapNotNull } from './map-not-null'; export interface RelationInfo<T extends object> { model: FirestoreConnectorModel<T> attr: RelationAttrInfo | undefined parentModels: RelationInfo<any>[] | undefined } export interface RelationAttrInfo { alias: string isArray: boolean filter: string | undefined isMorph: boolean /** * Indicates that this is a "virtual" attribute * which is metadata/index map for a repeatable component, * or a deep path to a non-repeatable component, * and the actual alias inside the component is this value. */ actualAlias: { componentAlias: string parentAlias: string } | undefined /** * Indicates that this is a metadata/index map, not a path to * an actual attribute. */ isMeta: boolean } export class RelationHandler<T extends object, R extends object = object> { constructor( private readonly thisEnd: RelationInfo<T>, private readonly otherEnds: RelationInfo<R>[], ) { if (!thisEnd.attr && !otherEnds.some(e => e.attr)) { throw new Error('Relation does not have any dominant ends defined'); } if (otherEnds.some(e => e.model.isComponent && (!e.attr || thisEnd.attr))) { throw new Error('Relation cannot have a dominant reference to a component'); } // Virtual collections are probably transient/unstable unless `hasStableIds` is explicitly set // so references to a virtual collection should not be stored in the database // But we allow virtual collections to refer to other virtual collections because they are not stored in the database if (thisEnd.attr && !thisEnd.model.options.virtualDataSource && otherEnds.some(e => e.model.options.virtualDataSource && !e.model.options.virtualDataSource.hasStableIds)) { throw new Error('Non-virtual collection cannot have a dominant relation to a virtual collection without stable IDs'); } } /** * Gets the alias of this relation, or `undefined` * if this end of the relation is not dominant. */ get alias(): string | undefined { return this.thisEnd.attr?.alias; } /** * Finds references to the related models on the given object. * The related models are not necessarily fetched. */ async findRelated(ref: Reference<T>, data: T, transaction: Transaction): Promise<Reference<R>[]> { const { attr } = this.thisEnd; const related = attr ? this._getRefInfo(data, attr) : await this._queryRelated(ref, transaction, false); return related.map(r => r.ref); } /** * Updates the the related models on the given object. */ async update(ref: Reference<T>, prevData: T | undefined, newData: T | undefined, editMode: 'create' | 'update', transaction: Transaction): Promise<void> { const { attr: thisAttr } = this.thisEnd; if (thisAttr) { // This end is dominant // So we know all the other ends directly without querying // Update operations will not touch keys that don't exist // If the data doesn't have the key, then don't update the relation because we aren't touching it // If newData is undefined then we are deleting and we do need to update the relation if ((editMode === 'update') && newData && (_.get(newData, thisAttr.alias) === undefined)) { return; } const prevValues = this._getRefInfo(prevData, thisAttr); const newValues = this._getRefInfo(newData, thisAttr); // Set the value stored in this document appropriately this._setThis(newData, thisAttr, newValues.map(v => this._makeRefToOther(v.ref, thisAttr))); // Set the value stored in the references documents appropriately const removed = _.differenceWith(prevValues, newValues, (a, b) => isEqualHandlingRef(a.ref, b.ref)); const added = _.differenceWith(newValues, prevValues, (a, b) => isEqualHandlingRef(a.ref, b.ref)); const related = [ ...removed.map(info => ({ info, set: false })), ...added.map(info => ({ info, set: true })), ]; await this._setAllRelated(related, ref, transaction); } else { // I.e. thisAttr == null (meaning this end isn't dominant) if (!newData) { // This end is being deleted and it is not dominant // so we need to search for the dangling references existing on other models const related = await this._queryRelated(ref, transaction, true); await this._setAllRelated(related.map(info => ({ info, set: false })), ref, transaction); } else { // This end isn't dominant // But it isn't being deleted so there is // no action required on the other side } } } /** * Populates the related models onto the given object for this relation. */ async populateRelated(ref: Reference<T>, data: T, transaction: Transaction): Promise<void> { const { attr } = this.thisEnd; // This could be a partial data update // If the attribute value does not exist in the data, then we ignore it if (attr && (_.get(data, attr.alias) !== undefined)) { const related = await this.findRelated(ref, data, transaction); const results = related.length ? await transaction.getNonAtomic(related) : []; const values = mapNotNull(results, snap => { const data = snap.data(); if (!data) { // TODO: // Should we throw an error if the reference can't be found or just silently omit it? strapi.log.warn( `Could not populate the reference "${snap.ref.path}" because it no longer exists. ` + 'This may be because the database has been modified outside of Strapi, or there is a bug in the Firestore connector.' ); } return data; }); // The values will be correctly coerced // into and array or single value by the method below this._setThis(data, attr, values); } } private get _singleOtherEnd(): RelationInfo<R> | undefined { return (this.otherEnds.length === 1) ? this.otherEnds[0] : undefined; } /** * Creates an appropriate `ReferenceShape` to store in the documents * at the other end, properly handling polymorphic references. * * @param ref The reference to this * @param otherAttr Attribute info of the other end (which refers to this) */ private _makeRefToThis(ref: Reference<T>, otherAttr: RelationAttrInfo): Reference<T> { if (otherAttr.isMorph && !(ref instanceof MorphReference)) { const { attr } = this.thisEnd; if (!attr && otherAttr.filter) { throw new Error('Polymorphic reference does not have the required information'); } if ((ref instanceof NormalReference) || (ref instanceof DeepReference)) { ref = new MorphReference(ref, attr ? attr.alias : null); } else { throw new Error(`Unknown type of reference: ${ref}`); } } return ref; } /** * Checks the `Reference` to store in this document, * properly handling polymorphic references. * * @param otherRef The reference to the other end */ private _makeRefToOther(otherRef: Reference<R> | null | undefined, thisAttr: RelationAttrInfo): Reference<R> | null { if (otherRef) { if (thisAttr.isMorph && !(otherRef instanceof MorphReference)) { // The reference would have been coerced to an instance of MorphReference // only if it was an object with the required info throw new Error('Polymorphic reference does not have the required information'); } else { return otherRef; } } return null; } private _setThis(data: T | undefined, { alias, isArray }: RelationAttrInfo, value: any) { if (data) { if (isArray) { const val = value ? _.castArray(value) : []; _.set(data, alias, val); } else { const val = value ? (Array.isArray(value) ? value[0] || null : value) : null; _.set(data, alias, val); } } } private async _setAllRelated(refs: { info: RefInfo<T, R>, set: boolean }[], thisRef: Reference<T>, transaction: Transaction) { refs = refs.filter(r => r.info.attr); // Batch-get all the references that we need to fetch // I.e. the ones inside component arrays that required manual manipulation const toGet: Reference<R>[] = []; const infos = new Array<{ attr: RelationAttrInfo, ref: Reference<R>, set: boolean, thisRefValue: Reference<T> | undefined, snapIndex?: number } | undefined>(refs.length); for (let i = 0; i < refs.length; i++) { const { info, set } = refs[i]; // Filter to those that have a dominant other end if (info.attr) { infos[i] = { attr: info.attr, ref: info.ref, thisRefValue: info.thisRefValue, set, }; // Set aside to fetch this relation if (info.attr.isMeta) { infos[i]!.snapIndex = toGet.length; toGet.push(info.ref); } } } const snaps = toGet.length ? await transaction.getAtomic(toGet) : []; // Perform all the write operations on the relations await Promise.all( infos.map(async info => { if (info) { const data = info.snapIndex !== undefined ? snaps[info.snapIndex].data() : undefined; const thisRefValue = info.thisRefValue || this._makeRefToThis(thisRef, info.attr); await this._setRelated(info.ref, info.attr, data, thisRefValue, info.set, transaction) } }) ); } private async _setRelated(ref: Reference<R>, attr: RelationAttrInfo, prevData: R | undefined, thisRefValue: Reference<T>, set: boolean, transaction: Transaction) { const value = set ? (attr.isArray ? FieldOperation.arrayUnion(thisRefValue) : thisRefValue) : (attr.isArray ? FieldOperation.arrayRemove(thisRefValue) : null); if (attr.isMeta) { if (!prevData) { // Relation no longer exists, do not update return; } const { componentAlias, parentAlias } = attr.actualAlias!; // The attribute is a metadata map for an array of components // This requires special handling // We need to atomically fetch and process the data then update // Extract a new object with only the fields that are being updated const newData: any = {}; const components = _.get(prevData, parentAlias); _.set(newData, parentAlias, components); for (const component of _.castArray(components)) { if (component) { FieldOperation.apply(component, componentAlias, value); } } await transaction.update(ref, newData, { updateRelations: false }); } else { // TODO: Safely handle relations that no longer exist await transaction.update(ref, { [attr.alias]: value } as object, { updateRelations: false }); } } private async _queryRelated(ref: Reference<T>, transaction: Transaction, atomic: boolean, otherEnds = this.otherEnds): Promise<RefInfo<T, R>[]> { const snaps = otherEnds.map(async otherEnd => { const { model, attr, parentModels } = otherEnd; if (parentModels && parentModels.length) { // Find instances of the parent document containing // a component instance that references this return await this._queryRelated(ref, transaction, atomic, parentModels); } if (attr) { // The refValue will be coerced appropriately // by the model that is performing the query const refValue = this._makeRefToThis(ref, attr); const operator = attr.isArray ? 'array-contains' : '=='; let q = model.db.where({ field: attr.alias, operator, value: refValue }); if (model.options.maxQuerySize) { q = q.limit(model.options.maxQuerySize); } const snap = atomic ? await transaction.getAtomic(q) : await transaction.getNonAtomic(q); return snap.docs.map(d => makeRefInfo(otherEnd, d.ref, refValue)); } else { return []; } }); return (await Promise.all(snaps)).flat(); } private _getRefInfo(data: T | undefined, thisAttr: RelationAttrInfo) { return mapNotNull( _.castArray(_.get(data, thisAttr.alias) || []), v => this._getSingleRefInfo(v) ); } private _getSingleRefInfo(ref: any): RefInfo<T, R> | null { let other = this._singleOtherEnd; if (ref) { if (!(ref instanceof Reference)) { throw new Error('Value is not an instance of Reference. Data must be coerced before updating relations.') } if (!other) { // Find the end which this reference relates to other = this.otherEnds.find(({ model }) => model.db.path === ref.parent.path); if (!other) { throw new StatusError( `Reference "${ref.path}" does not refer to any of the available models: ` + this.otherEnds.map(e => `"${e.model.uid}"`).join(', '), 400, ); } } return makeRefInfo(other, ref, undefined); } return null; } } interface RefInfo<T extends object, R extends object> { ref: Reference<R> model: FirestoreConnectorModel<R> /** * If the snapshot was found by querying, then this is the * reference value that was used in the query. */ thisRefValue: Reference<T> | undefined /** * The attribute info of the other end (referred to by `ref`). */ attr: RelationAttrInfo | undefined } function makeRefInfo<T extends object, R extends object>(info: RelationInfo<R>, ref: Reference<R>, thisRefValue: Reference<T> | undefined): RefInfo<T, R> { return { ...info, ref, thisRefValue, }; }
the_stack
import warning from 'warning'; import Handler, { Builder, FunctionalHandler, Pattern, Predicate, matchPattern, } from './Handler'; export default class TelegramHandler extends Handler { onCallbackQuery( ...args: | [Predicate, FunctionalHandler | Builder] | [FunctionalHandler | Builder] ) { if (args.length < 2) { const [handler] = args as [FunctionalHandler | Builder]; this.on((context) => context.event.isCallbackQuery, handler); } else { const [predicate, handler] = args as [ Predicate, FunctionalHandler | Builder ]; warning( typeof predicate === 'function', `'onCallbackQuery' only accepts function, but received ${typeof predicate}` ); this.on( (context) => context.event.isCallbackQuery && predicate(context.event.callbackQuery, context), handler ); } return this; } onPayload( ...args: | [Pattern, FunctionalHandler | Builder] | [FunctionalHandler | Builder] ) { if (args.length < 2) { const [handler] = args as [FunctionalHandler | Builder]; this.on((context) => context.event.isPayload, handler); } else { // eslint-disable-next-line prefer-const let [pattern, handler]: [Pattern, FunctionalHandler | Builder] = args as any; if ('build' in handler) { handler = handler.build(); } warning( typeof pattern === 'function' || typeof pattern === 'string' || pattern instanceof RegExp, `'onPayload' only accepts string, regex or function, but received ${typeof pattern}` ); if (typeof pattern === 'function') { const predicate: Predicate = pattern; this.on( (context) => context.event.isPayload && predicate(context.event.payload, context), handler ); } else { if (pattern instanceof RegExp) { const patternRegExp: RegExp = pattern; const _handler = handler; handler = (context) => { const match = patternRegExp.exec(context.event.payload); if (!match) return _handler(context); // reset index so we start at the beginning of the regex each time patternRegExp.lastIndex = 0; return _handler(context, match); }; } this.on( ({ event }) => event.isPayload && matchPattern(pattern, event.payload), handler ); } } return this; } onPhoto( ...args: | [Predicate, FunctionalHandler | Builder] | [FunctionalHandler | Builder] ) { if (args.length < 2) { const [handler] = args as [FunctionalHandler | Builder]; this.on((context) => context.event.isPhoto, handler); } else { const [predicate, handler] = args as [ Predicate, FunctionalHandler | Builder ]; warning( typeof predicate === 'function', `'onPhoto' only accepts function, but received ${typeof predicate}` ); this.on( (context) => context.event.isPhoto && predicate(context.event.photo, context), handler ); } return this; } onDocument( ...args: | [Predicate, FunctionalHandler | Builder] | [FunctionalHandler | Builder] ) { if (args.length < 2) { const [handler] = args as [FunctionalHandler | Builder]; this.on((context) => context.event.isDocument, handler); } else { const [predicate, handler] = args as [ Predicate, FunctionalHandler | Builder ]; warning( typeof predicate === 'function', `'onDocument' only accepts function, but received ${typeof predicate}` ); this.on( (context) => context.event.isDocument && predicate(context.event.document, context), handler ); } return this; } onAudio( ...args: | [Predicate, FunctionalHandler | Builder] | [FunctionalHandler | Builder] ) { if (args.length < 2) { const [handler] = args as [FunctionalHandler | Builder]; this.on((context) => context.event.isAudio, handler); } else { const [predicate, handler] = args as [ Predicate, FunctionalHandler | Builder ]; warning( typeof predicate === 'function', `'onAudio' only accepts function, but received ${typeof predicate}` ); this.on( (context) => context.event.isAudio && predicate(context.event.audio, context), handler ); } return this; } onGame( ...args: | [Predicate, FunctionalHandler | Builder] | [FunctionalHandler | Builder] ) { if (args.length < 2) { const [handler] = args as [FunctionalHandler | Builder]; this.on((context) => context.event.isGame, handler); } else { const [predicate, handler] = args as [ Predicate, FunctionalHandler | Builder ]; warning( typeof predicate === 'function', `'onGame' only accepts function, but received ${typeof predicate}` ); this.on( (context) => context.event.isGame && predicate(context.event.game, context), handler ); } return this; } onSticker( ...args: | [Predicate, FunctionalHandler | Builder] | [FunctionalHandler | Builder] ) { if (args.length < 2) { const [handler] = args as [FunctionalHandler | Builder]; this.on((context) => context.event.isSticker, handler); } else { const [predicate, handler] = args as [ Predicate, FunctionalHandler | Builder ]; warning( typeof predicate === 'function', `'onSticker' only accepts function, but received ${typeof predicate}` ); this.on( (context) => context.event.isSticker && predicate(context.event.sticker, context), handler ); } return this; } onVideo( ...args: | [Predicate, FunctionalHandler | Builder] | [FunctionalHandler | Builder] ) { if (args.length < 2) { const [handler] = args as [FunctionalHandler | Builder]; this.on((context) => context.event.isVideo, handler); } else { const [predicate, handler] = args as [ Predicate, FunctionalHandler | Builder ]; warning( typeof predicate === 'function', `'onVideo' only accepts function, but received ${typeof predicate}` ); this.on( (context) => context.event.isVideo && predicate(context.event.video, context), handler ); } return this; } onVoice( ...args: | [Predicate, FunctionalHandler | Builder] | [FunctionalHandler | Builder] ) { if (args.length < 2) { const [handler] = args as [FunctionalHandler | Builder]; this.on((context) => context.event.isVoice, handler); } else { const [predicate, handler] = args as [ Predicate, FunctionalHandler | Builder ]; warning( typeof predicate === 'function', `'onVoice' only accepts function, but received ${typeof predicate}` ); this.on( (context) => context.event.isVoice && predicate(context.event.voice, context), handler ); } return this; } onVideoNote( ...args: | [Predicate, FunctionalHandler | Builder] | [FunctionalHandler | Builder] ) { if (args.length < 2) { const [handler] = args as [FunctionalHandler | Builder]; this.on((context) => context.event.isVideoNote, handler); } else { const [predicate, handler] = args as [ Predicate, FunctionalHandler | Builder ]; warning( typeof predicate === 'function', `'onVideoNote' only accepts function, but received ${typeof predicate}` ); this.on( (context) => context.event.isVideoNote && predicate(context.event.videoNote, context), handler ); } return this; } onContact( ...args: | [Predicate, FunctionalHandler | Builder] | [FunctionalHandler | Builder] ) { if (args.length < 2) { const [handler] = args as [FunctionalHandler | Builder]; this.on((context) => context.event.isContact, handler); } else { const [predicate, handler] = args as [ Predicate, FunctionalHandler | Builder ]; warning( typeof predicate === 'function', `'onContact' only accepts function, but received ${typeof predicate}` ); this.on( (context) => context.event.isContact && predicate(context.event.contact, context), handler ); } return this; } onLocation( ...args: | [Predicate, FunctionalHandler | Builder] | [FunctionalHandler | Builder] ) { if (args.length < 2) { const [handler] = args as [FunctionalHandler | Builder]; this.on((context) => context.event.isLocation, handler); } else { const [predicate, handler] = args as [ Predicate, FunctionalHandler | Builder ]; warning( typeof predicate === 'function', `'onLocation' only accepts function, but received ${typeof predicate}` ); this.on( (context) => context.event.isLocation && predicate(context.event.location, context), handler ); } return this; } onVenue( ...args: | [Predicate, FunctionalHandler | Builder] | [FunctionalHandler | Builder] ) { if (args.length < 2) { const [handler] = args as [FunctionalHandler | Builder]; this.on((context) => context.event.isVenue, handler); } else { const [predicate, handler] = args as [ Predicate, FunctionalHandler | Builder ]; warning( typeof predicate === 'function', `'onVenue' only accepts function, but received ${typeof predicate}` ); this.on( (context) => context.event.isVenue && predicate(context.event.venue, context), handler ); } return this; } }
the_stack
import * as ts from 'typescript' import { VNodeFlags, ChildFlags } from './utils/flags' import isComponent from './utils/isComponent' import isFragment from './utils/isFragment' import createAssignHelper from './utils/createAssignHelper' import isNullOrUndefined from './utils/isNullOrUndefined' import getName from './utils/getName' import getValue from './utils/getValue' import svgAttributes from './utils/svgAttributes' import isNodeNull from './utils/isNodeNull' import handleWhiteSpace from './utils/handleWhiteSpace' import vNodeTypes from './utils/vNodeTypes' import updateSourceFile from './updateSourceFile' let NULL // All special attributes let PROP_HasKeyedChildren = '$HasKeyedChildren' let PROP_HasNonKeyedChildren = '$HasNonKeyedChildren' let PROP_VNODE_CHILDREN = '$HasVNodeChildren' let PROP_TEXT_CHILDREN = '$HasTextChildren' let PROP_ReCreate = '$ReCreate' let PROP_ChildFlag = '$ChildFlag' const TYPE_ELEMENT = 0 const TYPE_COMPONENT = 1 const TYPE_FRAGMENT = 2 export default () => { return (context: ts.TransformationContext): ts.Transformer<ts.SourceFile> => { return (sourceFile: ts.SourceFile) => { if (sourceFile.isDeclarationFile) { return sourceFile } context['createFragment'] = false context['createVNode'] = false context['createComponentVNode'] = false context['createTextVNode'] = false context['normalizeProps'] = false let newSourceFile = ts.visitEachChild(sourceFile, visitor, context) return updateSourceFile(newSourceFile, context) } function visitor(node: ts.Node): ts.VisitResult<ts.Node> { switch (node.kind) { case ts.SyntaxKind.JsxFragment: return createFragment((<ts.JsxFragment>node).children) case ts.SyntaxKind.JsxElement: return createVNode( <ts.JsxElement>node, (<ts.JsxElement>node).children ) case ts.SyntaxKind.JsxSelfClosingElement: return createVNode(<ts.JsxSelfClosingElement>node) case ts.SyntaxKind.JsxText: let text = handleWhiteSpace(node.getFullText()) if (text !== '') { /** * TypeScript internal module, src/compiler/transformers/jsx.ts, * unescapes HTML entities such as &nbsp; in JSX text that is * directly inside an element or a fragment. */ return ts.createLiteral( JSON.parse( ts .transpile(`<>${text}</>`, { jsx: ts.JsxEmit.React }) .replace(/^[\s\S]*?("[\s\S]*")[\s\S]*?$/, '$1') ) ) } break case ts.SyntaxKind.JsxExpression: if ((<ts.JsxExpression>node).expression) { return ts.visitNode((<ts.JsxExpression>node).expression, visitor) } break default: return ts.visitEachChild(node, visitor, context) } } function addCreateTextVNodeCalls(vChildren) { // When normalization is not needed we need to manually compile text into vNodes for (var j = 0; j < vChildren.elements.length; j++) { var aChild = vChildren.elements[j] if (aChild.kind === ts.SyntaxKind.StringLiteral) { vChildren.elements[j] = ts.createCall( ts.createIdentifier('createTextVNode'), [], [aChild] ) } } return vChildren } function transformTextNodes(vChildren) { context['createTextVNode'] = true if (vChildren.elements) { return addCreateTextVNodeCalls(vChildren) } if (vChildren.kind === ts.SyntaxKind.StringLiteral) { return ts.createCall( ts.createIdentifier('createTextVNode'), [], [vChildren] ) } } function createFragmentVNodeArgs(children, childFlags, key?) { var args = [] var hasChildren = !isNodeNull(children) var hasChildFlags = hasChildren && childFlags !== ChildFlags.HasInvalidChildren var hasKey = !isNodeNull(key) if (hasChildren) { if ( childFlags === ChildFlags.HasNonKeyedChildren || childFlags === ChildFlags.HasKeyedChildren || childFlags === ChildFlags.UnknownChildren || children.kind === ts.SyntaxKind.ArrayLiteralExpression ) { args.push(children) } else { args.push(ts.createArrayLiteral([children])) } } else if (hasChildFlags || hasKey) { args.push(NULL) } if (hasChildFlags) { args.push( typeof childFlags === 'number' ? ts.createNumericLiteral(childFlags + '') : childFlags ) } else if (hasKey) { args.push(ts.createNumericLiteral(ChildFlags.HasInvalidChildren + '')) } if (hasKey) { args.push(key) } return args } function createFragment(children?: ts.NodeArray<ts.JsxChild>) { let childrenResults = getVNodeChildren(children) let vChildren = childrenResults.children let childFlags if (!childrenResults.requiresNormalization) { if (childrenResults.parentCanBeKeyed) { childFlags = ChildFlags.HasKeyedChildren } else { childFlags = ChildFlags.HasNonKeyedChildren } if (childrenResults.hasSingleChild) { vChildren = ts.createArrayLiteral([vChildren]) } } else { childFlags = ChildFlags.UnknownChildren } if (vChildren && vChildren !== NULL && childrenResults.foundText) { vChildren = transformTextNodes(vChildren) } context['createFragment'] = true return ts.createCall( ts.createIdentifier('createFragment'), [], createFragmentVNodeArgs(vChildren, childFlags) ) } function createVNode( node: ts.JsxElement | ts.JsxSelfClosingElement, children?: ts.NodeArray<ts.JsxChild> ) { let vType let vProps let vChildren let childrenResults: any = {} let text if (children) { let openingElement = (<ts.JsxElement>node).openingElement vType = getVNodeType(openingElement.tagName) vProps = getVNodeProps( openingElement.attributes.properties, vType.vNodeType === TYPE_COMPONENT ) childrenResults = getVNodeChildren(children) vChildren = childrenResults.children } else { vType = getVNodeType((<ts.JsxSelfClosingElement>node).tagName) vProps = getVNodeProps( (<ts.JsxSelfClosingElement>node).attributes.properties, vType.vNodeType === TYPE_COMPONENT ) } let childFlags = ChildFlags.HasInvalidChildren let flags = vType.flags let props: any = vProps.props[0] || ts.createObjectLiteral() let childIndex = -1 let i = 0 if (vProps.hasReCreateFlag) { flags = flags | VNodeFlags.ReCreate } if (vProps.contentEditable) { flags = flags | VNodeFlags.ContentEditable } if (vType.vNodeType === TYPE_COMPONENT) { if (vChildren) { if ( !( vChildren.kind === ts.SyntaxKind.ArrayLiteralExpression && vChildren.elements.length === 0 ) ) { // Remove children from props, if it exists for (i = 0; i < props.properties.length; i++) { if ( props.properties[i] && props.properties[i].name.text === 'children' ) { childIndex = i break } } if (childIndex !== -1) { props.properties.splice(childIndex, 1) // Remove prop children } props.properties.push( ts.createPropertyAssignment(getName('children'), vChildren) ) vProps.props[0] = props } vChildren = NULL } } else { if ( ((vChildren && vChildren.kind === ts.SyntaxKind.ArrayLiteralExpression) || !vChildren) && vProps.propChildren ) { if (vProps.propChildren.kind === ts.SyntaxKind.StringLiteral) { text = handleWhiteSpace(vProps.propChildren.text) if (text !== '') { if (vType.vNodeType !== TYPE_FRAGMENT) { childrenResults.foundText = true childrenResults.hasSingleChild = true } vChildren = ts.createLiteral(text) } } else if (vProps.propChildren.kind === ts.SyntaxKind.JsxExpression) { if ( vProps.propChildren.expression.kind === ts.SyntaxKind.NullKeyword ) { vChildren = NULL childFlags = ChildFlags.HasInvalidChildren } else { vChildren = createVNode( vProps.propChildren.expression, vProps.propChildren.expression.children ) childFlags = ChildFlags.HasVNodeChildren } } else { vChildren = NULL childFlags = ChildFlags.HasInvalidChildren } } if ( (childrenResults && !childrenResults.requiresNormalization) || vProps.childrenKnown ) { if (vProps.hasKeyedChildren || childrenResults.parentCanBeKeyed) { childFlags = ChildFlags.HasKeyedChildren } else if ( vProps.hasNonKeyedChildren || childrenResults.parentCanBeNonKeyed ) { childFlags = ChildFlags.HasNonKeyedChildren } else if ( vProps.hasTextChildren || (childrenResults.foundText && childrenResults.hasSingleChild) ) { childrenResults.foundText = vType.vNodeType === TYPE_FRAGMENT childFlags = vType.vNodeType === TYPE_FRAGMENT ? ChildFlags.HasNonKeyedChildren : ChildFlags.HasTextChildren } else if (childrenResults.hasSingleChild) { childFlags = vType.vNodeType === TYPE_FRAGMENT ? ChildFlags.HasNonKeyedChildren : ChildFlags.HasVNodeChildren } } else { if (vProps.hasKeyedChildren) { childFlags = ChildFlags.HasKeyedChildren } else if (vProps.hasNonKeyedChildren) { childFlags = ChildFlags.HasNonKeyedChildren } } // Remove children from props, if it exists childIndex = -1 for (i = 0; i < props.properties.length; i++) { if ( props.properties[i].name && props.properties[i].name.text === 'children' ) { childIndex = i break } } if (childIndex !== -1) { props.properties.splice(childIndex, 1) // Remove prop children } } if (vChildren && vChildren !== NULL && childrenResults.foundText) { vChildren = transformTextNodes(vChildren) } let willNormalizeChildren = !(vType.vNodeType === TYPE_COMPONENT) && childrenResults && childrenResults.requiresNormalization && !vProps.childrenKnown if (vProps.childFlags) { // If $ChildFlag is provided it is runtime dependant childFlags = vProps.childFlags } else { childFlags = willNormalizeChildren ? ChildFlags.UnknownChildren : childFlags } // Delete empty objects if ( vProps.props.length === 1 && vProps.props[0] && !vProps.props[0].properties.length ) { vProps.props.splice(0, 1) } let createVNodeCall if (vType.vNodeType === TYPE_COMPONENT) { createVNodeCall = ts.createCall( ts.createIdentifier('createComponentVNode'), [], createComponentVNodeArgs( flags, vType.type, vProps.props, vProps.key, vProps.ref ) ) context['createComponentVNode'] = true } else if (vType.vNodeType === TYPE_ELEMENT) { createVNodeCall = ts.createCall( ts.createIdentifier('createVNode'), [], createVNodeArgs( flags, vType.type, vProps.className, vChildren, childFlags, vProps.props, vProps.key, vProps.ref, context ) ) context['createVNode'] = true } else if (vType.vNodeType === TYPE_FRAGMENT) { if ( !childrenResults.requiresNormalization && childrenResults.hasSingleChild ) { vChildren = ts.createArrayLiteral([vChildren]) } createVNodeCall = ts.createCall( ts.createIdentifier('createFragment'), [], createFragmentVNodeArgs(vChildren, childFlags, vProps.key) ) context['createFragment'] = true } // NormalizeProps will normalizeChildren too if (vProps.needsNormalization) { context['normalizeProps'] = true createVNodeCall = ts.createCall( ts.createIdentifier('normalizeProps'), [], [createVNodeCall] ) } return createVNodeCall } function getVNodeType(type) { let vNodeType let flags const text = type.getText() const textSplitted = text.split('.') const length = textSplitted.length const finalText = textSplitted[length - 1] if (isFragment(finalText)) { vNodeType = TYPE_FRAGMENT } else if (isComponent(finalText)) { vNodeType = TYPE_COMPONENT flags = VNodeFlags.ComponentUnknown } else { vNodeType = TYPE_ELEMENT type = ts.createLiteral(text) flags = vNodeTypes[text] || VNodeFlags.HtmlElement } return { type: type, vNodeType: vNodeType, flags: flags, } } function getVNodeProps(astProps, isComponent) { let props = [] let key = null let ref = null let className = null let hasTextChildren = false let hasKeyedChildren = false let hasNonKeyedChildren = false let childrenKnown = false let needsNormalization = false let hasReCreateFlag = false let propChildren = null let childFlags = null let contentEditable = false let assignArgs = [] for (let i = 0; i < astProps.length; i++) { let astProp = astProps[i] const initializer = astProp.initializer if (astProp.kind === ts.SyntaxKind.JsxSpreadAttribute) { needsNormalization = true assignArgs = [ts.createObjectLiteral(), astProp.expression] } else { let propName = astProp.name.text if ( !isComponent && (propName === 'className' || propName === 'class') ) { className = getValue(initializer, visitor) } else if (!isComponent && propName === 'htmlFor') { props.push( ts.createPropertyAssignment( getName('for'), getValue(initializer, visitor) ) ) } else if (!isComponent && propName === 'onDoubleClick') { props.push( ts.createPropertyAssignment( getName('onDblClick'), getValue(initializer, visitor) ) ) } else if (propName.substr(0, 11) === 'onComponent' && isComponent) { if (!ref) { ref = ts.createObjectLiteral([]) } ref.properties.push( ts.createPropertyAssignment( getName(propName), getValue(initializer, visitor) ) ) } else if (!isComponent && propName in svgAttributes) { // React compatibility for SVG Attributes props.push( ts.createPropertyAssignment( getName(svgAttributes[propName]), getValue(initializer, visitor) ) ) } else { switch (propName) { case 'noNormalize': case '$NoNormalize': throw 'Inferno JSX plugin:\n' + propName + ' is deprecated use: $HasVNodeChildren, or if children shape is dynamic you can use: $ChildFlag={expression} see inferno package:inferno-vnode-flags (ChildFlags) for possible values' case 'hasKeyedChildren': case 'hasNonKeyedChildren': throw 'Inferno JSX plugin:\n' + propName + ' is deprecated use: ' + '$' + propName.charAt(0).toUpperCase() + propName.slice(1) case PROP_ChildFlag: childrenKnown = true childFlags = getValue(initializer, visitor) break case PROP_VNODE_CHILDREN: childrenKnown = true break case PROP_TEXT_CHILDREN: childrenKnown = true hasTextChildren = true break case PROP_HasNonKeyedChildren: hasNonKeyedChildren = true childrenKnown = true break case PROP_HasKeyedChildren: hasKeyedChildren = true childrenKnown = true break case 'ref': ref = getValue(initializer, visitor) break case 'key': key = getValue(initializer, visitor) break case PROP_ReCreate: hasReCreateFlag = true break default: if (propName === 'children') { propChildren = astProp.initializer } if (propName.toLowerCase() === 'contenteditable') { contentEditable = true } props.push( ts.createPropertyAssignment( getName(propName), initializer ? getValue(initializer, visitor) : ts.createTrue() ) ) } } } } if (props.length) assignArgs.push(ts.createObjectLiteral(props)) return { props: assignArgs, key: isNullOrUndefined(key) ? NULL : key, ref: isNullOrUndefined(ref) ? NULL : ref, hasKeyedChildren: hasKeyedChildren, hasNonKeyedChildren: hasNonKeyedChildren, propChildren: propChildren, childrenKnown: childrenKnown, className: isNullOrUndefined(className) ? NULL : className, childFlags: childFlags, hasReCreateFlag: hasReCreateFlag, needsNormalization: needsNormalization, contentEditable: contentEditable, hasTextChildren: hasTextChildren, } } function getVNodeChildren(astChildren) { let children = [] let parentCanBeKeyed = false let requiresNormalization = false let foundText = false for (let i = 0; i < astChildren.length; i++) { let child = astChildren[i] let vNode = visitor(child) if (child.kind === ts.SyntaxKind.JsxExpression) { requiresNormalization = true } else if ( child.kind === ts.SyntaxKind.JsxText && handleWhiteSpace(child.getText()) !== '' ) { foundText = true } if (!isNullOrUndefined(vNode)) { children.push(vNode) /* * Loop direct children to check if they have key property set * If they do, flag parent as hasKeyedChildren to increase runtime performance of Inferno * When key already found within one of its children, they must all be keyed */ if (parentCanBeKeyed === false && child.openingElement) { let astProps = child.openingElement.attributes.properties let len = astProps.length while (parentCanBeKeyed === false && len-- > 0) { let prop = astProps[len] if (prop.name && prop.name.text === 'key') { parentCanBeKeyed = true } } } } } // Fix: When there is single child parent cant be keyed either, its faster to use patch than patchKeyed routine in that case let hasSingleChild = children.length === 1 return { parentCanBeKeyed: hasSingleChild === false && parentCanBeKeyed, children: hasSingleChild ? children[0] : ts.createArrayLiteral(children), foundText: foundText, parentCanBeNonKeyed: !hasSingleChild && !parentCanBeKeyed && !requiresNormalization && astChildren.length > 1, requiresNormalization: requiresNormalization, hasSingleChild: hasSingleChild, } } function createComponentVNodeArgs(flags, type, props, key, ref) { let args = [] let hasProps = props.length > 0 let hasKey = !isNodeNull(key) let hasRef = !isNodeNull(ref) args.push(ts.createNumericLiteral(flags + '')) args.push(type) if (hasProps) { props.length === 1 ? args.push(props[0]) : args.push(createAssignHelper(context, props)) } else if (hasKey || hasRef) { args.push(ts.createNull()) } if (hasKey) { args.push(key) } else if (hasRef) { args.push(ts.createNull()) } if (hasRef) { args.push(ref) } return args } function createVNodeArgs( flags, type, className, children, childFlags, props, key, ref, context ) { let args = [] let hasClassName = !isNodeNull(className) let hasChildren = !isNodeNull(children) let hasChildFlags = childFlags !== ChildFlags.HasInvalidChildren let hasProps = props.length > 0 let hasKey = !isNodeNull(key) let hasRef = !isNodeNull(ref) args.push(ts.createNumericLiteral(flags + '')) args.push(type) if (hasClassName) { args.push(className) } else if (hasChildren || hasChildFlags || hasProps || hasKey || hasRef) { args.push(ts.createNull()) } if (hasChildren) { args.push(children) } else if (hasChildFlags || hasProps || hasKey || hasRef) { args.push(ts.createNull()) } if (hasChildFlags) { args.push( typeof childFlags === 'number' ? ts.createNumericLiteral(childFlags + '') : childFlags ) } else if (hasProps || hasKey || hasRef) { args.push(ts.createNumericLiteral(ChildFlags.HasInvalidChildren + '')) } if (hasProps) { props.length === 1 ? args.push(props[0]) : args.push(createAssignHelper(context, props)) } else if (hasKey || hasRef) { args.push(ts.createNull()) } if (hasKey) { args.push(key) } else if (hasRef) { args.push(ts.createNull()) } if (hasRef) { args.push(ref) } return args } } }
the_stack
import * as aws from 'aws-sdk'; import * as cli from 'cli-color'; import * as _ from 'lodash'; import * as pathmod from 'path'; import * as request from 'request-promise-native'; import {AWSRegion} from '../aws-regions'; import {GenericCLIArguments} from '../cli/utils'; import def from '../default'; import getCurrentAWSRegion from '../getCurrentAWSRegion'; import {logger} from '../logger'; import {FAILURE, INTERRUPT, SUCCESS} from '../statusCodes'; import {formatSectionHeading, prettyFormatSmallMap, printSectionEntry, showFinalComandSummary} from './formatting'; import {getAllStackEvents} from './getAllStackEvents'; import getReliableStartTime from './getReliableStartTime'; import {getStackDescription} from './getStackDescription'; import {loadCFNStackPolicy} from "./loadCFNStackPolicy"; import {showStackEvents} from './showStackEvents'; import {stackArgsToCreateStackInput, stackArgsToUpdateStackInput} from "./stackArgsToX"; import {summarizeStackContents} from './summarizeStackContents'; import {summarizeStackDefinition} from './summarizeStackDefinition'; import {CfnOperation, StackArgs} from './types'; import {watchStack} from './watchStack'; import {lintTemplate} from './lint'; export async function isHttpTemplateAccessible(location?: string) { if (location) { try { await request.get(location); return true; } catch (e) { return false; } } else { return false; } } export abstract class AbstractCloudFormationStackCommand { public region: AWSRegion; readonly profile?: string; readonly assumeRoleArn?: string; readonly stackName: string; readonly argsfile: string; readonly environment: string; readonly shouldLintTemplate: boolean; protected cfnOperation: CfnOperation; protected startTime: Date; protected cfn: aws.CloudFormation; protected expectedFinalStackStatus: string[]; protected showTimesInSummary: boolean = true; protected showPreviousEvents: boolean = true; protected previousStackEventsPromise: Promise<aws.CloudFormation.StackEvents>; protected watchStackEvents: boolean = true; constructor(readonly argv: GenericCLIArguments, readonly stackArgs: StackArgs) { // region, profile, and assumeRoleArn are the only used for cli output here // configureAWS is called by loadStackArgs prior to this constructor // TODO We should cleanup / dry-up the resolution rules for these. this.region = def(getCurrentAWSRegion(), this.argv.region || this.stackArgs.Region); this.profile = ( // the resolved profile this.argv.profile || this.stackArgs.Profile || process.env.AWS_PROFILE || process.env.AWS_DEFAULT_PROFILE); // tslint:disable-line this.assumeRoleArn = this.argv.assumeRoleArn || this.stackArgs.AssumeRoleARN; // tslint:disable-line this.stackName = this.argv.stackName || this.stackArgs.StackName; // tslint:disable-line this.argsfile = argv.argsfile; this.environment = argv.environment; this.shouldLintTemplate = argv.lintTemplate; } async _setup() { this.cfn = new aws.CloudFormation(); if (this.showPreviousEvents) { this.previousStackEventsPromise = getAllStackEvents(this.stackName); } } async _updateStackTerminationPolicy() { if (_.isBoolean(this.stackArgs.EnableTerminationProtection)) { const cfn = new aws.CloudFormation(); return cfn.updateTerminationProtection({ StackName: this.stackName, EnableTerminationProtection: this.stackArgs.EnableTerminationProtection }).promise(); } } async _showCommandSummary() { const sts = new aws.STS(); const iamIdentPromise = sts.getCallerIdentity().promise(); const roleARN = this.stackArgs.ServiceRoleARN || this.stackArgs.RoleARN; console.log(); // blank line console.log(formatSectionHeading('Command Metadata:')); printSectionEntry('CFN Operation:', cli.magenta(this.cfnOperation)); printSectionEntry('iidy Environment:', cli.magenta(this.environment)); printSectionEntry('Region:', cli.magenta(this.region)); if (!_.isEmpty(this.profile)) { printSectionEntry('Profile:', cli.magenta(this.profile)); } printSectionEntry('CLI Arguments:', cli.blackBright(prettyFormatSmallMap(_.pick(this.argv, ['region', 'profile', 'argsfile']) as any))); printSectionEntry('IAM Service Role:', cli.blackBright(def('None', roleARN))); const iamIdent = await iamIdentPromise; printSectionEntry('Current IAM Principal:', cli.blackBright(iamIdent.Arn)); printSectionEntry('iidy Version:', cli.blackBright(require('../../package.json').version)); console.log(); } async run(): Promise<number> { await this._setup(); await this._showCommandSummary(); this.startTime = await getReliableStartTime(); return this._run(); } async _watchAndSummarize(stackId: string): Promise<number> { // Show user all the meta data and stack properties // TODO previous related stack, long-lived dependency stack, etc. // we use StackId below rather than StackName to be resilient to deletions const stackPromise = getStackDescription(stackId); await summarizeStackDefinition(stackId, this.region, this.showTimesInSummary, stackPromise); if (this.showPreviousEvents) { console.log(); console.log(formatSectionHeading('Previous Stack Events (max 10):')); await showStackEvents(stackId, 10, this.previousStackEventsPromise); } console.log(); if (this.watchStackEvents) { await watchStack(stackId, this.startTime); } console.log(); const stack = await summarizeStackContents(stackId); return showFinalComandSummary(_.includes(this.expectedFinalStackStatus, stack.StackStatus)); } async _run(): Promise<number> { throw new Error('Not implemented'); } async _runCreate() { if (_.isEmpty(this.stackArgs.Template)) { throw new Error('For create-stack you must provide at Template: parameter in your argsfile'); } try { const createStackInput = await stackArgsToCreateStackInput( this.stackArgs, this.argsfile, this.environment, this.stackName ); if (await this._requiresTemplateApproval(createStackInput.TemplateURL)) { return this._exitWithTemplateApprovalFailure(); } if (this.shouldLintTemplate && createStackInput.TemplateBody) { const errors = lintTemplate(createStackInput.TemplateBody, createStackInput.Parameters) if (!_.isEmpty(errors)) { return this.exitWithLintErrors(errors); } } const createStackOutput = await this.cfn.createStack(createStackInput).promise(); await this._updateStackTerminationPolicy(); return this._watchAndSummarize(createStackOutput.StackId as string); } catch (e) { if (e instanceof Error && e.message === 'CreateStack cannot be used with templates containing Transforms.') { logger.error(`Your stack template contains an AWS:: Transform so you need to use 'iidy create-or-update ${cli.red('--changeset')}'`); return INTERRUPT; } else { throw e; } } } async _runUpdate() { try { let updateStackInput = await stackArgsToUpdateStackInput(this.stackArgs, this.argsfile, this.environment, this.stackName); if (await this._requiresTemplateApproval(updateStackInput.TemplateURL)) { return this._exitWithTemplateApprovalFailure(); } if (this.argv.stackPolicyDuringUpdate) { const { StackPolicyBody: StackPolicyDuringUpdateBody, StackPolicyURL: StackPolicyDuringUpdateURL } = await loadCFNStackPolicy(this.argv.stackPolicyDuringUpdate as string, pathmod.join(process.cwd(), 'dummyfile')); updateStackInput = _.merge({StackPolicyDuringUpdateBody, StackPolicyDuringUpdateURL}, updateStackInput); } if (this.shouldLintTemplate && updateStackInput.TemplateBody) { const errors = lintTemplate(updateStackInput.TemplateBody, updateStackInput.Parameters); if (!_.isEmpty(errors)) { return this.exitWithLintErrors(errors); } } await this._updateStackTerminationPolicy(); // TODO consider conditionally calling setStackPolicy if the policy has changed const updateStackOutput = await this.cfn.updateStack(updateStackInput).promise(); return this._watchAndSummarize(updateStackOutput.StackId as string); } catch (e) { if (e instanceof Error && e.message === 'No updates are to be performed.') { logger.info('No changes detected so no stack update needed.'); return SUCCESS; } else if (e instanceof Error && e.message === 'UpdateStack cannot be used with templates containing Transforms.') { const command = this.normalizeIidyCLICommand(`update-stack ${cli.red('--changeset')}'`); logger.error(`Your stack template contains an AWS:: Transform so you need to use '${command}'`); return INTERRUPT; } else { throw e; } } } async _requiresTemplateApproval(TemplateURL?: string): Promise<boolean> { return !!(this.stackArgs.ApprovedTemplateLocation && !await isHttpTemplateAccessible(TemplateURL)); } _exitWithTemplateApprovalFailure(): number { logger.error('Template version has not been approved or the current IAM principal does not have permission to access it. Run:'); logger.error(' ' + this.normalizeIidyCLICommand(`template-approval request ${this.argsfile}`)); logger.error('to begin the approval process.'); return FAILURE; } normalizeIidyCLICommand(command: string): string { let cliArgs = `--region ${this.region}`; if (this.profile) { cliArgs += ` --profile ${this.profile}`; } return `iidy ${cliArgs} ${command}`; } exitWithLintErrors(errors: string[]): number { logger.error(`CFN template validation failed with ${errors.length} error${errors.length > 1 ? 's' : ''}:`) for(const error of errors) { logger.error(error); } return FAILURE; } }
the_stack
import * as cloudwatch from '@aws-cdk/aws-cloudwatch'; declare module "./cluster-ref" { /** * Create a clustered database with a given number of instances. * * @stability stable */ interface IDatabaseCluster { /** * Return the given named metric for this DBCluster. * * @stability stable */ metric(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The percentage of CPU utilization. * * Average over 5 minutes * * @stability stable */ metricCPUUtilization(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The number of database connections in use. * * Average over 5 minutes * * @stability stable */ metricDatabaseConnections(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The average number of deadlocks in the database per second. * * Average over 5 minutes * * @stability stable */ metricDeadlocks(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The amount of time that the instance has been running, in seconds. * * Average over 5 minutes * * @stability stable */ metricEngineUptime(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The amount of available random access memory, in bytes. * * Average over 5 minutes * * @stability stable */ metricFreeableMemory(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The amount of local storage available, in bytes. * * Average over 5 minutes * * @stability stable */ metricFreeLocalStorage(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The amount of network throughput received from clients by each instance, in bytes per second. * * Average over 5 minutes * * @stability stable */ metricNetworkReceiveThroughput(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The amount of network throughput both received from and transmitted to clients by each instance, in bytes per second. * * Average over 5 minutes * * @stability stable */ metricNetworkThroughput(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The amount of network throughput sent to clients by each instance, in bytes per second. * * Average over 5 minutes * * @stability stable */ metricNetworkTransmitThroughput(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The total amount of backup storage in bytes consumed by all Aurora snapshots outside its backup retention window. * * Average over 5 minutes * * @stability stable */ metricSnapshotStorageUsed(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The total amount of backup storage in bytes for which you are billed. * * Average over 5 minutes * * @stability stable */ metricTotalBackupStorageBilled(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The amount of storage used by your Aurora DB instance, in bytes. * * Average over 5 minutes * * @stability stable */ metricVolumeBytesUsed(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The number of billed read I/O operations from a cluster volume, reported at 5-minute intervals. * * Average over 5 minutes * * @stability stable */ metricVolumeReadIOPs(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The number of write disk I/O operations to the cluster volume, reported at 5-minute intervals. * * Average over 5 minutes * * @stability stable */ metricVolumeWriteIOPs(props?: cloudwatch.MetricOptions): cloudwatch.Metric; } } declare module "./cluster" { /** * A new or imported clustered database. * * @stability stable */ interface DatabaseClusterBase { /** * Return the given named metric for this DBCluster. * * @stability stable */ metric(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The percentage of CPU utilization. * * Average over 5 minutes * * @stability stable */ metricCPUUtilization(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The number of database connections in use. * * Average over 5 minutes * * @stability stable */ metricDatabaseConnections(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The average number of deadlocks in the database per second. * * Average over 5 minutes * * @stability stable */ metricDeadlocks(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The amount of time that the instance has been running, in seconds. * * Average over 5 minutes * * @stability stable */ metricEngineUptime(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The amount of available random access memory, in bytes. * * Average over 5 minutes * * @stability stable */ metricFreeableMemory(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The amount of local storage available, in bytes. * * Average over 5 minutes * * @stability stable */ metricFreeLocalStorage(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The amount of network throughput received from clients by each instance, in bytes per second. * * Average over 5 minutes * * @stability stable */ metricNetworkReceiveThroughput(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The amount of network throughput both received from and transmitted to clients by each instance, in bytes per second. * * Average over 5 minutes * * @stability stable */ metricNetworkThroughput(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The amount of network throughput sent to clients by each instance, in bytes per second. * * Average over 5 minutes * * @stability stable */ metricNetworkTransmitThroughput(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The total amount of backup storage in bytes consumed by all Aurora snapshots outside its backup retention window. * * Average over 5 minutes * * @stability stable */ metricSnapshotStorageUsed(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The total amount of backup storage in bytes for which you are billed. * * Average over 5 minutes * * @stability stable */ metricTotalBackupStorageBilled(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The amount of storage used by your Aurora DB instance, in bytes. * * Average over 5 minutes * * @stability stable */ metricVolumeBytesUsed(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The number of billed read I/O operations from a cluster volume, reported at 5-minute intervals. * * Average over 5 minutes * * @stability stable */ metricVolumeReadIOPs(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The number of write disk I/O operations to the cluster volume, reported at 5-minute intervals. * * Average over 5 minutes * * @stability stable */ metricVolumeWriteIOPs(props?: cloudwatch.MetricOptions): cloudwatch.Metric; } } declare module "./instance" { /** * A database instance. * * @stability stable */ interface IDatabaseInstance { /** * Return the given named metric for this DBInstance. * * @stability stable */ metric(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The percentage of CPU utilization. * * Average over 5 minutes * * @stability stable */ metricCPUUtilization(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The number of database connections in use. * * Average over 5 minutes * * @stability stable */ metricDatabaseConnections(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The amount of available storage space. * * Average over 5 minutes * * @stability stable */ metricFreeStorageSpace(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The amount of available random access memory. * * Average over 5 minutes * * @stability stable */ metricFreeableMemory(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The average number of disk read I/O operations per second. * * Average over 5 minutes * * @stability stable */ metricWriteIOPS(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The average number of disk write I/O operations per second. * * Average over 5 minutes * * @stability stable */ metricReadIOPS(props?: cloudwatch.MetricOptions): cloudwatch.Metric; } /** * A new or imported database instance. * * @stability stable */ interface DatabaseInstanceBase { /** * Return the given named metric for this DBInstance. * * @stability stable */ metric(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The percentage of CPU utilization. * * Average over 5 minutes * * @stability stable */ metricCPUUtilization(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The number of database connections in use. * * Average over 5 minutes * * @stability stable */ metricDatabaseConnections(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The amount of available storage space. * * Average over 5 minutes * * @stability stable */ metricFreeStorageSpace(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The amount of available random access memory. * * Average over 5 minutes * * @stability stable */ metricFreeableMemory(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The average number of disk read I/O operations per second. * * Average over 5 minutes * * @stability stable */ metricWriteIOPS(props?: cloudwatch.MetricOptions): cloudwatch.Metric; /** * The average number of disk write I/O operations per second. * * Average over 5 minutes * * @stability stable */ metricReadIOPS(props?: cloudwatch.MetricOptions): cloudwatch.Metric; } }
the_stack
import {fakeAsync, TestBed, tick} from "@angular/core/testing"; import {HttpClientTestingModule, HttpTestingController} from "@angular/common/http/testing"; import * as Immutable from "immutable"; import {ModelFileService} from "../../../../services/files/model-file.service"; import {LoggerService} from "../../../../services/utils/logger.service"; import {ModelFile} from "../../../../services/files/model-file"; import {RestService} from "../../../../services/utils/rest.service"; // noinspection JSUnusedLocalSymbols const DoNothing = {next: reaction => {}}; describe("Testing model file service", () => { let modelFileService: ModelFileService; let httpMock: HttpTestingController; beforeEach(() => { TestBed.configureTestingModule({ imports: [ HttpClientTestingModule ], providers: [ LoggerService, RestService, ModelFileService ] }); httpMock = TestBed.get(HttpTestingController); modelFileService = TestBed.get(ModelFileService); }); it("should create an instance", () => { expect(modelFileService).toBeDefined(); }); it("should register all events with the event source", () => { expect(modelFileService.getEventNames()).toEqual( ["model-init", "model-added", "model-updated", "model-removed"] ); }); it("should send correct model on an init event", fakeAsync(() => { let count = 0; let latestModel: Immutable.Map<string, ModelFile> = null; modelFileService.files.subscribe({ next: modelFiles => { count++; latestModel = modelFiles; } }); tick(); expect(count).toBe(1); expect(latestModel.size).toBe(0); let actualModelFiles = [ { name: "File.One", is_dir: false, local_size: 1234, remote_size: 4567, state: "default", downloading_speed: 99, eta: 54, full_path: "/full/path/to/file.one", children: [] } ]; let expectedModelFiles = [ new ModelFile({ name: "File.One", is_dir: false, local_size: 1234, remote_size: 4567, state: ModelFile.State.DEFAULT, downloading_speed: 99, eta: 54, full_path: "/full/path/to/file.one", children: Immutable.Set<ModelFile>() }) ]; modelFileService.notifyEvent("model-init", JSON.stringify(actualModelFiles)); tick(); expect(count).toBe(2); expect(latestModel.size).toBe(1); expect(Immutable.is(latestModel.get("File.One"), expectedModelFiles[0])).toBe(true); })); it("should send correct model on an added event", fakeAsync(() => { let initialModelFiles = [ { name: "File.One", is_dir: false, local_size: 1234, remote_size: 4567, state: "default", downloading_speed: 99, eta: 54, full_path: "/full/path/to/file.one", children: [] } ]; modelFileService.notifyEvent("model-init", JSON.stringify(initialModelFiles)); let count = 0; let latestModel: Immutable.Map<string, ModelFile> = null; modelFileService.files.subscribe({ next: modelFiles => { count++; latestModel = modelFiles; } }); tick(); expect(count).toBe(1); expect(latestModel.size).toBe(1); let addedModelFile = { new_file: { name: "File.Two", is_dir: false, local_size: 1234, remote_size: 4567, state: "default", downloading_speed: 99, eta: 54, full_path: "/full/path/to/file.two", children: [] }, old_file: {} }; let expectedModelFiles = [ new ModelFile({ name: "File.One", is_dir: false, local_size: 1234, remote_size: 4567, state: ModelFile.State.DEFAULT, downloading_speed: 99, eta: 54, full_path: "/full/path/to/file.one", children: Immutable.Set<ModelFile>() }), new ModelFile({ name: "File.Two", is_dir: false, local_size: 1234, remote_size: 4567, state: ModelFile.State.DEFAULT, downloading_speed: 99, eta: 54, full_path: "/full/path/to/file.two", children: Immutable.Set<ModelFile>() }) ]; modelFileService.notifyEvent("model-added", JSON.stringify(addedModelFile)); tick(); expect(count).toBe(2); expect(latestModel.size).toBe(2); expect(Immutable.is(latestModel.get("File.One"), expectedModelFiles[0])).toBe(true); expect(Immutable.is(latestModel.get("File.Two"), expectedModelFiles[1])).toBe(true); })); it("should send correct model on a removed event", fakeAsync(() => { let initialModelFiles = [ { name: "File.One", is_dir: false, local_size: 1234, remote_size: 4567, state: "default", downloading_speed: 99, eta: 54, full_path: "/full/path/to/file.one", children: [] } ]; modelFileService.notifyEvent("model-init", JSON.stringify(initialModelFiles)); let count = 0; let latestModel: Immutable.Map<string, ModelFile> = null; modelFileService.files.subscribe({ next: modelFiles => { count++; latestModel = modelFiles; } }); tick(); expect(count).toBe(1); expect(latestModel.size).toBe(1); let removedModelFile = { new_file: {}, old_file: { name: "File.One", is_dir: false, local_size: 1234, remote_size: 4567, state: "default", downloading_speed: 99, eta: 54, full_path: "/full/path/to/file.one", children: [] } }; modelFileService.notifyEvent("model-removed", JSON.stringify(removedModelFile)); tick(); expect(count).toBe(2); expect(latestModel.size).toBe(0); })); it("should send correct model on an updated event", fakeAsync(() => { let initialModelFiles = [ { name: "File.One", is_dir: false, local_size: 1234, remote_size: 4567, state: "default", downloading_speed: 99, eta: 54, full_path: "/full/path/to/file.one", children: [] } ]; modelFileService.notifyEvent("model-init", JSON.stringify(initialModelFiles)); let count = 0; let latestModel: Immutable.Map<string, ModelFile> = null; modelFileService.files.subscribe({ next: modelFiles => { count++; latestModel = modelFiles; } }); tick(); expect(count).toBe(1); expect(latestModel.size).toBe(1); let updatedModelFile = { new_file: { name: "File.One", is_dir: false, local_size: 4567, remote_size: 9012, state: "downloading", downloading_speed: 55, eta: 1, full_path: "/new/path/to/file.one", children: [] }, old_file: { name: "File.One", is_dir: false, local_size: 1234, remote_size: 4567, state: "default", downloading_speed: 99, eta: 54, full_path: "/full/path/to/file.one", children: [] } }; let expectedModelFiles = [ new ModelFile({ name: "File.One", is_dir: false, local_size: 4567, remote_size: 9012, state: ModelFile.State.DOWNLOADING, downloading_speed: 55, eta: 1, full_path: "/new/path/to/file.one", children: Immutable.Set<ModelFile>() }) ]; modelFileService.notifyEvent("model-updated", JSON.stringify(updatedModelFile)); tick(); expect(count).toBe(2); expect(latestModel.size).toBe(1); expect(Immutable.is(latestModel.get("File.One"), expectedModelFiles[0])).toBe(true); })); it("should send empty model on disconnect", fakeAsync(() => { let count = 0; let latestModel: Immutable.Map<string, ModelFile> = null; modelFileService.files.subscribe({ next: modelFiles => { count++; latestModel = modelFiles; } }); tick(); expect(count).toBe(1); expect(latestModel.size).toBe(0); modelFileService.notifyDisconnected(); tick(); expect(count).toBe(2); expect(latestModel.size).toBe(0); tick(4000); })); it("should send a GET on queue command", fakeAsync(() => { // Connect the service modelFileService.notifyConnected(); let modelFile = new ModelFile({ name: "File.One", is_dir: false, local_size: 4567, remote_size: 9012, state: ModelFile.State.DOWNLOADING, downloading_speed: 55, eta: 1, full_path: "/new/path/to/file.one", children: Immutable.Set<ModelFile>() }); let count = 0; modelFileService.queue(modelFile).subscribe({ next: reaction => { expect(reaction.success).toBe(true); count++; } }); httpMock.expectOne("/server/command/queue/File.One").flush("done"); tick(); expect(count).toBe(1); httpMock.verify(); })); it("should send correct GET requests on queue command", fakeAsync(() => { // Connect the service modelFileService.notifyConnected(); let modelFile; modelFile = new ModelFile({ name: "test", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.queue(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/queue/test").flush("done"); modelFile = new ModelFile({ name: "test space", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.queue(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/queue/test%2520space").flush("done"); modelFile = new ModelFile({ name: "test/slash", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.queue(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/queue/test%252Fslash").flush("done"); modelFile = new ModelFile({ name: "test\"doublequote", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.queue(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/queue/test%2522doublequote").flush("done"); modelFile = new ModelFile({ name: "/test/leadingslash", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.queue(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/queue/%252Ftest%252Fleadingslash").flush("done"); })); it("should send a GET on stop command", fakeAsync(() => { // Connect the service modelFileService.notifyConnected(); let modelFile = new ModelFile({ name: "File.One", is_dir: false, local_size: 4567, remote_size: 9012, state: ModelFile.State.DOWNLOADING, downloading_speed: 55, eta: 1, full_path: "/new/path/to/file.one", children: Immutable.Set<ModelFile>() }); let count = 0; modelFileService.stop(modelFile).subscribe({ next: reaction => { expect(reaction.success).toBe(true); count++; } }); httpMock.expectOne("/server/command/stop/File.One").flush("done"); tick(); expect(count).toBe(1); httpMock.verify(); })); it("should send correct GET requests on stop command", fakeAsync(() => { // Connect the service modelFileService.notifyConnected(); let modelFile; modelFile = new ModelFile({ name: "test", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.stop(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/stop/test").flush("done"); modelFile = new ModelFile({ name: "test space", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.stop(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/stop/test%2520space").flush("done"); modelFile = new ModelFile({ name: "test/slash", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.stop(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/stop/test%252Fslash").flush("done"); modelFile = new ModelFile({ name: "test\"doublequote", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.stop(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/stop/test%2522doublequote").flush("done"); modelFile = new ModelFile({ name: "/test/leadingslash", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.stop(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/stop/%252Ftest%252Fleadingslash").flush("done"); })); it("should send a GET on extract command", fakeAsync(() => { // Connect the service modelFileService.notifyConnected(); let modelFile = new ModelFile({ name: "File.One", is_dir: false, local_size: 4567, remote_size: 9012, state: ModelFile.State.DOWNLOADING, downloading_speed: 55, eta: 1, full_path: "/new/path/to/file.one", children: Immutable.Set<ModelFile>() }); let count = 0; modelFileService.extract(modelFile).subscribe({ next: reaction => { expect(reaction.success).toBe(true); count++; } }); httpMock.expectOne("/server/command/extract/File.One").flush("done"); tick(); expect(count).toBe(1); httpMock.verify(); })); it("should send correct GET requests on extract command", fakeAsync(() => { // Connect the service modelFileService.notifyConnected(); let modelFile; modelFile = new ModelFile({ name: "test", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.extract(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/extract/test").flush("done"); modelFile = new ModelFile({ name: "test space", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.extract(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/extract/test%2520space").flush("done"); modelFile = new ModelFile({ name: "test/slash", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.extract(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/extract/test%252Fslash").flush("done"); modelFile = new ModelFile({ name: "test\"doublequote", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.extract(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/extract/test%2522doublequote").flush("done"); modelFile = new ModelFile({ name: "/test/leadingslash", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.extract(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/extract/%252Ftest%252Fleadingslash").flush("done"); })); it("should send a GET on delete local command", fakeAsync(() => { // Connect the service modelFileService.notifyConnected(); let modelFile = new ModelFile({ name: "File.One", is_dir: false, local_size: 4567, remote_size: 9012, state: ModelFile.State.DOWNLOADING, downloading_speed: 55, eta: 1, full_path: "/new/path/to/file.one", children: Immutable.Set<ModelFile>() }); let count = 0; modelFileService.deleteLocal(modelFile).subscribe({ next: reaction => { expect(reaction.success).toBe(true); count++; } }); httpMock.expectOne("/server/command/delete_local/File.One").flush("done"); tick(); expect(count).toBe(1); httpMock.verify(); })); it("should send correct GET requests on delete local command", fakeAsync(() => { // Connect the service modelFileService.notifyConnected(); let modelFile; modelFile = new ModelFile({ name: "test", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.deleteLocal(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/delete_local/test").flush("done"); modelFile = new ModelFile({ name: "test space", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.deleteLocal(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/delete_local/test%2520space").flush("done"); modelFile = new ModelFile({ name: "test/slash", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.deleteLocal(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/delete_local/test%252Fslash").flush("done"); modelFile = new ModelFile({ name: "test\"doublequote", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.deleteLocal(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/delete_local/test%2522doublequote").flush("done"); modelFile = new ModelFile({ name: "/test/leadingslash", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.deleteLocal(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/delete_local/%252Ftest%252Fleadingslash").flush("done"); })); it("should send a GET on delete remote command", fakeAsync(() => { // Connect the service modelFileService.notifyConnected(); let modelFile = new ModelFile({ name: "File.One", is_dir: false, local_size: 4567, remote_size: 9012, state: ModelFile.State.DOWNLOADING, downloading_speed: 55, eta: 1, full_path: "/new/path/to/file.one", children: Immutable.Set<ModelFile>() }); let count = 0; modelFileService.deleteRemote(modelFile).subscribe({ next: reaction => { expect(reaction.success).toBe(true); count++; } }); httpMock.expectOne("/server/command/delete_remote/File.One").flush("done"); tick(); expect(count).toBe(1); httpMock.verify(); })); it("should send correct GET requests on delete remote command", fakeAsync(() => { // Connect the service modelFileService.notifyConnected(); let modelFile; modelFile = new ModelFile({ name: "test", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.deleteRemote(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/delete_remote/test").flush("done"); modelFile = new ModelFile({ name: "test space", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.deleteRemote(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/delete_remote/test%2520space").flush("done"); modelFile = new ModelFile({ name: "test/slash", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.deleteRemote(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/delete_remote/test%252Fslash").flush("done"); modelFile = new ModelFile({ name: "test\"doublequote", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.deleteRemote(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/delete_remote/test%2522doublequote").flush("done"); modelFile = new ModelFile({ name: "/test/leadingslash", state: ModelFile.State.DEFAULT, children: Immutable.Set<ModelFile>() }); modelFileService.deleteRemote(modelFile).subscribe(DoNothing); httpMock.expectOne("/server/command/delete_remote/%252Ftest%252Fleadingslash").flush("done"); })); });
the_stack
import { BiometricIDAvailableResult, ERROR_CODES, BiometricApi, BiometricResult, VerifyBiometricOptions } from './common'; import { Application, AndroidActivityResultEventData, Utils, AndroidApplication } from '@nativescript/core'; declare const com: any; const KEY_NAME = 'biometricprintauth'; const SECRET_BYTE_ARRAY = Array.create('byte', 16); const REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS = 788; // arbitrary const AuthenticationCallback = (<any>androidx.biometric.BiometricPrompt.AuthenticationCallback).extend({ resolve: null, reject: null, toEncrypt: null, toDecrypt: null, IV: null, pinFallBack: false, onAuthenticationError(code: number, error: string) { let returnCode: ERROR_CODES; let message: string; switch (code) { case androidx.biometric.BiometricPrompt.ERROR_CANCELED: { returnCode = ERROR_CODES.USER_CANCELLED; message = 'User Canceled'; break; } case androidx.biometric.BiometricPrompt.ERROR_NEGATIVE_BUTTON: { returnCode = ERROR_CODES.PASSWORD_FALLBACK_SELECTED; message = 'Negative Button Pressed'; break; } default: { returnCode = ERROR_CODES.RECOVERABLE_ERROR; message = error; } } this.reject({ code: returnCode, message, }); }, onAuthenticationFailed() { this.reject({ code: ERROR_CODES.NOT_RECOGNIZED, message: 'Fingerprint not recognized.', }); }, onAuthenticationSucceeded(result: androidx.biometric.BiometricPrompt.AuthenticationResult): void { let encrypted: string; let decrypted: string; let iv: string; try { if (this.toEncrypt) { // Howto do the encrypt/decrypt ? const nativeString = new java.lang.String(this.toEncrypt.toString()); const nativeBytes = nativeString.getBytes('UTF-8'); const cipher = result.getCryptoObject().getCipher(); const encryptedArray = cipher.doFinal(nativeBytes); encrypted = android.util.Base64.encodeToString(encryptedArray, android.util.Base64.DEFAULT).toString(); iv = android.util.Base64.encodeToString(cipher.getIV(), android.util.Base64.DEFAULT).toString(); } else if (this.toDecrypt) { const nativeBytes = android.util.Base64.decode(this.toDecrypt, android.util.Base64.DEFAULT); const decryptedBytes = result.getCryptoObject().getCipher().doFinal(nativeBytes); decrypted = new java.lang.String(decryptedBytes, java.nio.charset.StandardCharsets.UTF_8).toString(); } else if (!this.pinFallBack) { result.getCryptoObject().getCipher().doFinal(SECRET_BYTE_ARRAY); } this.resolve({ code: ERROR_CODES.SUCCESS, message: 'All OK', encrypted, decrypted, iv, }); } catch (error) { console.log(`Error in onAuthenticationSucceeded: ${error}`); this.reject({ code: ERROR_CODES.UNEXPECTED_ERROR, message: error, }); } }, }); export class BiometricAuth implements BiometricApi { private keyguardManager: android.app.KeyguardManager; private biometricPrompt: any; constructor() { this.keyguardManager = Utils.android.getApplicationContext().getSystemService('keyguard'); } available(): Promise<BiometricIDAvailableResult> { return new Promise((resolve, reject) => { try { if (!this.keyguardManager || !this.keyguardManager.isKeyguardSecure()) { resolve({ any: false, }); return; } // The fingerprint API is only available from Android 6.0 (M, Api level 23) if (android.os.Build.VERSION.SDK_INT < 23) { reject(`Your api version doesn't support fingerprint authentication`); return; } const biometricManager = androidx.biometric.BiometricManager.from(Utils.android.getApplicationContext()); const biometricConstants = androidx.biometric.BiometricManager; const biometricNoHardwareErrors: Array<number> = [biometricConstants.BIOMETRIC_ERROR_HW_UNAVAILABLE, biometricConstants.BIOMETRIC_ERROR_NO_HARDWARE, biometricConstants.BIOMETRIC_ERROR_SECURITY_UPDATE_REQUIRED, biometricConstants.BIOMETRIC_ERROR_UNSUPPORTED]; const canAuthenticate = biometricManager.canAuthenticate(androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG); if (!biometricManager || biometricNoHardwareErrors.includes(canAuthenticate)) { // Device doesn't support biometric authentication reject(`Device doesn't support biometric authentication or requires an update`); } else if (canAuthenticate === androidx.biometric.BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED || canAuthenticate == biometricConstants.BIOMETRIC_STATUS_UNKNOWN) { // If the user has not enrolled any biometrics, they still might have the device secure so we can fallback // to present the user with the swipe, password, pin device security screen regardless // the developer can handle this resolve by checking the `touch` property and determine if they want to use the // verifyFingerprint method or not since they'll know the user has no finger prints enrolled but do have a security option enabled // https://developer.android.com/reference/android/app/KeyguardManager.html#isDeviceSecure() only 23+ if (this.keyguardManager.isDeviceSecure()) { resolve({ any: true, biometrics: false, }); } else { reject(`User hasn't enrolled any biometrics to authenticate with`); } } else { // Phone has biometric hardware and is enrolled resolve({ any: true, biometrics: true, }); } } catch (ex) { console.log(`fingerprint-auth.available: ${ex}`); reject(ex); } }); } didBiometricDatabaseChange(): Promise<boolean> { return Promise.resolve(false); } // Following: https://developer.android.com/training/sign-in/biometric-auth#java as a guide verifyBiometric(options: VerifyBiometricOptions): Promise<BiometricResult> { return new Promise<BiometricResult>((resolve, reject) => { try { if (!this.keyguardManager) { reject({ code: ERROR_CODES.NOT_AVAILABLE, message: 'Keyguard manager not available.', }); } if (this.keyguardManager && !this.keyguardManager.isKeyguardSecure()) { reject({ code: ERROR_CODES.NOT_CONFIGURED, message: 'Secure lock screen hasn\'t been set up.\n Go to "Settings -> Security -> Screenlock" to set up a lock screen.', }); } const pinFallback = options?.pinFallback; let cryptoObject; if (!pinFallback) { BiometricAuth.generateSecretKey(options, reject); const cipher = this.getAndInitSecretKey(options, reject); cryptoObject = org.nativescript.plugins.fingerprint.Utils.createCryptoObject(cipher); } const executor = androidx.core.content.ContextCompat.getMainExecutor(Utils.android.getApplicationContext()); let authCallback = new AuthenticationCallback(); authCallback.resolve = resolve; authCallback.reject = reject; authCallback.toEncrypt = options?.secret; authCallback.toDecrypt = options?.android?.decryptText; authCallback.pinFallBack = pinFallback; this.biometricPrompt = new androidx.biometric.BiometricPrompt(this.getActivity(), executor, authCallback); if (pinFallback && android.os.Build.VERSION.SDK_INT < 30) { this.promptForPin(resolve, reject, options); } else if (pinFallback) { const builder = new androidx.biometric.BiometricPrompt.PromptInfo.Builder() .setTitle(options.title ? options.title : 'Login') .setSubtitle(options.subTitle ? options.subTitle : null) .setDescription(options.message ? options.message : null) .setConfirmationRequired(options.confirm ? options.confirm : false) // Confirm button after verify biometrics= .setAllowedAuthenticators(androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG | androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL); // PIN Fallback or Cancel this.biometricPrompt.authenticate(builder.build()); } else { const info = new androidx.biometric.BiometricPrompt.PromptInfo.Builder() .setTitle(options.title ? options.title : 'Login') .setSubtitle(options.subTitle ? options.subTitle : null) .setDescription(options.message ? options.message : null) .setConfirmationRequired(options.confirm ? options.confirm : false) // Confirm button after verify biometrics= .setNegativeButtonText(options.fallbackMessage ? options.fallbackMessage : 'Enter your password') // PIN Fallback or Cancel .setAllowedAuthenticators(androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG) // PIN Fallback or Cancel .build(); this.biometricPrompt.authenticate(info, cryptoObject); } } catch (ex) { console.log(`Error in biometrics-auth.verifyBiometric: ${ex}`); reject({ code: ERROR_CODES.UNEXPECTED_ERROR, message: ex, }); } }); } getAndInitSecretKey(options: VerifyBiometricOptions, reject, doNotRetry: boolean = false) { const cipher = this.getCipher(); const secretKey = this.getSecretKey(options?.keyName ?? KEY_NAME); const keyMode = options?.android?.decryptText ? javax.crypto.Cipher.DECRYPT_MODE : javax.crypto.Cipher.ENCRYPT_MODE; if (keyMode === javax.crypto.Cipher.DECRYPT_MODE) { const initializationVector = android.util.Base64.decode(options.android?.iv, android.util.Base64.DEFAULT); cipher.init(keyMode, secretKey, new javax.crypto.spec.IvParameterSpec(initializationVector)); } else { cipher.init(keyMode, secretKey); } return cipher; } verifyBiometricWithCustomFallback(options: VerifyBiometricOptions): Promise<BiometricResult> { return this.verifyBiometric(options); } close(): void { this.biometricPrompt?.cancelAuthentication(); } /** * Creates a symmetric key in the Android Key Store which can only be used after the user has * authenticated with device credentials within the last X seconds. */ private static generateSecretKey(options: VerifyBiometricOptions, reject): void { const keyStore = java.security.KeyStore.getInstance('AndroidKeyStore'); keyStore.load(null); const keyName = options?.keyName ?? KEY_NAME; if (options.keyName && (options.android?.decryptText || options.secret)) { const key = keyStore.getKey(keyName, null); if (key) return; // key already exists else { // need to reject as can neve decrypt without a key. if (options.android?.decryptText) { reject({ code: ERROR_CODES.UNEXPECTED_ERROR, message: `Key not available: ${keyName}`, }); } } } const keyGenerator = javax.crypto.KeyGenerator.getInstance(android.security.keystore.KeyProperties.KEY_ALGORITHM_AES, 'AndroidKeyStore'); const builder = new android.security.keystore.KeyGenParameterSpec.Builder(keyName, android.security.keystore.KeyProperties.PURPOSE_ENCRYPT | android.security.keystore.KeyProperties.PURPOSE_DECRYPT).setBlockModes([android.security.keystore.KeyProperties.BLOCK_MODE_CBC]).setEncryptionPaddings([android.security.keystore.KeyProperties.ENCRYPTION_PADDING_PKCS7]).setUserAuthenticationRequired(true); if (android.os.Build.VERSION.SDK_INT > 23) { builder.setInvalidatedByBiometricEnrollment(true); } keyGenerator.init(builder.build()); keyGenerator.generateKey(); } public promptForPin(resolve, reject, options) { const onActivityResult = (data: AndroidActivityResultEventData) => { if (data.requestCode === REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS) { if (data.resultCode === android.app.Activity.RESULT_OK) { // OK = -1 // the user has just authenticated via the ConfirmDeviceCredential activity resolve({ code: ERROR_CODES.SUCCESS, message: 'All OK', }); } else { // the user has quit the activity without providing credendials reject({ code: ERROR_CODES.USER_CANCELLED, message: 'User cancelled.', }); } } Application.android.off(AndroidApplication.activityResultEvent, onActivityResult); }; Application.android.on(AndroidApplication.activityResultEvent, onActivityResult); this.showAuthenticationScreen(options); } private getSecretKey(keyName?: string) { const keyStore = java.security.KeyStore.getInstance('AndroidKeyStore'); // Before the keystore can be accessed, it must be loaded. keyStore.load(null); return keyStore.getKey(keyName ?? KEY_NAME, null); } private deleteSecretKey(keyName?: string) { const keyStore = java.security.KeyStore.getInstance('AndroidKeyStore'); // Before the keystore can be accessed, it must be loaded. keyStore.load(null); if (keyStore.containsAlias(keyName ?? KEY_NAME)) { keyStore.deleteEntry(keyName ?? KEY_NAME); } } private getCipher(): javax.crypto.Cipher { return javax.crypto.Cipher.getInstance(`${android.security.keystore.KeyProperties.KEY_ALGORITHM_AES}/${android.security.keystore.KeyProperties.BLOCK_MODE_CBC}/${android.security.keystore.KeyProperties.ENCRYPTION_PADDING_PKCS7}`); } private getActivity(): any /* android.app.Activity */ { return Application.android.foregroundActivity || Application.android.startActivity; } /** * Starts the built-in Android ConfirmDeviceCredential activity. */ private showAuthenticationScreen(options): void { // https://developer.android.com/reference/android/app/KeyguardManager#createConfirmDeviceCredentialIntent(java.lang.CharSequence,%2520java.lang.CharSequence) const intent = (this.keyguardManager as any).createConfirmDeviceCredentialIntent(options && options.title ? options.title : null, options && options.fallbackMessage ? options.fallbackMessage : null); if (intent !== null) { this.getActivity().startActivityForResult(intent, REQUEST_CODE_CONFIRM_DEVICE_CREDENTIALS); } } }
the_stack
import { Duck } from '../../../index'; import randomFloat from '../../math/randomFloat'; import randomInt from '../../math/randomInt'; import Game from '../../game'; import Particle from './particle'; import Scene from '../../scene'; /** * @class ParticleEmitter * @classdesc Creates a DuckEngine ParticleEmitter * @description The ParticleEmitter Class. Emits, creates, and destroys particles * @since 1.0.0-beta */ export default class ParticleEmitter { /** * @memberof ParticleEmitter * @description A unique identifier for the ParticleEmitter * @type string * @since 1.0.0-beta */ public readonly id: string; protected particle: Particle; /** * @memberof ParticleEmitter * @description A range of numbers where particle x pos will be * @type Duck.Types.ParticleEmitter.Range * @since 1.0.0-beta */ public rangeX: Duck.Types.ParticleEmitter.Range; /** * @memberof ParticleEmitter * @description A range of numbers where particle y pos will be * @type Duck.Types.ParticleEmitter.Range * @since 1.0.0-beta */ public rangeY: Duck.Types.ParticleEmitter.Range; /** * @memberof ParticleEmitter * @description The starting amount of particle * @type number * @since 1.0.0-beta */ public readonly amount: number; /** * @memberof ParticleEmitter * @description The list of current particles * @type Particles[] * @since 1.0.0-beta */ public list: Particle[]; /** * @memberof ParticleEmitter * @description Game instance * @type Game * @since 1.0.0-beta */ public game: Game; /** * @memberof ParticleEmitter * @description Scene instance * @type Scene * @since 1.0.0-beta */ public scene: Scene; /** * @memberof ParticleEmitter * @description Determines if the ParticleEmitter is emitting or not * @type boolean * @since 1.0.0-beta */ public emitting: boolean; /** * @memberof ParticleEmitter * @description Determines if the ParticleEmitter is enabled or not * @type boolean * @since 2.0.0 */ public enabled: boolean; protected floatRangeX: Duck.Types.ParticleEmitter.Range; protected floatRangeY: Duck.Types.ParticleEmitter.Range; /** * @constructor ParticleEmitter * @description Creates ParticleEmitter instance * @param {Particle} particle Base particle that is cloned and modified from * @param {Duck.Types.ParticleEmitter.Range} rangeX Where the new emitted particles x position is. A range of 2 values * @param {Duck.Types.ParticleEmitter.Range} rangeY Where the new emitted particles y position is. A range of 2 values * @param {number} amount Amount of starting particles * @param {Game} game Game instance * @param {Scene} scene Scene instance * @since 1.0.0-beta */ constructor( particle: Particle, rangeX: Duck.Types.ParticleEmitter.Range, rangeY: Duck.Types.ParticleEmitter.Range, amount: number, game: Game, scene: Scene ) { this.id = particle.id; this.particle = particle; this.rangeX = rangeX; this.rangeY = rangeY; this.amount = amount; this.list = []; this.game = game; this.scene = scene; this.emitting = false; this.enabled = false; this.floatRangeX = [0, 0]; this.floatRangeY = [0, 0]; // create particles this.create(); } protected create() { for (let i = 0; i < this.amount; i++) { this.createOne(); } } protected createOne() { const obj = new Particle( this.particle.shape, this.particle.w, this.particle.h, this.particle.r, this.particle.originalFillColorOrIMGPath, this.game, this.scene ); obj.visible = true; obj.enabled = true; obj.position.x = randomInt(this.rangeX[0], this.rangeX[1]); obj.position.y = randomInt(this.rangeY[0], this.rangeY[1]); obj.floatVelocity.x = randomFloat( this.floatRangeX[0], this.floatRangeX[1], 1 ); obj.floatVelocity.y = randomFloat( this.floatRangeY[0], this.floatRangeY[1], 1 ); this.list.push(obj); // add to display list this.scene.displayList.add(obj); // add to physics list this.scene.physicsList.add(obj); } /** * @memberof ParticleEmitter * @description Starts emitting particles * @since 1.0.0-beta */ public emit() { this.emitting = true; this.enabled = true; } /** * @memberof ParticleEmitter * @description Stops emitting particles * @since 1.0.0-beta */ public stopEmit() { this.emitting = false; this.enabled = false; } /** * @memberof ParticleEmitter * @description Starts emitting particles for a certain duration * @param {number} ms Duration in milliseconds * @since 1.0.0-beta */ public emitFor(ms: number) { this.emitting = true; setTimeout(() => { this.emitting = false; }, ms); } /** * @memberof ParticleEmitter * @description Sets the new particles' position range * @param {Duck.Types.ParticleEmitter.Range} rangeX Where the new emitted particles x position is. A range of 2 values * @param {Duck.Types.ParticleEmitter.Range} rangeY Where the new emitted particles y position is. A range of 2 values * @since 1.0.0-beta */ public setRange( rangeX: Duck.Types.ParticleEmitter.Range, rangeY: Duck.Types.ParticleEmitter.Range ) { this.rangeX = rangeX; this.rangeY = rangeY; } /** * @memberof ParticleEmitter * @description Spawns new particles after the initial particles * @param {number} intervalMS How often a new particle gets spawned * @param {number} [limitTo] A limit to how many particles can be rendered at once, optional * @since 1.0.0-beta */ public keepEmitting(intervalMS: number, limitTo?: number) { setInterval(() => { if (limitTo) { if (this.list.length < limitTo) { this.createOne(); } } else { this.createOne(); } }, intervalMS); } /** * @memberof ParticleEmitter * @description Pops particles from the list if too many particles exist * @since 1.0.0 */ public offloadMaxAmount(limit: number) { if (this.list.length >= limit) { this.list.pop(); } // remove from display list ( this.scene.displayList.list.filter( (renderableObject) => renderableObject instanceof Particle ) as Particle[] ).pop(); // remove from physics list ( this.scene.displayList.list.filter( (obj) => obj instanceof Particle ) as Particle[] ).pop(); } /** * @memberof ParticleEmitter * @description Offloads particles based on position * @param {number} bounds The Bounds of the particles, a BoundsLike object that causes a particle to be offloaded * @since 2.0.0 */ public offloadBounds(bounds: Duck.Types.Math.BoundsLike) { this.list.forEach((particle, index) => { if (particle.position.x < bounds.x) { this.list.splice(index, 1); } if (particle.position.y < bounds.y) { this.list.splice(index, 1); } if (particle.position.x > bounds.w) { this.list.splice(index, 1); } if (particle.position.y > bounds.w) { this.list.splice(index, 1); } }); // remove from displayList this.scene.displayList.each((renderableObject, index) => { if (renderableObject instanceof Particle) { if (renderableObject.position.x < bounds.x) { this.list.splice(index, 1); } if (renderableObject.position.y < bounds.y) { this.list.splice(index, 1); } if (renderableObject.position.x > bounds.w) { this.list.splice(index, 1); } if (renderableObject.position.y > bounds.w) { this.list.splice(index, 1); } } }); // remove from physicsList this.scene.physicsList.each((obj, index) => { if (obj instanceof Particle) { if (obj instanceof Particle) { if (obj.position.x < bounds.x) { this.list.splice(index, 1); } if (obj.position.y < bounds.y) { this.list.splice(index, 1); } if (obj.position.x > bounds.w) { this.list.splice(index, 1); } if (obj.position.y > bounds.w) { this.list.splice(index, 1); } } } }); } /** * @memberof ParticleEmitter * @description Offloads particles based on how many seconds they existed for * @param {number} ageInSeconds Max amount of seconds a particle existed for * @since 1.0.0 */ public offloadMaxAge(ageInSeconds: number) { this.list.forEach((particle, index) => { if (particle.age >= ageInSeconds) { this.list.splice(index, 1); } }); // remove from displayList this.scene.displayList.each((renderableObject, index) => { if (renderableObject instanceof Particle) { if (renderableObject.age >= ageInSeconds) { this.scene.displayList.splice(index, 1); } } }); // remove from physicsList this.scene.physicsList.each((obj, index) => { if (obj instanceof Particle) { if (obj.age >= ageInSeconds) { this.scene.physicsList.splice(index, 1); } } }); } /** * @memberof ParticleEmitter * @description Sets the velocity of all particles * @param {'x'|'y'} axis 'x' or 'y' axis to change the velocity of all particles * @param {number} v Value to set the velocity of all particles * @since 1.0.0-beta */ public setVelocity(axis: 'x' | 'y', v: number) { this.list.forEach((particle) => { particle.setVelocity(axis, v); }); } /** * @memberof ParticleEmitter * @description Wobbles the particle on a random direction and axis * @param {number} v Value to set the wobble velocity to * @since 1.0.0-beta */ public wobble(v: number) { const r = randomInt(1, 4); if (r === 1) { this.list.forEach((particle) => { particle.setVelocity('x', v); }); } if (r === 2) { this.list.forEach((particle) => { particle.setVelocity('y', v); }); } if (r === 3) { this.list.forEach((particle) => { particle.setVelocity('x', -v); }); } if (r === 4) { this.list.forEach((particle) => { particle.setVelocity('y', -v); }); } } /** * @memberof ParticleEmitter * @description Sets the floatVelocity of all particles in between a range * @param {Duck.Types.ParticleEmitter.Range} rangeVX A range of 2 values for the floatVelocity.x, randomly chosen between that range * @param {Duck.Types.ParticleEmitter.Range} rangeVY A range of 2 values for the floatVelocity.y, randomly chosen between that range * @since 1.0.0-beta */ public float( rangeVX: Duck.Types.ParticleEmitter.Range, rangeVY: Duck.Types.ParticleEmitter.Range ) { this.floatRangeX = rangeVX; this.floatRangeY = rangeVY; this.list.forEach((particle) => { particle.floatVelocity.x = randomInt(rangeVX[0], rangeVX[1]); particle.floatVelocity.y = randomInt(rangeVY[0], rangeVY[1]); }); } /** * @memberof ParticleEmitter * @description Sets the fillColor of all particles * @param {string} fillColor Color * @since 1.0.0-beta */ public setFillColor(fillColor: string) { this.list.forEach((particle) => { particle.setFillColor(fillColor); }); } /** * @memberof ParticleEmitter * @description Sets the imagePath of all particles * @param {string} imagePath Image path * @since 1.0.0 */ public setImagePath(imagePath: string) { this.list.forEach((particle) => { particle.setImagePath(imagePath); }); } }
the_stack
import * as Clutter from 'clutter'; import * as Gio from 'gio'; import * as GLib from 'glib'; import { MsWindow } from 'src/layout/msWorkspace/msWindow'; import { Signal } from 'src/manager/msManager'; import { Allocate, AllocatePreferredSize } from 'src/utils/compatibility'; import { diffLists } from 'src/utils/diff_list'; import { registerGObjectClass } from 'src/utils/gjs'; import { InfinityTo0 } from 'src/utils/index'; import { getSettings } from 'src/utils/settings'; import { MsWorkspace, Tileable } from '../msWorkspace'; /** Extension imports */ const Me = imports.misc.extensionUtils.getCurrentExtension(); @registerGObjectClass export class BaseTilingLayout< S extends { key: string } > extends Clutter.LayoutManager { _state: S; icon: Gio.IconPrototype; msWorkspace: MsWorkspace; themeSettings: Gio.Settings; signals: Signal[]; private lastObservedTileableList: Tileable[] = []; constructor(msWorkspace: MsWorkspace, state: Partial<S> = {}) { super(); this._state = Object.assign({}, (this.constructor as any).state, state); this.icon = Gio.icon_new_for_string( `${Me.path}/assets/icons/tiling/${this._state.key}-symbolic.svg` ); this.msWorkspace = msWorkspace; this.themeSettings = getSettings('theme'); this.signals = []; this.registerToSignals(); GLib.idle_add(GLib.PRIORITY_DEFAULT, () => { this.afterInit(); return GLib.SOURCE_REMOVE; }); } afterInit() { this.onTileableListChanged(this.msWorkspace.tileableList); } get state() { return this._state; } set state(state) { this._state = state; } get tileableContainer() { return this.msWorkspace.msWorkspaceActor.tileableContainer; } get monitor() { return this.msWorkspace.monitor; } get tileableListVisible() { return this.msWorkspace.tileableList.filter((tileable) => { if (tileable === this.msWorkspace.appLauncher) { return ( tileable === this.msWorkspace.tileableFocused || this.msWorkspace.tileableList.length === 1 ); } else { return tileable.visible; } }); } registerToSignals() { this.signals.push( { from: this.msWorkspace, id: this.msWorkspace.connect( 'tileableList-changed', (_, tileableList) => { this.onTileableListChanged(tileableList); } ), }, { from: this.msWorkspace, id: this.msWorkspace.connect( 'tileable-focus-changed', (_, tileable, oldTileable) => { this.onFocusChanged(tileable, oldTileable); } ), }, { from: global.display, id: global.display.connect( 'workareas-changed', this.onWorkAreasChanged.bind(this) ), } ); } shouldBeVisible(_tileable: Tileable): boolean { return true; } /** Called when a new tileable enters the workspace. * When the layout is initialized this will be called for all tileables currently in the workspace. */ initializeTileable(tileable: Tileable) { if ( tileable === this.msWorkspace.appLauncher && tileable !== this.msWorkspace.tileableFocused ) { this.msWorkspace.appLauncher.hide(); } if (!tileable.get_parent() && this.shouldBeVisible(tileable)) { this.tileableContainer.add_child(tileable); } } /** Called when a tileable exits the workspace. * Any modifications to the tileable should be restored. * * It should end up parented to the tileableContainer. */ // eslint-disable-next-line @typescript-eslint/no-empty-function restoreTileable(_tileable: Tileable) {} tileTileable( _tileable: Tileable, _box: Clutter.ActorBox, _index: number, _siblingLength: number ) { /* * Function called automatically size of the container change */ } resolveBox(box?: Clutter.ActorBox): Clutter.ActorBox { if (!box) { box = new Clutter.ActorBox(); box.x2 = InfinityTo0(this.tileableContainer.allocation.get_width()); box.y2 = InfinityTo0( this.tileableContainer.allocation.get_height() ); } return box; } tileAll(box?: Clutter.ActorBox) { const resolvedBox = this.resolveBox(box); for (const tileable of this.tileableListVisible) { if (tileable instanceof MsWindow && tileable.dragged) return; this.tileTileable( tileable, resolvedBox, this.tileableListVisible.indexOf(tileable), this.tileableListVisible.length ); if (tileable instanceof MsWindow) { tileable.updateMetaWindowPositionAndSize(); } } } showAppLauncher() { const actor = this.msWorkspace.appLauncher; actor.visible = true; actor.set_scale(0.8, 0.8); actor.translation_x = actor.width * 0.1; actor.translation_y = actor.height * 0.1; actor.opacity = 0; actor.ease({ scale_x: 1, scale_y: 1, translation_x: 0, translation_y: 0, opacity: 255, duration: 250, mode: Clutter.AnimationMode.EASE_OUT_QUAD, }); } hideAppLauncher() { const actor = this.msWorkspace.appLauncher; actor.ease({ scale_x: 0.8, scale_y: 0.8, translation_x: actor.width * 0.1, translation_y: actor.height * 0.1, opacity: 0, duration: 250, mode: Clutter.AnimationMode.EASE_OUT_QUAD, onComplete: () => { actor.set_scale(1, 1); actor.translation_x = 0; actor.translation_y = 0; actor.opacity = 255; actor.visible = false; }, }); } onTileableListChanged(tileableList: Tileable[]) { const { added: enteringTileableList, removed: leavingTileableList } = diffLists(this.lastObservedTileableList, tileableList); this.lastObservedTileableList = [...tileableList]; for (const tileable of enteringTileableList) { this.initializeTileable(tileable); } for (const tileable of leavingTileableList) { if ( tileable instanceof MsWindow && Me.msWindowManager.msWindowList.includes(tileable) ) { this.restoreTileable(tileable); } } if ( this.msWorkspace.appLauncher.visible && this.msWorkspace.tileableFocused !== this.msWorkspace.appLauncher ) { this.hideAppLauncher(); } if (tileableList.length == 1 && !this.msWorkspace.appLauncher.visible) { this.showAppLauncher(); } this.tileAll(); this.layout_changed(); } // eslint-disable-next-line @typescript-eslint/no-empty-function onWorkAreasChanged() {} onFocusChanged(tileable: Tileable, oldTileable: Tileable | null) { if (tileable === this.msWorkspace.appLauncher) { this.tileAll(); GLib.idle_add(GLib.PRIORITY_DEFAULT, () => { this.showAppLauncher(); return GLib.SOURCE_REMOVE; }); } else if (oldTileable === this.msWorkspace.appLauncher) { this.hideAppLauncher(); this.tileAll(); } } getWorkspaceBounds() { const box = this.msWorkspace.msWorkspaceActor.tileableContainer.allocation; return { x: 0, y: 0, width: box.get_width(), height: box.get_height(), }; } applyGaps( x: number, y: number, width: number, height: number, screenGap?: number, gap?: number ) { // Reduces box size according to gap setting gap = gap || Me.layoutManager.gap; if (screenGap == undefined) { screenGap = Me.layoutManager.useScreenGap ? Me.layoutManager.screenGap : gap; } if ( (!gap && !screenGap) || // Never apply gaps if App Launcher is the only tileable this.msWorkspace.tileableList.length < 2 ) { return { x, y, width, height }; } const bounds = this.getWorkspaceBounds(); const edgeGap = screenGap; const halfGap = gap / 2; if (x === bounds.x) { // box is at screen left edge x += edgeGap; width -= edgeGap; } else { x += halfGap; width -= halfGap; } if (y === bounds.y) { // box is at screen top edge y += edgeGap; height -= edgeGap; } else { y += halfGap; height -= halfGap; } if (x + width === bounds.x + bounds.width) { // box is at screen right edge width -= edgeGap; } else { width -= halfGap; } if (y + height === bounds.y + bounds.height) { // box is at screen bottom edge height -= edgeGap; } else { height -= halfGap; } if (x < 0) x = 0; if (y < 0) y = 0; if (width < 1) width = 1; if (height < 1) height = 1; return { x, y, width, height }; } buildQuickWidget() { // return a widget to add to the panel } override vfunc_get_preferred_width( _container: Clutter.Container, _forHeight: number ): [number, number] { return [-1, -1]; } override vfunc_get_preferred_height( _container: Clutter.Container, _forWidth: number ): [number, number] { return [-1, -1]; } override vfunc_allocate( container: Clutter.Actor, box: Clutter.ActorBox, flags?: Clutter.AllocationFlags ) { this.tileAll(box); container.get_children().forEach((actor) => { if (this.msWorkspace.tileableList.includes(actor as Tileable)) { AllocatePreferredSize(actor, flags); } else { Allocate(actor, box, flags); } }); } onDestroy() { this.signals.forEach((signal) => { try { signal.from.disconnect(signal.id); } catch (error) { Me.log( `Failed to disconnect signal ${signal.id} from ${ signal.from } ${ signal.from.constructor.name } ${signal.from.toString()} ` ); } }); if (!Me.disableInProgress) { this.msWorkspace.tileableList.forEach((tileable) => { this.restoreTileable(tileable); }); } } }
the_stack
declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzqe { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqe>; public constructor(param0: com.google.firebase.ml.custom.FirebaseModelInputs, param1: com.google.firebase.ml.custom.FirebaseModelInputOutputOptions); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzqf { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqf>; public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzqg { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqg>; public constructor(param0: number, param1: native.Array<number>); public getType(): number; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzqh { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqh>; public constructor(param0: globalAndroid.content.Context); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzqi extends com.google.firebase.ml.common.internal.modeldownload.RemoteModelManagerInterface<com.google.firebase.ml.custom.FirebaseCustomRemoteModel> { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqi>; public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/, param1: any /* com.google.android.gms.internal.firebase_ml.zzpo*/); public getDownloadedModels(): com.google.android.gms.tasks.Task<java.util.Set<com.google.firebase.ml.custom.FirebaseCustomRemoteModel>>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzqj { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqj>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzqk { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqk>; public call(): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzql { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzql>; public then(param0: any): com.google.android.gms.tasks.Task; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzqm { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqm>; public call(): any; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzqn { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqn>; public onComplete(param0: com.google.android.gms.tasks.Task): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzqo extends java.lang.Object { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqo>; public getOutputIndex(param0: string): number; public getInputIndex(param0: string): number; public release(): void; public constructor(param0: any /* com.google.android.gms.internal.firebase_ml.zzpn*/, param1: com.google.firebase.ml.custom.FirebaseCustomLocalModel, param2: com.google.firebase.ml.custom.FirebaseCustomRemoteModel, param3: boolean); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzqp { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqp>; public onComplete(param0: com.google.android.gms.tasks.Task): void; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzqq extends com.google.android.gms.internal.firebase_ml.zzqu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqq>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzqr { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqr>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzqs { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqs>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzqt { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqt>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzqu { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqu>; /** * Constructs a new instance of the com.google.android.gms.internal.firebase_ml.zzqu interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { zzc(param0: java.nio.MappedByteBuffer): any /* com.google.android.gms.internal.firebase_ml.zzqw*/; }); public constructor(); } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzqv { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqv>; } } } } } } } declare module com { export module google { export module android { export module gms { export module internal { export module firebase_ml { export class zzqw { public static class: java.lang.Class<com.google.android.gms.internal.firebase_ml.zzqw>; } } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class CustomModelRegistrar { public static class: java.lang.Class<com.google.firebase.ml.custom.CustomModelRegistrar>; public constructor(); public getComponents(): java.util.List<com.google.firebase.components.Component<any>>; } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class FirebaseCustomLocalModel { public static class: java.lang.Class<com.google.firebase.ml.custom.FirebaseCustomLocalModel>; } export module FirebaseCustomLocalModel { export class Builder { public static class: java.lang.Class<com.google.firebase.ml.custom.FirebaseCustomLocalModel.Builder>; public constructor(); public setAssetFilePath(param0: string): com.google.firebase.ml.custom.FirebaseCustomLocalModel.Builder; public setFilePath(param0: string): com.google.firebase.ml.custom.FirebaseCustomLocalModel.Builder; public build(): com.google.firebase.ml.custom.FirebaseCustomLocalModel; } } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class FirebaseCustomRemoteModel { public static class: java.lang.Class<com.google.firebase.ml.custom.FirebaseCustomRemoteModel>; } export module FirebaseCustomRemoteModel { export class Builder { public static class: java.lang.Class<com.google.firebase.ml.custom.FirebaseCustomRemoteModel.Builder>; public constructor(param0: string); public build(): com.google.firebase.ml.custom.FirebaseCustomRemoteModel; } } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class FirebaseModelDataType { public static class: java.lang.Class<com.google.firebase.ml.custom.FirebaseModelDataType>; public static FLOAT32: number; public static INT32: number; public static BYTE: number; public static LONG: number; public constructor(); } export module FirebaseModelDataType { export class DataType { public static class: java.lang.Class<com.google.firebase.ml.custom.FirebaseModelDataType.DataType>; /** * Constructs a new instance of the com.google.firebase.ml.custom.FirebaseModelDataType$DataType interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); } } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class FirebaseModelInputOutputOptions { public static class: java.lang.Class<com.google.firebase.ml.custom.FirebaseModelInputOutputOptions>; } export module FirebaseModelInputOutputOptions { export class Builder { public static class: java.lang.Class<com.google.firebase.ml.custom.FirebaseModelInputOutputOptions.Builder>; public constructor(); public build(): com.google.firebase.ml.custom.FirebaseModelInputOutputOptions; public setOutputFormat(param0: number, param1: number, param2: native.Array<number>): com.google.firebase.ml.custom.FirebaseModelInputOutputOptions.Builder; public constructor(param0: com.google.firebase.ml.custom.FirebaseModelInputOutputOptions); public setInputFormat(param0: number, param1: number, param2: native.Array<number>): com.google.firebase.ml.custom.FirebaseModelInputOutputOptions.Builder; } } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class FirebaseModelInputs { public static class: java.lang.Class<com.google.firebase.ml.custom.FirebaseModelInputs>; } export module FirebaseModelInputs { export class Builder { public static class: java.lang.Class<com.google.firebase.ml.custom.FirebaseModelInputs.Builder>; public constructor(); public add(param0: any): com.google.firebase.ml.custom.FirebaseModelInputs.Builder; public build(): com.google.firebase.ml.custom.FirebaseModelInputs; } } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class FirebaseModelInterpreter { public static class: java.lang.Class<com.google.firebase.ml.custom.FirebaseModelInterpreter>; public static getInstance(param0: com.google.firebase.ml.custom.FirebaseModelInterpreterOptions): com.google.firebase.ml.custom.FirebaseModelInterpreter; public isStatsCollectionEnabled(): boolean; public run(param0: com.google.firebase.ml.custom.FirebaseModelInputs, param1: com.google.firebase.ml.custom.FirebaseModelInputOutputOptions): com.google.android.gms.tasks.Task<com.google.firebase.ml.custom.FirebaseModelOutputs>; public close(): void; public getOutputIndex(param0: string): com.google.android.gms.tasks.Task<java.lang.Integer>; public getInputIndex(param0: string): com.google.android.gms.tasks.Task<java.lang.Integer>; public setStatsCollectionEnabled(param0: boolean): void; } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class FirebaseModelInterpreterComponent { public static class: java.lang.Class<com.google.firebase.ml.custom.FirebaseModelInterpreterComponent>; } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class FirebaseModelInterpreterOptions { public static class: java.lang.Class<com.google.firebase.ml.custom.FirebaseModelInterpreterOptions>; public equals(param0: any): boolean; public hashCode(): number; } export module FirebaseModelInterpreterOptions { export class Builder { public static class: java.lang.Class<com.google.firebase.ml.custom.FirebaseModelInterpreterOptions.Builder>; public constructor(param0: com.google.firebase.ml.custom.FirebaseCustomLocalModel); public constructor(param0: com.google.firebase.ml.custom.FirebaseCustomRemoteModel); public build(): com.google.firebase.ml.custom.FirebaseModelInterpreterOptions; } } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class FirebaseModelOutputs { public static class: java.lang.Class<com.google.firebase.ml.custom.FirebaseModelOutputs>; public getOutput(param0: number): any; public constructor(param0: java.util.Map<java.lang.Integer,any>); } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class zza { public static class: java.lang.Class<com.google.firebase.ml.custom.zza>; public create(param0: com.google.firebase.components.ComponentContainer): any; } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class zzb { public static class: java.lang.Class<com.google.firebase.ml.custom.zzb>; public create(param0: com.google.firebase.components.ComponentContainer): any; } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class zzc { public static class: java.lang.Class<com.google.firebase.ml.custom.zzc>; public create(param0: com.google.firebase.components.ComponentContainer): any; } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class zzd { public static class: java.lang.Class<com.google.firebase.ml.custom.zzd>; } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class zze { public static class: java.lang.Class<com.google.firebase.ml.custom.zze>; } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class zzf { public static class: java.lang.Class<com.google.firebase.ml.custom.zzf>; } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class zzg { public static class: java.lang.Class<com.google.firebase.ml.custom.zzg>; } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class zzh { public static class: java.lang.Class<com.google.firebase.ml.custom.zzh>; public call(): any; } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class zzi { public static class: java.lang.Class<com.google.firebase.ml.custom.zzi>; public call(): any; } } } } } } declare module com { export module google { export module firebase { export module ml { export module custom { export class zzj { public static class: java.lang.Class<com.google.firebase.ml.custom.zzj>; } } } } } } //Generics information:
the_stack
module android.view{ import Resources = android.content.res.Resources; import Rect = android.graphics.Rect; import ViewConfiguration = android.view.ViewConfiguration; import SystemClock = android.os.SystemClock; import Log = android.util.Log; import Platform = androidui.util.Platform; const DEBUG = false; const TAG = "KeyEvent"; /** * Object used to report key and button events. * <p> * Each key press is described by a sequence of key events. A key press * starts with a key event with {@link #ACTION_DOWN}. If the key is held * sufficiently long that it repeats, then the initial down is followed * additional key events with {@link #ACTION_DOWN} and a non-zero value for * {@link #getRepeatCount()}. The last key event is a {@link #ACTION_UP} * for the key up. If the key press is canceled, the key up event will have the * {@link #FLAG_CANCELED} flag set. * </p><p> * Key events are generally accompanied by a key code ({@link #getKeyCode()}), * scan code ({@link #getScanCode()}) and meta state ({@link #getMetaState()}). * Key code constants are defined in this class. Scan code constants are raw * device-specific codes obtained from the OS and so are not generally meaningful * to applications unless interpreted using the {@link KeyCharacterMap}. * Meta states describe the pressed state of key modifiers * such as {@link #META_SHIFT_ON} or {@link #META_ALT_ON}. * </p><p> * Key codes typically correspond one-to-one with individual keys on an input device. * Many keys and key combinations serve quite different functions on different * input devices so care must be taken when interpreting them. Always use the * {@link KeyCharacterMap} associated with the input device when mapping keys * to characters. Be aware that there may be multiple key input devices active * at the same time and each will have its own key character map. * </p><p> * As soft input methods can use multiple and inventive ways of inputting text, * there is no guarantee that any key press on a soft keyboard will generate a key * event: this is left to the IME's discretion, and in fact sending such events is * discouraged. You should never rely on receiving KeyEvents for any key on a soft * input method. In particular, the default software keyboard will never send any * key event to any application targetting Jelly Bean or later, and will only send * events for some presses of the delete and return keys to applications targetting * Ice Cream Sandwich or earlier. Be aware that other software input methods may * never send key events regardless of the version. Consider using editor actions * like {@link android.view.inputmethod.EditorInfo#IME_ACTION_DONE} if you need * specific interaction with the software keyboard, as it gives more visibility to * the user as to how your application will react to key presses. * </p><p> * When interacting with an IME, the framework may deliver key events * with the special action {@link #ACTION_MULTIPLE} that either specifies * that single repeated key code or a sequence of characters to insert. * </p><p> * In general, the framework cannot guarantee that the key events it delivers * to a view always constitute complete key sequences since some events may be dropped * or modified by containing views before they are delivered. The view implementation * should be prepared to handle {@link #FLAG_CANCELED} and should tolerate anomalous * situations such as receiving a new {@link #ACTION_DOWN} without first having * received an {@link #ACTION_UP} for the prior key press. * </p><p> * Refer to {@link InputDevice} for more information about how different kinds of * input devices and sources represent keys and buttons. * </p> * * AndroidUI NOTE: some impl modified; */ export class KeyEvent{ /** Key code constant: Directional Pad Up key. * May also be synthesized from trackball motions. */ static KEYCODE_DPAD_UP = 38; /** Key code constant: Directional Pad Down key. * May also be synthesized from trackball motions. */ static KEYCODE_DPAD_DOWN = 40; /** Key code constant: Directional Pad Left key. * May also be synthesized from trackball motions. */ static KEYCODE_DPAD_LEFT = 37; /** Key code constant: Directional Pad Right key. * May also be synthesized from trackball motions. */ static KEYCODE_DPAD_RIGHT = 39; /** Key code constant: Directional Pad Center key. * May also be synthesized from trackball motions. */ static KEYCODE_DPAD_CENTER = 13; /** Key code constant: Enter key. */ static KEYCODE_ENTER = 13; /** Key code constant: Tab key. */ static KEYCODE_TAB = 9; /** Key code constant: Space key. */ static KEYCODE_SPACE = 32; /** Key code constant: Escape key. */ static KEYCODE_ESCAPE = 27; static KEYCODE_Backspace = 8; static KEYCODE_PAGE_UP = 33; static KEYCODE_PAGE_DOWN = 34; static KEYCODE_MOVE_HOME = 36; static KEYCODE_MOVE_END = 35; static KEYCODE_Digit0 = 48;//'0' static KEYCODE_Digit1 = 49;//'1' static KEYCODE_Digit2 = 50;//'2' static KEYCODE_Digit3 = 51;//'3' static KEYCODE_Digit4 = 52;//'4' static KEYCODE_Digit5 = 53;//'5' static KEYCODE_Digit6 = 54;//'6' static KEYCODE_Digit7 = 55;//'7' static KEYCODE_Digit8 = 56;//'8' static KEYCODE_Digit9 = 57;//'9' static KEYCODE_Key_a = 65;//'a' static KEYCODE_Key_b = 66;//'b' static KEYCODE_Key_c = 67;//'c' static KEYCODE_Key_d = 68;//'d' static KEYCODE_Key_e = 69;//'e' static KEYCODE_Key_f = 70;//'f' static KEYCODE_Key_g = 71;//'g' static KEYCODE_Key_h = 72;//'h' static KEYCODE_Key_i = 73;//'i' static KEYCODE_Key_j = 74;//'j' static KEYCODE_Key_k = 75;//'k' static KEYCODE_Key_l = 76;//'l' static KEYCODE_Key_m = 77;//'m' static KEYCODE_Key_n = 78;//'n' static KEYCODE_Key_o = 79;//'o' static KEYCODE_Key_p = 80;//'p' static KEYCODE_Key_q = 81;//'q' static KEYCODE_Key_r = 82;//'r' static KEYCODE_Key_s = 83;//'s' static KEYCODE_Key_t = 84;//'t' static KEYCODE_Key_u = 85;//'u' static KEYCODE_Key_v = 86;//'v' static KEYCODE_Key_w = 87;//'w' static KEYCODE_Key_x = 88;//'x' static KEYCODE_Key_y = 89;//'y' static KEYCODE_Key_z = 90;//'z' static KEYCODE_KeyA = 0x41;//65 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'A' static KEYCODE_KeyB = 0x42;//66 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'B' static KEYCODE_KeyC = 0x43;//67 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'C' static KEYCODE_KeyD = 0x44;//68 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'D' static KEYCODE_KeyE = 0x45;//69 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'E' static KEYCODE_KeyF = 0x46;//70 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'F' static KEYCODE_KeyG = 0x47;//71 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'G' static KEYCODE_KeyH = 0x48;//72 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'H' static KEYCODE_KeyI = 0x49;//73 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'I' static KEYCODE_KeyJ = 0x4a;//74 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'J' static KEYCODE_KeyK = 0x4b;//75 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'K' static KEYCODE_KeyL = 0x4c;//76 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'L' static KEYCODE_KeyM = 0x4d;//77 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'M' static KEYCODE_KeyN = 0x4e;//78 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'N' static KEYCODE_KeyO = 0x4f;//79 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'O' static KEYCODE_KeyP = 0x50;//80 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'P' static KEYCODE_KeyQ = 0x51;//81 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'Q' static KEYCODE_KeyR = 0x52;//82 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'R' static KEYCODE_KeyS = 0x53;//83 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'S' static KEYCODE_KeyT = 0x54;//84 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'T' static KEYCODE_KeyU = 0x55;//85 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'U' static KEYCODE_KeyV = 0x56;//86 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'V' static KEYCODE_KeyW = 0x57;//87 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'W' static KEYCODE_KeyX = 0x58;//88 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'X' static KEYCODE_KeyY = 0x59;//89 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'Y' static KEYCODE_KeyZ = 0x5a;//90 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'Z' static KEYCODE_Semicolon = 0x3b;//';' static KEYCODE_LessThan = 0x3c;//'<' static KEYCODE_Equal = 0x3d;//'=' static KEYCODE_MoreThan = 0x3e;//'>' static KEYCODE_Question = 0x3f;//'?' static KEYCODE_Comma = 0x2c;//',' static KEYCODE_Period = 0x2e;//'.' static KEYCODE_Slash = 0x2f;//'/' static KEYCODE_Quotation = 0x27;//''' static KEYCODE_LeftBracket = 0x5b;//'[' static KEYCODE_Backslash = 0x5c;//'\' static KEYCODE_RightBracket = 0x5d;//']' static KEYCODE_Minus = 0x2d;//'-' static KEYCODE_Colon = 0x3a;//':' static KEYCODE_Double_Quotation= 0x22;//'"' static KEYCODE_Backquote = 0x60;//'`' static KEYCODE_Tilde = 0x7e;//'~' static KEYCODE_Left_Brace = 0x7b;//'{' static KEYCODE_Or = 0x7c;//'|' static KEYCODE_Right_Brace = 0x7d;//'}' static KEYCODE_Del = 0x7f;//'Del' static KEYCODE_Exclamation = 0x21;//KeyEvent.KEYCODE_Digit1 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'!'(shift + '1') static KEYCODE_Right_Parenthesis= 0x29;//KeyEvent.KEYCODE_Digit0 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//')'(shift + '0') static KEYCODE_AT = 0x40;//KeyEvent.KEYCODE_Digit2 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'@'(shift + '2') static KEYCODE_Sharp = 0x23;//KeyEvent.KEYCODE_Digit3 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'#'(shift + '3') static KEYCODE_Dollar = 0x24;//KeyEvent.KEYCODE_Digit4 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'$'(shift + '4') static KEYCODE_Percent = 0x25;//KeyEvent.KEYCODE_Digit5 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'%'(shift + '5') static KEYCODE_Power = 0x5e;//KeyEvent.KEYCODE_Digit6 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'^'(shift + '6') static KEYCODE_And = 0x26;//KeyEvent.KEYCODE_Digit7 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'&'(shift + '7') static KEYCODE_Asterisk = 0x2a;//KeyEvent.KEYCODE_Digit8 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'*'(shift + '8') static KEYCODE_Left_Parenthesis = 0x28;//KeyEvent.KEYCODE_Digit9 & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'('(shift + '9') static KEYCODE_Underline = 0x5f;//KeyEvent.KEYCODE_Minus & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'_'(shift + '-') static KEYCODE_Add = 0x2b;//KeyEvent.KEYCODE_Equal & (KeyEvent.META_SHIFT_ON << KeyEvent.META_MASK_SHIFT);//'+'(shift + '=') //can't listen back on browser static KEYCODE_BACK = -1; //can't listen menu on browser static KEYCODE_MENU = -2; static KEYCODE_CHANGE_ANDROID_CHROME = { noMeta : { 186: KeyEvent.KEYCODE_Semicolon,//';' 187: KeyEvent.KEYCODE_Equal,//'=' 188: KeyEvent.KEYCODE_Comma,//',' 189: KeyEvent.KEYCODE_Minus,//'-' 190: KeyEvent.KEYCODE_Period,//'.' 191: KeyEvent.KEYCODE_Slash,//'/' 192: KeyEvent.KEYCODE_Quotation,//''' //192: KeyEvent.KEYCODE_Backquote,//'`' 219: KeyEvent.KEYCODE_LeftBracket,//'[' 220: KeyEvent.KEYCODE_Backslash,//'\' 221: KeyEvent.KEYCODE_RightBracket,//']' }, shift : { 186: KeyEvent.KEYCODE_Colon,//':' 187: KeyEvent.KEYCODE_Add,//'+' 188: KeyEvent.KEYCODE_LessThan,//'<' 189: KeyEvent.KEYCODE_Underline,//'_' 190: KeyEvent.KEYCODE_MoreThan,//'>' 191: KeyEvent.KEYCODE_Question,//'?' 192: KeyEvent.KEYCODE_Double_Quotation,//'"' //192: KeyEvent.KEYCODE_Tilde,//'~' 219: KeyEvent.KEYCODE_Left_Brace,//'{' 220: KeyEvent.KEYCODE_Or,//'|' 221: KeyEvent.KEYCODE_Right_Brace,//'}' }, ctrl : {}, alt : {} //TODO more code }; private static FIX_MAP_KEYCODE = { 186: KeyEvent.KEYCODE_Semicolon, // ; 187: KeyEvent.KEYCODE_Equal, // = 188: KeyEvent.KEYCODE_Comma, // , 189: KeyEvent.KEYCODE_Minus, // - 190: KeyEvent.KEYCODE_Period, // . 191: KeyEvent.KEYCODE_Slash, // / 192: KeyEvent.KEYCODE_Backquote, // ` 219: KeyEvent.KEYCODE_LeftBracket, // [ 220: KeyEvent.KEYCODE_Backslash, // \ 221: KeyEvent.KEYCODE_RightBracket, // ] 222: KeyEvent.KEYCODE_Quotation, // ' //numeric keypad 96: KeyEvent.KEYCODE_Digit0, 97: KeyEvent.KEYCODE_Digit1, 98: KeyEvent.KEYCODE_Digit2, 99: KeyEvent.KEYCODE_Digit3, 100: KeyEvent.KEYCODE_Digit4, 101: KeyEvent.KEYCODE_Digit5, 102: KeyEvent.KEYCODE_Digit6, 103: KeyEvent.KEYCODE_Digit7, 104: KeyEvent.KEYCODE_Digit8, 105: KeyEvent.KEYCODE_Digit9 }; /** * {@link #getAction} value: the key has been pressed down. */ static ACTION_DOWN = 0; /** * {@link #getAction} value: the key has been released. */ static ACTION_UP = 1; /** * {@link #getAction} value: multiple duplicate key events have * occurred in a row, or a complex string is being delivered. If the * key code is not {#link {@link #KEYCODE_UNKNOWN} then the * {#link {@link #getRepeatCount()} method returns the number of times * the given key code should be executed. * Otherwise, if the key code is {@link #KEYCODE_UNKNOWN}, then * this is a sequence of characters as returned by {@link #getCharacters}. */ //static ACTION_MULTIPLE = 2; static META_MASK_SHIFT:number = 16; static META_ALT_ON:number = 0x02; static META_SHIFT_ON:number = 0x1; static META_CTRL_ON:number = 0x1000; static META_META_ON:number = 0x10000; static FLAG_CANCELED = 0x20; static FLAG_CANCELED_LONG_PRESS = 0x100; private static FLAG_LONG_PRESS = 0x80; static FLAG_TRACKING = 0x200; private static FLAG_START_TRACKING = 0x40000000; mFlags:number; private mAction : number; private mKeyCode : number; private mDownTime : number; private mEventTime : number; private mAltKey : boolean; private mShiftKey : boolean; private mCtrlKey : boolean; private mMetaKey : boolean; protected mIsTypingKey:boolean; //private _activeKeyEvent : KeyboardEvent; private _downingKeyEventMap = new Map<number, KeyboardEvent[]>(); static obtain(action:number, code:number):KeyEvent { let ev:KeyEvent = new KeyEvent(); ev.mDownTime = SystemClock.uptimeMillis(); ev.mEventTime = SystemClock.uptimeMillis(); ev.mAction = action; ev.mKeyCode = code; //ev.mRepeatCount = repeat; //ev.mMetaState = metaState; //ev.mDeviceId = deviceId; //ev.mScanCode = scancode; //ev.mFlags = flags; //ev.mSource = source; //ev.mCharacters = characters; return ev; } initKeyEvent(keyEvent:KeyboardEvent, action:number){ this.mEventTime = SystemClock.uptimeMillis(); this.mKeyCode = keyEvent.keyCode; this.mAltKey = keyEvent.altKey; this.mShiftKey = keyEvent.shiftKey; this.mCtrlKey = keyEvent.ctrlKey; this.mMetaKey = keyEvent.metaKey; let keyIdentifier = keyEvent['keyIdentifier']+''; if(keyIdentifier){ this.mIsTypingKey = keyIdentifier.startsWith('U+');//use for check should level touch mode if(this.mIsTypingKey){ this.mKeyCode = Number.parseInt(keyIdentifier.substr(2), 16) || this.mKeyCode; } } //TODO check caps lock //a ==> A, b ==> B, ... if(this.mKeyCode>=KeyEvent.KEYCODE_Key_a && this.mKeyCode<=KeyEvent.KEYCODE_Key_z && this.mShiftKey && !this.mCtrlKey && !this.mAltKey && !this.mMetaKey){ this.mKeyCode -= 32; } //A ==> a, B ==> a, ... if(this.mKeyCode>=KeyEvent.KEYCODE_KeyA && this.mKeyCode<=KeyEvent.KEYCODE_KeyZ && !this.mShiftKey && !this.mCtrlKey && !this.mAltKey && !this.mMetaKey){ this.mKeyCode += 32; } //key code convert in android chrome if(Platform.isAndroid){ if(!this.mShiftKey && !this.mCtrlKey && !this.mAltKey && !this.mMetaKey){ this.mKeyCode = KeyEvent.KEYCODE_CHANGE_ANDROID_CHROME.noMeta[this.mKeyCode] || this.mKeyCode; }else if(this.mShiftKey && !this.mCtrlKey && !this.mAltKey && !this.mMetaKey){ this.mKeyCode = KeyEvent.KEYCODE_CHANGE_ANDROID_CHROME.shift[this.mKeyCode] || this.mKeyCode; }else if(!this.mShiftKey && this.mCtrlKey && !this.mAltKey && !this.mMetaKey){ this.mKeyCode = KeyEvent.KEYCODE_CHANGE_ANDROID_CHROME.ctrl[this.mKeyCode] || this.mKeyCode; }else if(!this.mShiftKey && !this.mCtrlKey && this.mAltKey && !this.mMetaKey){ this.mKeyCode = KeyEvent.KEYCODE_CHANGE_ANDROID_CHROME.alt[this.mKeyCode] || this.mKeyCode; } } // fix map key code this.mKeyCode = KeyEvent.FIX_MAP_KEYCODE[this.mKeyCode] || this.mKeyCode; if(action === KeyEvent.ACTION_DOWN){ this.mDownTime = SystemClock.uptimeMillis(); let keyEvents = this._downingKeyEventMap.get(keyEvent.keyCode); if(keyEvents == null){ keyEvents = []; this._downingKeyEventMap.set(keyEvent.keyCode, keyEvents); } keyEvents.push(keyEvent); }else if(action === KeyEvent.ACTION_UP){ this._downingKeyEventMap.delete(keyEvent.keyCode); } this.mAction = action; } /** Whether key will, by default, trigger a click on the focused view. * @hide */ static isConfirmKey(keyCode:number):boolean { switch (keyCode) { case KeyEvent.KEYCODE_DPAD_CENTER: case KeyEvent.KEYCODE_ENTER: return true; default: return false; } } isAltPressed():boolean{ return this.mAltKey; } isShiftPressed():boolean{ return this.mShiftKey; } isCtrlPressed():boolean{ return this.mCtrlKey; } isMetaPressed():boolean{ return this.mMetaKey; } /** * Retrieve the action of this key event. May be either * {@link #ACTION_DOWN}, {@link #ACTION_UP} * * @return The event action: ACTION_DOWN or ACTION_UP. */ getAction():number { return this.mAction; } /** * Call this during {@link Callback#onKeyDown} to have the system track * the key through its final up (possibly including a long press). Note * that only one key can be tracked at a time -- if another key down * event is received while a previous one is being tracked, tracking is * stopped on the previous event. */ startTracking():void { this.mFlags |= KeyEvent.FLAG_START_TRACKING; } /** * For {@link #ACTION_UP} events, indicates that the event is still being * tracked from its initial down event as per * {@link #FLAG_TRACKING}. */ isTracking():boolean { return (this.mFlags&KeyEvent.FLAG_TRACKING) != 0; } /** * For {@link #ACTION_DOWN} events, indicates that the event has been * canceled as per {@link #FLAG_LONG_PRESS}. */ isLongPress() { return this.getRepeatCount()===1; } getKeyCode():number { return this.mKeyCode; } /** * Retrieve the repeat count of the event. For both key up and key down * events, this is the number of times the key has repeated with the first * down starting at 0 and counting up from there. For multiple key * events, this is the number of down/up pairs that have occurred. * * @return The number of times the key has repeated. */ getRepeatCount() { let downArray = this._downingKeyEventMap.get(this.mKeyCode); return downArray ? downArray.length-1 : 0; } /** * Retrieve the time of the most recent key down event, * in the {@link android.os.SystemClock#uptimeMillis} time base. If this * is a down event, this will be the same as {@link #getEventTime()}. * Note that when chording keys, this value is the down time of the * most recently pressed key, which may <em>not</em> be the same physical * key of this event. * * @return Returns the most recent key down time, in the * {@link android.os.SystemClock#uptimeMillis} time base */ getDownTime():number { return this.mDownTime; } /** * Retrieve the time this event occurred, * in the {@link android.os.SystemClock#uptimeMillis} time base. * * @return Returns the time this event occurred, * in the {@link android.os.SystemClock#uptimeMillis} time base. */ getEventTime():number { return this.mEventTime; } /** * Deliver this key event to a {@link Callback} interface. If this is * an ACTION_MULTIPLE event and it is not handled, then an attempt will * be made to deliver a single normal event. * * @param receiver The Callback that will be given the event. * @param state State information retained across events. * @param target The target of the dispatch, for use in tracking. * * @return The return value from the Callback method that was called. */ dispatch(receiver:KeyEvent.Callback, state?:KeyEvent.DispatcherState, target?:any):boolean{ switch (this.mAction) { case KeyEvent.ACTION_DOWN: { this.mFlags &= ~KeyEvent.FLAG_START_TRACKING; if (DEBUG) Log.v(TAG, "Key down to " + target + " in " + state + ": " + this); let res = receiver.onKeyDown(this.getKeyCode(), this); if (state != null) { if (res && this.getRepeatCount() == 0 && (this.mFlags&KeyEvent.FLAG_START_TRACKING) != 0) { if (DEBUG) Log.v(TAG, " Start tracking!"); state.startTracking(this, target); } else if (this.isLongPress() && state.isTracking(this)) { if (receiver.onKeyLongPress(this.getKeyCode(), this)) { if (DEBUG) Log.v(TAG, " Clear from long press!"); state.performedLongPress(this); res = true; } } } return res; } case KeyEvent.ACTION_UP: if (DEBUG) Log.v(TAG, "Key up to " + target + " in " + state + ": " + this); if (state != null) { state.handleUpEvent(this); } return receiver.onKeyUp(this.getKeyCode(), this); //case ACTION_MULTIPLE: // final int count = mRepeatCount; // final int code = mKeyCode; // if (receiver.onKeyMultiple(code, count, this)) { // return true; // } // if (code != KeyEvent.KEYCODE_UNKNOWN) { // mAction = ACTION_DOWN; // mRepeatCount = 0; // boolean handled = receiver.onKeyDown(code, this); // if (handled) { // mAction = ACTION_UP; // receiver.onKeyUp(code, this); // } // mAction = ACTION_MULTIPLE; // mRepeatCount = count; // return handled; // } // return false; } return false; } hasNoModifiers(){ if(this.isAltPressed()) return false; if(this.isShiftPressed()) return false; if(this.isCtrlPressed()) return false; if(this.isMetaPressed()) return false; return true; } hasModifiers(modifiers:number){ if( (modifiers & KeyEvent.META_ALT_ON)===KeyEvent.META_ALT_ON && this.isAltPressed()) return true; if( (modifiers & KeyEvent.META_SHIFT_ON)===KeyEvent.META_SHIFT_ON && this.isShiftPressed()) return true; if( (modifiers & KeyEvent.META_META_ON)===KeyEvent.META_META_ON && this.isMetaPressed()) return true; if( (modifiers & KeyEvent.META_CTRL_ON)===KeyEvent.META_CTRL_ON && this.isCtrlPressed()) return true; } getMetaState():number { let meta = 0; if(this.isAltPressed()) meta |= KeyEvent.META_ALT_ON; if(this.isShiftPressed()) meta |= KeyEvent.META_SHIFT_ON; if(this.isCtrlPressed()) meta |= KeyEvent.META_CTRL_ON; if(this.isMetaPressed()) meta |= KeyEvent.META_META_ON; return meta; } toString() { return JSON.stringify(this); } isCanceled():boolean { return false; } static actionToString(action:number):string { switch (action) { case KeyEvent.ACTION_DOWN: return "ACTION_DOWN"; case KeyEvent.ACTION_UP: return "ACTION_UP"; //case ACTION_MULTIPLE: // return "ACTION_MULTIPLE"; default: return '' + (action); } } static keyCodeToString(keyCode:number):string { return String.fromCharCode(keyCode); } } export module KeyEvent{ export interface Callback{ /** * Called when a key down event has occurred. If you return true, * you can first call {@link KeyEvent#startTracking() * KeyEvent.startTracking()} to have the framework track the event * through its {@link #onKeyUp(int, KeyEvent)} and also call your * {@link #onKeyLongPress(int, KeyEvent)} if it occurs. * * @param keyCode The value in event.getKeyCode(). * @param event Description of the key event. * * @return If you handled the event, return true. If you want to allow * the event to be handled by the next receiver, return false. */ onKeyDown(keyCode:number, event:KeyEvent):boolean; /** * Called when a long press has occurred. If you return true, * the final key up will have {@link KeyEvent#FLAG_CANCELED} and * {@link KeyEvent#FLAG_CANCELED_LONG_PRESS} set. Note that in * order to receive this callback, someone in the event change * <em>must</em> return true from {@link #onKeyDown} <em>and</em> * call {@link KeyEvent#startTracking()} on the event. * * @param keyCode The value in event.getKeyCode(). * @param event Description of the key event. * * @return If you handled the event, return true. If you want to allow * the event to be handled by the next receiver, return false. */ onKeyLongPress(keyCode:number, event:KeyEvent):boolean; /** * Called when a key up event has occurred. * * @param keyCode The value in event.getKeyCode(). * @param event Description of the key event. * * @return If you handled the event, return true. If you want to allow * the event to be handled by the next receiver, return false. */ onKeyUp(keyCode:number, event:KeyEvent):boolean; } export class DispatcherState{ mDownKeyCode:number; mDownTarget:any; mActiveLongPresses = new android.util.SparseArray<number>(); /** * Reset back to initial state. * Stop any tracking associated with this target. */ reset(target:any) { if(target==null) { if (DEBUG) Log.v(TAG, "Reset: " + this); this.mDownKeyCode = 0; this.mDownTarget = null; this.mActiveLongPresses.clear(); }else{ if (this.mDownTarget == target) { if (DEBUG) Log.v(TAG, "Reset in " + target + ": " + this); this.mDownKeyCode = 0; this.mDownTarget = null; } } } /** * Start tracking the key code associated with the given event. This * can only be called on a key down. It will allow you to see any * long press associated with the key, and will result in * {@link KeyEvent#isTracking} return true on the long press and up * events. * * <p>This is only needed if you are directly dispatching events, rather * than handling them in {@link Callback#onKeyDown}. */ startTracking(event:KeyEvent , target:any) { if (event.getAction() != KeyEvent.ACTION_DOWN) { throw new Error( "Can only start tracking on a down event"); } if (DEBUG) Log.v(TAG, "Start trackingt in " + target + ": " + this); this.mDownKeyCode = event.getKeyCode(); this.mDownTarget = target; } /** * Return true if the key event is for a key code that is currently * being tracked by the dispatcher. */ isTracking(event:KeyEvent):boolean { return this.mDownKeyCode == event.getKeyCode(); } /** * Keep track of the given event's key code as having performed an * action with a long press, so no action should occur on the up. * <p>This is only needed if you are directly dispatching events, rather * than handling them in {@link Callback#onKeyLongPress}. */ performedLongPress(event:KeyEvent) { this.mActiveLongPresses.put(event.getKeyCode(), 1); } /** * Handle key up event to stop tracking. This resets the dispatcher state, * and updates the key event state based on it. * <p>This is only needed if you are directly dispatching events, rather * than handling them in {@link Callback#onKeyUp}. */ handleUpEvent(event:KeyEvent) { const keyCode = event.getKeyCode(); if (DEBUG) Log.v(TAG, "Handle key up " + event + ": " + this); let index = this.mActiveLongPresses.indexOfKey(keyCode); if (index >= 0) { if (DEBUG) Log.v(TAG, " Index: " + index); event.mFlags |= KeyEvent.FLAG_CANCELED | KeyEvent.FLAG_CANCELED_LONG_PRESS; this.mActiveLongPresses.removeAt(index); } if (this.mDownKeyCode == keyCode) { if (DEBUG) Log.v(TAG, " Tracking!"); event.mFlags |= KeyEvent.FLAG_TRACKING; this.mDownKeyCode = 0; this.mDownTarget = null; } } } } }
the_stack
import { lerp as scalar_lerp } from '../../mol-math/interpolate'; import { defaults } from '../../mol-util'; import { Mat3 } from '../linear-algebra/3d/mat3'; import { Mat4 } from '../linear-algebra/3d/mat4'; import { Quat } from '../linear-algebra/3d/quat'; import { Vec3 } from '../linear-algebra/3d/vec3'; interface SymmetryOperator { readonly name: string, readonly assembly?: { /** pointer to `pdbx_struct_assembly.id` or empty string */ readonly id: string, /** pointers to `pdbx_struct_oper_list.id` or empty list */ readonly operList: string[], /** (arbitrary) unique id of the operator to be used in suffix */ readonly operId: number }, /** pointer to `struct_ncs_oper.id` or -1 */ readonly ncsId: number, readonly hkl: Vec3, /** spacegroup symmetry operator index, -1 if not applicable */ readonly spgrOp: number, readonly matrix: Mat4, // cache the inverse of the transform readonly inverse: Mat4, // optimize the identity case readonly isIdentity: boolean, /** * Suffix based on operator type. * - Assembly: _assembly.operId * - Crytal: -op_ijk * - ncs: _ncsId */ readonly suffix: string } namespace SymmetryOperator { export const DefaultName = '1_555'; export const Default: SymmetryOperator = create(DefaultName, Mat4.identity()); export const RotationTranslationEpsilon = 0.005; export type CreateInfo = { assembly?: SymmetryOperator['assembly'], ncsId?: number, hkl?: Vec3, spgrOp?: number } export function create(name: string, matrix: Mat4, info?: CreateInfo): SymmetryOperator { let { assembly, ncsId, hkl, spgrOp } = info || { }; const _hkl = hkl ? Vec3.clone(hkl) : Vec3(); spgrOp = defaults(spgrOp, -1); ncsId = ncsId || -1; const suffix = getSuffix(info); if (Mat4.isIdentity(matrix)) return { name, assembly, matrix, inverse: Mat4.identity(), isIdentity: true, hkl: _hkl, spgrOp, ncsId, suffix }; if (!Mat4.isRotationAndTranslation(matrix, RotationTranslationEpsilon)) throw new Error(`Symmetry operator (${name}) must be a composition of rotation and translation.`); return { name, assembly, matrix, inverse: Mat4.invert(Mat4(), matrix), isIdentity: false, hkl: _hkl, spgrOp, ncsId, suffix }; } function getSuffix(info?: CreateInfo) { if (!info) return ''; if (info.assembly) { return `_${info.assembly.operId}`; } if (typeof info.spgrOp !== 'undefined' && typeof info.hkl !== 'undefined' && info.spgrOp !== -1) { const [i, j, k] = info.hkl; return `-${info.spgrOp + 1}_${5 + i}${5 + j}${5 + k}`; } if (info.ncsId !== -1) { return `_${info.ncsId}`; } return ''; } export function checkIfRotationAndTranslation(rot: Mat3, offset: Vec3) { const matrix = Mat4.identity(); for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { Mat4.setValue(matrix, i, j, Mat3.getValue(rot, i, j)); } } Mat4.setTranslation(matrix, offset); return Mat4.isRotationAndTranslation(matrix, RotationTranslationEpsilon); } export function ofRotationAndOffset(name: string, rot: Mat3, offset: Vec3, ncsId?: number) { const t = Mat4.identity(); for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { Mat4.setValue(t, i, j, Mat3.getValue(rot, i, j)); } } Mat4.setTranslation(t, offset); return create(name, t, { ncsId }); } const _q1 = Quat.identity(), _q2 = Quat(), _q3 = Quat(), _axis = Vec3(); export function lerpFromIdentity(out: Mat4, op: SymmetryOperator, t: number): Mat4 { const m = op.inverse; if (op.isIdentity) return Mat4.copy(out, m); const _t = 1 - t; // interpolate rotation Mat4.getRotation(_q2, m); Quat.slerp(_q2, _q1, _q2, _t); const angle = Quat.getAxisAngle(_axis, _q2); Mat4.fromRotation(out, angle, _axis); // interpolate translation Mat4.setValue(out, 0, 3, _t * Mat4.getValue(m, 0, 3)); Mat4.setValue(out, 1, 3, _t * Mat4.getValue(m, 1, 3)); Mat4.setValue(out, 2, 3, _t * Mat4.getValue(m, 2, 3)); return out; } export function slerp(out: Mat4, src: Mat4, tar: Mat4, t: number): Mat4 { if (Math.abs(t) <= 0.00001) return Mat4.copy(out, src); if (Math.abs(t - 1) <= 0.00001) return Mat4.copy(out, tar); // interpolate rotation Mat4.getRotation(_q2, src); Mat4.getRotation(_q3, tar); Quat.slerp(_q3, _q2, _q3, t); const angle = Quat.getAxisAngle(_axis, _q3); Mat4.fromRotation(out, angle, _axis); // interpolate translation Mat4.setValue(out, 0, 3, scalar_lerp(Mat4.getValue(src, 0, 3), Mat4.getValue(tar, 0, 3), t)); Mat4.setValue(out, 1, 3, scalar_lerp(Mat4.getValue(src, 1, 3), Mat4.getValue(tar, 1, 3), t)); Mat4.setValue(out, 2, 3, scalar_lerp(Mat4.getValue(src, 2, 3), Mat4.getValue(tar, 2, 3), t)); return out; } /** * Apply the 1st and then 2nd operator. ( = second.matrix * first.matrix). * Keep `name`, `assembly`, `ncsId`, `hkl` and `spgrOpId` properties from second. */ export function compose(first: SymmetryOperator, second: SymmetryOperator) { const matrix = Mat4.mul(Mat4(), second.matrix, first.matrix); return create(second.name, matrix, second); } export interface CoordinateMapper<T extends number> { (index: T, slot: Vec3): Vec3 } export interface ArrayMapping<T extends number> { readonly coordinates: Coordinates, readonly operator: SymmetryOperator, readonly invariantPosition: CoordinateMapper<T>, readonly position: CoordinateMapper<T>, x(index: T): number, y(index: T): number, z(index: T): number, r(index: T): number } export interface Coordinates { x: ArrayLike<number>, y: ArrayLike<number>, z: ArrayLike<number> } export function createMapping<T extends number>(operator: SymmetryOperator, coords: Coordinates, radius?: ((index: T) => number)): ArrayMapping<T> { const invariantPosition = SymmetryOperator.createCoordinateMapper(SymmetryOperator.Default, coords); const position = operator.isIdentity ? invariantPosition : SymmetryOperator.createCoordinateMapper(operator, coords); const { x, y, z } = createProjections(operator, coords); return { operator, coordinates: coords, invariantPosition, position, x, y, z, r: radius ? radius : _zeroRadius }; } export function createCoordinateMapper<T extends number>(t: SymmetryOperator, coords: Coordinates): CoordinateMapper<T> { if (t.isIdentity) return identityPosition(coords); return generalPosition(t, coords); } } export { SymmetryOperator }; function _zeroRadius(i: number) { return 0; } interface Projections { x(index: number): number, y(index: number): number, z(index: number): number } function createProjections(t: SymmetryOperator, coords: SymmetryOperator.Coordinates): Projections { if (t.isIdentity) return { x: projectCoord(coords.x), y: projectCoord(coords.y), z: projectCoord(coords.z) }; return { x: projectX(t, coords), y: projectY(t, coords), z: projectZ(t, coords) }; } function projectCoord(xs: ArrayLike<number>) { return function projectCoord(i: number) { return xs[i]; }; } function isW1(m: Mat4) { return m[3] === 0 && m[7] === 0 && m[11] === 0 && m[15] === 1; } function projectX({ matrix: m }: SymmetryOperator, { x: xs, y: ys, z: zs }: SymmetryOperator.Coordinates) { const xx = m[0], yy = m[4], zz = m[8], tx = m[12]; if (isW1(m)) { // this should always be the case. return function projectX_W1(i: number) { return xx * xs[i] + yy * ys[i] + zz * zs[i] + tx; }; } return function projectX(i: number) { const x = xs[i], y = ys[i], z = zs[i], w = (m[3] * x + m[7] * y + m[11] * z + m[15]) || 1.0; return (xx * x + yy * y + zz * z + tx) / w; }; } function projectY({ matrix: m }: SymmetryOperator, { x: xs, y: ys, z: zs }: SymmetryOperator.Coordinates) { const xx = m[1], yy = m[5], zz = m[9], ty = m[13]; if (isW1(m)) { // this should always be the case. return function projectY_W1(i: number) { return xx * xs[i] + yy * ys[i] + zz * zs[i] + ty; }; } return function projectY(i: number) { const x = xs[i], y = ys[i], z = zs[i], w = (m[3] * x + m[7] * y + m[11] * z + m[15]) || 1.0; return (xx * x + yy * y + zz * z + ty) / w; }; } function projectZ({ matrix: m }: SymmetryOperator, { x: xs, y: ys, z: zs }: SymmetryOperator.Coordinates) { const xx = m[2], yy = m[6], zz = m[10], tz = m[14]; if (isW1(m)) { // this should always be the case. return function projectZ_W1(i: number) { return xx * xs[i] + yy * ys[i] + zz * zs[i] + tz; }; } return function projectZ(i: number) { const x = xs[i], y = ys[i], z = zs[i], w = (m[3] * x + m[7] * y + m[11] * z + m[15]) || 1.0; return (xx * x + yy * y + zz * z + tz) / w; }; } function identityPosition<T extends number>({ x, y, z }: SymmetryOperator.Coordinates): SymmetryOperator.CoordinateMapper<T> { return function identityPosition(i: T, s: Vec3): Vec3 { s[0] = x[i]; s[1] = y[i]; s[2] = z[i]; return s; }; } function generalPosition<T extends number>({ matrix: m }: SymmetryOperator, { x: xs, y: ys, z: zs }: SymmetryOperator.Coordinates) { if (isW1(m)) { // this should always be the case. return function generalPosition_W1(i: T, r: Vec3): Vec3 { const x = xs[i], y = ys[i], z = zs[i]; r[0] = m[0] * x + m[4] * y + m[8] * z + m[12]; r[1] = m[1] * x + m[5] * y + m[9] * z + m[13]; r[2] = m[2] * x + m[6] * y + m[10] * z + m[14]; return r; }; } return function generalPosition(i: T, r: Vec3): Vec3 { r[0] = xs[i]; r[1] = ys[i]; r[2] = zs[i]; Vec3.transformMat4(r, r, m); return r; }; }
the_stack
import { Component, ElementRef, EventEmitter, forwardRef, Host, Inject, Input, NgZone, OnDestroy, OnInit, Output, QueryList, Renderer2, ViewChildren, ViewEncapsulation } from "@angular/core"; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms"; import {CommonUtils} from "../../common/core/utils/common-utils"; import {ArrayCollection} from "../../common/core/data/array-collection"; import {CallbackRemoval} from "../../common/core/utils/common-utils"; import {AbstractJigsawComponent} from "../../common/common"; export class SliderMark { value: number; label: string; style?: any; } /** * @internal */ @Component({ selector: 'jigsaw-mobile-slider-handle', templateUrl: './slider-handle.html', encapsulation: ViewEncapsulation.None }) export class JigsawMobileSliderHandle implements OnInit { private _value: number; @Input() public key: number; @Input() public get value() { return this._value; } public set value(value) { this._value = this._slider._verifyValue(value); this._valueToPos(); } @Output() public change = new EventEmitter<number>(); private _valueToPos() { this._offset = this._slider._transformValueToPos(this.value); this.setHandleStyle(); } private _offset: number = 0; /** * @internal */ public _$handleStyle = {}; private setHandleStyle() { if (isNaN(this._offset)) return; this._zone.runOutsideAngular(() => { if (this._slider.vertical) { // 兼容垂直滑动条; this._$handleStyle = { bottom: this._offset + "%" } } else { this._$handleStyle = { left: this._offset + "%" } } }) } private _dragging: boolean = false; public transformPosToValue(pos) { // 更新取得的滑动条尺寸. this._slider._refresh(); let dimensions = this._slider._dimensions; // bottom 在dom中的位置. let offset = this._slider.vertical ? dimensions.bottom : dimensions.left; let size = this._slider.vertical ? dimensions.height : dimensions.width; let posValue = this._slider.vertical ? pos.y - 6 : pos.x; if (this._slider.vertical) { posValue = posValue > offset ? offset : posValue; } else { posValue = posValue < offset ? offset : posValue; } let newValue = Math.abs(posValue - offset) / size * (this._slider.max - this._slider.min) + (this._slider.min - 0); // 保留两位小数 let m = this._calFloat(this._slider.step); // 解决出现的有时小数点多了N多位. newValue = Math.round(Math.round(newValue / this._slider.step) * this._slider.step * Math.pow(10, m)) / Math.pow(10, m); return this._slider._verifyValue(newValue); } /** * 计算需要保留小数的位数 * 子级组件需要用到 * @internal */ public _calFloat(value: number): number { // 增加步长的计算; let m = 0; try { m = this._slider.step.toString().split(".")[1].length; } catch (e) { } return m; } /** * @internal */ public _$startToDrag() { this._dragging = true; this._registerGlobalEvent(); } globalEventMouseMove: Function; globalEventMouseUp: Function; _registerGlobalEvent() { this.globalEventMouseMove = this._render.listen("document", "mousemove", (e) => { this._$updateValuePosition(e); }); this.globalEventMouseUp = this._render.listen("document", "mouseup", () => { this._dragging = false; this._destroyGlobalEvent(); }); } _destroyGlobalEvent() { if (this.globalEventMouseMove) { this.globalEventMouseMove(); } if (this.globalEventMouseUp) { this.globalEventMouseUp(); } } private _slider: JigsawMobileSlider; // 父组件; constructor(private _render: Renderer2, @Host() @Inject(forwardRef(() => JigsawMobileSlider)) slider: any, protected _zone: NgZone) { this._slider = slider; } /** * 改变value的值 * @internal */ public _$updateValuePosition(event?) { if (!this._dragging || this._slider.disabled) return; // 防止产生选中其他文本,造成鼠标放开后还可以拖拽的奇怪现象; event.stopPropagation(); event.preventDefault(); let pos = { x: event["clientX"], y: event["clientY"] }; let newValue = this.transformPosToValue(pos); if (this.value === newValue) return; this.value = newValue; this._slider._updateValue(this.key, newValue); } ngOnInit() { this._valueToPos(); } } /** * @description 滑动条组件. * * 何时使用 * 当用户需要在数值区间/自定义区间内进行选择时 */ @Component({ selector: 'jigsaw-mobile-slider, jm-slider', templateUrl: './slider.html', host: { '[class.jigsaw-slider-host]': 'true', '[class.jigsaw-slider-error]': '!valid', '[class.jigsaw-slider-vertical]': 'vertical', '[style.width]': 'width', '[style.height]': 'height' }, encapsulation: ViewEncapsulation.None, providers: [ {provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => JigsawMobileSlider), multi: true}, ] }) export class JigsawMobileSlider extends AbstractJigsawComponent implements ControlValueAccessor, OnInit, OnDestroy { constructor(private _element: ElementRef, private _render: Renderer2, protected _zone: NgZone) { super(); } @Input() public valid: boolean = true; // Todo 支持滑动条点击. @ViewChildren(JigsawMobileSliderHandle) private _sliderHandle: QueryList<JigsawMobileSliderHandle>; /** * @internal */ public _$value: ArrayCollection<number> = new ArrayCollection<number>(); private _removeRefreshCallback: CallbackRemoval = this._getRemoveRefreshCallback(); /** * slider的当前值, 类型 number | ArrayCollection<number> 支持多触点. * */ @Input() public get value(): number | ArrayCollection<number> { // 兼容返回单个值, 和多触点的数组; if (this._$value.length == 1) { return this._$value[0]; } else { return this._$value; } } public set value(value: number | ArrayCollection<number>) { this.writeValue(value); } /** * 设置单个的值。内部使用 * 子级组件需要用到 * @internal */ public _updateValue(index: number, value: number) { this._$value.set(index, value); this._$value.refresh(); } /** * 最后重新计算一下,垂直滚动条的位置 * 子级组件需要用到 * @internal */ public _refresh() { this._dimensions = this._element.nativeElement.getBoundingClientRect(); } /** * 使 value 支持双向绑定 * */ @Output() public valueChange = new EventEmitter<number | ArrayCollection<number>>(); // 当滑动条的组件值变化时,对外发出的事件 @Output() public change = this.valueChange; private _min: number = 0; /** * 可选范围的最小值 * */ @Input() public get min() { return this._min; } public set min(min: number) { this._min = min; } private _max: number = 100; /** * 输入范围的可选最大值. * */ @Input() public get max() { return this._max; } public set max(max: number) { this._max = max; } private _step: number = 1; /** * 每次变化的最小值, 最小支持小数点后两位. * */ @Input() public get step() { return this._step; } public set step(value: number) { this._step = value; } /** * 子级组件需要用到 * @internal */ public _transformValueToPos(value?) { // 检验值的合法性, 不合法转换成默认可接受的合法值; value = this._verifyValue(value); return (value - this.min) / (this.max - this.min) * 100; } /** * 子级组件需要用到 * @internal */ public _dimensions: ClientRect; /** * 垂直滑动条 默认 false * */ @Input() public vertical: boolean = false; /** * 是否禁用. 数据类型 boolean, 默认false; * */ @Input() public disabled: boolean = false; /** * @internal */ public _$trackStyle = {}; private _setTrackStyle(value?) { // 兼容双触点. let startPos: number = 0; let trackSize: number = CommonUtils.isDefined(value) ? this._transformValueToPos(value) : this._transformValueToPos(this.value); // 默认单触点位置 if (this._$value.length > 1) { let max: number = this._$value[0]; let min: number = this._$value[0]; this._$value.map(item => { if (max - item < 0) max = item; else if (item - min < 0) min = item; }); startPos = this._transformValueToPos(min); trackSize = Math.abs(this._transformValueToPos(max) - this._transformValueToPos(min)); } if (this.vertical) { // 垂直和水平两种 this._$trackStyle = { bottom: startPos + "%", height: trackSize + "%" } } else { this._$trackStyle = { left: startPos + "%", width: trackSize + "%" } } } /** * @internal */ public _$marks: any[] = []; private _marks: SliderMark[]; /** * marks 标签 使用格式为 [Object] 其中 Object 必须包含value 及label 可以有style 属性 例如: marks = [{value: 20, label: '20 ℃'}, */ @Input() public get marks(): SliderMark[] { return this._marks; } public set marks(value: SliderMark[]) { this._marks = value; this._calcMarks(); } private _calcMarks() { if (!this._marks || !this.initialized) return; this._$marks.splice(0, this._$marks.length); let size = Math.round(100 / this._marks.length); let margin = -Math.floor(size / 2); let vertical = this.vertical; this._marks.forEach(mark => { const richMark: any = {}; if (vertical) { richMark.dotStyle = { bottom: this._transformValueToPos(mark.value) + "%" }; richMark.labelStyle = { bottom: this._transformValueToPos(mark.value) + "%", "margin-bottom": margin + "%" }; } else { richMark.dotStyle = { top: "-2px", left: this._transformValueToPos(mark.value) + "%" }; richMark.labelStyle = { left: this._transformValueToPos(mark.value) + "%", width: size + "%", "margin-left": margin + "%" }; } // 如果用户自定义了样式, 要进行样式的合并; CommonUtils.extendObject(richMark.labelStyle, mark.style); richMark.label = mark.label; this._$marks.push(richMark); }); } ngOnInit() { super.ngOnInit(); // 计算slider 的尺寸. this._dimensions = this._element.nativeElement.getBoundingClientRect(); // 设置标记. this._calcMarks(); // 注册resize事件; this.resize(); } private _removeResizeEvent: Function; private resize() { this._zone.runOutsideAngular(() => { this._removeResizeEvent = this._render.listen("window", "resize", () => { // 计算slider 的尺寸. this._dimensions = this._element.nativeElement.getBoundingClientRect(); }) }) } /** * 暂没有使用场景. */ public ngOnDestroy() { if (this._removeResizeEvent) { this._removeResizeEvent(); } if (this._removeRefreshCallback) { this._removeRefreshCallback() } } /** * 校验value的合法性. 大于最大值,取最大值, 小于最小值取最小值 * 子级组件需要用到 * @internal */ public _verifyValue(value: number) { if (value - this.min < 0 && this.initialized) { return this.min; } else if (value - this.max > 0 && this.initialized) { return this.max; } else { return value; } } private _getRemoveRefreshCallback() { return this._$value.onRefresh(() => { this._zone.runOutsideAngular(() => this._setTrackStyle(this.value)); this.valueChange.emit(this.value); this._propagateChange(this.value); }); } private _propagateChange: any = () => { }; // ngModel触发的writeValue方法,只会在ngOnInit,ngAfterContentInit,ngAfterViewInit这些生命周期之后才调用 public writeValue(value: any): void { if(value instanceof Array) { value = new ArrayCollection(value); } if (value instanceof ArrayCollection) { if (this._$value !== value) { this._$value = value; if (this._removeRefreshCallback) { this._removeRefreshCallback(); } this._removeRefreshCallback = this._getRemoveRefreshCallback(); } } else { this._$value.splice(0, this._$value.length); this._$value.push(this._verifyValue(+value)); } // refresh的回调是异步的 this._$value.refresh(); } public registerOnChange(fn: any): void { this._propagateChange = fn; } public registerOnTouched(fn: any): void { } }
the_stack
import { Ref, SourceRec, SepCases, VariantLevel, Declarator, Union, Value, Fn, Raw, ComputeVariant, Bool, Separate, Flag, Permute, RawCase, TypeofSepCases, Tuple, SingleVariant, VariantLevelRec, CaseLayer, TypeOfCaseLayer, Matcher, Grouping, ConfigStructShape, Word, WordValue, WordDecl, } from './types' import {isRef} from './isRef' import {processDeclaratorsToShape} from './processDeclaratorsToShape' import {ctx, ctxWrap} from './ctx' import {applyConfigStruct, confStruct, validateRequiredFields} from './config' import {assert} from './assert' const nextID = (() => { let id = 0 return () => `__${(++id).toString(36)}` })() function getName(id: string, name?: string) { let result = name ?? id if (result in ctx.shape) result = `${id}_${result}` return result } // ------ export function separate< Src extends SourceRec, Variants extends Record<string, VariantLevel<Src> /* | VariantLevel<Src>[]*/>, Cases extends SepCases<Src, Variants> >({ name, variant, cases, source, sort, }: { source: Src name?: string variant: Variants cases: Cases sort?: Array<TypeofSepCases<Src, Variants, Cases>> | 'string' }): Separate<TypeofSepCases<Src, Variants, Cases>> { const id = nextID() const sources: Declarator[] = Object.values(source) const variants = {} as any for (const variantName in variant) { const variantRec = variant[variantName] if ( typeof variantRec !== 'object' || variantRec === null || Array.isArray(variantRec) ) { throw Error( `variant "${variantName}" should be an object with cases-objects`, ) } for (const singleMatchName in variantRec) { const singleMatch = variantRec[singleMatchName] if (typeof singleMatch !== 'object' || singleMatch === null) { throw Error( `variant "${variantName}/${singleMatchName}" should be an object with cases-objects`, ) } for (const singleMatchItem of Array.isArray(singleMatch) ? singleMatch : [singleMatch]) { for (const field in singleMatchItem) { if (!(field in source)) { throw Error( `variant "${variantName}/${singleMatchName}" has field "${field}" without source`, ) } } } } } for (const variantName in variant) { variants[variantName] = matcher(source, variant[variantName]) } const val: Separate<TypeofSepCases<Src, Variants, Cases>> = { id, name: getName(id, name), kind: 'separate', __t: null as any, prepared: {}, variant: variants, cases: traverseCases(id, variant, cases), } ctx.shape[val.name] = val ctx.items[val.id] = val addSourceRefs(val.id, sources) if (sort) config({grouping: {sortByFields: {[val.name]: sort}}}) return val } function traverseCases( id: string, variants: Record<string, Record<string, unknown> | Record<string, unknown>[]>, cases: Record<string, any>, ): Record<string, Declarator | Record<string, Declarator>> { const variantNames = Object.keys(variants) if (variantNames.length === 0) { console.warn(`empty variants for cases`, cases) return {} } const [first, ...rest] = variantNames return traverseCases_(first, rest, variants, cases) function traverseCases_( currentVariantName: string, nextVariants: string[], variants: Record< string, Record<string, unknown> | Record<string, unknown>[] >, cases: Record<string, Declarator | Record<string, unknown>>, ) { const resultCases: Record< string, Declarator | Record<string, Declarator> > = {} const variant = variants[currentVariantName] const branchNames = [ ...new Set( Array.isArray(variant) ? variant.flatMap(e => Object.keys(e)) : Object.keys(variant), ), '__', ] for (const branchName of branchNames) { if (!(branchName in cases)) continue const caseValue = cases[branchName] if (isRef(caseValue)) { resultCases[branchName] = caseValue addCasesRefs(id, [caseValue]) } else if (typeof caseValue === 'object' && caseValue !== null) { if (nextVariants.length > 0) { const [first, ...rest] = nextVariants resultCases[branchName] = traverseCases_( first, rest, variants, caseValue as Record<string, Declarator | Record<string, unknown>>, ) as Record<string, Declarator> } else { const val = value(caseValue) resultCases[branchName] = val addCasesRefs(id, [val]) // console.warn( // `incorrect case value for last branch "${branchName}"`, // caseValue, // ) } } else { const val = value(caseValue) resultCases[branchName] = val addCasesRefs(id, [val]) // console.warn( // `incorrect case value for branch "${branchName}"`, // caseValue, // ) } } return resultCases } } export function permute<T>({ name, items, noReorder, amount, sort, }: { name?: string items: T[] amount?: {min: number; max: number} noReorder?: boolean sort?: T[] | 'string' }) { const id = nextID() const permute: { items: T[] noReorder?: boolean amount?: {min: number; max: number} } = {items} if (typeof noReorder === 'boolean') { permute.noReorder = noReorder } if (amount) permute.amount = amount const val: Permute<T> = { id, name: getName(id, name), kind: 'permute', __t: null as any, prepared: {}, permute, } /* if (name === val.name) */ ctx.shape[val.name] = val ctx.items[val.id] = val addSourceRefs(val.id) if (sort) config({grouping: {sortByFields: {[val.name]: sort}}}) return val } export function flag({ name, needs, avoid, sort, }: { name?: string needs?: Declarator | Tuple<Declarator> avoid?: Declarator | Tuple<Declarator> sort?: boolean[] } = {}) { const id = nextID() const source: Declarator[] = [] const val: Flag = { id, name: getName(id, name), kind: 'flag', __t: null as any, prepared: {}, needs: needs ? Array.isArray(needs) ? needs.map(processDeclarator) : [processDeclarator(needs as Declarator)] : [], avoid: avoid ? Array.isArray(avoid) ? avoid.map(processDeclarator) : [processDeclarator(avoid as Declarator)] : [], decls: { true: value(true), false: value(false), }, } /* if (name === val.name) */ ctx.shape[val.name] = val ctx.items[val.id] = val addSourceRefs(val.id, source) addCasesRefs(val.id, [val.decls.true, val.decls.false]) if (sort) config({grouping: {sortByFields: {[val.name]: sort}}}) return val function processDeclarator(decl: Declarator) { source.push(decl) // if (decl.name !== decl.id) return decl.id // return decl.prepared } } export function bool<Src extends SourceRec>({ source, name, true: onTrue, false: onFalse, sort, }: { source: Src name?: string true?: SingleVariant<Src> false?: SingleVariant<Src> sort?: boolean[] }) { assert( (!onTrue && onFalse) || (onTrue && !onFalse), 'either true or false should be defined but not both', ) const id = nextID() const val: Bool = { id, name: getName(id, name), kind: 'bool', __t: false, prepared: {}, bool: { true: onTrue && singleMatcher(source, onTrue), false: onFalse && singleMatcher(source, onFalse), }, decls: { true: value(true), false: value(false), }, } /* if (name === val.name) */ ctx.shape[val.name] = val ctx.items[val.id] = val addSourceRefs(val.id, source) addCasesRefs(val.id, [val.decls.true, val.decls.false]) if (sort) config({grouping: {sortByFields: {[val.name]: sort}}}) return val } export function value<T>(value: T, name?: string) { const id = nextID() const val: Value<T> = { id, name: getName(id, name), kind: 'value', __t: value, prepared: {}, value, } /* if (name === val.name) */ ctx.shape[val.name] = val ctx.items[val.id] = val addSourceRefs(val.id) return val } export function union<OneOf extends string>( oneOf: Tuple<OneOf>, name?: string, ): Union<OneOf> export function union<OneOf extends string>(config: { oneOf: Tuple<OneOf> sort?: OneOf[] | 'string' }): Union<OneOf> export function union<OneOf extends string>( oneOf: Tuple<OneOf> | {oneOf: Tuple<OneOf>; sort?: OneOf[] | 'string'}, name?: string, ): Union<OneOf> { //@ts-ignore const items: Tuple<OneOf> = Array.isArray(oneOf) ? oneOf : oneOf.oneOf const id = nextID() const val: Union<OneOf> = { id, name: getName(id, name), kind: 'union', variants: items, __t: null as any, prepared: {}, } /* if (name === val.name) */ ctx.shape[val.name] = val ctx.items[val.id] = val addSourceRefs(val.id) if (!Array.isArray(oneOf) && 'sort' in oneOf) { config({grouping: {sortByFields: {[val.name]: oneOf.sort!}}}) } return val } export function computeFn<Src extends Tuple<Declarator> | SourceRec, T>({ source, fn, name, sort, }: { source: Src fn: ( args: { [K in keyof Src]: Src[K] extends Ref<infer S, unknown> ? S : never }, ) => T name?: string sort?: T[] | 'string' }) { const id = nextID() const val: Fn<T> = { id, name: getName(id, name), kind: 'fn', __t: null as any, prepared: {}, fn(args: Record<string, any>) { try { const mapped = argsToSource({ source, args, }) return fn(mapped) } catch (err) { console.error(err) console.log({source, val, args}) } }, } ctx.shape[val.name] = val ctx.items[val.id] = val addSourceRefs(val.id, source) if (sort) config({grouping: {sortByFields: {[val.name]: sort}}}) return val } export function computeVariants< Src extends SourceRec, Variants extends VariantLevelRec<Src>, Cases extends CaseLayer<Src, Variants> >({ source, variant, cases, name, sort, }: { source: Src variant: Variants cases: Cases name?: string sort?: Array<TypeOfCaseLayer<Src, Variants, Cases>> | 'string' }): ComputeVariant<TypeOfCaseLayer<Src, Variants, Cases>> { const id = nextID() const variants = {} as any for (const variantName in variant) { variants[variantName] = matcher(source, variant[variantName]) } const val: ComputeVariant<TypeOfCaseLayer<Src, Variants, Cases>> = { id, name: getName(id, name), kind: 'computeVariant', variant: variants, //@ts-ignore cases: traverseCases(id, variant, cases), __t: null as any, prepared: {}, } ctx.shape[val.name] = val ctx.items[val.id] = val addSourceRefs(val.id, source) if (sort) config({grouping: {sortByFields: {[val.name]: sort}}}) return val } export function computeVariant< Src extends SourceRec, Variant extends VariantLevel<Src>, Cases extends {[K in keyof Variant]: unknown} >({ source, variant, cases, name, sort, }: { source: Src variant: Variant cases: Cases name?: string sort?: Array<Cases[keyof Cases]> | 'string' }): ComputeVariant<Cases[keyof Cases]> { //@ts-ignore return computeVariants({ source, variant: {_: variant}, //@ts-ignore cases, name, //@ts-ignore sort, }) // const id = nextID() // const val: ComputeVariant<Cases[keyof Cases]> = { // id, // name: getName(id, name), // kind: 'computeVariant', // cases: cases as any, // variant: {_: matcher(source, variant)}, // __t: null as any, // prepared: {}, // } // ctx.shape[val.name] = val // ctx.items[val.id] = val // addSourceRefs(val.id, source) // if (sort) config({grouping: {sortByFields: {[val.name]: sort}}}) // return val } export function sortOrder(decls: Declarator[]) { const sortByFields = ctx.config.grouping!.sortByFields! const keys = Object.keys(sortByFields) const declNames = decls.map(decl => decl.name) assert( declNames.every(name => keys.includes(name)), () => { const missedDecls = declNames .filter(name => !keys.includes(name)) .join(',') return `decls ${missedDecls} are not sorted` }, ) const declNamesOrdered = [ ...declNames, ...keys.filter(key => !declNames.includes(key)), ] const result: Record<string, any> = {} for (const name of declNamesOrdered) result[name] = sortByFields[name] ctx.config.grouping!.sortByFields = result } function createWordsArray( x: TemplateStringsArray, args: Array<WordValue>, ): Array<WordValue> { if (args.length === 0) return x as any const words: Array<WordValue> = [x[0]] for (let i = 0; i < args.length; i++) { words.push(args[i], x[i + 1]) } return words } export function fmt(x: TemplateStringsArray, ...args: Array<Word>) { const decls = [...args.entries()] .filter(([, e]) => isRef(e)) .map(([idx, decl]) => { return { decl: decl as WordDecl, position: idx, key: `__${idx}`, } }) const blueprint = args.map(e => (isRef(e) ? null : e)) const sources: Record<string, WordDecl> = {} for (const {key, decl} of decls) { sources[key] = decl } return computeFn({ source: sources, fn(values) { const resultValues = [...blueprint] for (let i = 0; i < decls.length; i++) { const decl = decls[i] resultValues[decl.position] = String(values[decl.key]) } return createWordsArray(x, resultValues).join('') }, }) } /** convert internal variable map to object with human-readable fields * * args = {foo_1: 0, bar_2: 'ok'} * source = {foo: foo_1, bar: bar_2} * return = {foo: 0, bar: 'ok'} * source = [bar_2, foo_1] * return = ['ok', 0] */ function argsToSource<Src extends Tuple<Declarator> | SourceRec>({ source, args, }: { source: Src args: Record<string, any> }): { [K in keyof Src]: Src[K] extends Ref<infer T, unknown> ? T : never } { let namedArgs: any if (Array.isArray(source)) { namedArgs = source.map(item => { const {name} = item // if (!(name in args)) { // throw Error(`no "${item.name}/${item.id}" in args`) // } return name }) } else { const argsMap: Record<string, any> = {} for (const key in source) { const item = (source as SourceRec)[key] // if (!(item.name in args)) { // console.warn({source, args, key, name: item.name}) // throw Error(`no "${key}/${item.name}/${item.id}" in args`) // } argsMap[key] = args[item.name] } namedArgs = argsMap } return namedArgs } /** convert object with human-readable fields to internal variable map * * caseItem = {foo: 0, bar: 'ok'} * source = {foo: foo_1, bar: bar_2} * return = {foo_1: 0, bar_2: 'ok'} */ function sourceToArgs< Src extends SourceRec, Case extends Partial< {[K in keyof Src]: Src[K] extends Ref<infer S, unknown> ? S : never} > >(source: Src, caseItem: Case) { const realMatchMap = {} as Record<string, any> for (const alias in caseItem) { if (alias in source) { const resolvedName = source[alias].name realMatchMap[resolvedName] = caseItem[alias] } else { console.warn(`no alias "${alias}" in caseItem`, caseItem) console.trace('no alias') } } return realMatchMap } export function matcher< Src extends SourceRec, Variant extends VariantLevel<Src> >( source: Src, cases: Variant, ): { [K in keyof Variant]: Variant[K] extends Tuple<unknown> ? {[L in keyof Variant[K]]: Record<string, any>} : Record<string, any> } export function matcher< Src extends SourceRec, Variants extends VariantLevel<Src>[] >( source: Src, cases: Variants, ): [ ...{ [L in keyof Variants]: { [K in keyof Variants[L]]: Variants[L][K] extends Tuple<unknown> ? {[M in keyof Variants[L][K]]: Record<string, any>} : Record<string, any> } }, ] export function matcher< Src extends SourceRec, Variant extends VariantLevel<Src> | VariantLevel<Src>[] >(source: Src, cases: Variant) { const result = {} as any for (const key in cases) { result[key] = singleMatcher(source, cases[key]) as any } return result } function singleMatcher< Src extends SourceRec, VariantField extends SingleVariant<Src> >(source: Src, caseItem: VariantField) { if (Array.isArray(caseItem)) { return caseItem.map(caseItem => sourceToArgs(source, caseItem)) } return sourceToArgs( source, caseItem as Exclude<VariantField, Tuple<Matcher<Src>>>, ) } export function insert<T = unknown>(name: string, shape: RawCase): Raw<T> export function insert<T = unknown>(shape: RawCase): Raw<T> export function insert<T = unknown>(...args: [RawCase] | [string, RawCase]) { const id = nextID() let name: string let shape: RawCase if (typeof args[0] === 'string' && args[1]) { ;[name, shape] = args } else { ;[shape] = args name = id } const val: Raw<T> = { id, name: getName(id, name), kind: 'raw', value: shape, __t: null as any, prepared: shape, } /* if (name === val.name) */ ctx.shape[val.name] = val.prepared ctx.items[val.id] = val addSourceRefs(val.id) return val } export function config(data: { header?: string file?: string usedMethods?: string[] grouping?: Partial<Grouping<any>> }): void export function config<T>(data: { header?: string file?: string usedMethods?: string[] grouping: Partial<Grouping<T>> }): void export function config(data: { header?: string file?: string usedMethods?: string[] grouping?: Partial<Grouping<any>> }) { const configUpdated = applyConfigStruct( ctx.configValidator.shape, ctx.config, data, ) if (configUpdated) ctx.configUsed = true } function addSourceRefs( id: string, source?: Record<string, Declarator> | Tuple<Declarator> | Declarator[], ) { ctx.references[id] = [] if (source) { if (Array.isArray(source)) { for (const sourceItem of source) { ctx.references[sourceItem.id] = ctx.references[sourceItem.id] ?? [] ctx.references[sourceItem.id].push(id) } } else { for (const field in source) { const sourceId = (source as Record<string, Declarator>)[field].id ctx.references[sourceId] = ctx.references[sourceId] ?? [] ctx.references[sourceId].push(id) } } } } /** add inline references FROM id */ function addCasesRefs(id: string, targets: Declarator[]) { ctx.targets[id] = ctx.targets[id] ?? [] ctx.targets[id].push(...targets.map(e => e.id)) } export function exec(fn: () => void, struct: ConfigStructShape = confStruct) { return ctxWrap( { shape: {}, configUsed: false, items: {}, references: {}, targets: {}, config: {}, configValidator: struct, }, currCtx => { fn() if (!currCtx.configUsed) throw Error('no config() used') validateRequiredFields(currCtx.configValidator, currCtx.config) const plan = processDeclaratorsToShape() return { plan, items: currCtx.items, grouping: currCtx.config.grouping, header: currCtx.config.header ?? null, file: currCtx.config.file ?? null, config: currCtx.config, usedMethods: currCtx.config.usedMethods ?? null, } }, ) }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement, Operator } from "../shared"; /** * Statement provider for service [ses-pinpoint](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonpinpointemailservice.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class SesPinpoint extends PolicyStatement { public servicePrefix = 'ses'; /** * Statement provider for service [ses-pinpoint](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonpinpointemailservice.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to create a configuration set * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_CreateConfigurationSet.html */ public toCreateConfigurationSet() { return this.to('CreateConfigurationSet'); } /** * Grants permission to create a configuration set event destination * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_CreateConfigurationSetEventDestination.html */ public toCreateConfigurationSetEventDestination() { return this.to('CreateConfigurationSetEventDestination'); } /** * Grants permission to create a new pool of dedicated IP addresses * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_CreateDedicatedIpPool.html */ public toCreateDedicatedIpPool() { return this.to('CreateDedicatedIpPool'); } /** * Grants permission to create a new predictive inbox placement test * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_CreateDeliverabilityTestReport.html */ public toCreateDeliverabilityTestReport() { return this.to('CreateDeliverabilityTestReport'); } /** * Grants permission to start the process of verifying an email identity * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_CreateEmailIdentity.html */ public toCreateEmailIdentity() { return this.to('CreateEmailIdentity'); } /** * Grants permission to delete an existing configuration set * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_DeleteConfigurationSet.html */ public toDeleteConfigurationSet() { return this.to('DeleteConfigurationSet'); } /** * Grants permission to delete an event destination * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_DeleteConfigurationSetEventDestination.html */ public toDeleteConfigurationSetEventDestination() { return this.to('DeleteConfigurationSetEventDestination'); } /** * Grants permission to delete a dedicated IP pool * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_DeleteDedicatedIpPool.html */ public toDeleteDedicatedIpPool() { return this.to('DeleteDedicatedIpPool'); } /** * Grants permission to delete an email identity that you previously verified * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_DeleteEmailIdentity.html */ public toDeleteEmailIdentity() { return this.to('DeleteEmailIdentity'); } /** * Grants permission to get information about the email-sending status and capabilities * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_GetAccount.html */ public toGetAccount() { return this.to('GetAccount'); } /** * Grants permission to retrieve a list of the deny lists on which your dedicated IP addresses appear * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_GetBlacklistReports.html */ public toGetBlacklistReports() { return this.to('GetBlacklistReports'); } /** * Grants permission to get information about an existing configuration set * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_GetConfigurationSet.html */ public toGetConfigurationSet() { return this.to('GetConfigurationSet'); } /** * Grants permission to retrieve a list of event destinations that are associated with a configuration set * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_GetConfigurationSetEventDestinations.html */ public toGetConfigurationSetEventDestinations() { return this.to('GetConfigurationSetEventDestinations'); } /** * Grants permission to get information about a dedicated IP address * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_GetDedicatedIp.html */ public toGetDedicatedIp() { return this.to('GetDedicatedIp'); } /** * Grants permission to list the dedicated IP addresses that are associated with your account * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_GetDedicatedIps.html */ public toGetDedicatedIps() { return this.to('GetDedicatedIps'); } /** * Grants permission to get the status of the Deliverability dashboard * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_GetDeliverabilityDashboardOptions.html */ public toGetDeliverabilityDashboardOptions() { return this.to('GetDeliverabilityDashboardOptions'); } /** * Grants permission to retrieve the results of a predictive inbox placement test * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_GetDeliverabilityTestReport.html */ public toGetDeliverabilityTestReport() { return this.to('GetDeliverabilityTestReport'); } /** * Grants permission to retrieve all the deliverability data for a specific campaign * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_GetDomainDeliverabilityCampaign.html */ public toGetDomainDeliverabilityCampaign() { return this.to('GetDomainDeliverabilityCampaign'); } /** * Grants permission to retrieve inbox placement and engagement rates for the domains that you use to send email * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_GetDomainStatisticsReport.html */ public toGetDomainStatisticsReport() { return this.to('GetDomainStatisticsReport'); } /** * Grants permission to get information about a specific identity associated with your account * * Access Level: Read * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_GetEmailIdentity.html */ public toGetEmailIdentity() { return this.to('GetEmailIdentity'); } /** * Grants permission to list all of the configuration sets associated with your account * * Access Level: List * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_ListConfigurationSets.html */ public toListConfigurationSets() { return this.to('ListConfigurationSets'); } /** * Grants permission to list all of the dedicated IP pools that exist in your account * * Access Level: List * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_ListDedicatedIpPools.html */ public toListDedicatedIpPools() { return this.to('ListDedicatedIpPools'); } /** * Grants permission to retrieve a list of the predictive inbox placement tests that you've performed, regardless of their statuses * * Access Level: List * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_ListDeliverabilityTestReports.html */ public toListDeliverabilityTestReports() { return this.to('ListDeliverabilityTestReports'); } /** * Grants permission to retrieve deliverability data for all the campaigns that used a specific domain to send email during a specified time range * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_ListDomainDeliverabilityCampaigns.html */ public toListDomainDeliverabilityCampaigns() { return this.to('ListDomainDeliverabilityCampaigns'); } /** * Grants permission to list all of the email identities that are associated with your account * * Access Level: List * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_ListEmailIdentities.html */ public toListEmailIdentities() { return this.to('ListEmailIdentities'); } /** * Grants permission to retrieve a list of the tags (keys and values) that are associated with a specific resource * * Access Level: Read * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to enable or disable the automatic warm-up feature for dedicated IP addresses * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_PutAccountDedicatedIpWarmupAttributes.html */ public toPutAccountDedicatedIpWarmupAttributes() { return this.to('PutAccountDedicatedIpWarmupAttributes'); } /** * Grants permission to enable or disable the ability of your account to send email * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_PutAccountSendingAttributes.html */ public toPutAccountSendingAttributes() { return this.to('PutAccountSendingAttributes'); } /** * Grants permission to associate a configuration set with a dedicated IP pool * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_PutConfigurationSetDeliveryOptions.html */ public toPutConfigurationSetDeliveryOptions() { return this.to('PutConfigurationSetDeliveryOptions'); } /** * Grants permission to enable or disable collection of reputation metrics for emails that you send using a particular configuration set * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_PutConfigurationSetReputationOptions.html */ public toPutConfigurationSetReputationOptions() { return this.to('PutConfigurationSetReputationOptions'); } /** * Grants permission to enable or disable email sending for messages that use a particular configuration set * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_PutConfigurationSetSendingOptions.html */ public toPutConfigurationSetSendingOptions() { return this.to('PutConfigurationSetSendingOptions'); } /** * Grants permission to specify a custom domain to use for open and click tracking elements in email that you send using a particular configuration set * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_PutConfigurationSetTrackingOptions.html */ public toPutConfigurationSetTrackingOptions() { return this.to('PutConfigurationSetTrackingOptions'); } /** * Grants permission to move a dedicated IP address to an existing dedicated IP pool * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_PutDedicatedIpInPool.html */ public toPutDedicatedIpInPool() { return this.to('PutDedicatedIpInPool'); } /** * Grants permission to enable dedicated IP warm up attributes * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_PutDedicatedIpWarmupAttributes.html */ public toPutDedicatedIpWarmupAttributes() { return this.to('PutDedicatedIpWarmupAttributes'); } /** * Grants permission to enable or disable the Deliverability dashboard * * Access Level: Write * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_PutDeliverabilityDashboardOption.html */ public toPutDeliverabilityDashboardOption() { return this.to('PutDeliverabilityDashboardOption'); } /** * Grants permission to enable or disable DKIM authentication for an email identity * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_PutEmailIdentityDkimAttributes.html */ public toPutEmailIdentityDkimAttributes() { return this.to('PutEmailIdentityDkimAttributes'); } /** * Grants permission to enable or disable feedback forwarding for an identity * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_PutEmailIdentityFeedbackAttributes.html */ public toPutEmailIdentityFeedbackAttributes() { return this.to('PutEmailIdentityFeedbackAttributes'); } /** * Grants permission to enable or disable the custom MAIL FROM domain configuration for an email identity * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_PutEmailIdentityMailFromAttributes.html */ public toPutEmailIdentityMailFromAttributes() { return this.to('PutEmailIdentityMailFromAttributes'); } /** * Grants permission to send an email message * * Access Level: Write * * Possible conditions: * - .ifFeedbackAddress() * - .ifFromAddress() * - .ifFromDisplayName() * - .ifRecipients() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_SendEmail.html */ public toSendEmail() { return this.to('SendEmail'); } /** * Grants permission to add one or more tags (keys and values) to a specified resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to remove one or more tags (keys and values) from a specified resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update the configuration of an event destination for a configuration set * * Access Level: Write * * Possible conditions: * - .ifAwsResourceTag() * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_UpdateConfigurationSetEventDestination.html */ public toUpdateConfigurationSetEventDestination() { return this.to('UpdateConfigurationSetEventDestination'); } protected accessLevelList: AccessLevelList = { "Write": [ "CreateConfigurationSet", "CreateConfigurationSetEventDestination", "CreateDedicatedIpPool", "CreateDeliverabilityTestReport", "CreateEmailIdentity", "DeleteConfigurationSet", "DeleteConfigurationSetEventDestination", "DeleteDedicatedIpPool", "DeleteEmailIdentity", "PutAccountDedicatedIpWarmupAttributes", "PutAccountSendingAttributes", "PutConfigurationSetDeliveryOptions", "PutConfigurationSetReputationOptions", "PutConfigurationSetSendingOptions", "PutConfigurationSetTrackingOptions", "PutDedicatedIpInPool", "PutDedicatedIpWarmupAttributes", "PutDeliverabilityDashboardOption", "PutEmailIdentityDkimAttributes", "PutEmailIdentityFeedbackAttributes", "PutEmailIdentityMailFromAttributes", "SendEmail", "UpdateConfigurationSetEventDestination" ], "Read": [ "GetAccount", "GetBlacklistReports", "GetConfigurationSet", "GetConfigurationSetEventDestinations", "GetDedicatedIp", "GetDedicatedIps", "GetDeliverabilityDashboardOptions", "GetDeliverabilityTestReport", "GetDomainDeliverabilityCampaign", "GetDomainStatisticsReport", "GetEmailIdentity", "ListDomainDeliverabilityCampaigns", "ListTagsForResource" ], "List": [ "ListConfigurationSets", "ListDedicatedIpPools", "ListDeliverabilityTestReports", "ListEmailIdentities" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type configuration-set to the statement * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_CreateConfigurationSet.html * * @param configurationSetName - Identifier for the configurationSetName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onConfigurationSet(configurationSetName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ses:${Region}:${Account}:configuration-set/${ConfigurationSetName}'; arn = arn.replace('${ConfigurationSetName}', configurationSetName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type dedicated-ip-pool to the statement * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_DedicatedIp.html * * @param dedicatedIPPool - Identifier for the dedicatedIPPool. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onDedicatedIpPool(dedicatedIPPool: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ses:${Region}:${Account}:dedicated-ip-pool/${DedicatedIPPool}'; arn = arn.replace('${DedicatedIPPool}', dedicatedIPPool); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type deliverability-test-report to the statement * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_DeliverabilityTestReport.html * * @param reportId - Identifier for the reportId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onDeliverabilityTestReport(reportId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ses:${Region}:${Account}:deliverability-test-report/${ReportId}'; arn = arn.replace('${ReportId}', reportId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type identity to the statement * * https://docs.aws.amazon.com/pinpoint-email/latest/APIReference/API_IdentityInfo.html * * @param identityName - Identifier for the identityName. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onIdentity(identityName: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ses:${Region}:${Account}:identity/${IdentityName}'; arn = arn.replace('${IdentityName}', identityName); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Filters actions based on the "Return-Path" address, which specifies where bounces and complaints are sent by email feedback forwarding * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonses.html#amazonses-policy-keys * * Applies to actions: * - .toSendEmail() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifFeedbackAddress(value: string | string[], operator?: Operator | string) { return this.if(`FeedbackAddress`, value, operator || 'StringLike'); } /** * Filters actions based on the "From" address of a message * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonses.html#amazonses-policy-keys * * Applies to actions: * - .toSendEmail() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifFromAddress(value: string | string[], operator?: Operator | string) { return this.if(`FromAddress`, value, operator || 'StringLike'); } /** * Filters actions based on the "From" address that is used as the display name of a message * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonses.html#amazonses-policy-keys * * Applies to actions: * - .toSendEmail() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifFromDisplayName(value: string | string[], operator?: Operator | string) { return this.if(`FromDisplayName`, value, operator || 'StringLike'); } /** * Filters actions based on the recipient addresses of a message, which include the "To", "CC", and "BCC" addresses * * https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonses.html#amazonses-policy-keys * * Applies to actions: * - .toSendEmail() * * @param value The value(s) to check * @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike` */ public ifRecipients(value: string | string[], operator?: Operator | string) { return this.if(`Recipients`, value, operator || 'StringLike'); } }
the_stack
import * as assert from 'assert'; import {describe, it} from 'mocha'; import * as protos from '../../../protos'; import { DynamicRoutingParameters, getDynamicHeaderRequestParams, getHeaderRequestParams, getSingleRoutingHeaderParam, MessagesMap, } from '../../src/schema/proto'; import {Proto} from '../../src/schema/proto'; import {Options} from '../../src/schema/naming'; import {ResourceDatabase} from '../../src/schema/resource-database'; import {CommentsMap} from '../../src/schema/comments'; describe('src/schema/proto.ts', () => { describe('should get header parameters from http rule', () => { it('works with no parameter', () => { const httpRule: protos.google.api.IHttpRule = { post: '{=abc/*/d/*/ef/}', }; assert.deepStrictEqual([], getHeaderRequestParams(httpRule)); }); it('works only one parameter', () => { const httpRule: protos.google.api.IHttpRule = { post: '{param1=abc/*/d/*/ef/}', }; assert.deepStrictEqual([['param1']], getHeaderRequestParams(httpRule)); }); it('works with multiple parameter', () => { const httpRule: protos.google.api.IHttpRule = { post: '{param1.param2.param3=abc/*/d/*/ef/}', }; assert.deepStrictEqual( [['param1', 'param2', 'param3']], getHeaderRequestParams(httpRule) ); }); it('works with additional bindings', () => { const httpRule: protos.google.api.IHttpRule = { post: '{param1.param2.param3=abc/*/d/*/ef/}', additionalBindings: [ { post: '{foo1.foo2=foos/*}', }, { post: 'no_parameters_here', }, { post: '{bar1.bar2.bar3=bars/*}', }, ], }; assert.deepStrictEqual( [ ['param1', 'param2', 'param3'], ['foo1', 'foo2'], ['bar1', 'bar2', 'bar3'], ], getHeaderRequestParams(httpRule) ); }); it('dedups parameters', () => { const httpRule: protos.google.api.IHttpRule = { post: '{param1.param2.param3=abc/*/d/*/ef/}', additionalBindings: [ { post: '{foo1.foo2=foos/*}', }, { post: '{param1.param2.param3=abc/*/d/*/ef/}', }, { post: '{param1.param2.param3=abc/*/d/*/ef/}', }, ], }; assert.deepStrictEqual( [ ['param1', 'param2', 'param3'], ['foo1', 'foo2'], ], getHeaderRequestParams(httpRule) ); }); }); describe('should get all the dynamic routing header parameters from routing parameters rule', () => { it('returns array with an empty rule if an annotation is malformed', () => { const routingParameters: protos.google.api.IRoutingParameter[] = [ { field: 'name', pathTemplate: 'test/database', }, ]; const expectedRoutingParameters: DynamicRoutingParameters[][] = [ [ { fieldRetrieve: '', fieldSend: '', messageRegex: '', namedSegment: '', }, ], ]; assert.deepStrictEqual( expectedRoutingParameters, getDynamicHeaderRequestParams(routingParameters) ); }); it('works with a couple rules with the same parameter', () => { const routingParameters: protos.google.api.IRoutingParameter[] = [ { field: 'name', pathTemplate: '{routing_id=projects/*}/**}', }, { field: 'database', pathTemplate: '{routing_id=**}', }, { field: 'database', pathTemplate: '{routing_id=projects/*/databases/*}/documents/*/**', }, ]; const expectedRoutingParameters: DynamicRoutingParameters[][] = [ [ { fieldRetrieve: 'database', fieldSend: 'routing_id', messageRegex: '(?<routing_id>projects)/[^/]+/databases/[^/]+/documents/[^/]+(?:/.*)?', namedSegment: '(?<routing_id>projects/[^/]+/databases/[^/]+)', }, { fieldRetrieve: 'database', fieldSend: 'routing_id', messageRegex: '(?<routing_id>(?:/.*)?)', namedSegment: '(?<routing_id>.*)', }, { fieldRetrieve: 'name', fieldSend: 'routing_id', messageRegex: '(?<routing_id>projects)/[^/]+(?:/.*)?', namedSegment: '(?<routing_id>projects/[^/]+)', }, ], ]; assert.deepStrictEqual( expectedRoutingParameters, getDynamicHeaderRequestParams(routingParameters) ); }); it('works with a couple rules with different parameters', () => { const routingParameters: protos.google.api.IRoutingParameter[] = [ { field: 'name', pathTemplate: '{routing_id=projects/*}/**}', }, { field: 'app_profile_id', pathTemplate: '{profile_id=projects/*}/**', }, ]; const expectedRoutingParameters: DynamicRoutingParameters[][] = [ [ { fieldRetrieve: 'name', fieldSend: 'routing_id', messageRegex: '(?<routing_id>projects)/[^/]+(?:/.*)?', namedSegment: '(?<routing_id>projects/[^/]+)', }, ], [ { fieldRetrieve: 'app_profile_id', fieldSend: 'profile_id', messageRegex: '(?<profile_id>projects)/[^/]+(?:/.*)?', namedSegment: '(?<profile_id>projects/[^/]+)', }, ], ]; assert.deepStrictEqual( expectedRoutingParameters, getDynamicHeaderRequestParams(routingParameters) ); }); it('works with a several rules with different parameters', () => { const routingParameters: protos.google.api.IRoutingParameter[] = [ { field: 'name', pathTemplate: '{routing_id=projects/*}/**}', }, { field: 'name', pathTemplate: 'test/{routing_id=projects/*/databases/*}/documents/*/**', }, { field: 'app_profile_id', pathTemplate: '{profile_id=projects/*}/**', }, ]; const expectedRoutingParameters: DynamicRoutingParameters[][] = [ [ { fieldRetrieve: 'name', fieldSend: 'routing_id', messageRegex: 'test/(?<routing_id>projects)/[^/]+/databases/[^/]+/documents/[^/]+(?:/.*)?', namedSegment: '(?<routing_id>projects/[^/]+/databases/[^/]+)', }, { fieldRetrieve: 'name', fieldSend: 'routing_id', messageRegex: '(?<routing_id>projects)/[^/]+(?:/.*)?', namedSegment: '(?<routing_id>projects/[^/]+)', }, ], [ { fieldRetrieve: 'app_profile_id', fieldSend: 'profile_id', messageRegex: '(?<profile_id>projects)/[^/]+(?:/.*)?', namedSegment: '(?<profile_id>projects/[^/]+)', }, ], ]; assert.deepStrictEqual( expectedRoutingParameters, getDynamicHeaderRequestParams(routingParameters) ); }); }); describe('should get return an array from a single routing parameters rule', () => { it('should return an empty DynamicRoutingParameters interface if the annotation is malformed', () => { const routingRule: protos.google.api.IRoutingParameter = { field: 'name', pathTemplate: 'test/database', }; const expectedRoutingParameters: DynamicRoutingParameters = { fieldRetrieve: '', fieldSend: '', messageRegex: '', namedSegment: '', }; assert.deepStrictEqual( expectedRoutingParameters, getSingleRoutingHeaderParam(routingRule) ); }); it('works with no parameters', () => { const routingRule: protos.google.api.IRoutingParameter = {}; const expectedRoutingParameters: DynamicRoutingParameters = { fieldRetrieve: '', fieldSend: '', messageRegex: '', namedSegment: '', }; assert.deepStrictEqual( expectedRoutingParameters, getSingleRoutingHeaderParam(routingRule) ); }); it('works with no path template', () => { const routingRule: protos.google.api.IRoutingParameter = { field: 'name', }; const expectedRoutingParameters: DynamicRoutingParameters = { fieldRetrieve: 'name', fieldSend: 'name', messageRegex: '[^/]+', namedSegment: '[^/]+', }; assert.deepStrictEqual( expectedRoutingParameters, getSingleRoutingHeaderParam(routingRule) ); }); it('works with a basic path template', () => { const routingRule: protos.google.api.IRoutingParameter = { field: 'app_profile_id', pathTemplate: '{routing_id=**}', }; const expectedRoutingParameters: DynamicRoutingParameters = { fieldRetrieve: 'app_profile_id', fieldSend: 'routing_id', messageRegex: '(?<routing_id>(?:/.*)?)', namedSegment: '(?<routing_id>.*)', }; assert.deepStrictEqual( expectedRoutingParameters, getSingleRoutingHeaderParam(routingRule) ); }); it('works with a standard path template', () => { const routingRule: protos.google.api.IRoutingParameter = { field: 'app_profile_id', pathTemplate: '{routing_id=projects/*}/**', }; const expectedRoutingParameters: DynamicRoutingParameters = { fieldRetrieve: 'app_profile_id', fieldSend: 'routing_id', messageRegex: '(?<routing_id>projects)/[^/]+(?:/.*)?', namedSegment: '(?<routing_id>projects/[^/]+)', }; assert.deepStrictEqual( expectedRoutingParameters, getSingleRoutingHeaderParam(routingRule) ); }); }); describe('AugmentService', () => { it('should pass proto file name to the service', () => { const fd = new protos.google.protobuf.FileDescriptorProto(); fd.name = 'google/cloud/showcase/v1beta1/test.proto'; fd.package = 'google.cloud.showcase.v1beta1'; fd.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd.service[0].name = 'TestService'; fd.service[0].method = [ new protos.google.protobuf.MethodDescriptorProto(), ]; fd.service[0].method[0] = new protos.google.protobuf.MethodDescriptorProto(); fd.service[0].method[0].name = 'Test'; fd.service[0].method[0].outputType = '.google.cloud.showcase.v1beta1.TestOutput'; const options: Options = { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }; const allMessages: MessagesMap = {}; fd.messageType .filter(message => message.name) .forEach(message => { allMessages['.' + fd.package! + '.' + message.name!] = message; }); const commentsMap = new CommentsMap([fd]); const proto = new Proto({ fd, packageName: 'google.cloud.showcase.v1beta1', allMessages, allResourceDatabase: new ResourceDatabase(), resourceDatabase: new ResourceDatabase(), options, commentsMap, }); assert.strictEqual(proto.services[fd.service[0].name].protoFile, fd.name); }); }); describe('special work around for talent API', () => { it('The pagingFieldName should be undefined for SearchJobs & SearchProfiles rpc', () => { const fd = new protos.google.protobuf.FileDescriptorProto(); fd.name = 'google/cloud/talent/v4beta1/service.proto'; fd.package = 'google.cloud.talent.v4beta1'; fd.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd.service[0].name = 'service'; fd.service[0].method = [ new protos.google.protobuf.MethodDescriptorProto(), ]; fd.service[0].method[0] = new protos.google.protobuf.MethodDescriptorProto(); fd.service[0].method[0].name = 'SearchJobs'; fd.service[0].method[1] = new protos.google.protobuf.MethodDescriptorProto(); fd.service[0].method[1].name = 'SearchProfiles'; fd.service[0].method[2] = new protos.google.protobuf.MethodDescriptorProto(); fd.service[0].method[2].name = 'SearchJobsForAlert'; fd.service[0].method[3] = new protos.google.protobuf.MethodDescriptorProto(); fd.service[0].method[3].name = 'ListJobs'; fd.service[0].method[3].outputType = '.google.cloud.talent.v4beta1.ListJobsOutput'; fd.service[0].method[3].inputType = '.google.cloud.talent.v4beta1.ListJobsInput'; fd.messageType = [new protos.google.protobuf.DescriptorProto()]; fd.messageType[0] = new protos.google.protobuf.DescriptorProto(); fd.messageType[1] = new protos.google.protobuf.DescriptorProto(); fd.messageType[0].name = 'ListJobsOutput'; fd.messageType[1].name = 'ListJobsInput'; fd.messageType[0].field = [ new protos.google.protobuf.FieldDescriptorProto(), ]; fd.messageType[0].field[0] = new protos.google.protobuf.FieldDescriptorProto(); fd.messageType[0].field[0].name = 'next_page_token'; fd.messageType[0].field[0].label = protos.google.protobuf.FieldDescriptorProto.Label.LABEL_REPEATED; fd.messageType[1].field = [ new protos.google.protobuf.FieldDescriptorProto(), ]; fd.messageType[1].field[0] = new protos.google.protobuf.FieldDescriptorProto(); fd.messageType[1].field[0].name = 'page_size'; fd.messageType[1].field[1] = new protos.google.protobuf.FieldDescriptorProto(); fd.messageType[1].field[1].name = 'page_token'; const options: Options = { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }; const allMessages: MessagesMap = {}; fd.messageType .filter(message => message.name) .forEach(message => { allMessages['.' + fd.package! + '.' + message.name!] = message; }); const commentsMap = new CommentsMap([fd]); const proto = new Proto({ fd, packageName: 'google.cloud.talent.v4beta1', allMessages, allResourceDatabase: new ResourceDatabase(), resourceDatabase: new ResourceDatabase(), options, commentsMap, }); assert.deepStrictEqual( proto.services['service'].method[0].pagingFieldName, undefined ); assert.deepStrictEqual( proto.services['service'].method[1].pagingFieldName, undefined ); assert.deepStrictEqual( proto.services['service'].method[2].pagingFieldName, undefined ); assert.deepStrictEqual( proto.services['service'].method[3].pagingFieldName, 'next_page_token' ); }); it("should allow generate a proto has no service and its package name differ from service's", () => { const fd = new protos.google.protobuf.FileDescriptorProto(); fd.name = 'google/cloud/showcase/v1beta1/test.proto'; fd.package = 'google.cloud.showcase.v1beta1.errors'; const allMessages: MessagesMap = {}; fd.messageType .filter(message => message.name) .forEach(message => { allMessages['.' + fd.package! + '.' + message.name!] = message; }); const options: Options = { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }; const commentsMap = new CommentsMap([fd]); const proto = new Proto({ fd, packageName: 'google.cloud.talent.v4beta1', allMessages, allResourceDatabase: new ResourceDatabase(), resourceDatabase: new ResourceDatabase(), options, commentsMap, }); assert.deepStrictEqual(proto.fileToGenerate, true); }); it("should not allow generate a service proto with package name differ from the param's pakage name", () => { const fd = new protos.google.protobuf.FileDescriptorProto(); fd.name = 'google/cloud/showcase/v1beta1/test.proto'; fd.package = 'google.cloud.showcase.v1beta1.TestService'; fd.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd.service[0].name = 'service'; fd.service[0].method = [ new protos.google.protobuf.MethodDescriptorProto(), ]; fd.service[0].method[0] = new protos.google.protobuf.MethodDescriptorProto(); fd.service[0].method[0].name = 'Test'; fd.service[0].method[0].outputType = '.google.cloud.showcase.v1beta1.TestOutput'; const options: Options = { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }; const allMessages: MessagesMap = {}; fd.messageType .filter(message => message.name) .forEach(message => { allMessages['.' + fd.package! + '.' + message.name!] = message; }); const commentsMap = new CommentsMap([fd]); const proto = new Proto({ fd, packageName: 'google.cloud.showcase.v1beta1.MainService', allMessages, allResourceDatabase: new ResourceDatabase(), resourceDatabase: new ResourceDatabase(), options, commentsMap, }); assert.deepStrictEqual(proto.fileToGenerate, false); }); }); describe('throw error for misconfigured LRO', () => { it('throw error if method returns Operation, but without operation_info option', () => { const fd = new protos.google.protobuf.FileDescriptorProto(); fd.name = 'google/cloud/showcase/v1beta1/test.proto'; fd.package = 'google.cloud.showcase.v1beta1'; fd.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd.service[0].name = 'service'; fd.service[0].method = [ new protos.google.protobuf.MethodDescriptorProto(), ]; fd.service[0].method[0] = new protos.google.protobuf.MethodDescriptorProto(); fd.service[0].method[0].name = 'Test'; fd.service[0].method[0].outputType = '.google.longrunning.Operation'; const options: Options = { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }; const allMessages: MessagesMap = {}; fd.messageType .filter(message => message.name) .forEach(message => { allMessages['.' + fd.package! + '.' + message.name!] = message; }); const commentsMap = new CommentsMap([fd]); assert.throws(() => { new Proto({ fd, packageName: 'google.cloud.showcase.v1beta1', allMessages, allResourceDatabase: new ResourceDatabase(), resourceDatabase: new ResourceDatabase(), options, commentsMap, }); }, 'rpc "google.cloud.showcase.v1beta1.Test" returns google.longrunning.Operation but is missing option google.longrunning.operation_info'); }); it('throw error if method returns Operation, but without operation_info option', () => { const fd = new protos.google.protobuf.FileDescriptorProto(); fd.name = 'google/cloud/showcase/v1beta1/test.proto'; fd.package = 'google.cloud.showcase.v1beta1'; fd.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd.service[0].name = 'service'; fd.service[0].method = [ new protos.google.protobuf.MethodDescriptorProto(), ]; fd.service[0].method[0] = new protos.google.protobuf.MethodDescriptorProto(); fd.service[0].method[0].name = 'Test'; fd.service[0].method[0].outputType = '.google.longrunning.Operation'; const options: Options = { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }; fd.service[0].method[0].options = new protos.google.protobuf.MethodOptions(); fd.service[0].method[0].options['.google.longrunning.operationInfo'] = {}; const allMessages: MessagesMap = {}; fd.messageType .filter(message => message.name) .forEach(message => { allMessages['.' + fd.package! + '.' + message.name!] = message; }); const commentsMap = new CommentsMap([fd]); assert.throws(() => { new Proto({ fd, packageName: 'google.cloud.showcase.v1beta1', allMessages, allResourceDatabase: new ResourceDatabase(), resourceDatabase: new ResourceDatabase(), options, commentsMap, }); }, /rpc "google.cloud.showcase.v1beta1.Test" has google.longrunning.operation_info but is missing option google.longrunning.operation_info.metadata_type/); }); }); describe('should add diregapic option for Proto class', () => { it('should be false when diregapic is not set', () => { const fd = new protos.google.protobuf.FileDescriptorProto(); const proto = new Proto({ fd, packageName: 'google.cloud.example.v1beta1', allMessages: {}, allResourceDatabase: new ResourceDatabase(), resourceDatabase: new ResourceDatabase(), options: { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }, commentsMap: new CommentsMap([fd]), }); assert.strictEqual(proto.diregapic, undefined); }); it('should be true when diregapic is set', () => { const fd = new protos.google.protobuf.FileDescriptorProto(); const proto = new Proto({ fd, packageName: 'google.cloud.example.v1beta1', allMessages: {}, allResourceDatabase: new ResourceDatabase(), resourceDatabase: new ResourceDatabase(), options: { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), diregapic: true, }, commentsMap: new CommentsMap([fd]), }); assert.strictEqual(proto.diregapic, true); }); }); describe('should support pagination for non-gRPC APIs, diregapic mode', () => { it('should be page field if diregapic mode and use "max_results" as field name', () => { const fd = new protos.google.protobuf.FileDescriptorProto(); fd.name = 'google/cloud/showcase/v1beta1/test.proto'; fd.package = 'google.cloud.showcase.v1beta1'; fd.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd.service[0].name = 'service'; fd.service[0].method = [ new protos.google.protobuf.MethodDescriptorProto(), ]; fd.service[0].method[0] = new protos.google.protobuf.MethodDescriptorProto(); fd.service[0].method[0].name = 'List'; fd.service[0].method[0].outputType = '.google.cloud.showcase.v1beta1.AddressList'; fd.service[0].method[0].inputType = '.google.cloud.showcase.v1beta1.ListAddressesRequest'; fd.messageType = [new protos.google.protobuf.DescriptorProto()]; fd.messageType[0] = new protos.google.protobuf.DescriptorProto(); fd.messageType[1] = new protos.google.protobuf.DescriptorProto(); fd.messageType[0].name = 'AddressList'; fd.messageType[1].name = 'ListAddressesRequest'; fd.messageType[0].field = [ new protos.google.protobuf.FieldDescriptorProto(), ]; fd.messageType[0].field[0] = new protos.google.protobuf.FieldDescriptorProto(); fd.messageType[0].field[0].name = 'next_page_token'; fd.messageType[0].field[0].label = protos.google.protobuf.FieldDescriptorProto.Label.LABEL_REPEATED; fd.messageType[0].field[0].type = protos.google.protobuf.FieldDescriptorProto.Type.TYPE_MESSAGE; fd.messageType[0].field[0].typeName = '.google.cloud.showcase.v1beta1.Address'; fd.messageType[1].field = [ new protos.google.protobuf.FieldDescriptorProto(), ]; fd.messageType[1].field[0] = new protos.google.protobuf.FieldDescriptorProto(); fd.messageType[1].field[0].name = 'max_results'; fd.messageType[1].field[1] = new protos.google.protobuf.FieldDescriptorProto(); fd.messageType[1].field[1].name = 'page_token'; const options: Options = { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), diregapic: true, }; const allMessages: MessagesMap = {}; fd.messageType .filter(message => message.name) .forEach(message => { allMessages['.' + fd.package! + '.' + message.name!] = message; }); const commentsMap = new CommentsMap([fd]); const proto = new Proto({ fd, packageName: 'google.cloud.showcase.v1beta1', allMessages, allResourceDatabase: new ResourceDatabase(), resourceDatabase: new ResourceDatabase(), options, commentsMap, }); assert.deepStrictEqual( proto.services['service'].method[0].pagingFieldName, 'next_page_token' ); assert.deepStrictEqual(proto.services['service'].paging[0].name, 'List'); assert.deepStrictEqual( proto.services['service'].paging[0].inputType, '.google.cloud.showcase.v1beta1.ListAddressesRequest' ); assert.deepStrictEqual( proto.services['service'].paging[0].outputType, '.google.cloud.showcase.v1beta1.AddressList' ); assert.deepStrictEqual( proto.services['service'].paging[0].pagingResponseType, '.google.cloud.showcase.v1beta1.Address' ); }); it('should not be page field if api is not google discovery api but use "max_result"', () => { const fd = new protos.google.protobuf.FileDescriptorProto(); fd.name = 'google/cloud/showcase/v1beta1/test.proto'; fd.package = 'google.cloud.showcase.v1beta1'; fd.service = [new protos.google.protobuf.ServiceDescriptorProto()]; fd.service[0].name = 'service'; fd.service[0].method = [ new protos.google.protobuf.MethodDescriptorProto(), ]; fd.service[0].method[0] = new protos.google.protobuf.MethodDescriptorProto(); fd.service[0].method[0].name = 'List'; fd.service[0].method[0].outputType = '.google.cloud.showcase.v1beta1.AddressList'; fd.service[0].method[0].inputType = '.google.cloud.showcase.v1beta1.ListAddressesRequest'; fd.messageType = [new protos.google.protobuf.DescriptorProto()]; fd.messageType[0] = new protos.google.protobuf.DescriptorProto(); fd.messageType[1] = new protos.google.protobuf.DescriptorProto(); fd.messageType[0].name = 'AddressList'; fd.messageType[1].name = 'ListAddressesRequest'; fd.messageType[0].field = [ new protos.google.protobuf.FieldDescriptorProto(), ]; fd.messageType[0].field[0] = new protos.google.protobuf.FieldDescriptorProto(); fd.messageType[0].field[0].name = 'next_page_token'; fd.messageType[0].field[0].label = protos.google.protobuf.FieldDescriptorProto.Label.LABEL_REPEATED; fd.messageType[1].field = [ new protos.google.protobuf.FieldDescriptorProto(), ]; fd.messageType[1].field[0] = new protos.google.protobuf.FieldDescriptorProto(); fd.messageType[1].field[0].name = 'max_results'; fd.messageType[1].field[1] = new protos.google.protobuf.FieldDescriptorProto(); fd.messageType[1].field[1].name = 'page_token'; const options: Options = { grpcServiceConfig: new protos.grpc.service_config.ServiceConfig(), }; const allMessages: MessagesMap = {}; fd.messageType .filter(message => message.name) .forEach(message => { allMessages['.' + fd.package! + '.' + message.name!] = message; }); const commentsMap = new CommentsMap([fd]); const proto = new Proto({ fd, packageName: 'google.cloud.showcase.v1beta1', allMessages, allResourceDatabase: new ResourceDatabase(), resourceDatabase: new ResourceDatabase(), options, commentsMap, }); assert.deepStrictEqual( proto.services['service'].method[0].pagingFieldName, undefined ); assert.deepStrictEqual(proto.services['service'].paging.length, 0); }); }); });
the_stack
import { execSync } from "child_process"; import { existsSync, readFileSync } from "fs"; /** * ServerVersion contains versioning information for the server, * consistent with what other components provide, even if some * of it doesn't really make sense for a Node server. */ export interface ServerVersion { /** The ATC version of the server e.g. 5.0.0 */ version: string; /** * The number of commits in the development branch that produced this * version of ATC - if known. */ commits?: string; /** * The hash of the commit at which this ATC instance was built - if known. */ hash?: string; /** * The "Enterprise Linux" release for which this version of ATC was built * (which should never actually matter for Traffic Portal) - if known. */ elRelease?: string; /** * The CPU architecture for which this version of ATC was built (which * should REALLY never matter for Traffic Portal) - if known. */ arch?: string; } /** Converts the given version to a string. */ export function versionToString(v: ServerVersion): string { let ret = `traffic-portal-${v.version}`; // Can't allow either-or, because since git hashes could // possibly be entirely numeric that would make the case // where only one is present confusing - is it commit // count or hash? if (v.commits) { ret += `-${v.commits}`; if (v.hash) { ret += `.${v.hash}`; } } if (v.elRelease) { ret += `.${v.elRelease}`; } if (v.arch) { ret += `.${v.arch}`; } return ret; } function isServerVersion(v: unknown): v is ServerVersion { // tslint:disable completed-docs if (typeof(v) !== "object") { console.error("version does not represent a server version"); return false; } if (!v) { console.error("'null' is not a valid server version"); return false; } if (!Object.prototype.hasOwnProperty.call(v, "version")) { console.error("version missing required field 'version'"); return false; } if (typeof((v as {version: unknown; }).version) !== "string") { return false; } if (Object.prototype.hasOwnProperty.call(v, "commits") && (typeof((v as {commits: unknown; }).commits)) !== "string") { console.error(`version property 'commits' has incorrect type; want: string, got: ${typeof((v as {commits: unknown; }).commits)}`); return false; } if (Object.prototype.hasOwnProperty.call(v, "hash") && (typeof((v as {hash: unknown; }).hash)) !== "string") { console.error(`version property 'hash' has incorrect type; want: string, got: ${typeof((v as {hash: unknown; }).hash)}`); return false; } if (Object.prototype.hasOwnProperty.call(v, "elRelease") && (typeof((v as {elRelease: unknown; }).elRelease)) !== "string") { console.error(`version property 'elRelease' has incorrect type; want: string, got: ${typeof((v as {elRelease: unknown; }).elRelease)}`); return false; } if (Object.prototype.hasOwnProperty.call(v, "arch") && (typeof((v as {arch: unknown; }).arch)) !== "string") { console.error(`version property 'arch' has incorrect type; want: string, got: ${typeof((v as {arch: unknown; }).arch)}`); return false; } return true; // tslint:enable completed-docs } interface BaseConfig { /** Whether or not SSL certificate errors from Traffic Ops will be ignored. */ insecure?: boolean; /** The port on which Traffic Portal listens. */ port: number; /** The URL of the Traffic Ops API. */ trafficOps: URL; /** Whether or not to serve HTTPS */ useSSL?: boolean; /** Contains all of the versioning information. */ version: ServerVersion; } interface ConfigWithSSL { /** The path to the SSL certificate Traffic Portal will use. */ certPath: string; /** The path to the SSL private key Traffic Portal will use. */ keyPath: string; /** Whether or not to serve HTTPS */ useSSL: true; } interface ConfigWithoutSSL { /** Whether or not to serve HTTPS */ useSSL?: false; } /** ServerConfig holds server configuration. */ export type ServerConfig = BaseConfig & (ConfigWithSSL | ConfigWithoutSSL); /** * isConfig checks specifically the contents of configuration files * passed through JSON.parse, so it doesn't validate the 'version', since * that doesn't need to be in the configuration file. */ function isConfig(c: unknown): c is ServerConfig { // tslint:disable completed-docs if (typeof(c) !== "object") { throw new Error("configuration is not an object"); } if (!c) { throw new Error("'null' is not a valid configuration"); } if (Object.prototype.hasOwnProperty.call(c, "insecure")) { if (typeof((c as {insecure: unknown; }).insecure) !== "boolean") { throw new Error("'insecure' must be a boolean"); } } else { (c as {insecure: boolean; }).insecure = false; } if (!Object.prototype.hasOwnProperty.call(c, "port")) { throw new Error("'port' is required"); } if (typeof((c as {port: unknown; }).port) !== "number") { throw new Error("'port' must be a number"); } if (!Object.prototype.hasOwnProperty.call(c, "trafficOps")) { throw new Error("'trafficOps' is required"); } if (typeof((c as {trafficOps: unknown; }).trafficOps) !== "string") { throw new Error("'trafficOps' must be a string"); } try { (c as {trafficOps: URL; }).trafficOps = new URL((c as {trafficOps: string; }).trafficOps); } catch (e) { throw new Error(`'trafficOps' is not a valid URL: ${e}`); } if (Object.prototype.hasOwnProperty.call(c, "useSSL")) { if (typeof((c as {useSSL: unknown; }).useSSL) !== "boolean") { throw new Error("'useSSL' must be a boolean"); } if ((c as {useSSL: boolean; }).useSSL) { if (!Object.prototype.hasOwnProperty.call(c, "certPath")) { throw new Error("'certPath' is required to use SSL"); } if (typeof((c as {certPath: unknown; }).certPath) !== "string") { throw new Error("'certPath' must be a string"); } if (!Object.prototype.hasOwnProperty.call(c, "keyPath")) { throw new Error("'keyPath' is required to use SSL"); } if (typeof((c as {keyPath: unknown; }).keyPath) !== "string") { throw new Error("'keyPath' must be a string"); } } } return true; // tstlint:enable completed-docs } const defaultVersionFile = "/etc/traffic-portal/version.json"; /** * Retrieves the server's version from the file path provided. * * @param path The path to a version file containing a ServerVersion object. * Defaults to /etc/traffic-portal/version.json. If this file doesn't exist, * the version may be deduced from the execution environment using git and * looking for the ATC VERSION file. */ export function getVersion(path?: string): ServerVersion { if (!path) { path = defaultVersionFile; } if (existsSync(path)) { const v = JSON.parse(readFileSync(path, {encoding: "utf8"})); if (isServerVersion(v)) { return v; } throw new Error(`contents of version file '${path}' does not represent an ATC version`); } if (!existsSync("../../VERSION")) { throw new Error(`'${path}' doesn't exist and '../../VERSION' doesn't exist`); } const ver: ServerVersion = { version: readFileSync("../../VERSION", {encoding: "utf8"}).trimEnd() }; try { ver.commits = String(execSync("git rev-list HEAD", {encoding: "utf8"}).split("\n").length); ver.hash = execSync("git rev-parse --short=8 HEAD", {encoding: "utf8"}).trimEnd(); } catch (e) { console.warn("getting git parts of version:", e); } try { const releaseNo = execSync("rpm -q --qf '%{version}' -f /etc/redhat-release", {encoding: "utf8"}).trimEnd(); ver.elRelease = `el${releaseNo}`; } catch (e) { ver.elRelease = "el7"; console.warn(`getting RHEL version: ${e}`); } try { ver.arch = execSync("uname -m", {encoding: "utf8"}); } catch (e) { console.warn(`getting system architecture: ${e}`); } return ver; } interface Args { trafficOps?: URL; insecure?: boolean; port?: number; certPath?: string; keyPath?: string; configFile: string; } export const defaultConfigFile = "/etc/traffic-portal/config.js"; export function getConfig(args: Args, ver: ServerVersion): ServerConfig { let cfg: ServerConfig = { insecure: false, port: 4200, trafficOps: new URL("https://example.com"), useSSL: false, version: ver }; let readFromFile = false; if (existsSync(args.configFile)) { const cfgFromFile = JSON.parse(readFileSync(args.configFile, {encoding: "utf8"})); try { if (isConfig(cfgFromFile)) { cfg = cfgFromFile; cfg.version = ver; } } catch (err) { throw new Error(`invalid configuration file at '${args.configFile}': ${err}`); } readFromFile = true; } else if (args.configFile !== defaultConfigFile) { throw new Error(`no such configuration file: ${args.configFile}`); } if (args.port) { cfg.port = args.port; } if (isNaN(cfg.port) || cfg.port <= 0 || cfg.port > 65535) { throw new Error(`invalid port: ${cfg.port}`); } if (args.trafficOps) { cfg.trafficOps = args.trafficOps; } else if (!readFromFile) { if (Object.prototype.hasOwnProperty.call(process.env, "TO_URL")) { const envURL = (process.env as {TO_URL: string; }).TO_URL; try { cfg.trafficOps = new URL(envURL); } catch (e) { throw new Error(`invalid Traffic Ops URL from environment: ${envURL}`); } } else { throw new Error("Traffic Ops URL must be specified"); } } if (readFromFile && cfg.useSSL) { if (args.certPath) { cfg.certPath = args.certPath; } if (args.keyPath) { cfg.keyPath = args.keyPath; } } else if (!readFromFile || cfg.useSSL === undefined) { if (args.certPath) { if (!args.keyPath) { throw new Error("must specify either both a key path and a cert path, or neither"); } cfg = { certPath: args.certPath, insecure: cfg.insecure, keyPath: args.keyPath, port: cfg.port, trafficOps: cfg.trafficOps, useSSL: true, version: ver }; } else if (args.keyPath) { throw new Error("must specify either both a key path and a cert path, or neither"); } } if (cfg.useSSL) { if (!existsSync(cfg.certPath)) { throw new Error(`no such certificate file: ${cfg.certPath}`); } if (!existsSync(cfg.keyPath)) { throw new Error(`no such key file: ${cfg.keyPath}`); } } return cfg; }
the_stack
import * as tfc from '@tensorflow/tfjs-core'; import {DataType, Tensor, variableGrads} from '@tensorflow/tfjs-core'; import {getNextUniqueTensorId} from './backend/state'; import {getScopedTensorName, getUniqueTensorName} from './common'; import {Constraint} from './constraints'; import {NotImplementedError} from './errors'; import {Shape} from './keras_format/common'; import {HasShape} from './types'; const DEFAULT_VARIABLE_NAME_PREFIX = 'Variable'; /** * A `tf.layers.LayerVariable` is similar to a `tf.Tensor` in that it has a * dtype and shape, but its value is mutable. The value is itself represented * as a`tf.Tensor`, and can be read with the `read()` method and updated with * the `write()` method. */ export class LayerVariable { readonly dtype: DataType; readonly shape: Shape; readonly id: number; // The fully scoped name of this Variable, including a unique suffix if needed readonly name: string; // The originally requested fully scoped name of this Variable, not including // any unique suffix. This may be needed when restoring weights because this // original name is used as a key. readonly originalName: string; private trainable_: boolean; protected readonly val: tfc.Variable; readonly constraint: Constraint; /** * Construct Variable from a `tf.Tensor`. * * If not explicitly named, the Variable will be given a name with the * prefix 'Variable'. Variable names are unique. In the case of name * collision, suffixies '_<num>' will be added to the name. * * @param val Initial value of the Variable. * @param name Name of the variable. If `null` or `undefined` is provided, it * will default a name with the prefix 'Variable'. * @param constraint Optional, projection function to be applied to the * variable after optimize updates * @throws ValueError if `name` is `null` or `undefined`. */ constructor( val: Tensor, dtype: DataType = 'float32', name = DEFAULT_VARIABLE_NAME_PREFIX, trainable = true, constraint: Constraint = null) { this.dtype = dtype == null ? 'float32' : dtype; this.shape = val.shape; this.id = getNextUniqueTensorId(); name = name == null ? DEFAULT_VARIABLE_NAME_PREFIX : name; this.originalName = getScopedTensorName(name); this.name = getUniqueTensorName(this.originalName); this.trainable_ = trainable; this.constraint = constraint; this.val = tfc.variable(val, this.trainable_, this.name, this.dtype); } /** * Get a snapshot of the Variable's value. * * The returned value is a snapshot of the Variable's value at the time of * the invocation. Future mutations in the value of the tensor will only * be reflected by future calls to this method. */ read(): Tensor { this.assertNotDisposed(); return this.val; } /** * Update the value of the Variable. * * @param newVal: The new value to update to. Must be consistent with the * dtype and shape of the Variable. * @return This Variable. */ write(newVal: Tensor) { // TODO(cais): Once TF.js Core supports Tensor.dtype, check dtype match. this.assertNotDisposed(); checkShapesMatch(this.val, newVal); // Skip updating if this is the exact same tensor. if (this.val.id !== newVal.id) { this.val.assign(newVal); if (this.constraint != null) { this.val.assign(this.constraint.apply(this.val)); } } return this; } /** * Dispose this LayersVariable instance from memory. */ dispose(): void { this.assertNotDisposed(); this.val.dispose(); } protected assertNotDisposed(): void { if (this.val.isDisposed) { throw new Error(`LayersVariable ${this.name} is already disposed.`); } } get trainable(): boolean { return this.trainable_; } set trainable(trainable: boolean) { this.trainable_ = trainable; this.val.trainable = trainable; } } function checkShapesMatch(x: HasShape, y: HasShape): void { if (x.shape.toString() !== y.shape.toString()) { throw new Error( 'Shape mismatch: ' + JSON.stringify(x.shape) + ' vs. ' + JSON.stringify(y.shape)); } } /** * Create a Variable. * @param x The initial value of the `Variable`. * @param dtype optional, the type of the variable. * @param name optional, the name of the variable, default provided by * Variable. * @param constraint optional, a constraint to be applied after every update. * @return The newly instantiated `Variable`. */ export function variable( x: Tensor, dtype?: DataType, name?: string, constraint?: Constraint): LayerVariable { return new LayerVariable(x, dtype, name, true, constraint); } /** * Instantiates an all-zeros Variable and returns it. * * @param shape Shape of the tensor. * @param dtype DType of the tensor. * @param name Name of the tensor. * @return An all-zero Variable. */ export function zerosVariable( shape: Shape, dtype?: DataType, name?: string): LayerVariable { // TODO(cais): Implement logic for dtype. return new LayerVariable(tfc.zeros(shape), dtype, name); } /** * Instantiates an all-zeros tensor of the same shape as another tensor. * * @param x The other tensor. * @param dtype DType of the tensor. * @param name Name of the tensor. * @return A newly instantiated Variable. */ export function zerosLike( x: Tensor, dtype?: DataType, name?: string): LayerVariable { return new LayerVariable(tfc.zerosLike(x), dtype, name); } /** * Instantiates an all-ones tensor and returns it. * * @param shape Shape of the tensor. * @param dtype DType of the tensor. * @param name Name of the tensor. * @return An all-ones Variable. */ export function onesVariable( shape: Shape, dtype?: DataType, name?: string): LayerVariable { // TODO(cais): Implement logic for dtype. const allocated = tfc.ones(shape); return new LayerVariable(allocated, dtype, name); } /** * Instantiates an all-ones tensor of the same shape as another tensor. * * @param x The other tensor. * @param dtype DType of the tensor. * @param name Name of the tensor. * @return A newly instantiated Variable. */ export function onesLike( x: Tensor, dtype?: DataType, name?: string): LayerVariable { const allocated = tfc.onesLike(x); return new LayerVariable(allocated, dtype, name); } /** * Instantiate an identity matrix and returns it, as a Variable * * @param size Number of rows/columns. * @param dtype Data type of returned Variable. * @param name Name of returned Variable. * @return A Variable, an identity matrix. */ export function eyeVariable( size: number, dtype?: DataType, name?: string): LayerVariable { return new LayerVariable(tfc.eye(size), dtype, name); } /** * Get a Variable with uniform distribution of values. * @param shape Shape of the tensor. * @param minval Lower bound of the uniform distribution. * @param maxval Upper bound of the uniform distribution. * @param dtype * @param seed * @param name Optional name. * @return The uniform-random Variable. */ export function randomUniformVariable( shape: Shape, minval: number, maxval: number, dtype?: DataType, seed?: number, name = 'randomUniform'): LayerVariable { return new LayerVariable( tfc.randomUniform(shape, minval, maxval, dtype), dtype, name); } /** * Get a Variable with truncated-normal distribution of values. * @param shape Shape of the tensor. * @param mean mean value of the normal distribution. * @param stddev standard deviation of the normal distribution. * @param dtype * @param seed * @param name Optional name. * @return The truncated-normal-random Variable. */ export function truncatedNormalVariable( shape: Shape, mean = 0.0, stddev = 1.0, dtype?: DataType, seed?: number, name = 'truncatedNormal'): LayerVariable { // TODO(cais): Implement logic for dtype and seed once they are supported // by deeplearn.js. dtype = dtype || 'float32'; if (dtype !== 'float32' && dtype !== 'int32') { throw new NotImplementedError( `randomNormal does not support dType ${dtype}.`); } return new LayerVariable( tfc.truncatedNormal(shape, mean, stddev, dtype, seed), dtype, name); } /** * Get a Variable with normal distribution of values. * @param shape Shape of the tensor. * @param mean mean value of the normal distribution. * @param stddev standard deviation of the normal distribution. * @param dtype * @param seed * @param name Optional name. * @return The truncated-normal-random Variable. */ export function randomNormalVariable( shape: Shape, mean = 0.0, stddev = 1.0, dtype?: DataType, seed?: number, name = 'randomNormal'): LayerVariable { dtype = dtype || 'float32'; if (dtype !== 'float32' && dtype !== 'int32') { throw new NotImplementedError( `randomNormalVariable does not support dType ${dtype}.`); } return new LayerVariable( tfc.randomNormal(shape, mean, stddev, dtype, seed), dtype, name); } /** * Update the value of a Variable. * @param x The Variable to be updated. * @param xNew The new value to update to. * @return The Variable updated. */ export function update(x: LayerVariable, xNew: Tensor): LayerVariable { return x.write(xNew); } /** * Update the value of a Variable by adding an increment. * @param x The Variable to be updated. * @param increment The incrment to add to `x`. * @return The Variable updated. */ export function updateAdd(x: LayerVariable, increment: Tensor): LayerVariable { return x.write(tfc.add(x.read(), increment)); } /** * Update the value of a Variable by subtracting a decrement. * @param x The Variable to be updated. * @param decrement The decrement to subtract from `x`. * @return The Variable updated. */ export function updateSub(x: LayerVariable, decrement: Tensor): LayerVariable { return x.write(tfc.sub(x.read(), decrement)); } /** * Get the values of an array of Variables. * * @param tensors An `Array` of `Variable`s to get the values of. * @return The values of the inputs, as an `Array` of`tf.Tensor`s. */ export function batchGetValue(xs: LayerVariable[]): Tensor[] { return xs.map(x => x.read()); } /** * Update the value of multiple Variables at once. * * @param variablesAndValues An `Array`, each element is of type * [Variable, Tensor]. The first item is the * `Variable` of which the value is to be updated. The second item * carries the new value. */ export function batchSetValue( variablesAndValues: Array<[LayerVariable, Tensor]>): void { variablesAndValues.forEach(variableAndValue => { const variable: LayerVariable = variableAndValue[0]; variable.write(variableAndValue[1]); }); } /** * Returns the gradients of `variables` w.r.t. the return value of `lossFn`. * @param lossFn A function which returns a Scalar to be used as the function * value (i.e., numerator) for differentiation. * @param variables List of variables to be used as the independent variables * (i.e., denominator) for differentiation. * @returns An Array of gradients tensors. */ export function gradients( lossFn: () => tfc.Scalar, variables: LayerVariable[]): Tensor[] { // TODO(cais): The return type signature can be simplified if deeplearn makes // the corresponding type public. const variableList = variables.map(variable => variable.read() as tfc.Variable); const valudAndGrads = variableGrads(lossFn, variableList); return variables.map(variable => valudAndGrads.grads[variable.name]); }
the_stack
import { Touch, ScrollEventArgs, TouchEventArgs, Component, EventHandler, selectAll, getUniqueID, removeClass } from '@syncfusion/ej2-base'; import { NotifyPropertyChanges, INotifyPropertyChanged, Property, Browser, detach, createElement as buildTag } from '@syncfusion/ej2-base'; import { classList, SwipeEventArgs, isNullOrUndefined } from '@syncfusion/ej2-base'; import { VScrollModel } from './v-scroll-model'; type HTEle = HTMLElement; type Str = string; const CLS_ROOT: Str = 'e-vscroll'; const CLS_RTL: Str = 'e-rtl'; const CLS_DISABLE: Str = 'e-overlay'; const CLS_VSCROLLBAR: Str = 'e-vscroll-bar'; const CLS_VSCROLLCON: Str = 'e-vscroll-content'; const CLS_NAVARROW: Str = 'e-nav-arrow'; const CLS_NAVUPARROW: Str = 'e-nav-up-arrow'; const CLS_NAVDOWNARROW: Str = 'e-nav-down-arrow'; const CLS_VSCROLLNAV: Str = 'e-scroll-nav'; const CLS_VSCROLLNAVUP: Str = 'e-scroll-up-nav'; const CLS_VSCROLLNAVDOWN: Str = 'e-scroll-down-nav'; const CLS_DEVICE: Str = 'e-scroll-device'; const CLS_OVERLAY: Str = 'e-scroll-overlay'; const CLS_UPOVERLAY: Str = 'e-scroll-up-overlay'; const CLS_DOWNOVERLAY: Str = 'e-scroll-down-overlay'; const OVERLAY_MAXWID: number = 40; interface TapEventArgs { name: string originalEvent: TouchEventArgs | TouchEvent | KeyboardEvent } /** * VScroll module is introduces vertical scroller when content exceeds the current viewing area. * It can be useful for the components like Toolbar, Tab which needs vertical scrolling alone. * Hidden content can be view by touch moving or icon click. * ```html * <div id="scroll"/> * <script> * var scrollObj = new VScroll(); * scrollObj.appendTo("#scroll"); * </script> * ``` */ @NotifyPropertyChanges export class VScroll extends Component<HTMLElement> implements INotifyPropertyChanged { private touchModule: Touch; private scrollEle: HTEle; private scrollItems: HTEle; private uniqueId: boolean; private timeout: number; private keyTimeout: boolean; private keyTimer: number; private browser: string; private browserCheck: boolean; private ieCheck: boolean; /* eslint-disable */ private isDevice: Boolean; private customStep: boolean; /** * Specifies the up or down scrolling distance of the vertical scrollbar moving. * * @default null */ @Property(null) public scrollStep: number; /** * Initialize the event handler * * @private * @returns {void} */ protected preRender(): void { this.browser = Browser.info.name; this.browserCheck = this.browser === 'mozilla'; this.isDevice = Browser.isDevice; this.customStep = true; const ele: HTEle = this.element; this.ieCheck = this.browser === 'edge' || this.browser === 'msie'; this.initialize(); if (ele.id === '') { ele.id = getUniqueID('vscroll'); this.uniqueId = true; } ele.style.display = 'block'; if (this.enableRtl) { ele.classList.add(CLS_RTL); } } /** * To Initialize the vertical scroll rendering * * @private * @returns {void} */ protected render(): void { this.touchModule = new Touch(this.element, { scroll: this.touchHandler.bind(this), swipe: this.swipeHandler.bind(this) }); EventHandler.add(this.scrollEle, 'scroll', this.scrollEventHandler, this); if (!this.isDevice) { this.createNavIcon(this.element); } else { this.element.classList.add(CLS_DEVICE); this.createOverlayElement(this.element); } this.setScrollState(); EventHandler.add(this.element, 'wheel', this.wheelEventHandler, this); } private setScrollState(): void { if (isNullOrUndefined(this.scrollStep) || this.scrollStep < 0) { this.scrollStep = this.scrollEle.offsetHeight; this.customStep = false; } else { this.customStep = true; } } /** * Initializes a new instance of the VScroll class. * * @param {VScrollModel} options - Specifies VScroll model properties as options. * @param {string | HTMLElement} element - Specifies the element for which vertical scrolling applies. */ public constructor(options?: VScrollModel, element?: string | HTMLElement) { super(options, <HTEle | string>element); } private initialize(): void { const scrollCnt: HTEle = buildTag('div', { className: CLS_VSCROLLCON }); const scrollBar: HTEle = buildTag('div', { className: CLS_VSCROLLBAR }); scrollBar.setAttribute('tabindex', '-1'); const ele: HTEle = this.element; const innerEle: HTEle[] = [].slice.call(ele.children); for (const ele of innerEle) { scrollCnt.appendChild(ele); } scrollBar.appendChild(scrollCnt); ele.appendChild(scrollBar); scrollBar.style.overflowY = 'hidden'; this.scrollEle = scrollBar; this.scrollItems = scrollCnt; } protected getPersistData(): string { const keyEntity: string[] = ['scrollStep']; return this.addOnPersist(keyEntity); } /** * Returns the current module name. * * @returns {string} - It returns the current module name. * @private */ protected getModuleName(): string { return 'vScroll'; } /** * Removes the control from the DOM and also removes all its related events. * * @returns {void} */ public destroy(): void { const el: HTEle = this.element; el.style.display = ''; removeClass([this.element], [CLS_ROOT, CLS_DEVICE]); const navs: HTEle[] = selectAll('.e-' + el.id + '_nav.' + CLS_VSCROLLNAV, el); const overlays: HTEle[] = selectAll('.' + CLS_OVERLAY, el); [].slice.call(overlays).forEach((ele: HTMLElement) => { detach(ele); }); for (const elem of [].slice.call(this.scrollItems.children)) { el.appendChild(elem); } if (this.uniqueId) { this.element.removeAttribute('id'); } detach(this.scrollEle); if (navs.length > 0) { detach(navs[0]); if (!isNullOrUndefined(navs[1])) { detach(navs[1]); } } EventHandler.remove(this.scrollEle, 'scroll', this.scrollEventHandler); this.touchModule.destroy(); this.touchModule = null; super.destroy(); } /** * Specifies the value to disable/enable the VScroll component. * When set to `true` , the component will be disabled. * * @param {boolean} value - Based on this Boolean value, VScroll will be enabled (false) or disabled (true). * @returns {void}. */ public disable(value: boolean): void { const navEle: HTMLElement[] = selectAll('.e-scroll-nav:not(.' + CLS_DISABLE + ')', this.element); if (value) { this.element.classList.add(CLS_DISABLE); } else { this.element.classList.remove(CLS_DISABLE); } [].slice.call(navEle).forEach((el: HTMLElement) => { el.setAttribute('tabindex', !value ? '0' : '-1'); }); } private createOverlayElement(element: HTEle): void { const id: string = element.id.concat('_nav'); const downOverlayEle: HTEle = buildTag('div', { className: CLS_OVERLAY + ' ' + CLS_DOWNOVERLAY }); const clsDown: string = 'e-' + element.id.concat('_nav ' + CLS_VSCROLLNAV + ' ' + CLS_VSCROLLNAVDOWN); const downEle: HTEle = buildTag('div', { id: id.concat('down'), className: clsDown }); const navItem: HTEle = buildTag('div', { className: CLS_NAVDOWNARROW + ' ' + CLS_NAVARROW + ' e-icons' }); downEle.appendChild(navItem); const upEle: HTEle = buildTag('div', { className: CLS_OVERLAY + ' ' + CLS_UPOVERLAY }); if (this.ieCheck) { downEle.classList.add('e-ie-align'); } element.appendChild(downOverlayEle); element.appendChild(downEle); element.insertBefore(upEle, element.firstChild); this.eventBinding([downEle]); } private createNavIcon(element: HTEle): void { const id: string = element.id.concat('_nav'); const clsDown: string = 'e-' + element.id.concat('_nav ' + CLS_VSCROLLNAV + ' ' + CLS_VSCROLLNAVDOWN); const nav: HTEle = buildTag('div', { id: id.concat('_down'), className: clsDown }); nav.setAttribute('aria-disabled', 'false'); const navItem: HTEle = buildTag('div', { className: CLS_NAVDOWNARROW + ' ' + CLS_NAVARROW + ' e-icons' }); const clsUp: string = 'e-' + element.id.concat('_nav ' + CLS_VSCROLLNAV + ' ' + CLS_VSCROLLNAVUP); const navElement: HTEle = buildTag('div', { id: id.concat('_up'), className: clsUp + ' ' + CLS_DISABLE }); navElement.setAttribute('aria-disabled', 'true'); const navUpItem: HTEle = buildTag('div', { className: CLS_NAVUPARROW + ' ' + CLS_NAVARROW + ' e-icons' }); navElement.appendChild(navUpItem); nav.appendChild(navItem); nav.setAttribute('tabindex', '0'); element.appendChild(nav); element.insertBefore(navElement, element.firstChild); if (this.ieCheck) { nav.classList.add('e-ie-align'); navElement.classList.add('e-ie-align'); } this.eventBinding([nav, navElement]); } private onKeyPress(ev: KeyboardEvent): void { if (ev.key === 'Enter') { const timeoutFun: () => void = () => { this.keyTimeout = true; this.eleScrolling(10, <HTEle>ev.target, true); }; this.keyTimer = window.setTimeout(() => { timeoutFun(); }, 100); } } private onKeyUp(ev: KeyboardEvent): void { if (ev.key !== 'Enter') { return; } if (this.keyTimeout) { this.keyTimeout = false; } else { (<HTEle>ev.target).click(); } clearTimeout(this.keyTimer); } private eventBinding(element: HTEle[]): void { [].slice.call(element).forEach((ele: HTEle) => { new Touch(ele, { tapHold: this.tabHoldHandler.bind(this), tapHoldThreshold: 500 }); ele.addEventListener('keydown', this.onKeyPress.bind(this)); ele.addEventListener('keyup', this.onKeyUp.bind(this)); ele.addEventListener('mouseup', this.repeatScroll.bind(this)); ele.addEventListener('touchend', this.repeatScroll.bind(this)); ele.addEventListener('contextmenu', (e: Event) => { e.preventDefault(); }); EventHandler.add(ele, 'click', this.clickEventHandler, this); }); } private repeatScroll(): void { clearInterval(this.timeout); } private tabHoldHandler(ev: TapEventArgs): void { let trgt: HTEle = ev.originalEvent.target as HTEle; trgt = this.contains(trgt, CLS_VSCROLLNAV) ? <HTEle>trgt.firstElementChild : trgt; const scrollDistance: number = 10; const timeoutFun: () => void = () => { this.eleScrolling(scrollDistance, trgt, true); }; this.timeout = window.setInterval(() => { timeoutFun(); }, 50); } private contains(element: HTEle, className: string): boolean { return element.classList.contains(className); } private eleScrolling(scrollDis: number, trgt: HTEle, isContinuous: boolean): void { let classList: DOMTokenList = trgt.classList; if (classList.contains(CLS_VSCROLLNAV)) { classList = trgt.querySelector('.' + CLS_NAVARROW).classList; } if (classList.contains(CLS_NAVDOWNARROW)) { this.frameScrollRequest(scrollDis, 'add', isContinuous); } else if (classList.contains(CLS_NAVUPARROW)) { this.frameScrollRequest(scrollDis, '', isContinuous); } } private clickEventHandler(event: Event): void { this.eleScrolling(this.scrollStep, <HTEle>event.target, false); } private wheelEventHandler(e: WheelEvent): void { e.preventDefault(); this.frameScrollRequest(this.scrollStep, (e.deltaY > 0 ? 'add' : ''), false); } private swipeHandler(e: SwipeEventArgs): void { const swipeElement: HTEle = this.scrollEle; let distance: number; if (e.velocity <= 1) { distance = e.distanceY / (e.velocity * 10); } else { distance = e.distanceY / e.velocity; } let start: number = 0.5; const animate: () => void = () => { const step: number = Math.sin(start); if (step <= 0) { window.cancelAnimationFrame(step); } else { if (e.swipeDirection === 'Up') { swipeElement.scrollTop += distance * step; } else if (e.swipeDirection === 'Down') { swipeElement.scrollTop -= distance * step; } start -= 0.02; window.requestAnimationFrame(animate as FrameRequestCallback); } }; animate(); } private scrollUpdating(scrollVal: number, action: string): void { if (action === 'add') { this.scrollEle.scrollTop += scrollVal; } else { this.scrollEle.scrollTop -= scrollVal; } } private frameScrollRequest(scrollValue: number, action: string, isContinuous: boolean): void { const step: number = 10; if (isContinuous) { this.scrollUpdating(scrollValue, action); return; } if (!this.customStep) { [].slice.call(selectAll('.' + CLS_OVERLAY, this.element)).forEach((el: HTMLElement) => { scrollValue -= el.offsetHeight; }); } const animate: () => void = () => { if (scrollValue < step) { window.cancelAnimationFrame(step); } else { this.scrollUpdating(step, action); scrollValue -= step; window.requestAnimationFrame(animate as FrameRequestCallback); } }; animate(); } private touchHandler(e: ScrollEventArgs): void { const el: HTEle = this.scrollEle; const distance: number = e.distanceY; if (e.scrollDirection === 'Up') { el.scrollTop = el.scrollTop + distance; } else if (e.scrollDirection === 'Down') { el.scrollTop = el.scrollTop - distance; } } private arrowDisabling(addDisableCls: HTEle, removeDisableCls: HTEle): void { if (this.isDevice) { const arrowEle: HTMLElement = isNullOrUndefined(addDisableCls) ? removeDisableCls : addDisableCls; const arrowIcon: HTMLElement = arrowEle.querySelector('.' + CLS_NAVARROW) as HTMLElement; if (isNullOrUndefined(addDisableCls)) { classList(arrowIcon, [CLS_NAVDOWNARROW], [CLS_NAVUPARROW]); } else { classList(arrowIcon, [CLS_NAVUPARROW], [CLS_NAVDOWNARROW]); } } else { addDisableCls.classList.add(CLS_DISABLE); addDisableCls.setAttribute('aria-disabled', 'true'); addDisableCls.removeAttribute('tabindex'); removeDisableCls.classList.remove(CLS_DISABLE); removeDisableCls.setAttribute('aria-disabled', 'false'); removeDisableCls.setAttribute('tabindex', '0'); } this.repeatScroll(); } private scrollEventHandler(e: Event): void { const target: HTEle = <HTEle>e.target; const height: number = target.offsetHeight; const navUpEle: HTEle = (<HTEle>this.element.querySelector('.' + CLS_VSCROLLNAVUP)); const navDownEle: HTEle = (<HTEle>this.element.querySelector('.' + CLS_VSCROLLNAVDOWN)); const upOverlay: HTEle = (<HTEle>this.element.querySelector('.' + CLS_UPOVERLAY)); const downOverlay: HTEle = (<HTEle>this.element.querySelector('.' + CLS_DOWNOVERLAY)); let scrollTop: number = target.scrollTop; if (scrollTop <= 0) { scrollTop = -scrollTop; } if (this.isDevice) { if (scrollTop < OVERLAY_MAXWID) { upOverlay.style.height = scrollTop + 'px'; } else { upOverlay.style.height = '40px'; } if ((target.scrollHeight - Math.ceil(height + scrollTop)) < OVERLAY_MAXWID) { downOverlay.style.height = (target.scrollHeight - Math.ceil(height + scrollTop)) + 'px'; } else { downOverlay.style.height = '40px'; } } if (scrollTop === 0) { this.arrowDisabling(navUpEle, navDownEle); } else if (Math.ceil(height + scrollTop + .1) >= target.scrollHeight) { this.arrowDisabling(navDownEle, navUpEle); } else { const disEle: HTEle = <HTEle>this.element.querySelector('.' + CLS_VSCROLLNAV + '.' + CLS_DISABLE); if (disEle) { disEle.classList.remove(CLS_DISABLE); disEle.setAttribute('aria-disabled', 'false'); disEle.setAttribute('tabindex', '0'); } } } /** * Gets called when the model property changes.The data that describes the old and new values of property that changed. * * @param {VScrollModel} newProp - It contains the new value of data. * @param {VScrollModel} oldProp - It contains the old value of data. * @returns {void} * @private */ public onPropertyChanged(newProp: VScrollModel, oldProp: VScrollModel): void { for (const prop of Object.keys(newProp)) { switch (prop) { case 'scrollStep': this.setScrollState(); break; case 'enableRtl': if (newProp.enableRtl) { this.element.classList.add(CLS_RTL); } else { this.element.classList.remove(CLS_RTL); } break; } } } }
the_stack